text:
<?php

namespace Point\PointSales\Vesa;

use Point\PointSales\Models\Retur;
use Point\PointSales\Models\Sales\Invoice;

trait ReturVesa
{
    public static function getVesa()
    {
        $array = self::vesaApproval();
        $array = self::vesaReject($array);

        return $array;
    }

    public static function getVesaApproval()
    {
        return self::vesaApproval([], false);
    }

    public static function getVesaReject()
    {
        return self::vesaReject([], false);
    }

    private static function vesaApproval($array = [], $merge_into_group = true)
    {
        $list_retur = self::joinFormulir()->with('person')->open()->approvalPending()->notArchived()->selectOriginal()->orderByStandard();
        // Grouping vesa
        if ($merge_into_group && $list_retur->get()->count() > 5) {
            array_push($array, [
                'url' => url('sales/point/indirect/retur/vesa-approval'),
                'deadline' => $list_retur->orderBy('form_date')->first()->formulir->form_date,
                'message' => 'you have many retur sales waiting to be approved',
                'permission_slug' => 'approval.point.sales.return'
            ]);

            return $array;
        }

        // Push all
        foreach ($list_retur->get() as $retur) {
            array_push($array, [
                'url' => url('sales/point/indirect/retur/' . $retur->id),
                'deadline' => $retur->required_date ? : $retur->formulir->form_date,
                'message' => 'Please approve this retur sales '
                    . formulir($retur->formulir)
                    . ' customer ' . $retur->person->name . '',
                'permission_slug' => 'approval.point.sales.return'
            ]);
        }

        return $array;
    }

    private static function vesaReject($array = [], $merge_into_group = true)
    {
        $list_retur = self::joinFormulir()->open()->approvalRejected()->notArchived()->selectOriginal()->orderByStandard();

        // Grouping vesa
        if ($merge_into_group && $list_retur->get()->count() > 5) {
            array_push($array, [
                'url' => url('sales/point/indirect/retur/vesa-rejected'),
                'deadline' => $list_retur->orderBy('form_date')->first()->form_date,
                'message' => 'retur sales rejected, please edit your forms',
                'permission_slug' => 'update.point.sales.return'
            ]);

            return $array;
        }

        // Push all
        foreach ($list_retur->get() as $retur) {
            array_push($array, [
                'url' => url('sales/point/indirect/retur/' . $retur->id.'/edit'),
                'deadline' => $retur->required_date ? : $retur->formulir->form_date,
                'message' => 'retur sales '
                    . $retur->formulir->form_number
                    . ' customer ' . $retur->person->name . ' Rejected, please edit your forms',
                'permission_slug' => 'update.point.sales.return'
            ]);
        }

        return $array;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Abstractions.Models;
using BTCPayServer.Client.Models;
using BTCPayServer.Lightning;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Lightning;
using BTCPayServer.Services;
using LNURL;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BTCPayServer.Data.Payouts.LightningLike
{
    public class LightningLikePayoutHandler : IPayoutHandler
    {
        public const string LightningLikePayoutHandlerOnionNamedClient =
            nameof(LightningLikePayoutHandlerOnionNamedClient);

        public const string LightningLikePayoutHandlerClearnetNamedClient =
            nameof(LightningLikePayoutHandlerClearnetNamedClient);

        private readonly BTCPayNetworkProvider _btcPayNetworkProvider;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly UserService _userService;
        private readonly IAuthorizationService _authorizationService;

        public LightningLikePayoutHandler(BTCPayNetworkProvider btcPayNetworkProvider,
            IHttpClientFactory httpClientFactory, UserService userService, IAuthorizationService authorizationService)
        {
            _btcPayNetworkProvider = btcPayNetworkProvider;
            _httpClientFactory = httpClientFactory;
            _userService = userService;
            _authorizationService = authorizationService;
        }

        public bool CanHandle(PaymentMethodId paymentMethod)
        {
            return (paymentMethod.PaymentType == LightningPaymentType.Instance  ||  paymentMethod.PaymentType == LNURLPayPaymentType.Instance ) &&
                   _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethod.CryptoCode)?.SupportLightning is true;
        }

        public Task TrackClaim(PaymentMethodId paymentMethodId, IClaimDestination claimDestination)
        {
            return Task.CompletedTask;
        }

        public HttpClient CreateClient(Uri uri)
        {
            return _httpClientFactory.CreateClient(uri.IsOnion()
                ? LightningLikePayoutHandlerOnionNamedClient
                : LightningLikePayoutHandlerClearnetNamedClient);
        }

        public async Task<(IClaimDestination destination, string error)> ParseClaimDestination(PaymentMethodId paymentMethodId, string destination, CancellationToken cancellationToken)
        {
            destination = destination.Trim();
            var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode);
            try
            {
                string lnurlTag = null;
                var lnurl = destination.IsValidEmail()
                    ? LNURL.LNURL.ExtractUriFromInternetIdentifier(destination)
                    : LNURL.LNURL.Parse(destination, out lnurlTag);

                if (lnurlTag is null)
                {
                    using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    using var t = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancellationToken);
                    var info = (LNURLPayRequest)(await LNURL.LNURL.FetchInformation(lnurl, CreateClient(lnurl), t.Token));
                    lnurlTag = info.Tag;
                }

                if (lnurlTag.Equals("payRequest", StringComparison.InvariantCultureIgnoreCase))
                {
                    return (new LNURLPayClaimDestinaton(destination), null);
                }
            }
            catch (FormatException)
            {
            }
            catch
            {
                return (null, "The LNURL / Lightning Address provided was not online.");
            }

            var result =
                BOLT11PaymentRequest.TryParse(destination, out var invoice, network.NBitcoinNetwork)
                    ? new BoltInvoiceClaimDestination(destination, invoice)
                    : null;

            if (result == null)
                return (null, "A valid BOLT11 invoice or LNURL Pay or Lightning address was not provided.");
            if (invoice.ExpiryDate.UtcDateTime < DateTime.UtcNow)
            {
                return (null,
                    "The BOLT11 invoice submitted has expired.");
            }

            return (result, null);
        }

        public (bool valid, string error) ValidateClaimDestination(IClaimDestination claimDestination, PullPaymentBlob pullPaymentBlob)
        {
            if (claimDestination is not BoltInvoiceClaimDestination bolt)
                return (true, null);
            var invoice = bolt.PaymentRequest;
            if (pullPaymentBlob is not null && (invoice.ExpiryDate.UtcDateTime - DateTime.UtcNow) < pullPaymentBlob.BOLT11Expiration)
            {
                return (false,
                    $"The BOLT11 invoice must have an expiry date of at least {(long)pullPaymentBlob.BOLT11Expiration.TotalDays} days from submission (Provided was only {(invoice.ExpiryDate.UtcDateTime - DateTime.UtcNow).Days}).");
            }
            return (true, null);
        }

        public IPayoutProof ParseProof(PayoutData payout)
        {
            BitcoinLikePayoutHandler.ParseProofType(payout.Proof, out var raw, out var proofType);
            if (proofType is null)
            {
                return null;
            }
            if (proofType == PayoutLightningBlob.PayoutLightningBlobProofType)
            {
                return raw.ToObject<PayoutLightningBlob>();
            }

            return raw.ToObject<ManualPayoutProof>();
        }

        public void StartBackgroundCheck(Action<Type[]> subscribe)
        {
        }

        public Task BackgroundCheck(object o)
        {
            return Task.CompletedTask;
        }

        public Task<decimal> GetMinimumPayoutAmount(PaymentMethodId paymentMethodId, IClaimDestination claimDestination)
        {
            return Task.FromResult(Money.Satoshis(1).ToDecimal(MoneyUnit.BTC));
        }

        public Dictionary<PayoutState, List<(string Action, string Text)>> GetPayoutSpecificActions()
        {
            return new Dictionary<PayoutState, List<(string Action, string Text)>>();
        }

        public Task<StatusMessageModel> DoSpecificAction(string action, string[] payoutIds, string storeId)
        {
            return Task.FromResult<StatusMessageModel>(null);
        }

        public async Task<IEnumerable<PaymentMethodId>> GetSupportedPaymentMethods(StoreData storeData)
        {
            var result = new List<PaymentMethodId>();
            var methods = storeData.GetEnabledPaymentMethods(_btcPayNetworkProvider).Where(id => id.PaymentId.PaymentType == LightningPaymentType.Instance).OfType<LightningSupportedPaymentMethod>();
            foreach (LightningSupportedPaymentMethod supportedPaymentMethod in methods)
            {
                if (!supportedPaymentMethod.IsInternalNode)
                {
                    result.Add(supportedPaymentMethod.PaymentId);
                    continue;
                }

                foreach (UserStore storeDataUserStore in storeData.UserStores)
                {
                    if (!await _userService.IsAdminUser(storeDataUserStore.ApplicationUserId))
                        continue;
                    result.Add(supportedPaymentMethod.PaymentId);
                    break;
                }

            }

            return result;
        }

        public Task<IActionResult> InitiatePayment(PaymentMethodId paymentMethodId, string[] payoutIds)
        {
            return Task.FromResult<IActionResult>(new RedirectToActionResult("ConfirmLightningPayout",
                "UILightningLikePayout", new { cryptoCode = paymentMethodId.CryptoCode, payoutIds }));
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.beholder.memelang.model.analisador;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Alisson
 */
public class Escopo {

    private final String nome;
    private List<Escopo> subEscopos = new ArrayList();
    private final Escopo pai;

    public Escopo(String nome)
    {
        this.nome = nome;
        this.pai = null;
    }
    public Escopo(String nome, Escopo pai)
    {
        this.nome = nome;
        this.pai = pai;
    }

    /**
     * Cria um escopo novo e retorna ele.
     *
     * @param nome
     * @param escopoAtual escopo a ser adicionado o novo
     * @return
     */
    public static Escopo criaEVaiEscopoNovo(String nome,Escopo escopoAtual) {
        Escopo novo = new Escopo(nome, escopoAtual);
        escopoAtual.getSubEscopos().add(novo);
        return novo;
    }

    public static boolean verificaSeExisteNoEscopo(String nome,List<Identificador> tabelaSimbolos, Escopo escopoAtual) {
        for (Identificador id : tabelaSimbolos) {
            if (id.getEscopo() == escopoAtual && id.getNome().equals(nome)) {
                return true;
            }
        }
        return false;
    }

    public static boolean verificaEscopoSimilar(Escopo escopoAtual){
        if(escopoAtual.getPai() == null){
            return false;
        }
        for (Escopo sub: escopoAtual.getPai().getSubEscopos()) {
            if(escopoAtual.nome.equals(sub.nome)){
                return true;
            }
        }
        return false;
    }

    public Escopo getPai()
    {
        return pai;
    }

    public List<Escopo> getSubEscopos()
    {
        return subEscopos;
    }

    public void setSubEscopos(List<Escopo> subEscopos)
    {
        this.subEscopos = subEscopos;
    }

    public String getNome()
    {
        return nome;
    }

    @Override
    public String toString()
    {
        if (this.getPai() != null)
        {
            return this.getPai() + "->" + this.nome;
        }else{
            return this.nome;
        }
    }

}


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

/**
 * @fileoverview Invalid syntax .ts file, used by scripts/linters/
 * js_ts_linter_test.py. Ts ignore is used but no comment explains
 * the ts-ignore.
 */

let a: string;

// 1. No comment to explain the @ts-ignore.

// @ts-ignore
let b: number = a;

// 2. Comment with invalid format.

// We need ts-ignore here to test lint checks.
// @ts-ignore
b = a;


text:
class HttpResponseBase(object):
    status_code = 200

    def __init__(self, content_type=None, status=None, reason=None, charset=None):
        pass

class HttpResponse(HttpResponseBase):
    def __init__(self, content=b"", *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Content is a bytestring. See the `content` property methods.
        self.content = content

class HttpResponseRedirectBase(HttpResponse):
    def __init__(self, redirect_to, *args, **kwargs):
        super().__init__(*args, **kwargs)
        ...

class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
    status_code = 301

class HttpResponseRedirect(HttpResponseRedirectBase):
    status_code = 302

class HttpResponseNotFound(HttpResponse):
    status_code = 404

class JsonResponse(HttpResponse):

    def __init__(
        self,
        data,
        encoder=...,
        safe=True,
        json_dumps_params=None,
        **kwargs
    ):
        # fake code to represent what is going on :)
        kwargs.setdefault("content_type", "application/json")
        data = str(data)
        super().__init__(content=data, **kwargs)


text:
package psidev.psi.mi.jami.datasource;

/**
 * A source locator of an object in a file
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
22/03/13

 */
public class FileSourceLocator {

    private int lineNumber = -1;
    private int charNumber = -1;

    /**
     *
Constructor for FileSourceLocator.

     *
     * @param lineNumber a int.
     * @param charNumber a int.
     */
    public FileSourceLocator(int lineNumber, int charNumber){
        this.lineNumber = lineNumber;
        this.charNumber = charNumber;
    }

    /**
     * The line number in the file where the object is located
     *
     * @return the line number
     */
    public int getLineNumber() {
        return lineNumber;
    }

    /**
     * The character number in the file where the object is located.
     *
     * @return the character number
     */
    public int getCharNumber() {
        return charNumber;
    }

    /**
     *
toString

     *
     * @return a {@link java.lang.String} object.
     */
    public String toString() {
        return "Line: " + lineNumber + ", Character: " + charNumber;
    }
}


text:
#include "third_party/blink/renderer/core/frame/dom_timer.h"

#include "base/numerics/clamped_math.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/scheduled_action.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h"

namespace blink {

namespace {

// Step 11 of the algorithm at
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html requires
// that a timeout less than 4ms is increased to 4ms when the nesting level is
// greater than 5.
constexpr int kMaxTimerNestingLevel = 5;
constexpr base::TimeDelta kMinimumInterval = base::Milliseconds(4);
constexpr base::TimeDelta kMaxHighResolutionInterval = base::Milliseconds(32);

}  // namespace

int DOMTimer::Install(ExecutionContext* context,
                      ScheduledAction* action,
                      base::TimeDelta timeout,
                      bool single_shot) {
  int timeout_id = context->Timers()->InstallNewTimeout(context, action,
                                                        timeout, single_shot);
  return timeout_id;
}

void DOMTimer::RemoveByID(ExecutionContext* context, int timeout_id) {
  DOMTimer* timer = context->Timers()->RemoveTimeoutByID(timeout_id);
  DEVTOOLS_TIMELINE_TRACE_EVENT_INSTANT(
      "TimerRemove", inspector_timer_remove_event::Data, context, timeout_id);
  // Eagerly unregister as ExecutionContext observer.
  if (timer)
    timer->SetExecutionContext(nullptr);
}

DOMTimer::DOMTimer(ExecutionContext* context,
                   ScheduledAction* action,
                   base::TimeDelta timeout,
                   bool single_shot,
                   int timeout_id)
    : ExecutionContextLifecycleObserver(context),
      TimerBase(nullptr),
      timeout_id_(timeout_id),
      // Step 9:
      nesting_level_(context->Timers()->TimerNestingLevel()),
      action_(action) {
  DCHECK_GT(timeout_id, 0);

  // Step 10:
  if (timeout.is_negative())
    timeout = base::TimeDelta();

  // Steps 12 and 13:
  // Note: The implementation increments the nesting level before using it to
  // adjust timeout, contrary to what the spec requires crbug.com/1108877.
  IncrementNestingLevel();

  // Step 11:
  // Note: The implementation uses >= instead of >, contrary to what the spec
  // requires crbug.com/1108877.
  int max_nesting_level = features::IsMaxUnthrottledTimeoutNestingLevelEnabled()
                              ? features::GetMaxUnthrottledTimeoutNestingLevel()
                              : kMaxTimerNestingLevel;
  // Under AlignWakeUps experiment, avoid timer alignment if the original delay
  // is small, to avoid being affected by ongoing experiments on delay clamping
  // MaxUnthrottledTimeoutNestingLevel and SetTimeoutZeroWithoutClamping.
  // TODO(1153139) Remove this logic one experiments have shipped.
  bool precise = (timeout < kMinimumInterval) ||
                 (scheduler::IsAlignWakeUpsDisabledForProcess() &&
                  timeout < kMaxHighResolutionInterval);

  if (nesting_level_ >= max_nesting_level && timeout < kMinimumInterval)
    timeout = kMinimumInterval;

  // Select TaskType based on nesting level.
  TaskType task_type;
  if (nesting_level_ >= kMaxTimerNestingLevel) {
    task_type = TaskType::kJavascriptTimerDelayedHighNesting;
  } else if (timeout.is_zero()) {
    task_type = TaskType::kJavascriptTimerImmediate;
    DCHECK_LT(nesting_level_, max_nesting_level);
  } else {
    task_type = TaskType::kJavascriptTimerDelayedLowNesting;
  }
  MoveToNewTaskRunner(context->GetTaskRunner(task_type));

  // Clamping up to 1ms for historical reasons crbug.com/402694.
  // Removing clamp for single_shot behind a feature flag.
  if (!single_shot || !blink::features::IsSetTimeoutWithoutClampEnabled())
    timeout = std::max(timeout, base::Milliseconds(1));

  if (single_shot)
    StartOneShot(timeout, FROM_HERE, precise);
  else
    StartRepeating(timeout, FROM_HERE, precise);

  DEVTOOLS_TIMELINE_TRACE_EVENT_INSTANT(
      "TimerInstall", inspector_timer_install_event::Data, context, timeout_id,
      timeout, single_shot);
  const char* name = single_shot ? "setTimeout" : "setInterval";
  async_task_context_.Schedule(context, name);
  probe::BreakableLocation(context, name);
}

DOMTimer::~DOMTimer() = default;

void DOMTimer::Dispose() {
  Stop();
}

void DOMTimer::Stop() {
  if (!action_)
    return;

  async_task_context_.Cancel();
  const bool is_interval = !RepeatInterval().is_zero();
  probe::BreakableLocation(GetExecutionContext(),
                           is_interval ? "clearInterval" : "clearTimeout");

  // Need to release JS objects potentially protected by ScheduledAction
  // because they can form circular references back to the ExecutionContext
  // which will cause a memory leak.
  if (action_)
    action_->Dispose();
  action_ = nullptr;
  TimerBase::Stop();
}

void DOMTimer::ContextDestroyed() {
  Stop();
}

void DOMTimer::Fired() {
  ExecutionContext* context = GetExecutionContext();
  DCHECK(context);
  context->Timers()->SetTimerNestingLevel(nesting_level_);
  DCHECK(!context->IsContextPaused());
  // Only the first execution of a multi-shot timer should get an affirmative
  // user gesture indicator.

  DEVTOOLS_TIMELINE_TRACE_EVENT("TimerFire", inspector_timer_fire_event::Data,
                                context, timeout_id_);
  const bool is_interval = !RepeatInterval().is_zero();
  probe::UserCallback probe(context, is_interval ? "setInterval" : "setTimeout",
                            g_null_atom, true);
  probe::AsyncTask async_task(context, &async_task_context_,
                              is_interval ? "fired" : nullptr);

  // Simple case for non-one-shot timers.
  if (IsActive()) {
    DCHECK(is_interval);

    // Steps 12 and 13:
    // Note: The implementation increments the nesting level before using it to
    // adjust timeout, contrary to what the spec requires crbug.com/1108877.
    IncrementNestingLevel();

    // Make adjustments when the nesting level becomes >= |kMaxNestingLevel|.
    // Note: The implementation uses >= instead of >, contrary to what the spec
    // requires crbug.com/1108877.
    int max_nesting_level =
        features::IsMaxUnthrottledTimeoutNestingLevelEnabled()
            ? features::GetMaxUnthrottledTimeoutNestingLevel()
            : kMaxTimerNestingLevel;
    // Step 11:
    if (nesting_level_ == max_nesting_level &&
        RepeatInterval() < kMinimumInterval) {
      AugmentRepeatInterval(kMinimumInterval - RepeatInterval());
    }
    if (nesting_level_ == kMaxTimerNestingLevel) {
      // Move to the TaskType that corresponds to nesting level >=
      // |kMaxNestingLevel|.
      MoveToNewTaskRunner(
          context->GetTaskRunner(TaskType::kJavascriptTimerDelayedHighNesting));
    }

    DCHECK(nesting_level_ < max_nesting_level ||
           RepeatInterval() >= kMinimumInterval);

    // No access to member variables after this point, it can delete the timer.
    action_->Execute(context);

    context->Timers()->SetTimerNestingLevel(0);

    return;
  }

  // Unregister the timer from ExecutionContext before executing the action
  // for one-shot timers.
  ScheduledAction* action = action_.Release();
  context->Timers()->RemoveTimeoutByID(timeout_id_);

  action->Execute(context);

  // Eagerly clear out |action|'s resources.
  action->Dispose();

  // ExecutionContext might be already gone when we executed action->execute().
  ExecutionContext* execution_context = GetExecutionContext();
  if (!execution_context)
    return;

  execution_context->Timers()->SetTimerNestingLevel(0);
  // Eagerly unregister as ExecutionContext observer.
  SetExecutionContext(nullptr);
}

void DOMTimer::Trace(Visitor* visitor) const {
  visitor->Trace(action_);
  ExecutionContextLifecycleObserver::Trace(visitor);
}

void DOMTimer::IncrementNestingLevel() {
  nesting_level_ = base::ClampAdd(nesting_level_, 1);
}

}  // namespace blink


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Parent Suite A">
    <suite-files>
        <suite-file path="suiteA.xml"/>
    </suite-files>
</suite>


text:
namespace CGAL {

class Decomposition_mark {

  bool mark;

  friend std::ostream& operator<<(std::ostream& out, const Decomposition_mark& m);
  friend std::istream& operator>>(std::istream& in, Decomposition_mark& m);

 public:
  Decomposition_mark() {}
  Decomposition_mark(bool m) : mark(m) {}

  bool operator==(const Decomposition_mark& m) const {
    return mark == m.mark;
  }

  bool operator!=(const Decomposition_mark& m) const {
    return !*this==m;
  }

  Decomposition_mark operator!() const {
    return Decomposition_mark(!mark);
  }

  Decomposition_mark operator&&(const Decomposition_mark& m) const {
    return Decomposition_mark(mark && m.mark);
  }

  Decomposition_mark operator||(const Decomposition_mark& m) const {
    return Decomposition_mark(mark || m.mark);
  }
};

std::ostream& operator<<(std::ostream& out, const Decomposition_mark& m) {
  out << m.mark;
  return out;
}

std::istream& operator>>(std::istream& in, Decomposition_mark& m) {
  in >> m.mark;
  return in;
}

} //namespace CGAL
#endif // CGAL_DECOMPOSITION_MARK_H


text:
<?php
namespace Google\Service\Shopping;

class ShoppingModelCategoryJsonV1 extends \Google\Collection
{
  public $id;
  public $parents;
  public $shortName;
  public $url;

  public function setId($id)
  {
    $this->id = $id;
  }

  public function getId()
  {
    return $this->id;
  }

  public function setParents($parents)
  {
    $this->parents = $parents;
  }

  public function getParents()
  {
    return $this->parents;
  }

  public function setShortName($shortName)
  {
    $this->shortName = $shortName;
  }

  public function getShortName()
  {
    return $this->shortName;
  }

  public function setUrl($url)
  {
    $this->url = $url;
  }

  public function getUrl()
  {
    return $this->url;
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB)
// Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source
// schema.
// Generated on: 2016.05.30 at 07:47:34 PM JST
//
package org.sbml._2001.ns.celldesigner;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

// TODO: Auto-generated Javadoc
/**
 * List of residue modification.
 *

 * Java class for listOfModifications complex type.
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType name="listOfModifications">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence maxOccurs="unbounded">
 *         <element name="modification">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <attribute name="residue" use="required" type="{http://www.sbml.org/2001/ns/celldesigner}SId" />
 *                 <attribute name="state" use="required">
 *                   <simpleType>
 *                     <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *                       <enumeration value="phosphorylated"/>
 *                       <enumeration value="acetylated"/>
 *                       <enumeration value="ubiquitinated"/>
 *                       <enumeration value="methylated"/>
 *                       <enumeration value="hydroxylated"/>
 *                       <enumeration value="don't care"/>
 *                       <enumeration value="unknown"/>
 *                       <enumeration value="glycosylated"/>
 *                       <enumeration value="myristoylated"/>
 *                       <enumeration value="palmytoylated"/>
 *                       <enumeration value="prenylated"/>
 *                       <enumeration value="protonated"/>
 *                       <enumeration value="sulfated"/>
 *                     </restriction>
 *                   </simpleType>
 *                 </attribute>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listOfModifications", propOrder = {"modification"})
public class ListOfModifications {

  /** The modification. */
  @XmlElement(required = true)
  protected List<ListOfModifications.Modification> modification;

  /**
   * Gets the value of the modification property.
   *

   * This accessor method returns a reference to the live list, not a snapshot.
   * Therefore any modification you make to the returned list will be present
   * inside the JAXB object. This is why there is not a set method
   * for the modification property.
   *

   * For example, to add a new item, do as follows:
   *
   *

   * getModification().add(newItem);
   *

   *

   * Objects of the following type(s) are allowed in the list
   * {@link ListOfModifications.Modification }
   *
   * @return the modification
   */
  public List<ListOfModifications.Modification> getModification() {
    if (modification == null) {
      modification = new ArrayList<ListOfModifications.Modification>();
    }
    return this.modification;
  }

  /**
   *

   * Java class for anonymous complex type.
   *

   * The following schema fragment specifies the expected content contained
   * within this class.
   *
   *

   * <complexType>
   *   <complexContent>
   *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
   *       <attribute name="residue" use="required" type="{http://www.sbml.org/2001/ns/celldesigner}SId" />
   *       <attribute name="state" use="required">
   *         <simpleType>
   *           <restriction base="{http://www.w3.org/2001/XMLSchema}string">
   *             <enumeration value="phosphorylated"/>
   *             <enumeration value="acetylated"/>
   *             <enumeration value="ubiquitinated"/>
   *             <enumeration value="methylated"/>
   *             <enumeration value="hydroxylated"/>
   *             <enumeration value="don't care"/>
   *             <enumeration value="unknown"/>
   *             <enumeration value="glycosylated"/>
   *             <enumeration value="myristoylated"/>
   *             <enumeration value="palmytoylated"/>
   *             <enumeration value="prenylated"/>
   *             <enumeration value="protonated"/>
   *             <enumeration value="sulfated"/>
   *           </restriction>
   *         </simpleType>
   *       </attribute>
   *     </restriction>
   *   </complexContent>
   * </complexType>
   *

   */
  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(name = "")
  public static class Modification {

    /** The residue. */
    @XmlAttribute(name = "residue", required = true)
    protected String residue;
    /** The state. */
    @XmlAttribute(name = "state", required = true)
    protected String state;

    /**
     * Gets the value of the residue property.
     *
     * @return
     *         possible object is {@link String }
     */
    public String getResidue() {
      return residue;
    }

    /**
     * Sets the value of the residue property.
     *
     * @param value
     *        allowed object is {@link String }
     */
    public void setResidue(String value) {
      this.residue = value;
    }

    /**
     * Gets the value of the state property.
     *
     * @return
     *         possible object is {@link String }
     */
    public String getState() {
      return state;
    }

    /**
     * Sets the value of the state property.
     *
     * @param value
     *        allowed object is {@link String }
     */
    public void setState(String value) {
      this.state = value;
    }
  }
}


text:
Devwik = function() {}; //Provide a name space
Devwik.SQL = function() {};

Future = Npm.require('fibers/future');
//Using the node.js MYSQL driver from https://github.com/felixge/node-mysql
Fiber = Npm.require('fibers');
mysql = Npm.require('mysql');
mysql = Npm.require('mysql');
//based on http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
Devwik.toType = function(obj) {
	return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.messaging.eventhubs;

import com.azure.core.amqp.models.AmqpAnnotatedMessage;
import com.azure.core.exception.AzureException;
import com.azure.messaging.eventhubs.implementation.ManagementChannel;
import org.apache.qpid.proton.Proton;
import org.apache.qpid.proton.amqp.messaging.AmqpValue;
import org.apache.qpid.proton.message.Message;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.azure.core.amqp.AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME;
import static com.azure.core.amqp.AmqpMessageConstant.OFFSET_ANNOTATION_NAME;
import static com.azure.core.amqp.AmqpMessageConstant.SEQUENCE_NUMBER_ANNOTATION_NAME;
import static com.azure.messaging.eventhubs.TestUtils.APPLICATION_PROPERTIES;
import static com.azure.messaging.eventhubs.TestUtils.ENQUEUED_TIME;
import static com.azure.messaging.eventhubs.TestUtils.OFFSET;
import static com.azure.messaging.eventhubs.TestUtils.OTHER_SYSTEM_PROPERTY;
import static com.azure.messaging.eventhubs.TestUtils.PARTITION_KEY;
import static com.azure.messaging.eventhubs.TestUtils.SEQUENCE_NUMBER;
import static com.azure.messaging.eventhubs.TestUtils.getMessage;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class EventHubMessageSerializerTest {
    private final EventHubMessageSerializer serializer = new EventHubMessageSerializer();

    @Test
    public void deserializeMessageNotNull() {
        assertThrows(NullPointerException.class, () -> serializer.deserialize(null, EventData.class));
    }

    @Test
    public void deserializeClassNotNull() {
        assertThrows(NullPointerException.class, () -> serializer.deserialize(Proton.message(), null));
    }

    @Test
    public void serializeObjectNotNull() {
        assertThrows(NullPointerException.class, () -> serializer.serialize(null));
    }

    /**
     * Verify that we cannot serialize something that is not of type EventData.
     */
    @Test
    public void cannotSerializeObject() {
        String something = "oops";
        assertThrows(IllegalArgumentException.class, () -> serializer.serialize(something));
    }

    /**
     * Verify we can only deserialize supported classes.
     */
    @Test
    public void cannotDeserializeObject() {
        final Message message = getMessage("hello-world".getBytes(UTF_8));
        assertThrows(IllegalArgumentException.class, () -> serializer.deserialize(message, EventHubAsyncClient.class));
    }

    /**
     * Verify that we can deserialize a proton-j message with all the correct contents to {@link EventData}.
     */
    @Test
    public void deserializeEventData() {
        // Arrange
        final Map<String, Object> systemPropertiesMap = new HashMap<>();
        systemPropertiesMap.put(OFFSET_ANNOTATION_NAME.getValue(), OFFSET);
        systemPropertiesMap.put(ENQUEUED_TIME_UTC_ANNOTATION_NAME.getValue(), ENQUEUED_TIME);
        systemPropertiesMap.put(SEQUENCE_NUMBER_ANNOTATION_NAME.getValue(), SEQUENCE_NUMBER);

        final Message message = getMessage("hello-world".getBytes(UTF_8));

        // Act
        final EventData eventData = serializer.deserialize(message, EventData.class);

        // Assert
        // Verifying all our system properties were properly deserialized.
        Assertions.assertEquals(ENQUEUED_TIME, eventData.getEnqueuedTime());
        Assertions.assertEquals(OFFSET, eventData.getOffset());
        Assertions.assertEquals(PARTITION_KEY, eventData.getPartitionKey());
        Assertions.assertEquals(SEQUENCE_NUMBER, eventData.getSequenceNumber());

        final Map<String, Object> actualSystemProperties = eventData.getSystemProperties();
        systemPropertiesMap.forEach((key, value) -> {
            final boolean containsKey = actualSystemProperties.containsKey(key);
            final Object actualValue = actualSystemProperties.get(key);
            Assertions.assertTrue(containsKey);
            Assertions.assertEquals(value, actualValue);
        });

        // Verify that the message annotations in the raw AMQP message also match the ones in getSystemProperties()
        Assertions.assertTrue(eventData.getSystemProperties().containsKey(OTHER_SYSTEM_PROPERTY));
        final Object otherPropertyValue = eventData.getSystemProperties().get(OTHER_SYSTEM_PROPERTY);
        Assertions.assertTrue(otherPropertyValue instanceof Boolean);
        Assertions.assertTrue((Boolean) otherPropertyValue);

        final AmqpAnnotatedMessage amqpMessage = eventData.getRawAmqpMessage();
        Assertions.assertTrue(amqpMessage.getMessageAnnotations().containsKey(OTHER_SYSTEM_PROPERTY));
        final Object otherPropertyValue2 = amqpMessage.getMessageAnnotations().get(OTHER_SYSTEM_PROPERTY);
        Assertions.assertTrue(otherPropertyValue2 instanceof Boolean);
        Assertions.assertTrue((Boolean) otherPropertyValue2);

        // Verifying our application properties are the same.
        Assertions.assertEquals(APPLICATION_PROPERTIES.size(), eventData.getProperties().size());
        APPLICATION_PROPERTIES.forEach((key, value) -> {
            Assertions.assertTrue(eventData.getProperties().containsKey(key));
            Assertions.assertEquals(value, eventData.getProperties().get(key));
        });
    }

    /**
     * Verify we can deserialize a message to {@link PartitionProperties}.
     */
    @Test
    public void deserializePartitionProperties() {
        // Arrange
        final String eventHubName = "my-event-hub";
        final String id = "partition-id-test";
        final long beginningSequenceNumber = 1343L;
        final long lastEnqueuedSequenceNumber = 1500L;
        final String lastEnqueuedOffset = "102";
        final Date lastEnqueuedTimeAsDate = new Date(1569275540L);
        final Instant lastEnqueuedTime = lastEnqueuedTimeAsDate.toInstant();
        final boolean isEmpty = true;

        final Map<String, Object> values = new HashMap<>();
        values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName);
        values.put(ManagementChannel.MANAGEMENT_PARTITION_NAME_KEY, id);
        values.put(ManagementChannel.MANAGEMENT_RESULT_BEGIN_SEQUENCE_NUMBER, beginningSequenceNumber);
        values.put(ManagementChannel.MANAGEMENT_RESULT_LAST_ENQUEUED_SEQUENCE_NUMBER, lastEnqueuedSequenceNumber);
        values.put(ManagementChannel.MANAGEMENT_RESULT_LAST_ENQUEUED_OFFSET, lastEnqueuedOffset);
        values.put(ManagementChannel.MANAGEMENT_RESULT_LAST_ENQUEUED_TIME_UTC, lastEnqueuedTimeAsDate);
        values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IS_EMPTY, isEmpty);

        final AmqpValue amqpValue = new AmqpValue(values);

        final Message message = Proton.message();
        message.setBody(amqpValue);

        // Act
        final PartitionProperties partitionProperties = serializer.deserialize(message, PartitionProperties.class);

        // Assert
        Assertions.assertNotNull(partitionProperties);
        Assertions.assertEquals(eventHubName, partitionProperties.getEventHubName());
        Assertions.assertEquals(id, partitionProperties.getId());
        Assertions.assertEquals(beginningSequenceNumber, partitionProperties.getBeginningSequenceNumber());
        Assertions.assertEquals(lastEnqueuedSequenceNumber, partitionProperties.getLastEnqueuedSequenceNumber());
        Assertions.assertEquals(lastEnqueuedOffset, partitionProperties.getLastEnqueuedOffset());
        Assertions.assertEquals(lastEnqueuedTime, partitionProperties.getLastEnqueuedTime());
        Assertions.assertEquals(isEmpty, partitionProperties.isEmpty());
    }

    /**
     * Verify we can deserialize a message to {@link EventHubProperties}.
     */
    @Test
    public void deserializeEventHubProperties() {
        // Arrange
        final String eventHubName = "my-event-hub";
        final Date createdAtAsDate = new Date(1569275540L);
        final Instant createdAt = createdAtAsDate.toInstant();
        final String[] partitionIds = new String[]{"1", "foo", "bar", "baz"};

        final Map<String, Object> values = new HashMap<>();
        values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName);
        values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate);
        values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds);

        final AmqpValue amqpValue = new AmqpValue(values);

        final Message message = Proton.message();
        message.setBody(amqpValue);

        // Act
        final EventHubProperties properties = serializer.deserialize(message, EventHubProperties.class);

        // Assert
        Assertions.assertNotNull(properties);
        Assertions.assertEquals(eventHubName, properties.getName());
        Assertions.assertEquals(createdAt, properties.getCreatedAt());
        Assertions.assertArrayEquals(partitionIds, properties.getPartitionIds().stream().toArray(String[]::new));
    }

    /**
     * Verify that it throws if the value is not what we expect. In this case, eventHubName is not a string.
     */
    @Test
    public void throwsWhenIncorrectTypeInResponse() {
        // Arrange
        final Long eventHubName = 100L;
        final Date createdAtAsDate = new Date(1569275540L);
        final String[] partitionIds = new String[]{"1", "foo", "bar", "baz"};

        final Map<String, Object> values = new HashMap<>();
        values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName);
        values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate);
        values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, partitionIds);

        final AmqpValue amqpValue = new AmqpValue(values);

        final Message message = Proton.message();
        message.setBody(amqpValue);

        assertThrows(AzureException.class, () -> {
            // Act
            serializer.deserialize(message, EventHubProperties.class);
        });
    }

    /**
     * Verify that it throws if the value in the map is null.
     */
    @Test
    public void throwsWhenNullValueInResponse() {
        // Arrange
        final String eventHubName = "event-hub-name-test";
        final Date createdAtAsDate = new Date(1569275540L);

        final Map<String, Object> values = new HashMap<>();
        values.put(ManagementChannel.MANAGEMENT_ENTITY_NAME_KEY, eventHubName);
        values.put(ManagementChannel.MANAGEMENT_RESULT_CREATED_AT, createdAtAsDate);
        values.put(ManagementChannel.MANAGEMENT_RESULT_PARTITION_IDS, null);

        final AmqpValue amqpValue = new AmqpValue(values);

        final Message message = Proton.message();
        message.setBody(amqpValue);

        assertThrows(AzureException.class, () -> {
            // Act
            serializer.deserialize(message, EventHubProperties.class);
        });
    }
}


text:
module Users
  class Create < Mutations::Command
    include Skylight::Helpers
    include Auth::ConsentHelpers

    required do
      string :name
      string :email
      string :password
      string :password_confirmation
    end

    optional do
      boolean :agree_to_terms
    end

    instrument_method
    def validate
      maybe_validate_tos
      email.downcase!
      add_error :email, :*, 'Already registered' if User.find_by(email: email)
      if password != password_confirmation
        add_error :password, :*, 'Password and confirmation do not match.'
      end
    end

    instrument_method
    def execute
      params = { email:                 email,
                 password:              password,
                 password_confirmation: password_confirmation,
                 name:                  name }
      params[:agreed_to_terms_at] = Time.now if User::ENFORCE_TOS
      user   = User.create!(params)
      device = Devices::Create.run!(user: user)
      UserMailer
        .welcome_email(user)
        .deliver_later unless User::SKIP_EMAIL_VALIDATION
      {message: "Check your email!"}
    end
  end
end


text:
package org.wikidata.wdtk.dumpfiles.wmf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wikidata.wdtk.dumpfiles.DumpContentType;
import org.wikidata.wdtk.dumpfiles.DumpProcessingController;
import org.wikidata.wdtk.dumpfiles.MwDumpFile;
import org.wikidata.wdtk.util.DirectoryManager;
import org.wikidata.wdtk.util.WebResourceFetcher;
import org.wikidata.wdtk.util.WebResourceFetcherImpl;

/**
 * Class for providing access to available dumpfiles provided by the Wikimedia
 * Foundation. The preferred access point for this class is
 * {@link DumpProcessingController#processAllRecentRevisionDumps()}, since this
 * method takes care of freeing resources and might also provide parallelized
 * downloading/processing in the future.
 *

 * Typically, the Web will be accessed to find information about dumps available
 * online. This Web access is mediated by a {@link WebResourceFetcherImpl}
 * object, provided upon construction. If null is given instead, the class will
 * operate in offline mode, using only previously downloaded files.
 *

 * The location of the Wikimedia download site is currently hardwired, since the
 * extraction methods used to get the data are highly specific to the format of
 * files on this site. Other sites (if any) would most likely need different
 * methods.
 *
 * @author Markus Kroetzsch
 *
 */
public class WmfDumpFileManager {

	static final Logger logger = LoggerFactory
			.getLogger(WmfDumpFileManager.class);

	/**
	 * The regular expression that a date stamp should match.
	 */
	static final String DATE_STAMP_PATTERN = "\\d\\d\\d\\d\\d\\d\\d\\d";

	/**
	 * The name of the directory where downloaded dump files are stored.
	 */
	public static final String DOWNLOAD_DIRECTORY_NAME = "dumpfiles";

	final String projectName;
	final DirectoryManager dumpfileDirectoryManager;
	final WebResourceFetcher webResourceFetcher;

	/**
	 * Constructor.
	 *
	 * @param projectName
	 *            name of the project to obtain dumps for as used in the folder
	 *            structure of the dump site, e.g., "wikidatawiki"
	 * @param downloadDirectoryManager
	 *            the directory manager for the directory where the download
	 *            directory for dump files should be; it will be created if
	 *            needed
	 * @param webResourceFetcher
	 *            the web resource fetcher to access web resources or null if no
	 *            web access should happen
	 * @throws IOException
	 *             if it was not possible to access the directory for managing
	 *             dumpfiles
	 */
	public WmfDumpFileManager(String projectName,
			DirectoryManager downloadDirectoryManager,
			WebResourceFetcher webResourceFetcher) throws IOException {
		this.projectName = projectName;
		this.dumpfileDirectoryManager = downloadDirectoryManager
				.getSubdirectoryManager(
						WmfDumpFileManager.DOWNLOAD_DIRECTORY_NAME)
				.getSubdirectoryManager(projectName);
		this.webResourceFetcher = webResourceFetcher;

		WmfDumpFileManager.logger.info("Using download directory "
				+ this.dumpfileDirectoryManager.toString());
	}

	/**
	 * Finds all page revision dump files, online or locally, that are relevant
	 * to obtain the most current state of the data. Revision dump files are
	 * dumps that contain page revisions in MediaWiki's XML format.
	 *

	 * If the parameter preferCurrent is true, then dumps that contain
	 * only the current versions of all files will be preferred if available
	 * anywhere, even over previously downloaded dump files that contain all
	 * versions. However, dump files may still contain non-current revisions,
	 * and when processing multiple dumps there might even be overlaps (one
	 * revision occurring in multiple dumps).
	 *

	 * The result is ordered with the most recent dump first. If a dump file A
	 * contains revisions of a page P, and Rmax is the maximal revision of P in
	 * A, then every dump file that comes after A should contain only revisions
	 * of P that are smaller than or equal to Rmax. In other words, the maximal
	 * revision found in the first file that contains P at all should also be
	 * the maximal revision overall.
	 *
	 * @param preferCurrent
	 *            should dumps with current revisions be preferred?
	 * @return an ordered list of all dump files that match the given criteria
	 */
	public List<MwDumpFile> findAllRelevantRevisionDumps(boolean preferCurrent) {
		MwDumpFile mainDump;
		if (preferCurrent) {
			mainDump = findMostRecentDump(DumpContentType.CURRENT);
		} else {
			mainDump = findMostRecentDump(DumpContentType.FULL);
		}
		if (mainDump == null) {
			return findAllDumps(DumpContentType.DAILY);
		}

		List<MwDumpFile> result = new ArrayList<>();

		for (MwDumpFile dumpFile : findAllDumps(DumpContentType.DAILY)) {
			if (dumpFile.getDateStamp().compareTo(mainDump.getDateStamp()) > 0) {
				result.add(dumpFile);
			}
		}

		result.add(mainDump);

		if (logger.isInfoEnabled()) {
			StringBuilder logMessage = new StringBuilder();
			logMessage.append("Found ")
					.append(result.size())
					.append(" relevant dumps to process:");
			for (MwDumpFile dumpFile : result) {
				logMessage.append("\n * ").append(dumpFile.toString());
			}
			logger.info(logMessage.toString());
		}

		return result;
	}

	/**
	 * Finds the most recent dump of the given type that is actually available.
	 *
	 * @param dumpContentType
	 *            the type of the dump to look for
	 * @return most recent main dump or null if no such dump exists
	 */
	public MwDumpFile findMostRecentDump(DumpContentType dumpContentType) {
		List<MwDumpFile> dumps = findAllDumps(dumpContentType);

		for (MwDumpFile dump : dumps) {
			if (dump.isAvailable()) {
				return dump;
			}
		}
		return null;
	}

	/**
	 * Returns a list of all dump files of the given type available either
	 * online or locally. For dumps available both online and locally, the local
	 * version is included. The list is ordered with most recent dump date
	 * first. Online dumps found by this method might not be available yet (if
	 * their directory has been created online but the file was not uploaded or
	 * completely written yet).
	 *
	 * @return a list of dump files of the given type
	 */
	public List<MwDumpFile> findAllDumps(DumpContentType dumpContentType) {
		List<MwDumpFile> localDumps = findDumpsLocally(dumpContentType);
		if (this.webResourceFetcher != null) {
			List<MwDumpFile> onlineDumps = findDumpsOnline(dumpContentType);
			return mergeDumpLists(localDumps, onlineDumps);
		} else {
			return localDumps;
		}
	}

	/**
	 * Merges a list of local and online dumps. For dumps available both online
	 * and locally, only the local version is included. The list is order with
	 * most recent dump date first.
	 *
	 * @return a merged list of dump files
	 */
	List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,
			List<MwDumpFile> onlineDumps) {
		List<MwDumpFile> result = new ArrayList<>(localDumps);

		HashSet<String> localDateStamps = new HashSet<>();
		for (MwDumpFile dumpFile : localDumps) {
			localDateStamps.add(dumpFile.getDateStamp());
		}
		for (MwDumpFile dumpFile : onlineDumps) {
			if (!localDateStamps.contains(dumpFile.getDateStamp())) {
				result.add(dumpFile);
			}
		}
		result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));
		return result;
	}

	/**
	 * Finds out which dump files of the given type have been downloaded
	 * already. The result is a list of objects that describe the available dump
	 * files, in descending order by their date. Not all of the dumps included
	 * might be actually available.
	 *
	 * @param dumpContentType
	 *            the type of dump to consider
	 * @return list of objects that provide information on available dumps
	 */
	List<MwDumpFile> findDumpsLocally(DumpContentType dumpContentType) {

		String directoryPattern = WmfDumpFile.getDumpFileDirectoryName(
				dumpContentType, "*");

		List<String> dumpFileDirectories;
		try {
			dumpFileDirectories = this.dumpfileDirectoryManager
					.getSubdirectories(directoryPattern);
		} catch (IOException e) {
			logger.error("Unable to access dump directory: " + e.toString());
			return Collections.emptyList();
		}

		List<MwDumpFile> result = new ArrayList<>();

		for (String directory : dumpFileDirectories) {
			String dateStamp = WmfDumpFile
					.getDateStampFromDumpFileDirectoryName(dumpContentType,
							directory);
			if (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) {
				WmfLocalDumpFile dumpFile = new WmfLocalDumpFile(dateStamp,
						this.projectName, dumpfileDirectoryManager,
						dumpContentType);
				if (dumpFile.isAvailable()) {
					result.add(dumpFile);
				} else {
					logger.error("Incomplete local dump file data. Maybe delete "
							+ dumpFile.getDumpfileDirectory()
							+ " to attempt fresh download.");
				}
			} // else: silently ignore directories that don't match
		}

		result.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));

		logger.info("Found " + result.size() + " local dumps of type "
				+ dumpContentType + ": " + result);

		return result;
	}

	/**
	 * Finds out which dump files of the given type are available for download.
	 * The result is a list of objects that describe the available dump files,
	 * in descending order by their date. Not all of the dumps included might be
	 * actually available.
	 *
	 * @return list of objects that provide information on available full dumps
	 */
	List<MwDumpFile> findDumpsOnline(DumpContentType dumpContentType) {
		List<String> dumpFileDates = findDumpDatesOnline(dumpContentType);

		List<MwDumpFile> result = new ArrayList<>();

		for (String dateStamp : dumpFileDates) {
			if (dumpContentType == DumpContentType.DAILY) {
				result.add(new WmfOnlineDailyDumpFile(dateStamp,
						this.projectName, this.webResourceFetcher,
						this.dumpfileDirectoryManager));
			} else if (dumpContentType == DumpContentType.JSON) {
				result.add(new JsonOnlineDumpFile(dateStamp, this.projectName,
						this.webResourceFetcher, this.dumpfileDirectoryManager));
			} else {
				result.add(new WmfOnlineStandardDumpFile(dateStamp,
						this.projectName, this.webResourceFetcher,
						this.dumpfileDirectoryManager, dumpContentType));
			}
		}

		logger.info("Found " + result.size() + " online dumps of type "
				+ dumpContentType + ": " + result);

		return result;
	}

	/**
	 * Finds out which dump files are available for download in a given
	 * directory. The result is a list of YYYYMMDD date stamps, ordered newest
	 * to oldest. The list is based on the directories or files found at the
	 * target location, without considering whether or not each dump is actually
	 * available.
	 *

	 * The implementation is rather uniform since all cases supported thus far
	 * use directory/file names that start with a date stamp. If the date would
	 * occur elsewhere or in another form, then more work would be needed.
	 *
	 * @param dumpContentType
	 *            the type of dump to consider
	 * @return list of date stamps
	 */
	List<String> findDumpDatesOnline(DumpContentType dumpContentType) {
		List<String> result = new ArrayList<>();
		try (InputStream in = this.webResourceFetcher
				.getInputStreamForUrl(WmfDumpFile.getDumpFileWebDirectory(
						dumpContentType, this.projectName))) {

			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(in, StandardCharsets.UTF_8));
			String inputLine;
			while ((inputLine = bufferedReader.readLine()) != null) {
				String dateStamp = "";
				if (inputLine.startsWith("
")) {
					// old format of HTML file lists
					dateStamp = inputLine.substring(27, 35);
				} else if (inputLine.startsWith("<a href=")) {
					// new Jan 2015 of HTML file lists
					dateStamp = inputLine.substring(9, 17);
				}
				if (dateStamp.matches(WmfDumpFileManager.DATE_STAMP_PATTERN)) {
					result.add(dateStamp);
				}
			}
			bufferedReader.close();
		} catch (IOException e) {
			logger.error("Failed to fetch available dump dates online.");
		}

		result.sort(Collections.reverseOrder());
		return result;
	}
}


text:
package org.olat.portfolio.ui.artefacts.collect;

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.impl.Form;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.generic.wizard.StepFormBasicController;
import org.olat.core.gui.control.generic.wizard.StepsEvent;
import org.olat.core.gui.control.generic.wizard.StepsRunContext;
import org.olat.portfolio.model.artefacts.AbstractArtefact;

/**
 * Description:

 * controller to let the user ensure that he has the copyright on this artefact
 *
 *

 * Initial Date: 28.07.2010

 *
 * @author Roman Haag, roman.haag@frentix.com, http://www.frentix.com
 */
public class EPCollectStepForm02 extends StepFormBasicController {

	private AbstractArtefact artefact;
	private MultipleSelectionElement crCheck;

	public EPCollectStepForm02(UserRequest ureq, WindowControl windowControl, Form form, StepsRunContext stepsRunContext, int layoutDefault,
			String customLayoutPageName, AbstractArtefact artefact) {
		super(ureq, windowControl, form, stepsRunContext, layoutDefault, customLayoutPageName);
		this.artefact = artefact;
		initForm(ureq);
	}

	/**
	 * @see org.olat.core.gui.control.generic.wizard.StepFormBasicController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer,
	 *      org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest)
	 */
	@Override
	protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
		setFormDescription("copyright.intro.text");

		String[] theKeys = new String[] { Boolean.TRUE.toString() };
		String[] theValues = new String[] { translate("copyright.yes") };
		crCheck = uifactory.addCheckboxesHorizontal("copyright.label", null, formLayout, theKeys, theValues, null);
		if (getFromRunContext("copyright.accepted") != null && (Boolean) getFromRunContext("copyright.accepted")) {
			crCheck.select(Boolean.TRUE.toString(), true);
		}
		//signature > 0 means, collection wizzard can be sure its from OLAT, < 0 means get an approval by user (the target value is the negative one)
		if (artefact.getSignature() > 0 ){
			crCheck.select(Boolean.TRUE.toString(), true);
		}
		crCheck.addActionListener(this, FormEvent.ONCHANGE);
	}

	/**
	 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#formInnerEvent(org.olat.core.gui.UserRequest,
	 *      org.olat.core.gui.components.form.flexible.FormItem,
	 *      org.olat.core.gui.components.form.flexible.impl.FormEvent)
	 */
	@Override
	protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
		super.formInnerEvent(ureq, source, event);
		if (source == crCheck) {
			validateAndSetError();
		}
	}

	/**
	 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#validateFormLogic(org.olat.core.gui.UserRequest)
	 */
	@Override
	protected boolean validateFormLogic(UserRequest ureq) {
		return super.validateFormLogic(ureq) && validateAndSetError();
	}

	private boolean validateAndSetError() {
		if (!crCheck.isSelected(0)	|| (getFromRunContext("copyright.accepted") != null && !(Boolean) getFromRunContext("copyright.accepted"))) {
			crCheck.setErrorKey("copyright.error", null);
			return false;
		} else {
			crCheck.showError(false);
			return true;
		}
	}

	/**
	 * @see org.olat.core.gui.control.generic.wizard.StepFormBasicController#formOK(org.olat.core.gui.UserRequest)
	 */
	@Override
	protected void formOK(UserRequest ureq) {
		// its accepted, as form has been validated before
		if (isUsedInStepWizzard()) {
			addToRunContext("copyright.accepted", true);
			fireEvent(ureq, StepsEvent.ACTIVATE_NEXT);
		} else {
			// if used outside steps wizzard, persist stuff here
		}
	}

	/**
	 * @see org.olat.core.gui.control.generic.wizard.StepFormBasicController#doDispose()
	 */
	@Override
	protected void doDispose() {
		// nothing
	}
}


text:
/*
 Created by Jonathan Nicholas

Listen for scroll
get window position
loop through all nav links
 get section based on link
 check the window position vs position of section
  add active class to section in window
 else
  remove active class

*/

(function(){
    $("#header").hide();
    $(document).on("scroll", checkLocation);

    // Check the location of widow position and compare to achor points
    function checkLocation(event){
        var headerOffset = ($(".navbar-toggle").is(":visible"))? $(".navbar-header").outerHeight() : $("#header").outerHeight();

        if ($(this).scrollTop() >= $("#intro").outerHeight() - headerOffset ) {
            $('#header').fadeIn();
        } else {
            $('#header').fadeOut();
        }

        var currentScrollPos = $(document).scrollTop() + headerOffset ;

        $("#myNavbar li a").each(function(){
            var currentLink = $(this);
            var linkSection = $(currentLink.attr("href"));

            if(linkSection.position().top  <= currentScrollPos  && linkSection.position().top + linkSection.outerHeight(true) > currentScrollPos ){
                currentLink.addClass("nav-active");
            }else{
                currentLink.removeClass("nav-active");
            }
        })
    }

    //Click event for nav links and arrow to scroll to anchor
    $('#myNavbar li a[href^="#"], .arrow-wrap').on('click', function (event) {
        event.preventDefault();
        var currentLink = $(this);
        var linkSection = $(currentLink.attr("href"));
        var headerOffset = ($(".navbar-toggle").is(":visible"))? $(".navbar-header").outerHeight() : $("#header").outerHeight();
        var linkSectionPos = linkSection.position().top - headerOffset;

        $("#myNavbar li a").removeClass("nav-active");
        currentLink.addClass("nav-active");
        $(document).off("scroll", checkLocation);

        $("#myNavbar").collapse('hide');

        $('html, body').stop().animate({
            'scrollTop': linkSectionPos
        }, 800, 'swing', function () {
            $(document).on("scroll", checkLocation);
            checkLocation();
        });

    });

})();


text:
namespace gpu {
class ContextSupport;
class GLInProcessContext;

namespace gles2 {
class GLES2Interface;
class GLES2Implementation;
struct ContextCreationAttribHelper;
}
}

namespace gpu_blink {

class GPU_BLINK_EXPORT WebGraphicsContext3DInProcessCommandBufferImpl
    : public WebGraphicsContext3DImpl {
 public:
  enum MappedMemoryReclaimLimit {
    kNoLimit = 0,
  };

  static scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl>
  CreateOffscreenContext(
      const gpu::gles2::ContextCreationAttribHelper& attributes);

  static scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> WrapContext(
      scoped_ptr<::gpu::GLInProcessContext> context,
      const gpu::gles2::ContextCreationAttribHelper& attributes);

  ~WebGraphicsContext3DInProcessCommandBufferImpl() override;

  size_t GetMappedMemoryLimit();

  bool InitializeOnCurrentThread();
  void SetLock(base::Lock* lock);

  ::gpu::ContextSupport* GetContextSupport();

  ::gpu::gles2::GLES2Implementation* GetImplementation() {
    return real_gl_;
  }

 private:
  WebGraphicsContext3DInProcessCommandBufferImpl(
      scoped_ptr<::gpu::GLInProcessContext> context,
      const gpu::gles2::ContextCreationAttribHelper& attributes,
      bool is_offscreen,
      gfx::AcceleratedWidget window);

  void OnContextLost();

  bool MaybeInitializeGL();

  // Used to try to find bugs in code that calls gl directly through the gl api
  // instead of going through WebGraphicsContext3D.
  void ClearContext();

  ::gpu::gles2::ContextCreationAttribHelper attributes_;

  bool is_offscreen_;
  // Only used when not offscreen.
  gfx::AcceleratedWidget window_;

  // The context we use for OpenGL rendering.
  scoped_ptr< ::gpu::GLInProcessContext> context_;
  // The GLES2Implementation we use for OpenGL rendering.
  ::gpu::gles2::GLES2Implementation* real_gl_;
};

}  // namespace gpu_blink

#endif  // GPU_BLINK_WEBGRAPHICSCONTEXT3D_IN_PROCESS_COMMAND_BUFFER_IMPL_H_


text:
import com.twilio.twiml.Conference;
import com.twilio.twiml.Dial;
import com.twilio.twiml.VoiceResponse;
import com.twilio.twiml.TwiMLException;

public class Example {
    public static void main(String[] args) {
        Conference conference = new Conference.Builder("SimpleRoom")
            .muted(true).build();
        Dial dial = new Dial.Builder().conference(conference).build();
        VoiceResponse response = new VoiceResponse.Builder().dial(dial).build();

        try {
            System.out.println(response.toXml());
        } catch (TwiMLException e) {
            e.printStackTrace();
        }
    }
}


text:
#include "tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.h"

#include "tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h"
#include "tensorflow/core/distributed_runtime/eager/eager_client.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/lib/strings/strcat.h"

namespace tensorflow {

namespace {

void DestroyRemoteTensorHandle(EagerContext* ctx, const string& remote_task,
                               uint64 context_id, uint64 op_id, int output_num,
                               bool ready) {
  if (ctx->GetContextId() != context_id) {
    // This means that this tensor was pointing to a remote device, which
    // has been changed out from under us. Simply return since there is
    // nothing we can do.
    return;
  }

  eager::EagerClient* eager_client;
  Status status = ctx->GetClient(remote_task, &eager_client);
  if (!status.ok()) {
    LOG(INFO) << "Unable to destroy remote tensor handle because the target "
              << remote_task << " is no longer available.";
    return;
  }

  std::unique_ptr<eager::EnqueueRequest> request(new eager::EnqueueRequest);
  request->set_context_id(context_id);

  auto* handle_to_decref = request->add_queue()->mutable_handle_to_decref();
  handle_to_decref->set_op_id(op_id);
  handle_to_decref->set_output_num(output_num);

  VLOG(3) << "Sending request to delete " << request->DebugString();
  std::unique_ptr<EagerNode> node(
      absl::make_unique<eager::DestroyTensorHandleNode>(std::move(request),
                                                        eager_client, ready));
  auto& executor = ctx->Executor();
  if (executor.Async()) {
    Status status = executor.AddOrExecute(std::move(node));
    if (!status.ok()) {
      LOG(ERROR) << "Unable to destroy remote tensor handles: "
                 << status.error_message();
    }
  } else {
    // This thread may still hold tensorflow::StreamingRPCState::mu_. We need
    // to send out the destroy request in a new thread to avoid deadlock.
    auto* released_node = node.release();
    (*ctx->runner())([ctx, released_node] {
      Status status =
          ctx->Executor().AddOrExecute(absl::WrapUnique(released_node));
      if (!status.ok()) {
        LOG(ERROR) << "Unable to destroy remote tensor handles: "
                   << status.error_message();
      }
    });
  }
}
}  // namespace

RemoteTensorHandleData::RemoteTensorHandleData(int64 op_id, int output_num,
                                               const TensorShape& shape,
                                               const string& remote_task,
                                               uint64 context_id,
                                               EagerContext* ctx)
    : op_id_(op_id),
      output_num_(output_num),
      shape_(shape),
      remote_task_(remote_task),
      context_id_(context_id),
      ctx_(ctx) {
  DCHECK(op_id_ >= 0 && output_num_ >= 0)
      << "Op ID and output num should be >= 0. Op ID: " << op_id
      << ", Output num: " << output_num;
  ctx->Ref();
}

RemoteTensorHandleData::~RemoteTensorHandleData() {
  DestroyRemoteTensorHandle(ctx_, remote_task_, context_id_, op_id_,
                            output_num_, /*ready=*/true);
  ctx_->Unref();
}

Status RemoteTensorHandleData::Tensor(const tensorflow::Tensor** t) const {
  return errors::Unavailable(
      "Unable to get a tensor for a remote device. Please copy the tensor "
      "handle to a local device using TFE_TensorHandleCopyToDevice");
}

Status RemoteTensorHandleData::TensorValue(tensorflow::TensorValue* t) {
  return errors::Unavailable(
      "Unable to get a tensor for a remote device. Please copy the tensor "
      "handle to a local device using TFE_TensorHandleCopyToDevice");
}

Status RemoteTensorHandleData::Shape(TensorShape* shape) const {
  *shape = shape_;

  return Status::OK();
}

Status RemoteTensorHandleData::NumDims(int* num_dims) const {
  *num_dims = shape_.dims();

  return Status::OK();
}

Status RemoteTensorHandleData::Dim(int dim_index, int64* dim) const {
  *dim = shape_.dim_size(dim_index);

  return Status::OK();
}

Status RemoteTensorHandleData::NumElements(int64* num_elements) const {
  *num_elements = shape_.num_elements();

  return Status::OK();
}

string RemoteTensorHandleData::DebugString() const {
  return strings::StrCat("RemoteTensorHandleData:", " op_id: ", op_id_,
                         " output_num: ", output_num_);
}

UnshapedRemoteTensorHandleData::UnshapedRemoteTensorHandleData(
    int64 op_id, int32 output_num, const string& remote_task, uint64 context_id,
    EagerContext* ctx)
    : op_id_(op_id),
      output_num_(output_num),
      delete_remote_tensor_(true),
      remote_task_(remote_task),
      context_id_(context_id),
      ctx_(ctx) {
  DCHECK(op_id_ >= 0 && output_num_ >= 0)
      << "Op ID and output num should be >= 0. Op ID: " << op_id
      << ", Output num: " << output_num;
  ctx->Ref();
}

UnshapedRemoteTensorHandleData::~UnshapedRemoteTensorHandleData() {
  if (delete_remote_tensor_) {
    DestroyRemoteTensorHandle(ctx_, remote_task_, context_id_, op_id_,
                              output_num_, /*ready=*/false);
  }
  ctx_->Unref();
}

Status UnshapedRemoteTensorHandleData::Tensor(
    const tensorflow::Tensor** t) const {
  return errors::Unavailable(
      "Unable to get a tensor for a remote handle. Please copy the tensor "
      "handle to a local device using TFE_TensorHandleCopyToDevice");
}

Status UnshapedRemoteTensorHandleData::TensorValue(tensorflow::TensorValue* t) {
  return errors::Unavailable(
      "Unable to get a tensor for a remote handle. Please copy the tensor "
      "handle to a local device using TFE_TensorHandleCopyToDevice");
}

Status UnshapedRemoteTensorHandleData::Shape(TensorShape* shape) const {
  return errors::Unavailable(
      "Unable to get shape information for an async remote handle. Please wait "
      "until it is ready");
}

Status UnshapedRemoteTensorHandleData::NumDims(int* num_dims) const {
  return errors::Unavailable(
      "Unable to get shape information for an async remote handle. Please wait "
      "until it is ready");
}

Status UnshapedRemoteTensorHandleData::Dim(int dim_index, int64* dim) const {
  return errors::Unavailable(
      "Unable to get shape information for an async remote handle. Please wait "
      "until it is ready");
}

Status UnshapedRemoteTensorHandleData::NumElements(int64* num_elements) const {
  return errors::Unavailable(
      "Unable to get shape information for an async remote handle. Please wait "
      "until it is ready");
}

string UnshapedRemoteTensorHandleData::DebugString() const {
  return strings::StrCat("UnshapedRemoteTensorHandleDat:", " op_id: ", op_id_,
                         " output_num: ", output_num_);
}

}  // namespace tensorflow


text:
import {Machine} from "../../models/Machine";
import {MachineState} from "../../models/MachineState";
import {LocalesService} from "../../services/LocalesService";
import {MachineService} from "../../services/MachineService";
import {StorageService} from "../../services/StorageService";
import {Component, EventEmitter, ChangeDetectorRef} from '@angular/core';
import {Modal, BSModalContext} from 'angular2-modal/plugins/bootstrap';
import {overlayConfigFactory} from "angular2-modal";
import {AddMachineComponent} from "../add-machine/add-machine.component";
import {UpdateMachineComponent} from "../update-machine/update-machine.component";
import {Response} from "@angular/http";
import {Technician} from "../../models/Technician";
import {Location} from "../../models/Location";

@Component({
  selector: 'list-machine',
  templateUrl: './list-machine.component.html',
  styleUrls: ['./list-machine.component.css']
})
export class ListMachineComponent {

  public listMachineLocales;

    // Component interaction data
  public machines : Machine[];
  public selections : boolean[];
  public numSelections: number = 0;

  public onCreatedMachine = AddMachineComponent.onCreatedMachine;
  public onDeletedMachine = new EventEmitter(true);

  constructor(
    public localesService: LocalesService,
    public machineService: MachineService,
    public store: StorageService,
    public modal: Modal,
    public cdr: ChangeDetectorRef
  ) {

    this.selections = [];
    this.machines = [];

    this.listMachineLocales = localesService.get_ListMachineComponent_Locales();

    this.onCreatedMachine.subscribe((created: boolean) => {this.getMachines()});

    this.onDeletedMachine.subscribe((deleted: boolean) => {
      this.getMachines();
      this.numSelections = 0;
      this.cdr.detectChanges();
    });

    this.getMachines();
  }

  /** Actions */

  public getMachines() {
    this.machineService.listMachines().subscribe(
      (response: Response) => {
        if (response.ok && response.json().success) {
          let data = response.json().data;

          this.machines = [];

          for (let i = 0; i < data.length; i++) {
            let machine =
              new Machine(
                new Location(data[i].location.name),
                data[i].type,
                data[i].state,
                //FIXME: Workaround until have the technician in the response
                new Technician(''),
                data[i].description
              );

            machine.id = data[i].id;

            this.machines.push(machine);
          }

          for (let i = 0; i < this.machines.length; i++)
            this.selections[i] = false;
        }

        else {
          //FIXME: Manage error
        }
      },
      (err) => {
        //FIXME: Manage error
      },
      () => {}
    );
  }

  public selectMachine(index: number) {

    if (this.selections[index] == false)
      this.numSelections += 1;

    else
      this.numSelections -= 1;

    this.selections[index] = !this.selections[index];
  }

  public addIssue() {
    let machinesSelected = this.getSelectedMachines();

    // TODO Completar
  }

  public deleteMachine() {
    let machinesSelected : Machine[] = this.getSelectedMachines();

    // Si no se han seleccionado maquinas avisa y sal
    if (machinesSelected.length == 0) {
      this.modal.alert().body(this.listMachineLocales.no_selected_machine).open();
      return;
    }

    // Pone el texto correspondiente al aviso de borrado de maquinas
    let bodyext= "";

    if (machinesSelected.length == 1) {
      bodyext = this.listMachineLocales.delete_a_machine;
    } else {
      bodyext = this.listMachineLocales.delete_machines;
    }

    // Muestra el aviso de confirmacion
    this.modal.confirm()
      .title(this.listMachineLocales.delete_confirm_title)
      .body(bodyext)
      .okBtn(this.listMachineLocales.delete_confirm_confirm_button)
      .cancelBtn(this.listMachineLocales.delete_confirm_cancel_button)
      .open()
      .then((resultPromise) => {
        resultPromise.result.then((result) => {
          // Aqui llega cuando el usuario pulsa el boton OPERATIVE

          let err : boolean = false;
          let deleteErr : boolean = false;
          let i : number = 0;
          let subscriptionStateClosed : boolean = true;

          while (i < machinesSelected.length) {
            this.machineService.deleteMachine(machinesSelected[i].id).subscribe(
              (deletedOK: Response) => {

                if (deletedOK.ok) {
                  let newMachinesList : Machine[] = [];
                  let newSelectionList : boolean[] = [];

                  for (let j = 0; j < machinesSelected.length; j++) {
                    for (let k = this.machines.length - 1; k >= 0; k--) {
                      if (this.machines[k].id !== machinesSelected[j].id) {
                        newMachinesList.push(this.machines[k]);
                        break;
                      }
                    }
                  }

                  for (let i = 0; i < newMachinesList.length; i++)
                    newSelectionList.push(false);

                  this.machines = newMachinesList;
                  this.selections = newSelectionList;
                }
                else
                  deleteErr = true;

              },
              (error) => {
                err = true;
              }
            );

            if (err) {
              this.modal.alert().body('No se han podido eliminar las máquinas. ¿Está conectado a internet?').open();
              break;
            }

            else if (deleteErr) {
              this.modal.alert().body('Ha habido un error en el servidor al intentar eliminar las máquinas.').open();
              break;
            }

            i++;
          }
        },
          () => {} // Aqui llega cuando pulsa cancel
        ).then(() => {this.onDeletedMachine.emit(true)});
      });
  }
  public addMachine() {
    this.modal.open(AddMachineComponent, overlayConfigFactory({ isBlocking: false }, BSModalContext));
  }

  public showMachineData(machine: Machine) {
    let addMachine = AddMachineComponent;
    this.modal.open(addMachine, overlayConfigFactory({ isBlocking: false }, BSModalContext));
  }

  /** Utility */

  private getSelectedMachines() : Machine[] {
    var machinesSelected : Machine[] = [];

    for (let i = 0 ; i < this.machines.length ; i++)
      if(this.selections[i])
        machinesSelected[machinesSelected.length] = this.machines[i];

    return machinesSelected;
  }

  public getMachineState(machineState : MachineState) : string {

    switch (machineState.toString().toUpperCase()) {
      case MachineState[MachineState.OPERATIVE]:
        return this.localesService.get_MachineStateModel_Locales().ok;

      case MachineState[MachineState.WAREHOUSE]:
        return this.localesService.get_MachineStateModel_Locales().almacenada;

      case MachineState[MachineState.OUT_OF_SERVICE]:
        return this.localesService.get_MachineStateModel_Locales().retirada;
    }
  }

  public updateMachineListCounter() {
    let machinesSelected = this.getSelectedMachines();

    if (machinesSelected.length == 1) {
      // FIXME Arreglar que el tecnico de la maquina no se añade automaticamente en el formulario
      this.modal.open(
        UpdateMachineComponent,
        overlayConfigFactory({
          isBlocking: false,
          machine: machinesSelected[0]
        }, BSModalContext ));

    }
    else if (machinesSelected.length == 0) {
      this.modal.alert().body(this.listMachineLocales.no_selected_machine).open();
    }
    else {
      this.modal.alert().body(this.listMachineLocales.update_machines).open();
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.gemstone.gemfire.compression (Apache Geode 1.0.0-incubating.M2)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.gemstone.gemfire.compression

Interfaces

Compressor

Classes

SnappyCompressor

Exceptions

CompressionException


text:
var mkvtools = require('../lib/mkvtools'),
    hashFiles = require('hash-files'),
    expect = require('expect.js'),
    path = require('path'),
    fs = require('fs');

describe('mkvtools', function() {
  describe('mkvinfo', function() {
    it('should provide an output on end', function(done) {
      var info = [];

      mkvtools.info(path.resolve(__dirname, 'assets/test-file.mkv'))
        .on('error', function(err) {
          done(new Error(err));
        })
        .on('data', function(chunk) {
          info.push(chunk);
        })
        .on('end', function() {
          var video = fs.readFileSync(path.resolve(__dirname, 'assets/test-file.nfo'));
          expect(Buffer.concat(info).toString()).to.equal(video.toString());
          done();
        })
        .run();
    });
  });

  describe('mkvextract', function() {
    it('should extract a video stream', function(done) {
      mkvtools.extract(path.resolve(__dirname, 'assets/test-file.mkv'))
        .mode('tracks')
        .addOutput('0', path.resolve(__dirname, 'assets/test-file-video.avi'))
        .on('error', function(err) {
          done(new Error(err));
        })
        .on('end', function() {
          var video = hashFiles.sync({files: [path.resolve(__dirname, 'assets/test-file-video.avi')]});
          expect(video).to.equal('ce0450d73114f9fe069a52f63d7ac5c08e70f231');
          done();
        })
        .run();
    });

    it('should emit an error when no mode was set', function(done) {
      mkvtools.extract(path.resolve(__dirname, 'mkvtools.js'))
        .on('error', function() {
          done();
        })
        .on('end', function() {
          done(new Error('mkvtools emitted an `end` event when an error was expected.'));
        })
        .run();
    });

    it('should emit an error when processing an invalid file', function(done) {
      mkvtools.extract(path.resolve(__dirname, 'mkvtools.js'))
        .mode('tracks')
        .on('error', function() {
          done();
        })
        .on('end', function() {
          done(new Error('mkvtools emitted an `end` event when an error was expected.'));
        })
        .run();
    });
  });
});


text:
package com.englishtown.vertx.jersey;

import io.vertx.core.*;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

/**
 * {@link JerseyVerticle} unit tests
 */
@RunWith(MockitoJUnitRunner.class)
public class JerseyVerticleTest {

    JerseyVerticle jerseyVerticle;
    JsonObject config = new JsonObject();

    @Mock
    Vertx vertx;
    @Mock
    Context context;
    @Mock
    JerseyServer jerseyServer;
    @Mock
    JerseyOptions options;
    @Mock
    Future<Void> startedResult;
    @Mock
    AsyncResult<HttpServer> asyncResult;
    @Captor
    ArgumentCaptor<Handler<AsyncResult<HttpServer>>> handlerCaptor;

    @Before
    public void setUp() {
        when(vertx.getOrCreateContext()).thenReturn(context);
        when(context.config()).thenReturn(config);
        jerseyVerticle = new JerseyVerticle(jerseyServer, options);
        jerseyVerticle.init(vertx, context);
    }

    @Test
    public void testStart() throws Exception {

        jerseyVerticle.start(startedResult);

        verify(startedResult, never()).complete();
        verify(startedResult, never()).fail(any(Throwable.class));

        verify(jerseyServer).init(any(JerseyOptions.class), handlerCaptor.capture());

        when(asyncResult.succeeded()).thenReturn(true).thenReturn(false);

        handlerCaptor.getValue().handle(asyncResult);
        verify(startedResult).complete();
        verify(startedResult, never()).fail(any(Throwable.class));

        handlerCaptor.getValue().handle(asyncResult);
        verify(startedResult).complete();
        verify(startedResult).fail(any(Throwable.class));

    }

}