text:
/**
 * generated by Xtext 2.9.1
 */
package org.xtuml.bp.ui.xtext.myDsl.impl;

import java.util.Collection;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;

import org.xtuml.bp.ui.xtext.myDsl.MyDslPackage;
import org.xtuml.bp.ui.xtext.myDsl.findLogicalOr;
import org.xtuml.bp.ui.xtext.myDsl.findLogicalXor;

/**
 *
 * An implementation of the model object 'find Logical Or'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link org.xtuml.bp.ui.xtext.myDsl.impl.findLogicalOrImpl#getF F}

 *

 *
 * @generated
 */
public class findLogicalOrImpl extends MinimalEObjectImpl.Container implements findLogicalOr
{
  /**
   * The cached value of the '{@link #getF() F}' containment reference list.
   *
   *
   * @see #getF()
   * @generated
   * @ordered
   */
  protected EList<findLogicalXor> f;

  /**
   *
   *
   * @generated
   */
  protected findLogicalOrImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return MyDslPackage.Literals.FIND_LOGICAL_OR;
  }

  /**
   *
   *
   * @generated
   */
  public EList<findLogicalXor> getF()
  {
    if (f == null)
    {
      f = new EObjectContainmentEList<findLogicalXor>(findLogicalXor.class, this, MyDslPackage.FIND_LOGICAL_OR__F);
    }
    return f;
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case MyDslPackage.FIND_LOGICAL_OR__F:
        return ((InternalEList<?>)getF()).basicRemove(otherEnd, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case MyDslPackage.FIND_LOGICAL_OR__F:
        return getF();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @SuppressWarnings("unchecked")
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case MyDslPackage.FIND_LOGICAL_OR__F:
        getF().clear();
        getF().addAll((Collection<? extends findLogicalXor>)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case MyDslPackage.FIND_LOGICAL_OR__F:
        getF().clear();
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case MyDslPackage.FIND_LOGICAL_OR__F:
        return f != null && !f.isEmpty();
    }
    return super.eIsSet(featureID);
  }

} //findLogicalOrImpl


text:
/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { AfeNgSelectComponent } from './afe-ng-select.component';
import { DummyDataSource } from '../form-entry/data-sources/dummy-data-source';

describe('Component: AFE-select-component Unit Tests', () => {
    let dummyDataSource = new DummyDataSource();
    let component = new AfeNgSelectComponent();

    afterEach(() => {
        TestBed.resetTestingModule();
    });

    it('should create an instance of Mult select component', () => {

        expect(component).toBeTruthy();

    });

    it('should have required properties', (done) => {
        expect(component.dataSource).toBeUndefined;
        expect(component.multiple).toBeUndefined;
        expect(component.question_options.length).toBe(0);
        expect(component.selected_question_option).toBeUndefined;
        expect(component.subject).toBeUndefined;
        expect(component.extras).toBeUndefined;
        expect(component.errors.length).toBe(0);
        done();
    });

    it('should have all the required functions defined and callable', (done) => {

        spyOn(component, 'ngOnInit').and.callThrough();
        component.ngOnInit();
        expect(component.ngOnInit).toHaveBeenCalled();
        component.dataSource = dummyDataSource;
        spyOn(component, 'getData').and.callThrough();
        let foundResults = component.getData('k');
        expect(component.getData).toHaveBeenCalled();
        spyOn(component, 'resolveSelectedOption').and.callThrough();
        component.resolveSelectedOption('a8afc8b8-1350-11df-a1f1-0026b9348838');
        expect(component.resolveSelectedOption).toHaveBeenCalled();
        spyOn(component, 'getChangingText').and.callThrough();
        component.getChangingText('k');
        expect(component.getChangingText).toHaveBeenCalled();

        done();

    });

});

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/datapipeline/DataPipeline_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace DataPipeline
{
namespace Model
{
  enum class OperatorType
  {
    NOT_SET,
    EQ,
    REF_EQ,
    LE,
    GE,
    BETWEEN
  };

namespace OperatorTypeMapper
{
AWS_DATAPIPELINE_API OperatorType GetOperatorTypeForName(const Aws::String& name);

AWS_DATAPIPELINE_API Aws::String GetNameForOperatorType(OperatorType value);
} // namespace OperatorTypeMapper
} // namespace Model
} // namespace DataPipeline
} // namespace Aws


text:
namespace remoting {

namespace {

// TODO(solb) Move into location shared with client plugin.
const char* const kXmppServer = "talk.google.com";
const int kXmppPort = 5222;
const bool kXmppUseTls = true;

// Interval at which to log performance statistics, if enabled.
const int kPerfStatsIntervalMs = 60000;

}

ChromotingJniInstance::ChromotingJniInstance(ChromotingJniRuntime* jni_runtime,
                                             const char* username,
                                             const char* auth_token,
                                             const char* host_jid,
                                             const char* host_id,
                                             const char* host_pubkey,
                                             const char* pairing_id,
                                             const char* pairing_secret,
                                             const char* capabilities)
    : jni_runtime_(jni_runtime),
      host_id_(host_id),
      host_jid_(host_jid),
      create_pairing_(false),
      stats_logging_enabled_(false),
      capabilities_(capabilities),
      weak_factory_(this) {
  DCHECK(jni_runtime_->ui_task_runner()->BelongsToCurrentThread());

  // Intialize XMPP config.
  xmpp_config_.host = kXmppServer;
  xmpp_config_.port = kXmppPort;
  xmpp_config_.use_tls = kXmppUseTls;
  xmpp_config_.username = username;
  xmpp_config_.auth_token = auth_token;
  xmpp_config_.auth_service = "oauth2";

  // Initialize |authenticator_|.
  scoped_ptr<protocol::ThirdPartyClientAuthenticator::TokenFetcher>
      token_fetcher(new TokenFetcherProxy(
          base::Bind(&ChromotingJniInstance::FetchThirdPartyToken,
                     weak_factory_.GetWeakPtr()),
          host_pubkey));

  std::vector<protocol::AuthenticationMethod> auth_methods;
  auth_methods.push_back(protocol::AuthenticationMethod::Spake2Pair());
  auth_methods.push_back(protocol::AuthenticationMethod::Spake2(
      protocol::AuthenticationMethod::HMAC_SHA256));
  auth_methods.push_back(protocol::AuthenticationMethod::Spake2(
      protocol::AuthenticationMethod::NONE));
  auth_methods.push_back(protocol::AuthenticationMethod::ThirdParty());

  authenticator_.reset(new protocol::NegotiatingClientAuthenticator(
      pairing_id, pairing_secret, host_id_,
      base::Bind(&ChromotingJniInstance::FetchSecret, this),
      token_fetcher.Pass(), auth_methods));

  // Post a task to start connection
  jni_runtime_->display_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniInstance::ConnectToHostOnDisplayThread,
                 this));
}

ChromotingJniInstance::~ChromotingJniInstance() {
  // This object is ref-counted, so this dtor can execute on any thread.
  // Ensure that all these objects have been freed already, so they are not
  // destroyed on some random thread.
  DCHECK(!view_);
  DCHECK(!client_context_);
  DCHECK(!video_renderer_);
  DCHECK(!authenticator_);
  DCHECK(!client_);
  DCHECK(!signaling_);
  DCHECK(!client_status_logger_);
}

void ChromotingJniInstance::Disconnect() {
  if (!jni_runtime_->display_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->display_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&ChromotingJniInstance::Disconnect, this));
    return;
  }

  // This must be destroyed on the display thread before the producer is gone.
  view_.reset();

  // The weak pointers must be invalidated on the same thread they were used.
  view_weak_factory_->InvalidateWeakPtrs();

  jni_runtime_->network_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniInstance::DisconnectFromHostOnNetworkThread,
                 this));
}

void ChromotingJniInstance::FetchThirdPartyToken(
    const GURL& token_url,
    const std::string& client_id,
    const std::string& scope,
    base::WeakPtr<TokenFetcherProxy> token_fetcher_proxy) {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());
  DCHECK(!token_fetcher_proxy_.get());

  __android_log_print(ANDROID_LOG_INFO,
                      "ThirdPartyAuth",
                      "Fetching Third Party Token from user.");

  token_fetcher_proxy_ = token_fetcher_proxy;
  jni_runtime_->ui_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniRuntime::FetchThirdPartyToken,
                 base::Unretained(jni_runtime_),
                 token_url,
                 client_id,
                 scope));
}

void ChromotingJniInstance::HandleOnThirdPartyTokenFetched(
    const std::string& token,
    const std::string& shared_secret) {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  __android_log_print(
      ANDROID_LOG_INFO, "ThirdPartyAuth", "Third Party Token Fetched.");

  if (token_fetcher_proxy_.get()) {
    token_fetcher_proxy_->OnTokenFetched(token, shared_secret);
    token_fetcher_proxy_.reset();
  } else {
    __android_log_print(
        ANDROID_LOG_WARN,
        "ThirdPartyAuth",
        "Ignored OnThirdPartyTokenFetched() without a pending fetch.");
  }
}

void ChromotingJniInstance::ProvideSecret(const std::string& pin,
                                          bool create_pairing,
                                          const std::string& device_name) {
  DCHECK(jni_runtime_->ui_task_runner()->BelongsToCurrentThread());
  DCHECK(!pin_callback_.is_null());

  create_pairing_ = create_pairing;

  if (create_pairing)
    SetDeviceName(device_name);

  jni_runtime_->network_task_runner()->PostTask(FROM_HERE,
                                                base::Bind(pin_callback_, pin));
}

void ChromotingJniInstance::RedrawDesktop() {
  if (!jni_runtime_->display_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->display_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&ChromotingJniInstance::RedrawDesktop, this));
    return;
  }

  jni_runtime_->RedrawCanvas();
}

void ChromotingJniInstance::SendMouseEvent(
    int x, int y,
    protocol::MouseEvent_MouseButton button,
    bool button_down) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::SendMouseEvent,
                              this, x, y, button, button_down));
    return;
  }

  protocol::MouseEvent event;
  event.set_x(x);
  event.set_y(y);
  event.set_button(button);
  if (button != protocol::MouseEvent::BUTTON_UNDEFINED)
    event.set_button_down(button_down);

  client_->input_stub()->InjectMouseEvent(event);
}

void ChromotingJniInstance::SendMouseWheelEvent(int delta_x, int delta_y) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&ChromotingJniInstance::SendMouseWheelEvent, this,
                   delta_x, delta_y));
    return;
  }

  protocol::MouseEvent event;
  event.set_wheel_delta_x(delta_x);
  event.set_wheel_delta_y(delta_y);
  client_->input_stub()->InjectMouseEvent(event);
}

bool ChromotingJniInstance::SendKeyEvent(int key_code, bool key_down) {
  uint32 usb_key_code = AndroidKeycodeToUsbKeycode(key_code);
  if (!usb_key_code) {
    LOG(WARNING) << "Ignoring unknown keycode: " << key_code;
    return false;
  }

  SendKeyEventInternal(usb_key_code, key_down);
  return true;
}

void ChromotingJniInstance::SendTextEvent(const std::string& text) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&ChromotingJniInstance::SendTextEvent, this, text));
    return;
  }

  protocol::TextEvent event;
  event.set_text(text);
  client_->input_stub()->InjectTextEvent(event);
}

void ChromotingJniInstance::SendClientMessage(const std::string& type,
                                              const std::string& data) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(
            &ChromotingJniInstance::SendClientMessage, this, type, data));
    return;
  }

  protocol::ExtensionMessage extension_message;
  extension_message.set_type(type);
  extension_message.set_data(data);
  client_->host_stub()->DeliverClientMessage(extension_message);
}

void ChromotingJniInstance::RecordPaintTime(int64 paint_time_ms) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::RecordPaintTime, this,
                              paint_time_ms));
    return;
  }

  if (stats_logging_enabled_)
    video_renderer_->GetStats()->video_paint_ms()->Record(paint_time_ms);
}

void ChromotingJniInstance::OnConnectionState(
    protocol::ConnectionToHost::State state,
    protocol::ErrorCode error) {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  EnableStatsLogging(state == protocol::ConnectionToHost::CONNECTED);

  client_status_logger_->LogSessionStateChange(state, error);

  if (create_pairing_ && state == protocol::ConnectionToHost::CONNECTED) {
    protocol::PairingRequest request;
    DCHECK(!device_name_.empty());
    request.set_client_name(device_name_);
    client_->host_stub()->RequestPairing(request);
  }

  jni_runtime_->ui_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniRuntime::OnConnectionState,
                 base::Unretained(jni_runtime_),
                 state,
                 error));
}

void ChromotingJniInstance::OnConnectionReady(bool ready) {
  // We ignore this message, since OnConnectionState tells us the same thing.
}

void ChromotingJniInstance::OnRouteChanged(
    const std::string& channel_name,
    const protocol::TransportRoute& route) {
  std::string message = "Channel " + channel_name + " using " +
      protocol::TransportRoute::GetTypeString(route.type) + " connection.";
  __android_log_print(ANDROID_LOG_INFO, "route", "%s", message.c_str());
}

void ChromotingJniInstance::SetCapabilities(const std::string& capabilities) {
  jni_runtime_->ui_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniRuntime::SetCapabilities,
                 base::Unretained(jni_runtime_),
                 capabilities));
}

void ChromotingJniInstance::SetPairingResponse(
    const protocol::PairingResponse& response) {

  jni_runtime_->ui_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniRuntime::CommitPairingCredentials,
                 base::Unretained(jni_runtime_),
                 host_id_, response.client_id(), response.shared_secret()));
}

void ChromotingJniInstance::DeliverHostMessage(
    const protocol::ExtensionMessage& message) {
  jni_runtime_->ui_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniRuntime::HandleExtensionMessage,
                 base::Unretained(jni_runtime_),
                 message.type(),
                 message.data()));
}

protocol::ClipboardStub* ChromotingJniInstance::GetClipboardStub() {
  return this;
}

protocol::CursorShapeStub* ChromotingJniInstance::GetCursorShapeStub() {
  return this;
}

void ChromotingJniInstance::InjectClipboardEvent(
    const protocol::ClipboardEvent& event) {
  NOTIMPLEMENTED();
}

void ChromotingJniInstance::SetCursorShape(
    const protocol::CursorShapeInfo& shape) {
  if (!jni_runtime_->display_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->display_task_runner()->PostTask(
        FROM_HERE,
        base::Bind(&ChromotingJniInstance::SetCursorShape, this, shape));
    return;
  }

  jni_runtime_->UpdateCursorShape(shape);
}

void ChromotingJniInstance::ConnectToHostOnDisplayThread() {
  DCHECK(jni_runtime_->display_task_runner()->BelongsToCurrentThread());

  view_.reset(new JniFrameConsumer(jni_runtime_, this));
  view_weak_factory_.reset(new base::WeakPtrFactory<JniFrameConsumer>(
      view_.get()));
  frame_consumer_ = new FrameConsumerProxy(jni_runtime_->display_task_runner(),
                                           view_weak_factory_->GetWeakPtr());

  jni_runtime_->network_task_runner()->PostTask(
      FROM_HERE,
      base::Bind(&ChromotingJniInstance::ConnectToHostOnNetworkThread,
                 this));
}

void ChromotingJniInstance::ConnectToHostOnNetworkThread() {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();

  client_context_.reset(new ClientContext(
      jni_runtime_->network_task_runner().get()));
  client_context_->Start();

  SoftwareVideoRenderer* renderer =
      new SoftwareVideoRenderer(client_context_->main_task_runner(),
                                client_context_->decode_task_runner(),
                                frame_consumer_);
  view_->set_frame_producer(renderer);
  video_renderer_.reset(renderer);

  client_.reset(new ChromotingClient(client_context_.get(),
                                     this,
                                     video_renderer_.get(),
                                     scoped_ptr<AudioPlayer>()));

  signaling_.reset(new XmppSignalStrategy(
      net::ClientSocketFactory::GetDefaultFactory(),
      jni_runtime_->url_requester(), xmpp_config_));

  client_status_logger_.reset(
      new ClientStatusLogger(ServerLogEntry::ME2ME,
                             signaling_.get(),
                             ServiceUrls::GetInstance()->directory_bot_jid()));

  protocol::NetworkSettings network_settings(
      protocol::NetworkSettings::NAT_TRAVERSAL_FULL);

  // Use Chrome's network stack to allocate ports for peer-to-peer channels.
  scoped_ptr<protocol::ChromiumPortAllocator> port_allocator(
      protocol::ChromiumPortAllocator::Create(jni_runtime_->url_requester(),
                                              network_settings));

  scoped_ptr<protocol::TransportFactory> transport_factory(
      new protocol::LibjingleTransportFactory(
          signaling_.get(),
          port_allocator.PassAs<cricket::HttpPortAllocatorBase>(),
          network_settings));

  client_->Start(signaling_.get(), authenticator_.Pass(),
                 transport_factory.Pass(), host_jid_, capabilities_);
}

void ChromotingJniInstance::DisconnectFromHostOnNetworkThread() {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  host_id_.clear();

  stats_logging_enabled_ = false;

  // |client_| must be torn down before |signaling_|.
  client_.reset();
  client_status_logger_.reset();
  client_context_.reset();
  video_renderer_.reset();
  authenticator_.reset();
  signaling_.reset();
}

void ChromotingJniInstance::FetchSecret(
    bool pairable,
    const protocol::SecretFetchedCallback& callback) {
  if (!jni_runtime_->ui_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->ui_task_runner()->PostTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::FetchSecret,
                              this, pairable, callback));
    return;
  }

  // Delete pairing credentials if they exist.
  jni_runtime_->CommitPairingCredentials(host_id_, "", "");

  pin_callback_ = callback;
  jni_runtime_->DisplayAuthenticationPrompt(pairable);
}

void ChromotingJniInstance::SetDeviceName(const std::string& device_name) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::SetDeviceName, this,
                              device_name));
    return;
  }

  device_name_ = device_name;
}

void ChromotingJniInstance::SendKeyEventInternal(int usb_key_code,
                                                 bool key_down) {
  if (!jni_runtime_->network_task_runner()->BelongsToCurrentThread()) {
    jni_runtime_->network_task_runner()->PostTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::SendKeyEventInternal,
                              this, usb_key_code, key_down));
    return;
  }

  protocol::KeyEvent event;
  event.set_usb_keycode(usb_key_code);
  event.set_pressed(key_down);
  client_->input_stub()->InjectKeyEvent(event);
}

void ChromotingJniInstance::EnableStatsLogging(bool enabled) {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  if (enabled && !stats_logging_enabled_) {
    jni_runtime_->network_task_runner()->PostDelayedTask(
        FROM_HERE, base::Bind(&ChromotingJniInstance::LogPerfStats, this),
        base::TimeDelta::FromMilliseconds(kPerfStatsIntervalMs));
  }
  stats_logging_enabled_ = enabled;
}

void ChromotingJniInstance::LogPerfStats() {
  DCHECK(jni_runtime_->network_task_runner()->BelongsToCurrentThread());

  if (!stats_logging_enabled_)
    return;

  ChromotingStats* stats = video_renderer_->GetStats();
  __android_log_print(ANDROID_LOG_INFO, "stats",
                      "Bandwidth:%.0f FrameRate:%.1f Capture:%.1f Encode:%.1f "
                      "Decode:%.1f Render:%.1f Latency:%.0f",
                      stats->video_bandwidth()->Rate(),
                      stats->video_frame_rate()->Rate(),
                      stats->video_capture_ms()->Average(),
                      stats->video_encode_ms()->Average(),
                      stats->video_decode_ms()->Average(),
                      stats->video_paint_ms()->Average(),
                      stats->round_trip_ms()->Average());

  client_status_logger_->LogStatistics(stats);

  jni_runtime_->network_task_runner()->PostDelayedTask(
      FROM_HERE, base::Bind(&ChromotingJniInstance::LogPerfStats, this),
      base::TimeDelta::FromMilliseconds(kPerfStatsIntervalMs));
}

}  // namespace remoting


text:
I just had the wierdest meeting ever.  Basically the boss called me into his office and was like ZOMG!!! The NSA IS WIRETAPPING US ALL!!!  Anyway, he went on some crazy rant about how everything is from our cell phones to our toaster ovens are backdoored and that he's under NDA and isn't even supposed to be talking to me.  He said he wants to open source the web app and won't say why.

The web app was originally open source so its probably not a big deal to contribute our changes back and it'd get him to shut up for a while.

## Submission Instructions

You will receive [50 points] for completing this anomaly.

Go to [https://github.com/benjholla/NCDC2014](https://github.com/benjholla/NCDC2014), fork the project, and push a commit of your changes to your forked project. Make sure you actually push your changes, you will not receive points if your changes are not in the repo!

Submit a link to your fork in IScore.

### Bonus Points
P.S.  For [5 extra points] submit a short paragraph of the sneakiest, craziest, obscure, or random software backdoor you can think of.  Links to articles, snarky comments, and ridiculous conspiracy theories welcome, but try to actually think of something practical-ish.


text:
//
//  UIViewController+ProductLayer.h
//  Opinator
//
//  Created by Oliver Drobnik on 6/18/14.
//  Copyright (c) 2014 ProductLayer. All rights reserved.
//

@class PLYServer;

/**
 Category adding common stuff to be used by UIViewControllers
 */
@interface UIViewController (ProductLayer)

/**
 Server to use for requests. If not set the shared server will be used.
 */
@property (nonatomic, strong) PLYServer *productLayerServer;

@end


text:
namespace uti
{
	struct quaternion
	{
		float4 data;
		TAT_DEF quaternion();
		TAT_DEF quaternion(float4 data);
		TAT_DEF uti::quaternion operator+(const uti::quaternion& right) const;
		TAT_DEF uti::quaternion operator*(const uti::quaternion& right) const;
	};

	TAT_DEF quaternion make_quaternion_identity();

	TAT_DEF quaternion make_quaternion(float angle, float axis_x, float axis_y, float axis_z);

	TAT_DEF quaternion make_quaternion(float angle, float4 axis);

	TAT_DEF quaternion make_quaternion(float w);

	TAT_DEF quaternion make_quaternion_direct(float w, float x, float y, float z);

	TAT_DEF float44 quaternion_as_matrix(const uti::quaternion& q);

	TAT_DEF quaternion quaternion_conjugate(const uti::quaternion& q);

	TAT_DEF float quaternion_modulus(const uti::quaternion& q);

	TAT_DEF quaternion quaternion_inverse(const uti::quaternion& q);

	TAT_DEF quaternion quaternion_combine(const uti::quaternion& a, const uti::quaternion b);
}


text:
package net.apnic.rdapd.rdap;

import com.fasterxml.jackson.annotation.JsonFormat;

import net.apnic.rdapd.history.Revision;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Optional;

/**
 * One RDAP object's history record
 */
public class RdapRecord {
    private final ZonedDateTime applicableFrom;
    private final ZonedDateTime applicableUntil;
    private final RdapObject content;

    public RdapRecord(ZonedDateTime applicableFrom, ZonedDateTime applicableUntil, RdapObject content) {
        this.applicableFrom = applicableFrom;
        this.applicableUntil = applicableUntil;
        this.content = content;
    }

    public RdapRecord(Revision revision) {
        this(revision.getValidFrom().withZoneSameInstant(ZoneOffset.UTC),
                Optional.ofNullable(revision.getValidUntil()).map(
                        d -> d.withZoneSameInstant(ZoneOffset.UTC)
                ).orElse(null), revision.getContents());
    }

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
    public ZonedDateTime getApplicableFrom() {
        return applicableFrom;
    }

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
    public ZonedDateTime getApplicableUntil() {
        return applicableUntil;
    }

    public RdapObject getContent() {
        return content;
    }
}


text:
SCRATCH_DIR="foo"
DATA_DIR="bar"

# try to figure out where we're running from, then delete contents of scratch dir
if [ -d "test/scratch" ]; then
  SCRATCH_DIR="test/scratch/local"
  DATA_DIR="test/data"
elif [ -d "../scratch" ]; then
  SCRATCH_DIR="../scratch/local"
  DATA_DIR="../data"
else
  echo -e "Don't know where test dirs are."
  echo -e "Run from veb dir or test/scripts dir.\n"
  exit 1
fi

FILES=${DATA_DIR}/small-files.txt
DIRS=${DATA_DIR}/small-dirs.txt

echo "Making dirs..."
cat $DIRS | tr "\n" "\0" | xargs -0 -I{} mkdir -p "${SCRATCH_DIR}/{}"
echo "  done."

echo "Making files with random 2MB of content..."
cat $FILES | tr "\n" "\0" | xargs -0 -I{} sh -c 'dd if=/dev/urandom of="$1/$2" bs=1048576 count=2' -- $SCRATCH_DIR {}
echo "  done."


text:
static char applicationHookedKey;
@implementation UIApplication (WhiteList)

#pragma mark -
#pragma mark - Replacement method

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
          sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL whiteListResult = sourceApplicationMatches(sourceApplication);

    if (whiteListResult)
    {
        if ([self respondsToSelector:@selector(application:handleOpenURL:)])
        {
            return [(id)self application:application handleOpenURL:url];
        }
        else
        {
            // What point to return YES here?
            // This method is called if delegate doesn't implement application:openURL:sourceApplication:annotation:
            // And now we also checked that it doesn't implement application:handleOpenURL:
            // So it is actually not handling URL schemes at all!!!
            return NO;
        }
    }

    return NO;
}

- (BOOL)swizzledApplication:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL whiteListResult = sourceApplicationMatches(sourceApplication);

    if (whiteListResult)
    {
        return [(id)self swizzledApplication:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    }

    return NO;
}

#pragma mark -
#pragma mark - Swizzle

- (void)setupURLSchemeFilter
{
    if (![self delegateHooked])
    {
        // Save hooking
        objc_setAssociatedObject(self, &applicationHookedKey, NSStringFromClass([self.delegate class]), OBJC_ASSOCIATION_RETAIN);

        Method original;

        original = class_getInstanceMethod([self.delegate class], @selector(application:openURL:sourceApplication:annotation:));

        SEL addedSelector = @selector(swizzledApplication:openURL:sourceApplication:annotation:);

        if (original)
        {
            class_addMethod([self.delegate class], addedSelector, [self methodForSelector:addedSelector], method_getTypeEncoding(original));

            Method swizzle = class_getInstanceMethod([self.delegate class], addedSelector);
            method_exchangeImplementations(original, swizzle);
        }
        else
        {
            addedSelector = @selector(application:openURL:sourceApplication:annotation:);

            Method newMethod = class_getInstanceMethod([self class], addedSelector);

            class_addMethod([self.delegate class], addedSelector,
                            [self methodForSelector:addedSelector], method_getTypeEncoding(newMethod));
        }

    }
}

#pragma mark -
#pragma mark - Hooking setup

- (BOOL)delegateHooked
{
    return !self.delegate || [objc_getAssociatedObject(self, &applicationHookedKey) isEqual:NSStringFromClass([self.delegate class])];
}

@end


text:
namespace device {

namespace {
// The maximum value of the report size for a single item in a HID report is 32
// bits. From the Device Class Definition for HID v1.11, sec. 8.2: "An item
// field cannot span more than 4 bytes in a report. For example, a 32-bit item
// must start on a byte boundary to satisfy this condition."
static constexpr uint32_t kMaxItemReportSizeBits = 32;

// On Windows, HID report length is reported (in bytes) as a USHORT which
// imposes a practical limit of 2^16-1 bytes. Apply the same upper limit when
// computing the maximum report size.
static constexpr uint64_t kMaxReasonableReportLengthBits =
    std::numeric_limits<uint16_t>::max() * 8;

// Limit the maximum depth of the parser when inspecting nested collections.
static constexpr int kMaxReasonableCollectionDepth = 50;
}  // namespace

HidCollection::HidCollection(HidCollection* parent,
                             uint32_t usage_page,
                             uint32_t usage,
                             uint32_t type)
    : parent_(parent), usage_(usage, usage_page), collection_type_(type) {}

HidCollection::~HidCollection() = default;

// static
std::vector<std::unique_ptr<HidCollection>> HidCollection::BuildCollections(
    const std::vector<std::unique_ptr<HidReportDescriptorItem>>& items) {
  std::vector<std::unique_ptr<HidCollection>> collections;
  // This HID report descriptor parser implements a state machine described
  // in the HID specification. See section 6.2.2 Report Descriptor.
  HidItemStateTable state;
  int depth = 0;
  for (const auto& current_item : items) {
    switch (current_item->tag()) {
      case HidReportDescriptorItem::kTagCollection:
        // Add a new collection. Collections at the top-most level describe
        // separate components of the device and are often treated as separate
        // devices. Nested components represent logical collections of fields
        // within a report.
        ++depth;
        if (depth <= kMaxReasonableCollectionDepth)
          AddCollection(*current_item, collections, state);
        state.local.Reset();
        break;
      case HidReportDescriptorItem::kTagEndCollection:
        if (depth <= kMaxReasonableCollectionDepth) {
          // Mark the end of the current collection. Subsequent items describe
          // reports associated with the parent collection.
          if (state.collection)
            state.collection = state.collection->parent_;
        }
        state.local.Reset();
        if (depth > 0)
          --depth;
        break;
      case HidReportDescriptorItem::kTagInput:
      case HidReportDescriptorItem::kTagOutput:
      case HidReportDescriptorItem::kTagFeature:
        // Add a report item to an input, output, or feature report within the
        // current collection. The properties of the report item are determined
        // by the current descriptor item and the current item state table.
        // Changes to input, output, and feature reports are propagated to all
        // ancestor collections.
        if (state.collection) {
          auto* collection = state.collection.get();
          while (collection) {
            collection->AddReportItem(current_item->tag(),
                                      current_item->GetShortData(), state);
            collection = collection->parent_;
          }
        }
        state.local.Reset();
        break;
      case HidReportDescriptorItem::kTagPush:
        // Push a copy of the current global state onto the stack. If there is
        // no global state, the push has no effect and is ignored.
        if (!state.global_stack.empty())
          state.global_stack.push_back(state.global_stack.back());
        break;
      case HidReportDescriptorItem::kTagPop:
        // Pop the top item of the global state stack, returning to the
        // previously pushed state. If there is no such item, the pop has no
        // effect and is ignored.
        if (!state.global_stack.empty())
          state.global_stack.pop_back();
        break;
      case HidReportDescriptorItem::kTagReportId:
        // Update the current report ID. The report ID is global, but is not
        // affected by push and pop. Changes to the report ID are propagated to
        // all ancestor collections.
        if (state.collection) {
          state.report_id = current_item->GetShortData();
          auto* collection = state.collection.get();
          while (collection) {
            collection->report_ids_.push_back(state.report_id);
            collection = collection->parent_;
          }
        }
        break;
      case HidReportDescriptorItem::kTagUsagePage:
      case HidReportDescriptorItem::kTagLogicalMinimum:
      case HidReportDescriptorItem::kTagLogicalMaximum:
      case HidReportDescriptorItem::kTagPhysicalMinimum:
      case HidReportDescriptorItem::kTagPhysicalMaximum:
      case HidReportDescriptorItem::kTagUnitExponent:
      case HidReportDescriptorItem::kTagUnit:
      case HidReportDescriptorItem::kTagReportSize:
      case HidReportDescriptorItem::kTagReportCount:
      case HidReportDescriptorItem::kTagUsage:
      case HidReportDescriptorItem::kTagUsageMinimum:
      case HidReportDescriptorItem::kTagUsageMaximum:
      case HidReportDescriptorItem::kTagDesignatorIndex:
      case HidReportDescriptorItem::kTagDesignatorMinimum:
      case HidReportDescriptorItem::kTagDesignatorMaximum:
      case HidReportDescriptorItem::kTagStringIndex:
      case HidReportDescriptorItem::kTagStringMinimum:
      case HidReportDescriptorItem::kTagStringMaximum:
      case HidReportDescriptorItem::kTagDelimiter:
        // Update the value associated with a local or global item in the item
        // state table.
        state.SetItemValue(current_item->tag(), current_item->GetShortData(),
                           current_item->payload_size());
        break;
      default:
        break;
    }
  }
  return collections;
}

// static
void HidCollection::AddCollection(
    const HidReportDescriptorItem& item,
    std::vector<std::unique_ptr<HidCollection>>& collections,
    HidItemStateTable& state) {
  // Extract |usage| and |usage_page| from the current state. The usage page may
  // be set either by a global usage page, or in the high-order bytes of a local
  // usage value. When both are provided, the local usage value takes
  // precedence.
  uint32_t usage = state.local.usages.empty() ? 0 : state.local.usages.front();
  uint32_t usage_page = (usage >> 16) & 0xffff;
  if (usage_page == 0 && !state.global_stack.empty())
    usage_page = state.global_stack.back().usage_page;
  // Create the new collection. If it is a child of another collection, append
  // it to that collection's list of children. Otherwise, append it to the list
  // of top-level collections in |collections|.
  uint32_t collection_type = item.GetShortData();
  auto collection = std::make_unique<HidCollection>(
      state.collection, usage_page, usage, collection_type);
  if (state.collection) {
    state.collection->children_.push_back(std::move(collection));
    state.collection = state.collection->children_.back().get();
  } else {
    collections.push_back(std::move(collection));
    state.collection = collections.back().get();
  }
}

void HidCollection::AddChildForTesting(
    std::unique_ptr<HidCollection> collection) {
  children_.push_back(std::move(collection));
}

void HidCollection::AddReportItem(HidReportDescriptorItem::Tag tag,
                                  uint32_t report_info,
                                  const HidItemStateTable& state) {
  // Get the correct report map for the current report item (input, output,
  // or feature). The new item will be appended to a report in this report map.
  std::unordered_map<uint8_t, HidReport>* reports = nullptr;
  if (tag == HidReportDescriptorItem::kTagInput)
    reports = &input_reports_;
  else if (tag == HidReportDescriptorItem::kTagOutput)
    reports = &output_reports_;
  else if (tag == HidReportDescriptorItem::kTagFeature)
    reports = &feature_reports_;
  else
    return;
  // Fetch the report with the |report_id| matching this item, or insert a new
  // report into the map if it does not yet exist.
  HidReport* report = nullptr;
  auto find_it = reports->find(state.report_id);
  if (find_it == reports->end()) {
    auto emplace_result = reports->emplace(state.report_id, HidReport());
    report = &emplace_result.first->second;
  } else {
    report = &find_it->second;
  }
  // Create the report item and append it to the report.
  report->push_back(HidReportItem::Create(tag, report_info, state));
}

void HidCollection::GetMaxReportSizes(size_t* max_input_report_bits,
                                      size_t* max_output_report_bits,
                                      size_t* max_feature_report_bits) const {
  DCHECK(max_input_report_bits);
  DCHECK(max_output_report_bits);
  DCHECK(max_feature_report_bits);
  struct {
    const std::unordered_map<uint8_t, HidReport>& reports;
    size_t& max_report_bits;
  } report_lists[]{
      {input_reports_, *max_input_report_bits},
      {output_reports_, *max_output_report_bits},
      {feature_reports_, *max_feature_report_bits},
  };
  auto collection_info = mojom::HidCollectionInfo::New();
  collection_info->usage =
      mojom::HidUsageAndPage::New(usage_.usage, usage_.usage_page);
  collection_info->report_ids.insert(collection_info->report_ids.end(),
                                     report_ids_.begin(), report_ids_.end());
  for (const auto& entry : report_lists) {
    entry.max_report_bits = 0;
    for (const auto& report : entry.reports) {
      uint64_t report_bits = 0;
      for (const auto& item : report.second) {
        uint64_t report_size = item->GetReportSize();
        // Report size can be at most 32 bits, but some devices specify larger
        // sizes. Warn if the size is too large, but still allow the report to
        // affect the maximum report size.
        if (report_size > kMaxItemReportSizeBits) {
          LOG(WARNING) << base::StringPrintf(
              "encountered report item with invalid report size (%" PRIu64
              ">%u)",
              report_size, kMaxItemReportSizeBits);
        }
        // Report size and report count are both 32-bit values. A 64-bit integer
        // type is needed to avoid overflow when computing the product.
        uint64_t report_count = item->GetReportCount();
        uint64_t item_bits = report_size * report_count;
        // Ignore this report if adding the size of this item would extend the
        // total report length beyond the reasonable maximum.
        if (item_bits > kMaxReasonableReportLengthBits ||
            report_bits > kMaxReasonableReportLengthBits - item_bits) {
          report_bits = 0;
          break;
        }
        report_bits += item_bits;
      }
      DCHECK_LE(report_bits, kMaxReasonableReportLengthBits);
      entry.max_report_bits =
          std::max(entry.max_report_bits, static_cast<size_t>(report_bits));
    }
  }
}

mojom::HidCollectionInfoPtr HidCollection::ToMojo() const {
  auto collection = mojom::HidCollectionInfo::New();
  struct {
    const std::unordered_map<uint8_t, HidReport>& in;
    std::vector<mojom::HidReportDescriptionPtr>& out;
  } report_lists[]{
      {input_reports_, collection->input_reports},
      {output_reports_, collection->output_reports},
      {feature_reports_, collection->feature_reports},
  };

  collection->usage =
      mojom::HidUsageAndPage::New(usage_.usage, usage_.usage_page);
  collection->report_ids.insert(collection->report_ids.end(),
                                report_ids_.begin(), report_ids_.end());
  collection->collection_type = collection_type_;

  for (const auto& report_list : report_lists) {
    for (const auto& report : report_list.in) {
      auto report_description = mojom::HidReportDescription::New();
      report_description->report_id = report.first;
      for (const auto& item : report.second)
        report_description->items.push_back(item->ToMojo());
      report_list.out.push_back(std::move(report_description));
    }
  }

  for (const auto& child : children_)
    collection->children.push_back(child->ToMojo());

  return collection;
}

}  // namespace device


text:
/**
 * Attaches event handlers for IE8, stops event propagation and prevents default event behavior.
 * @param {object} el The element to which the event will be attached.
 * @param {object} eventName The event to be attached.
 * @param {function} handler The handler to be invoked when the event occurs.
 */
function addEventListener(el, eventName, handler) {
  eventName.preventDefault ? eventName.preventDefault() :
    (eventName.returnValue = false);
  eventName.stopPropagation ? eventName.stopPropagation() :
    (eventName.cancelBubble = true);
  if (el.addEventListener) {
    el.addEventListener(eventName, handler);
  } else {
    el.attachEvent('on' + eventName, function() {
      handler.call(el);
    });
  }
}

/** Attaches event listeners to toggle dropdown menu elements */
function attachToggles() {
  var clickPairs = [['.category-option', toggleCategoryOption]];
  var keydownPairs = [['.search-filter-container', searchNav],
  ['.search-filters', searchNav],
  ['.category-option', searchNav],
  ['.user-menu', userNav],
  ['.user-menu-item', userNav]];
  for (var i = 0; i < clickPairs.length; i++) {
    var trigger = document.querySelectorAll(clickPairs[i][0]);
    for (var j = 0; j < trigger.length; j++) {
      addEventListener(trigger[j], 'click', clickPairs[i][1]);
    }
  }
  for (var k = 0; k < keydownPairs.length; k++) {
    var trigger = document.querySelectorAll(keydownPairs[k][0]);
    for (var l = 0; l < trigger.length; l++) {
      addEventListener(trigger[l], 'keydown', keydownPairs[k][1]);
    }
  }
}

function attachSearchListeners() {
  var searchClickTrigger = document.getElementById('search-submit-button');
  var searchEnterTrigger = document.getElementById('query_field');
  addEventListener(searchClickTrigger, 'click', fetchSearchResults);
  addEventListener(searchEnterTrigger, 'keypress', fetchSearchResults);
}

/**
 * Listens for document ready (i.e. readyState not loading), and invokes callback.
 * @param {function} fn The function to be invoked once ready detected.
 */
function ready(fn) {
  if (document.readyState != 'loading') {
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading') {
        fn();
      }
    });
  }
}

/** Calls attachToggles once ready is detected */
ready(attachToggles);
// will uncomment this out when we refactor to single page search
// ready(attachSearchListeners);


text:
from django.contrib import messages
from django.shortcuts import render, redirect
from django.utils.translation import ugettext as _
from django.views.generic import ListView
from django.contrib.auth.views import redirect_to_login
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.shortcuts import resolve_url

try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

from .tasks import judge_code_submission
from .forms import CodeSubmissionForm
from .models import CodingProblem, CodeSubmission

class CodingProblemListView(ListView):
    model = CodingProblem

    def get_queryset(self):
        return CodingProblem.objects.filter(public=True)

def coding_problem(request, slug):
    problem = CodingProblem.objects.get(slug=slug)
    user = request.user

    if request.method == 'POST':
        if not user.is_authenticated:
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(settings.LOGIN_URL)
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            return redirect_to_login(path,
                                     resolved_login_url,
                                     REDIRECT_FIELD_NAME)

        submission = CodeSubmission(
            problem=problem,
            user=user)
        submission_form = CodeSubmissionForm(request.POST, instance=submission)
        if submission_form.is_valid():
            submission_form.save()

            # send task
            judge_code_submission.delay(submission.id)

            # keep only the top 10 submissions
            for n, s in enumerate(CodeSubmission.objects.filter(user=user, problem=problem).order_by("submission_time").reverse()):
                if n >= 10:
                    s.delete()

            messages.success(request,
                             _('Your code was successfully submitted'))
            return redirect('coding-problem-detail', slug)
        else:
            messages.error(request,
                           _('Please correct the error below.'))
    else:
        submission_form = CodeSubmissionForm()

        if user.is_authenticated:
            submissions = problem.user_submissions(user)
            try:
                latest_submission = submissions.earliest()
                submission_form.initial["language"] = latest_submission.language
                submission_form.initial["code"] = latest_submission.code
            except CodeSubmission.DoesNotExist:
                pass
        else:
            submissions = []

        return render(request, 'candidates/codingproblem_detail.html', {
            'problem': problem,
            'submission_form': submission_form,
            'examples': problem.examples,
            'submissions': submissions
        })


text:
<?php

namespace tests\TransactPRO\Gate\Request;

use TransactPRO\Gate\Request\RequestExecutorInterface;
use TransactPRO\Gate\Response\Response;

class BasicRequestExecutor implements RequestExecutorInterface
{
    /** @var string */
    private $url;
    /** @var bool */
    private $verifySSL;

    /**
     * @param string $url Gateway url
     * @param bool $verifySSL
     */
    public function __construct($url, $verifySSL)
    {
        $this->url       = $url;
        $this->verifySSL = $verifySSL;
    }

    /**
     * @param string $action Action to execute
     * @param array $postData Data for sending
     * @return Response
     */
    public function executeRequest($action, array $postData)
    {
        return new Response(Response::STATUS_ERROR, 'NotImplemented');
    }

}


text:
<?php

require_once 'Crypt/Hash.php';

abstract class Crypt_Hash_TestCase extends PhpseclibTestCase
{
    static public function setUpBeforeClass()
    {
        if (!defined('CRYPT_HASH_MODE')) {
            define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_INTERNAL);
        }
    }

    public function setUp()
    {
        if (defined('CRYPT_HASH_MODE') && CRYPT_HASH_MODE !== CRYPT_HASH_MODE_INTERNAL) {
            $this->markTestSkipped(
                'Skipping test because CRYPT_HASH_MODE is not defined as CRYPT_HASH_MODE_INTERNAL.'
            );
        }
    }

    protected function assertHashesTo(Crypt_Hash $hash, $message, $expected)
    {
        $this->assertEquals(
            strtolower($expected),
            bin2hex($hash->hash($message)),
            sprintf("Failed asserting that '%s' hashes to '%s'.", $message, $expected)
        );
    }

    protected function assertHMACsTo(Crypt_Hash $hash, $key, $message, $expected)
    {
        $hash->setKey($key);

        $this->assertEquals(
            strtolower($expected),
            bin2hex($hash->hash($message)),
            sprintf(
                "Failed asserting that '%s' HMACs to '%s' with key '%s'.",
                $message,
                $expected,
                $key
            )
        );
    }
}


text:
package com.xd.demi.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by demi on 2017/2/13.
 */

public class MyViewPager extends ViewPager {
    private float x = 0,y=0;
    public MyViewPager(Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch(ev.getAction()){
            case MotionEvent.ACTION_DOWN :
                x=ev.getX();
                y=ev.getY();
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                if(Math.abs(ev.getX()-x)>Math.abs(ev.getY()-y)){
                    getParent().requestDisallowInterceptTouchEvent(true);
                }else {
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                    break;
        }

        return super.onTouchEvent(ev);
    }
}


text:
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/jce.jar
#include <javax/crypto/Mac.hpp>

extern void unimplemented_(const char16_t* name);
javax::crypto::Mac::Mac(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

javax::crypto::Mac::Mac(MacSpi* arg0, ::java::security::Provider* arg1, ::java::lang::String* arg2)
    : Mac(*static_cast< ::default_init_tag* >(0))
{
    ctor(arg0, arg1, arg2);
}

sun::security::util::Debug*& javax::crypto::Mac::debug()
{
    clinit();
    return debug_;
}
sun::security::util::Debug* javax::crypto::Mac::debug_;
sun::security::util::Debug*& javax::crypto::Mac::pdebug()
{
    clinit();
    return pdebug_;
}
sun::security::util::Debug* javax::crypto::Mac::pdebug_;
bool& javax::crypto::Mac::skipDebug()
{
    clinit();
    return skipDebug_;
}
bool javax::crypto::Mac::skipDebug_;
int32_t& javax::crypto::Mac::warnCount()
{
    clinit();
    return warnCount_;
}
int32_t javax::crypto::Mac::warnCount_;

void ::javax::crypto::Mac::ctor(MacSpi* arg0, ::java::security::Provider* arg1, ::java::lang::String* arg2)
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::javax::crypto::Mac::ctor(MacSpi* arg0, ::java::security::Provider* arg1, ::java::lang::String* arg2)");
}

/* private: void ::javax::crypto::Mac::ctor(::java::security::Provider_Service* arg0, ::java::util::Iterator* arg1, ::java::lang::String* arg2) */
void javax::crypto::Mac::chooseFirstProvider()
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::chooseFirstProvider()");
}

/* private: void javax::crypto::Mac::chooseProvider(::java::security::Key* arg0, ::java::security::spec::AlgorithmParameterSpec* arg1) */
java::lang::Object* javax::crypto::Mac::clone()
{ /* stub */
    unimplemented_(u"java::lang::Object* javax::crypto::Mac::clone()");
    return 0;
}

int8_tArray* javax::crypto::Mac::doFinal()
{ /* stub */
    unimplemented_(u"int8_tArray* javax::crypto::Mac::doFinal()");
    return 0;
}

int8_tArray* javax::crypto::Mac::doFinal(::int8_tArray* arg0)
{ /* stub */
    unimplemented_(u"int8_tArray* javax::crypto::Mac::doFinal(::int8_tArray* arg0)");
    return 0;
}

void javax::crypto::Mac::doFinal(::int8_tArray* arg0, int32_t arg1)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::doFinal(::int8_tArray* arg0, int32_t arg1)");
}

java::lang::String* javax::crypto::Mac::getAlgorithm()
{ /* stub */
return algorithm ; /* getter */
}

javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0)
{ /* stub */
    clinit();
    unimplemented_(u"javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0)");
    return 0;
}

javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0, ::java::lang::String* arg1)
{ /* stub */
    clinit();
    unimplemented_(u"javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0, ::java::lang::String* arg1)");
    return 0;
}

javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0, ::java::security::Provider* arg1)
{ /* stub */
    clinit();
    unimplemented_(u"javax::crypto::Mac* javax::crypto::Mac::getInstance(::java::lang::String* arg0, ::java::security::Provider* arg1)");
    return 0;
}

int32_t javax::crypto::Mac::getMacLength()
{ /* stub */
    unimplemented_(u"int32_t javax::crypto::Mac::getMacLength()");
    return 0;
}

java::security::Provider* javax::crypto::Mac::getProvider()
{ /* stub */
return provider ; /* getter */
}

void javax::crypto::Mac::init_(::java::security::Key* arg0)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::init_(::java::security::Key* arg0)");
}

void javax::crypto::Mac::init_(::java::security::Key* arg0, ::java::security::spec::AlgorithmParameterSpec* arg1)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::init_(::java::security::Key* arg0, ::java::security::spec::AlgorithmParameterSpec* arg1)");
}

void javax::crypto::Mac::reset()
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::reset()");
}

void javax::crypto::Mac::update(int8_t arg0)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::update(int8_t arg0)");
}

void javax::crypto::Mac::update(::int8_tArray* arg0)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::update(::int8_tArray* arg0)");
}

void javax::crypto::Mac::update(::java::nio::ByteBuffer* arg0)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::update(::java::nio::ByteBuffer* arg0)");
}

void javax::crypto::Mac::update(::int8_tArray* arg0, int32_t arg1, int32_t arg2)
{ /* stub */
    unimplemented_(u"void javax::crypto::Mac::update(::int8_tArray* arg0, int32_t arg1, int32_t arg2)");
}

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

java::lang::Class* javax::crypto::Mac::class_()
{
    static ::java::lang::Class* c = ::class_(u"javax.crypto.Mac", 16);
    return c;
}

java::lang::Class* javax::crypto::Mac::getClass0()
{
    return class_();
}


text:
local function FillMenu(menu, SpawnName, GroupName)
    menu:AddOption("unrestrict", function() RunConsoleCommand("_FAdmin", "UnRestrictWeapon", SpawnName) end)

    menu:AddSpacer("")
    for k,v in SortedPairsByMemberValue(FAdmin.Access.Groups, "ADMIN", true) do
        menu:AddOption(k, function() RunConsoleCommand("_FAdmin", "RestrictWeapon", SpawnName, k) end)
    end
end

local function RestrictWeaponMenu()
    local frame = vgui.Create("DFrame")
    frame:SetTitle("Restrict weapons")
    frame:SetSize(ScrW() / 2, ScrH() - 50)
    frame:Center()
    frame:SetVisible(true)
    frame:MakePopup()

    local WeaponMenu = vgui.Create("FAdmin_weaponPanel", frame)
    WeaponMenu.HideAmmo = true
    function WeaponMenu:DoGiveWeapon(SpawnName)
        local menu = DermaMenu()
        menu:SetPos(gui.MouseX(), gui.MouseY())
        FillMenu(menu, SpawnName)
        menu:Open()
    end
    WeaponMenu:BuildList()
    WeaponMenu:StretchToParent(0,25,0,0)
end

FAdmin.StartHooks["Restrict"] = function()
    FAdmin.Access.AddPrivilege("Restrict", 3)
    FAdmin.ScoreBoard.Server:AddPlayerAction("Restrict weapons", "fadmin/icons/weapon", Color(0, 155, 0, 255), true, RestrictWeaponMenu)
end


text:
"use strict";
const config_1 = require('../models/config');
const SilentError = require('silent-error');
const Command = require('../ember-cli/lib/models/command');
const SetCommand = Command.extend({
    name: 'set',
    description: 'Set a value in the configuration.',
    works: 'everywhere',
    availableOptions: [
        { name: 'global', type: Boolean, 'default': false, aliases: ['g'] },
    ],
    asBoolean: function (raw) {
        if (raw == 'true' || raw == '1') {
            return true;
        }
        else if (raw == 'false' || raw == '' || raw == '0') {
            return false;
        }
        else {
            throw new SilentError(`Invalid boolean value: "${raw}"`);
        }
    },
    asNumber: function (raw) {
        if (Number.isNaN(+raw)) {
            throw new SilentError(`Invalid number value: "${raw}"`);
        }
        return +raw;
    },
    run: function (commandOptions, rawArgs) {
        return new Promise(resolve => {
            const config = commandOptions.global ? config_1.CliConfig.fromGlobal() : config_1.CliConfig.fromProject();
            if (config === null) {
                throw new SilentError('No config found. If you want to use global configuration, '
                    + 'you need the --global argument.');
            }
            let [jsonPath, rawValue] = rawArgs;
            if (rawValue === undefined) {
                [jsonPath, rawValue] = jsonPath.split('=', 2);
                if (rawValue === undefined) {
                    throw new SilentError('Must specify a value.');
                }
            }
            const type = config.typeOf(jsonPath);
            let value = rawValue;
            switch (type) {
                case 'boolean':
                    value = this.asBoolean(rawValue);
                    break;
                case 'number':
                    value = this.asNumber(rawValue);
                    break;
                case 'string':
                    value = rawValue;
                    break;
                default: value = JSON.parse(rawValue);
            }
            config.set(jsonPath, value);
            config.save();
            resolve();
        });
    }
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = SetCommand;
//# sourceMappingURL=/Users/hansl/Sources/angular-cli/packages/@angular/cli/commands/set.js.map


text:
using EndGate.Server;

namespace EndGate.Server.BoundingObject
{
    /// <summary>
    /// Abstract bounds type that is used to detect intersections.
    /// </summary>
    public abstract class Bounds2d
    {
        /// <summary>
        /// Initiates a bounded object with an initial position of (0, 0).
        /// </summary>
        public Bounds2d() : this(Vector2d.Zero)
        {
        }

        /// <summary>
        /// Initiates a bounded object.
        /// </summary>
        /// <param name="position">The initial position of the bounds2d</param>
        public Bounds2d(Vector2d position)
        {
            Position = position;
            Rotation = 0;
        }

        /// <summary>
        /// Gets or sets the Position of the bounds.
        /// </summary>
        public Vector2d Position { get; set; }
        /// <summary>
        /// Gets or sets the Rotation of the bounds.
        /// </summary>
        public double Rotation { get; set; }

        /// <summary>
        /// Scales the size of the bounded object.
        /// </summary>
        /// <param name="x">Value to multiply the horizontal component by.</param>
        /// <param name="y">Value to multiply the vertical component by.</param>
        public abstract void Scale(double x, double y);

        /// <summary>
        /// Determines if the current bounded object contains the provided Vector2d.
        /// </summary>
        /// <param name="point">A point to check containment on.</param>
        /// <returns>Whether the bounds contains the point.</returns>
        public abstract bool Contains(Vector2d point);
        /// <summary>
        /// Determines if the current bounded object completely contains another bounded object.
        /// </summary>
        /// <param name="obj">A bounded object to check containment on.</param>
        /// <returns>Whether the bounds contains the object.</returns>
        public abstract bool Contains(Bounds2d obj);
        /// <summary>
        /// Determines if the current bounded object completely contains the provided BoundingCircle.
        /// </summary>
        /// <param name="circle">A circle to check containment on.</param>
        /// <returns>Whether the bounds contains the circle.</returns>
        public abstract bool Contains(BoundingCircle circle);
        /// <summary>
        /// Determines if the current bounded object completely contains the provided BoundingRectangle.
        /// </summary>
        /// <param name="rectangle">A rectangle to check containment on.</param>
        /// <returns>Whether the bounds contains the rectangle.</returns>
        public abstract bool Contains(BoundingRectangle rectangle);

        /// <summary>
        /// Determines if the current bounded object intersects another bounded object.
        /// </summary>
        /// <param name="obj">Bounding object to check collision with.</param>
        /// <returns>Whether the bounds intersects the object.</returns>
        public abstract bool Intersects(Bounds2d obj);
        /// <summary>
        /// Determines if the current bounded object is intersecting the provided BoundingCircle.
        /// </summary>
        /// <param name="circle">BoundingCircle to check intersection with.</param>
        /// <returns>Whether the bounds intersects the BoundingCircle.</returns>
        public abstract bool Intersects(BoundingCircle circle);
        /// <summary>
        /// Determines if the current bounded object is intersecting the provided BoundingRectangle.
        /// </summary>
        /// <param name="rectangle">BoundingRectangle to check intersection with.</param>
        /// <returns>Whether the bounds intersects the BoundingRectangle.</returns>
        public abstract bool Intersects(BoundingRectangle rectangle);
    }
}


text:
<?php
return array (
  'Archive' => 'Arkiv',
  'Choose if new content should be public or private by default' => 'Vælg om nyt indhold som standard skal være offentlig eller privat',
  'Choose the kind of membership you want to provide for this workspace.' => 'Vælg den type af medlemskab som du vil give til dette workspace.',
  'Choose the security level for this workspace to define the visibleness.' => 'Vælg sikkerhedsgraden for dette workspace for at definere synlighed.',
  'Delete' => 'Slet',
  'Save' => 'Gem',
  'Unarchive' => 'U-arkivér',
);


text:
{% extends "api/api_base.html" %}

{% block content %}

High School Dropouts by Race

URL Format: http://data.nationalpriorities.org/api/dropouts_race/list.<format>?...

Allowed Keys: 'state', 'year', 'key'

Example: http://data.nationalpriorities.org/api/dropouts_race/list.json?state=OH&year=2006

{% endblock %}


text:
<?php

namespace AppBundle\Service;

use AppBundle\Entity\Format;
use AppBundle\Formatting\BoldFormatStrategy;
use AppBundle\Formatting\FormatStrategy;
use AppBundle\Formatting\FormatStrategyFactory;
use AppBundle\Formatting\ItalicFormatStrategy;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Stopwatch\Stopwatch;
use function mb_substr;

/**
 * Description of FormatService
 *
 * @author Draeius
 */
class FormatService {

    const USE_CACHE = false;

    /**
     *
     * @var FormatStrategy[]
     */
    private $pendingStrategies;
    private $cache;

    /**
     *
     * @var EntityManager
     */
    private $entityManager;

    /**
     *
     * @var Stopwatch
     */
    private $stopwatch;
    private static $formats = [];

    public function __construct($cache, $em, $stopwatch) {
        $this->pendingStrategies = array();
        $this->cache = $cache;
        $this->entityManager = $em;
        $this->stopwatch = $stopwatch;
    }

    public function parse(string $text, bool $allowedOnly = false): string {
        if ($text == '') {
            return $text;
        }

        $this->stopwatch->start('formatting');

        $key = md5($text . $allowedOnly); //allowed mit in den key, da es 2 Varianten geben kann. Mit und ohne allowed Tags

        if ($this->cache->contains($key) && self::USE_CACHE) {
            $result = $this->cache->fetch($key); // ist schon im Cache
        } else {
            //noch nicht im Cache
            $array = preg_split('/(?=`[^`])/', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

            $result = $this->formatArray($array, $allowedOnly); //verarbeiten
            $this->cache->save($key, $result); //in den Cache packen
        }
        $this->stopwatch->stop('formatting');
        return $result;
    }

    private function formatArray(array $array, bool $allowedOnly): string {
        $count = count($array);
        $factory = new FormatStrategyFactory($this->entityManager);

        for ($index = 0; $index < $count; $index++) {
            $text = $array[$index] != null ? $array[$index] : '';

            $strategy = $factory->getStrategyForText($text, $allowedOnly);

            $lastStrategy = array_pop($this->pendingStrategies);
            if ($lastStrategy == null || $lastStrategy->openAfterStrategy($strategy)) {
                $array[$index] = $strategy->start($text);
            }

            if ($lastStrategy != null && $lastStrategy->closeForStrategy($strategy)) {
                $array[$index] = $lastStrategy->end($array[$index]);
            } else {
                array_push($this->pendingStrategies, $lastStrategy);
            }

            if ($strategy->needsClosing()) {
                array_push($this->pendingStrategies, $strategy);
            }
        }

        $this->closeAll($array);

        return implode('', $array);
//        for ($index = 0; $index < $count; $index++) {
//            $this->formatPart($array[$index], $allowedOnly);
//        }
//        $this->closeAll($array);
//        return implode('', $array);
    }

    private function formatPart(string &$text, bool $allowedOnly) {
        if (mb_substr($text, 0, 1) != '`') {
            return;
        }

        $format = $this->getFormat(mb_substr($text, 1, 1));

        if (!$format->getId()) {
            return; //format existiert nicht
        }

        if ($allowedOnly && !$format->getIsAllowed()) {
            return; //format ist nicht erlaubt
        }

        if ($format->getColor()) {
            $this->formatColor($format, $text);
            return;
        }
        $this->formatStyle($format, $text);
    }

    private function formatColor(Format &$format, string &$text) {
        /* @var $lastFormat Format */
        $lastFormat = array_pop($this->pendingStrategies);

        if ($lastFormat && $lastFormat->getColor()) {
            array_pop($this->pendingStrategies);
            $this->addToArray($format);
            $text = '</' . $lastFormat->getTag() . '>' . $this->printFormat($format) . substr($text, strlen($format->getCode()) + 1);
            return;
        } else {
            if ($lastFormat) {
                array_push($this->pendingStrategies, $lastFormat);
            }
            array_push($this->pendingStrategies, $format);
            $text = $this->printFormat($format) . substr($text, strlen($format->getCode()) + 1);
            return;
        }
    }

    private function formatStyle(Format &$format, string &$text) {
        if (!in_array($format, $this->pendingStrategies)) {
            $this->addToArray($format);
            $text = $this->printFormat($format) . substr($text, strlen($format->getCode()) + 1);
            return;
        }

        $text = substr($text, strlen($format->getCode()) + 1);
        do {
            /* @var $lastFormat Format */
            $lastFormat = array_pop($this->pendingStrategies);
            if ($lastFormat) {
                $text = '</' . $lastFormat->getTag() . '>' . $text;
            }
        } while ($lastFormat != $format);
    }

    private function closeAll(array &$array) {
        $text = '';
        while ($strategy = array_pop($this->pendingStrategies)) {
            $text = $strategy->end($text);
        }
        array_push($array, $text);
    }

    private function printFormat(Format $format) {
        $result = '<' . ($format->getTag() ? $format->getTag() : 'span');

        if ($format->getStyle()) {
            $result .= ' class="' . $format->getStyle() . '"';
        }

        if ($format->getColor()) {
            $result .= ' style="color: #' . $format->getColor() . ';"';
        }

        return $result . '>';
    }

    private function getFormat(string $code): Format {
        if (array_key_exists($code, self::$formats)) {
            return self::$formats[$code];
        }
        $format = $this->entityManager->getRepository('AppBundle:Format')
                ->findByCode($code);

        if (!$format) {
            $format = new Format();
        }
        self::$formats[$code] = $format;
        return $format;
    }

    private function addToArray(Format $format) {
        if (!$format) {
            return;
        }
        if (!$format->getId()) {
            return;
        }
        if ($format->getTag() == "br") {
            return;
        }
        array_push($this->pendingStrategies, $format);
    }

}


text:
using System;
public class Ex1{
	public static void Line()
		{
			int x = Convert.ToInt32(Console.ReadLine());
			for(int i = 0; i < x; i++)
				Console.WriteLine("-------------------------------------");
		}

	static void Main(string [] args)
	{
		Console.Write("Number? ");
		Line();
		Console.Write("Another Number? ");
		Line();
		Console.WriteLine("End");
	}
}


text:
cask 'devonthink-pro-office' do
  version '2.9.14'
  sha256 'fd425a5beb6e179bac7f61ad1b0564de358991a7d571d64a989e26e7b52b06e1'

  # amazonaws.com/DTWebsiteSupport was verified as official when first introduced to the cask
  url "https://s3.amazonaws.com/DTWebsiteSupport/download/devonthink/#{version}/DEVONthink_Pro_Office.app.zip"
  appcast 'http://www.devon-technologies.com/fileadmin/templates/filemaker/sparkle.php?product=300125739&format=xml',
          checkpoint: '7f6d6c712da496696fbac9e0fc2dcc210e0b45134b1bd69c3ce107ae2b1ab786'
  name 'DEVONthink Pro Office'
  homepage 'https://www.devontechnologies.com/products/devonthink/devonthink-pro-office.html'

  depends_on macos: '>= :mountain_lion'

  # Renamed for consistency: app name is different in the Finder and in a shell.
  # Original discussion: https://github.com/caskroom/homebrew-cask/pull/3838
  app 'DEVONthink Pro.app', target: 'DEVONthink Pro Office.app'
end


text:
/*
  Rejected in glibc (http://sourceware.org/ml/libc-alpha/2006-03/msg00125.html)
*/

#include <errno.h>
#include <string.h>
#include <stdlib.h>

#ifdef HAVE___PROGNAME
extern const char *__progname;
#else
static const char *__progname = NULL;
#endif

const char *
getprogname(void)
{
#if defined(HAVE_PROGRAM_INVOCATION_SHORT_NAME)
	if (__progname == NULL)
		__progname = program_invocation_short_name;
#elif defined(HAVE_GETEXECNAME)
	/* getexecname(3) returns an absolute pathname, normalize it. */
	if (__progname == NULL)
		setprogname(getexecname());
#endif

	return __progname;
}

void
setprogname(const char *progname)
{
	const char *last_slash;

	last_slash = strrchr(progname, '/');
	if (last_slash == NULL)
		__progname = progname;
	else
		__progname = last_slash + 1;
}


text:
package sample.maps;

import com.google.gdata.client.*;
import com.google.gdata.client.maps.*;
import com.google.gdata.data.*;
import com.google.gdata.data.maps.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.URL;

public class DeleteFeature {

  public static void main(String[] args) {
    MapsService myService = new MapsService("deleteFeature");
    try {
     // Replace username and password with your authentication credentials
      myService.setUserCredentials("username","password");
      deleteFeature(myService);
    } catch(AuthenticationException e) {
      System.out.println("Authentication Exception");
    } catch(ServiceException e) {
      System.out.println("Service Exception: " + e.getMessage());
    } catch(IOException e) {
      System.out.println("I/O Exception");
    }
  }

  public static void deleteFeature(MapsService myService)
    throws ServiceException, IOException {

    // Request the default metafeed
	// Replace userID, mapID and featureID with appropriate values for your map
    final URL editFeatureUrl = new URL("http://maps.google.com/maps/feeds/features/userID/mapID/full/featureID");

    myService.delete(editFeatureUrl);
  }
}


text:
.class final Lnet/clickdev/music/MusicPlaybackService$Shuffler;
.super Ljava/lang/Object;
.source "MusicPlaybackService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lnet/clickdev/music/MusicPlaybackService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x1a
    name = "Shuffler"
.end annotation

# instance fields
.field private final mHistoryOfNumbers:Ljava/util/LinkedList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/LinkedList",
            "<",
            "Ljava/lang/Integer;",
            ">;"
        }
    .end annotation
.end field

.field private mPrevious:I

.field private final mPreviousNumbers:Ljava/util/TreeSet;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/TreeSet",
            "<",
            "Ljava/lang/Integer;",
            ">;"
        }
    .end annotation
.end field

.field private final mRandom:Ljava/util/Random;

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 2992
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 2980
    new-instance v0, Ljava/util/LinkedList;

    invoke-direct {v0}, Ljava/util/LinkedList;-><init>()V

    iput-object v0, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mHistoryOfNumbers:Ljava/util/LinkedList;

    .line 2982
    new-instance v0, Ljava/util/TreeSet;

    invoke-direct {v0}, Ljava/util/TreeSet;-><init>()V

    iput-object v0, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPreviousNumbers:Ljava/util/TreeSet;

    .line 2984
    new-instance v0, Ljava/util/Random;

    invoke-direct {v0}, Ljava/util/Random;-><init>()V

    iput-object v0, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mRandom:Ljava/util/Random;

    .line 2993
    return-void
.end method

.method private cleanUpHistory()V
    .locals 3

    .prologue
    .line 3017
    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mHistoryOfNumbers:Ljava/util/LinkedList;

    invoke-virtual {v1}, Ljava/util/LinkedList;->isEmpty()Z

    move-result v1

    if-nez v1, :cond_0

    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mHistoryOfNumbers:Ljava/util/LinkedList;

    invoke-virtual {v1}, Ljava/util/LinkedList;->size()I

    move-result v1

    const/16 v2, 0x3e8

    if-lt v1, v2, :cond_0

    .line 3018
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    const/4 v1, 0x1

    const/16 v2, 0x1f4

    invoke-static {v1, v2}, Ljava/lang/Math;->max(II)I

    move-result v1

    if-ge v0, v1, :cond_0

    .line 3019
    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPreviousNumbers:Ljava/util/TreeSet;

    iget-object v2, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mHistoryOfNumbers:Ljava/util/LinkedList;

    invoke-virtual {v2}, Ljava/util/LinkedList;->removeFirst()Ljava/lang/Object;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/util/TreeSet;->remove(Ljava/lang/Object;)Z

    .line 3018
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 3022
    .end local v0    # "i":I
    :cond_0
    return-void
.end method

# virtual methods
.method public nextInt(I)I
    .locals 3
    .param p1, "interval"    # I

    .prologue
    .line 3002
    :cond_0
    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mRandom:Ljava/util/Random;

    invoke-virtual {v1, p1}, Ljava/util/Random;->nextInt(I)I

    move-result v0

    .line 3004
    .local v0, "next":I
    iget v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPrevious:I

    if-ne v0, v1, :cond_1

    const/4 v1, 0x1

    if-le p1, v1, :cond_1

    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPreviousNumbers:Ljava/util/TreeSet;

    invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/util/TreeSet;->contains(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_0

    .line 3005
    :cond_1
    iput v0, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPrevious:I

    .line 3006
    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mHistoryOfNumbers:Ljava/util/LinkedList;

    iget v2, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPrevious:I

    invoke-static {v2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/util/LinkedList;->add(Ljava/lang/Object;)Z

    .line 3007
    iget-object v1, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPreviousNumbers:Ljava/util/TreeSet;

    iget v2, p0, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->mPrevious:I

    invoke-static {v2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/util/TreeSet;->add(Ljava/lang/Object;)Z

    .line 3008
    invoke-direct {p0}, Lnet/clickdev/music/MusicPlaybackService$Shuffler;->cleanUpHistory()V

    .line 3009
    return v0
.end method


text:
        Min: String=Minimum Length; Number=Minimum Value; Binary=n/a

        Average: String=Average Length; Number=Average Value; Binary=n/a

        Max: String=Maximum Length; Number=Maximum Value; Binary=Length

        Std Dev: String=Of Lengths; Number=Of Values; Binary=n/a


text:
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 642AC823
sudo apt-get update -y
sudo apt-get install -y dirmngr nodejs npm wget python gcc g++ make git

sudo ln -s /usr/bin/nodejs /usr/bin/node
sudo npm install -g grunt grunt-cli bower

# build nvd3
git clone https://github.com/novus/nvd3.git
cd $PWD/nvd3
sudo npm install
grunt production


text:
import argparse
import pandas as pd

def imagecoordinates_flipyaxis(input_file, output_file, image_height, offset=[0,0]):
    df = pd.read_csv(input_file, sep='\t')

    x = df.copy().y # create copy instead of view
    df.y = image_height-(df.x + 1) + offset[1] # since maximal y index = height-1
    df.x = x + offset[0]
    df.to_csv(output_file, sep="\t", index=False)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('input_file', type=argparse.FileType('r'), help='original file')
    parser.add_argument('out_file_str', type=str, help='string of output file name')
    parser.add_argument('image_height', type=int, help='height of image')
    parser.add_argument('offset_x', type=int, help='offset in x direction (width)', default=0)
    parser.add_argument('offset_y', type=int, help='offset in y direction (height)', default=0)
    args = parser.parse_args()
    imagecoordinates_flipyaxis(args.input_file.name, args.out_file_str, args.image_height, [args.offset_x, args.offset_y])
    # imagecoordinates_flipyaxis(args.input_file.name, args.out_file_str, int(args.image_height))


text:
namespace Microsoft.Azure.Management.BotService.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The parameters to provide for the Web Chat channel.
    /// </summary>
    public partial class WebChatChannelProperties
    {
        /// <summary>
        /// Initializes a new instance of the WebChatChannelProperties class.
        /// </summary>
        public WebChatChannelProperties()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the WebChatChannelProperties class.
        /// </summary>
        /// <param name="webChatEmbedCode">Web chat control embed code</param>
        /// <param name="sites">The list of Web Chat sites</param>
        public WebChatChannelProperties(string webChatEmbedCode = default(string), IList<WebChatSite> sites = default(IList<WebChatSite>))
        {
            WebChatEmbedCode = webChatEmbedCode;
            Sites = sites;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets web chat control embed code
        /// </summary>
        [JsonProperty(PropertyName = "webChatEmbedCode")]
        public string WebChatEmbedCode { get; private set; }

        /// <summary>
        /// Gets or sets the list of Web Chat sites
        /// </summary>
        [JsonProperty(PropertyName = "sites")]
        public IList<WebChatSite> Sites { get; set; }

    }
}


text:
$(function () {
  var active_nav = $('.nav-item.is-active');

  if (document.getElementById("nav-category") !== null) {
    $('#nav-panel-category').css({
      'min-width': $('#nav-category').outerWidth() + 'px',
      'top': ($('#nav-category').offset().top + $('#nav-category').outerHeight()) + 'px',
      'left': $('#nav-category').offset().left + 'px'
    });

    $('#nav-category').on({
      'click': function (e) {
        $(this).trigger('togglePanel');
        $('#nav-publisher').trigger('hidePanel');
        $('#nav-price').trigger('hidePanel');
      },
      'togglePanel': function () {
        active_nav.toggleClass('is-active');
        $(this).toggleClass('is-active');
        $('#nav-panel-category').toggle('normal');
      },
      'hidePanel': function () {
        active_nav.removeClass('is-active');
        $(this).removeClass('is-active');
        $('#nav-panel-category').hide('normal');
      }
    });
  }

  if (document.getElementById("nav-price") !== null) {
    $('#nav-panel-price').css({
      'min-width': $('#nav-price').outerWidth() + 'px',
      'top': ($('#nav-price').offset().top + $('#nav-price').outerHeight()) + 'px',
      'left': $('#nav-price').offset().left + 'px'
    });

    $('#nav-price').on({
      'click': function (e) {
        $(this).trigger('togglePanel');
        $('#nav-category').trigger('hidePanel');
        $('#nav-publisher').trigger('hidePanel');
      },
      'togglePanel': function () {
        active_nav.toggleClass('is-active');
        $(this).toggleClass('is-active');
        $('#nav-panel-price').toggle('normal');
      },
      'hidePanel': function () {
        active_nav.removeClass('is-active');
        $(this).removeClass('is-active');
        $('#nav-panel-price').hide('normal');
      }
    });
  }

  if (document.getElementById("nav-publisher") !== null) {
    $('#nav-panel-publisher').css({
      'min-width': $('#nav-publisher').outerWidth() + 'px',
      'top': ($('#nav-publisher').offset().top + $('#nav-publisher').outerHeight()) + 'px',
      'left': $('#nav-publisher').offset().left + 'px'
    });

    $('#nav-publisher').on({
      'click': function (e) {
        $(this).trigger('togglePanel');
        $('#nav-category').trigger('hidePanel');
        $('#nav-price').trigger('hidePanel');
      },
      'togglePanel': function () {
        active_nav.toggleClass('is-active');
        $(this).toggleClass('is-active');
        $('#nav-panel-publisher').toggle('normal');
      },
      'hidePanel': function () {
        active_nav.removeClass('is-active');
        $(this).removeClass('is-active');
        $('#nav-panel-publisher').hide('normal');
      }
    });
  }
});


text:
import lfc
from optparse import OptionParser

if __name__ == "__main__":
        parser = OptionParser(usage="%prog <se_name> [--surl] [--dn] [--lfn]", version="%prog 1.3")
	parser.add_option("--surl", action="store_true", dest="surl",    default=False, help="Get Storage URL")
	parser.add_option("--dn",  action="store_true", dest="owner",  default=False, help="Get Owner")
	parser.add_option("--lfn", action="store_true", dest="lfn",    default=False, help="Get LFN")
        (options, args) = parser.parse_args()

	if len(args) >= 3 or len(args) < 1:
		parser.error("wrong number of parameters")

	se_name = args[0]
	users={}

	flags = lfc.CNS_LIST_BEGIN
	lista = lfc.lfc_list()
	replica = lfc.lfc_listreplicax("",se_name, "", flags, lista)

	lfn="\0"*4096

	columns = "fileId"
	columns_sub = "------"
	if options.surl:
		columns += "   |   SURL"
		columns_sub += "-----------"
	if options.lfn:
		columns += "   |   LFN"
		columns_sub += "----------"
	if options.owner:
		columns += "   |   Owner's DN"
		columns_sub += "-----------------"
	print columns
	print columns_sub

	try:
		while replica is not None:
			res = str(replica.fileid)

			if options.surl:
				res += "|" + str(replica.sfn).replace('\0', '')

			if options.lfn:
				lfc.lfc_getpath("", replica.fileid, lfn)
				res = res + "|" + lfn.strip().replace('\0', '')

			if options.owner:
				buf = lfc.lfc_filestatg()
				lfc.lfc_statr(replica.sfn, buf)

				username="\0"*1024
				if buf.uid not in users:
					if lfc.lfc_getusrbyuid(buf.uid, username) == 0:
						# Adding user to the list in order to resolve him/her only once
						dn = username.strip().replace('\0', '')
						users[buf.uid] = dn
					else:
						users[buf.uid] = "unknown"
				res = res + "|" + users[buf.uid]

			print res

			flags = lfc.CNS_LIST_CONTINUE
			replica = lfc.lfc_listreplicax("",se_name, "", flags, lista)

	except (KeyboardInterrupt, SystemExit):
		print "Interrupted by user."

	flags = lfc.CNS_LIST_END
	lfc.lfc_listreplicax("",se_name, "", flags, lista)

	if options.owner:
		print "-----------------------------------------------------"
		print "List of users' DNs:"
		for userId in users:
			print users[userId]


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

    <link href="<?php echo base_url() ?>assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet" />

    <link href="<?php echo base_url() ?>assets/css/back/paper-dashboard.css" rel="stylesheet"/>
    <link href="<?php echo base_url() ?>assets/css/back/style.css" rel="stylesheet" />

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
    <link href="<?php echo base_url() ?>assets/back/css/themify-icons.css" rel="stylesheet">

    <?php print_r($data);  ?>

Apakan akan melakukan pembayaran lagi ?

Pembayaran

              <?php $i = 1; $total = 0; foreach ($data as $data): ?>

                  <?php echo $i ?>
                  Rp. <?php echo $data['nominal'] ?>

              <?php $i++; $total = $total + $data['nominal']; endforeach; ?>

                Total
                Rp. <?php echo $total ?>

            <button class="btn btn-danger" name="button">Tidak</button>
            <button class="btn btn-success" name="button">Iya, lakukan pembayaran lagi </button>


text:
package com.m12y.flippy_bird.core.input;

import com.badlogic.gdx.InputProcessor;
import com.m12y.flippy_bird.core.logic.Game;

public class GameInputProcessor implements InputProcessor {
    private final Game game;

    public GameInputProcessor(Game game) {
        this.game = game;
    }

    @Override
    public boolean keyDown(int keycode) {
        game.bird.flip();
        return true;
    }

    @Override
    public boolean keyUp(int keycode) {
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        game.bird.flip();
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}


text:
class Chef
  #
  # Extending module.
  #
  module Provisioning
    #
    # Extending module.
    #
    module OpenNebulaDriver
      VERSION = '0.4.5'
    end
  end
end