text:
<?php     include("../common/header.php");   ?>
<!-- from http://www.ush.it/2009/02/08/php-filesystem-attack-vectors/ -->

<?php hint("will include the arg specified in the GET parameter \"library\", appends .php to end, escape with NULL byte %00"); ?>

<form action="/LFI-2/index.php" method="GET">
    <input type="text" name="library">
</form>

<?php
include("includes/".$_GET['library'].".php");
?>


text:
from django.shortcuts import get_object_or_404

from games.core.models import Game
from games.utils.decorators import render_to

@render_to('core/home.html')
def home(request):
    return {
        'games': Game.objects.all(),
    }

@render_to('core/game_details.html')
def game_details(request, game_id):
    game = get_object_or_404(Game, id=game_id)
    return {
        'game': game,
        'recent_scores': game.score_set.all().order_by('-play_date')[:10]
    }

redpajama_set_name: RedPajamaGithub


text:
.treeview ul{list-style:none;margin:0;padding:0}
.treeview div.hitarea{cursor:pointer;float:left;height:15px;margin-left:-15px;width:15px}
.treeview li{background:url(images/icons/tv-item.gif) 0 0 no-repeat;margin:0}
.treeview a.selected{background-color:#f2f2de}
#treecontrol{margin:1em 0}.treeview .hover{color:red;cursor:pointer}
.treeview .collapsable{background-image:url(images/icons/tv-collapsable.gif)}
.treeview .expandable{background-image:url(images/icons/tv-expandable.gif)}
.treeview .last{background-image:url(images/icons/tv-item-last.gif)}
.treeview .lastCollapsable{background-image:url(images/icons/tv-collapsable-last.gif)}
.treeview .lastExpandable{background-image:url(images/icons/tv-expandable-last.gif)}
.filetree li,.treeview li{padding:0 0 2px 18px !important}
.filetree span.folder,.filetree span.file{display:block;height:15px;padding-left:16px}
.filetree span.folder{background:url(images/icons/folder.gif) 0 0 no-repeat}
.filetree span.file{background:url(images/icons/file.gif) 0 0 no-repeat}


text:
#ifndef FILE_TRANSFER_DB_H
#define FILE_TRANSFER_DB_H

#include "condor_classad.h"
#include "reli_sock.h"

typedef struct
{
	const char *fullname; /* file name in the destination */
	filesize_t   bytes; /* size in bytes */
	time_t elapsed; /* elapsed seconds */
	char *daemon; /* deamon doing the download */
	ReliSock *sockp; /* associated socket for getting source info */
	time_t transfer_time;  /* epoch time when transfer is initiated */
	int delegation_method_id; /* 0 if it's not a delegation, 1 if it is */
} file_transfer_record;

void file_transfer_db(file_transfer_record *rp, ClassAd *ad);

#endif


text:
package com.ircclouds.irc.api.commands;

public class PartChanCmd implements ICommand
{
	private static final String PART_ID = "PART";

	private String channel;
	private String partMsg;

	public PartChanCmd(String aChannel, String aPartMsg)
	{
		channel = aChannel;
		partMsg = aPartMsg;
	}

	@Override
	public String asString()
	{
		return PART_ID + " " + channel + " :" + partMsg;
	}

}


text:
import { Reporter } from '@stryker-mutator/api/report';

export type StrictReporter = Required<Reporter>;


text:
import {FilterFilter} from './filters/filter.filter';
import {MomentFilter} from './filters/moment.filter';
import {CapitalizeFilter} from './filters/capitalize.filter';
import {HumanReadableFilter} from './filters/human_readable.filter';
import {TruncatCharactersFilter} from './filters/truncate_characters.filter';
import {TruncateWordsFilter} from './filters/truncate_words.filter';
import {TrustHtmlFilter} from './filters/trust_html.filter';
import {UcFirstFilter} from './filters/ucfirst.filter';

angular.module('app.filters')
	.filter('filter', FilterFilter)
	.filter('moment', MomentFilter)
	.filter('capitalize', CapitalizeFilter)
	.filter('humanReadable', HumanReadableFilter)
	.filter('truncateCharacters', TruncatCharactersFilter)
	.filter('truncateWords', TruncateWordsFilter)
	.filter('trustHtml', TrustHtmlFilter)
	.filter('ucfirst', UcFirstFilter);


text:
struct Obj {
  Obj();
  Obj(const Obj &);
  Obj(Obj &&);
  virtual ~Obj();
};

template <typename T>
struct StatusOr {
  StatusOr(const T &);
  StatusOr(T &&);
};

struct NonTemplate {
  NonTemplate(const Obj &);
  NonTemplate(Obj &&);
};

template <typename T>
T Make();

StatusOr<Obj> PositiveStatusOrConstValue() {
  const Obj obj = Make<Obj>();
  return obj;
  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
}

NonTemplate PositiveNonTemplateConstValue() {
  const Obj obj = Make<Obj>();
  return obj;
  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
}

Obj PositiveSelfConstValue() {
  const Obj obj = Make<Obj>();
  return obj;
  // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: constness of 'obj' prevents automatic move [performance-no-automatic-move]
}

// FIXME: Ideally we would warn here too.
NonTemplate PositiveNonTemplateLifetimeExtension() {
  const Obj &obj = Make<Obj>();
  return obj;
}

// FIXME: Ideally we would warn here too.
StatusOr<Obj> PositiveStatusOrLifetimeExtension() {
  const Obj &obj = Make<Obj>();
  return obj;
}

// Negatives.

StatusOr<Obj> Temporary() {
  return Make<const Obj>();
}

StatusOr<Obj> ConstTemporary() {
  return Make<const Obj>();
}

StatusOr<Obj> Nrvo() {
  Obj obj = Make<Obj>();
  return obj;
}

StatusOr<Obj> Ref() {
  Obj &obj = Make<Obj &>();
  return obj;
}

StatusOr<Obj> ConstRef() {
  const Obj &obj = Make<Obj &>();
  return obj;
}

const Obj global;

StatusOr<Obj> Global() {
  return global;
}

struct FromConstRefOnly {
  FromConstRefOnly(const Obj &);
};

FromConstRefOnly FromConstRefOnly() {
  const Obj obj = Make<Obj>();
  return obj;
}


text:
/// <reference path='IMatch.ts' />
/// <reference path='MatchAny.ts' />
/// <reference path='MatchValue.ts' />


text:
import DS from 'ember-data';

const { Model, attr } = DS;

export default Model.extend({
  defaultLocation: attr(),
  degree: attr("string"),
  firstName: attr("string"),
  lastName: attr("string"),
  photos: attr(),
  role: attr("string"),
  speciality: attr(),
  suffix: attr("string"),
  uid: attr("string")
});


text:
#ifndef CAFFE2_OPERATORS_OPERATOR_FALLBACK_H_
#define CAFFE2_OPERATORS_OPERATOR_FALLBACK_H_

#include "caffe2/core/common.h"
#include "caffe2/core/context.h"
#include "caffe2/core/context_gpu.h"
#include "caffe2/core/operator.h"
#include "caffe2/proto/caffe2.pb.h"

namespace caffe2 {

/**
 * @brief A templated class to allow one to wrap a CPU operator as an MKL
 * operator.
 *
 * This class can be used when one does not have the MKL implementation ready
 * yet for an operator. Essentially, what this op does is to automatically
 * deal with data copy for you. Plausibly, this causes a lot of overhead and
 * is not optimal, so you should use this operator mostly for quick prototyping
 * purpose.
 *
 * All the input and output of the original operator should be TensorCPU.
 *
 * Example usage: if you have a class MyMagicOp that is CPU based, and you use
 * the registration code
 *     REGISTER_CPU_OPERATOR(MyMagic, MyMagicOp);
 * to register the CPU side, you can create its corresponding MKL operator
 * (with performance hits of course) via
 *     REGISTER_MKL_OPERATOR(MyMagic,
 *                            MKLFallbackOp<MyMagicOp>);
 *
 * Advanced usage: if you want to have some specific outputs never copied, you
 * can use the SkipOutputCopy template argument to do that. For example, if
 * MyMagic produces two outputs and the first output is always going to live on
 * the CPU, you can do
 *     REGISTER_CUDA_OPERATOR(MyMagic,
 *                            MKLFallbackOp<MyMagicOp, SkipIndices<0>>);
 */
template <class CPUOp, typename SkipOutputCopy = SkipIndices<>>
class MKLFallbackOp final : public Operator<MKLContext> {
 public:
  USE_OPERATOR_FUNCTIONS(MKLContext);
  MKLFallbackOp(const OperatorDef& def, Workspace* ws)
      : Operator<MKLContext>(def, ws) {
    CAFFE_ENFORCE_EQ(def.device_option().device_type(), MKLDNN);
    OperatorDef base_def_(def);
    // base_def_ runs on CPU, so we will set its device option to CPU.
    base_def_.clear_device_option();
    base_def_.mutable_device_option()->set_device_type(CPU);
    // Set up the symbols for the local workspace.
    for (const string& name : def.input()) {
      local_input_blobs_.push_back(local_ws_.CreateBlob(name));
      CHECK_NOTNULL(local_input_blobs_.back());
    }
    base_op_.reset(new CPUOp(base_def_, &local_ws_));
    for (const string& name : def.output()) {
      local_output_blobs_.push_back(local_ws_.GetBlob(name));
      CHECK_NOTNULL(local_output_blobs_.back());
    }
  }

  bool RunOnDevice() override {
    for (int i = 0; i < InputSize(); ++i) {
      if (OperatorBase::InputIsType<MKLMemory<float>>(i)) {
        OperatorBase::Input<MKLMemory<float>>(i).CopyTo(
            local_input_blobs_[i]->template GetMutable<TensorCPU>());
      } else if (OperatorBase::InputIsType<MKLMemory<double>>(i)) {
        OperatorBase::Input<MKLMemory<double>>(i).CopyTo(
            local_input_blobs_[i]->template GetMutable<TensorCPU>());
      } else {
        VLOG(1) << "Input " << i << " is not MKLMemory. Skipping copy.";
        // Note(jiayq): This removes a const but conceptually
        // local_input_blobs will only be used as const blob input for the
        // base op so we are still fine.
        local_input_blobs_[i]->ShareExternal(
            const_cast<void*>(OperatorBase::Inputs()[i]->GetRaw()),
            OperatorBase::Inputs()[i]->meta());
      }
    }

    if (!base_op_->Run()) {
      LOG(ERROR) << "Base op run failed in MKLFallbackOp. Def: "
                 << ProtoDebugString(def());
      return false;
    }

    for (int i = 0; i < OutputSize(); ++i) {
      if (SkipOutputCopy::Contains(i)) {
        VLOG(1) << "Copy output: index " << i << " skipped.";
        continue;
      }
      CAFFE_ENFORCE(
          local_output_blobs_[i]->template IsType<TensorCPU>(),
          "MKL fallback op currently does not support non-TensorCPU "
          "output type who needs copying.");
      const auto& src = local_output_blobs_[i]->template Get<TensorCPU>();
      if (src.IsType<float>()) {
        Blob* dst = OperatorBase::OutputBlob(i);
        if (!dst->IsType<MKLMemory<float>>() ||
            dst->Get<MKLMemory<float>>().dims() != src.dims()) {
          dst->Reset(new MKLMemory<float>(src.dims());
        }
        dst->GetMutable<MKLMemory<float>>()->CopyFrom(src);
      } else if (src.IsType<double>()) {
        Blob* dst = OperatorBase::OutputBlob(i);
        if (!dst->IsType<MKLMemory<double>>() ||
            dst->Get<MKLMemory<double>>().dims() != src.dims()) {
          dst->Reset(new MKLMemory<double>(src.dims());
        }
        dst->GetMutable<MKLMemory<double>>()->CopyFrom(src);
      } else {
        CAFFE_THROW("MKLMemory only supports float and double.");
      }
    }
    return true;
  }

 protected:
  Workspace local_ws_;
  vector<Blob*> local_input_blobs_;
  vector<Blob*> local_output_blobs_;
  std::unique_ptr<CPUOp> base_op_;
};

} // namespace caffe2

#endif // CAFFE2_OPERATORS_OPERATOR_FALLBACK_H_


text:
package com.linkedin.thirdeye.client.diffsummary;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.Test;

public class HierarchyNodeTest {

  // Since HierarchyNode has cyclic reference between current node and parent node, the toString() will encounter
  // overflowStack exception if it doesn't take care of the cyclic reference carefully.
  @Test
  public void testToString() {
    Row root = new Row(new Dimensions(), new DimensionValues());
    HierarchyNode rootNode = new HierarchyNode(root);

    Row child = new Row(new Dimensions(Collections.singletonList("country")),
        new DimensionValues(Collections.singletonList("US")), 20, 30);
    HierarchyNode childNode = new HierarchyNode(1, 0, child, rootNode);

    childNode.toString();
  }

  @Test
  public void testSimpleEquals() throws Exception {
    Row root1 = new Row(new Dimensions(), new DimensionValues());
    HierarchyNode rootNode1 = new HierarchyNode(root1);

    Row root2 = new Row(new Dimensions(), new DimensionValues());
    HierarchyNode rootNode2 = new HierarchyNode(root2);

    Assert.assertEquals(rootNode1, rootNode2);
    Assert.assertTrue(HierarchyNode.equalHierarchy(rootNode1, rootNode2));

    Row root3 = new Row(new Dimensions(Collections.singletonList("country")),
        new DimensionValues(Collections.singletonList("US")));
    HierarchyNode rootNode3 = new HierarchyNode(root3);
    Assert.assertNotEquals(rootNode1, rootNode3);
  }

  @Test
  public void testHierarchicalEquals() throws Exception {
    HierarchyNode rootNode1 = buildHierarchicalNodes();
    HierarchyNode rootNode2 = buildHierarchicalNodes();

    Assert.assertTrue(HierarchyNode.equalHierarchy(rootNode1, rootNode2));
  }

  /**
   * Hierarchy 1:
   *      A
   *     / \
   *    B  C
   *
   * Hierarchy 2:
   *      A
   *
   * Failed because structure difference.
   */
  @Test
  public void testHierarchicalEqualsFail1() {
    HierarchyNode rootNode1 = buildHierarchicalNodes();

    Row rootRow = new Row(new Dimensions(), new DimensionValues(), 30, 45);
    HierarchyNode rootNode2 = new HierarchyNode(rootRow);

    Assert.assertEquals(rootNode1, rootNode2);
    Assert.assertFalse(HierarchyNode.equalHierarchy(rootNode1, rootNode2));
  }

  /**
   * Hierarchy 1:
   *      A
   *     / \
   *    B  C
   *
   * Hierarchy 2:
   *      A'
   *
   * Failed because data difference.
   */
  @Test
  public void testHierarchicalEqualsFail2() throws Exception {
    HierarchyNode rootNode1 = buildHierarchicalNodes();

    Row rootRow = new Row(new Dimensions(), new DimensionValues(), 20, 15);
    HierarchyNode rootNode2 = new HierarchyNode(rootRow);

    Assert.assertNotEquals(rootNode1, rootNode2);
    Assert.assertFalse(HierarchyNode.equalHierarchy(rootNode1, rootNode2));
  }

  /**
   * Hierarchy 1:
   *      A
   *     ^ ^
   *     / \
   *    v  v
   *    B  C
   *
   * Hierarchy 2:
   *      A
   *      ^
   *       \
   *       v
   *       C
   *
   * Failed because Hierarchy 2's A doesn't have a reference to B.
   */
  @Test
  public void testHierarchicalEqualsFail3() throws Exception {
    HierarchyNode rootNode1 = buildHierarchicalNodes();

    List<List<Row>> rows = buildHierarchicalRows();
    // Root level
    Row rootRow = rows.get(0).get(0);
    HierarchyNode rootNode2 = new HierarchyNode(rootRow);

    // Level 1
    Row INRow = rows.get(1).get(1);
    HierarchyNode INNode = new HierarchyNode(1, 1, INRow, rootNode2);

    Assert.assertEquals(rootNode1, rootNode2);
    Assert.assertFalse(HierarchyNode.equalHierarchy(rootNode1, rootNode2));
  }

  private List<List<Row>> buildHierarchicalRows() {
    List<List<Row>> hierarchicalRows = new ArrayList<>();
    // Root level
    List<Row> rootLevel = new ArrayList<>();
    rootLevel.add(new Row(new Dimensions(), new DimensionValues(), 30, 45));
    hierarchicalRows.add(rootLevel);

    // Level 1
    List<Row> level1 = new ArrayList<>();
    Row row1 = new Row(new Dimensions(Collections.singletonList("country")),
        new DimensionValues(Collections.singletonList("US")), 20, 30);
    level1.add(row1);

    Row row2 = new Row(new Dimensions(Collections.singletonList("country")),
        new DimensionValues(Collections.singletonList("IN")), 10, 15);
    level1.add(row2);

    hierarchicalRows.add(level1);

    return hierarchicalRows;
  }

  private HierarchyNode buildHierarchicalNodes() {
    List<List<Row>> rows = buildHierarchicalRows();
    // Root level
    Row rootRow = rows.get(0).get(0);
    HierarchyNode rootNode = new HierarchyNode(rootRow);

    // Level 1
    Row USRow = rows.get(1).get(0);
    HierarchyNode USNode = new HierarchyNode(1, 0, USRow, rootNode);

    Row INRow = rows.get(1).get(1);
    HierarchyNode INNode = new HierarchyNode(1, 1, INRow, rootNode);

    return rootNode;
  }
}


text:
    {% include navigation.html %}

{{ page.title }}


text:
package trader.exchanges;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.bitfinex.v1.service.polling.BitfinexTradeService;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.Order;
import com.xeiam.xchange.dto.trade.LimitOrder;
import com.xeiam.xchange.dto.trade.MarketOrder;
import com.xeiam.xchange.service.polling.marketdata.PollingMarketDataService;
import eu.verdelhan.ta4j.*;
import trader.TickListener;
import trader.exchanges.utils.BitfinexUtils;
import trader.strategies.BasicStrategy;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jkahn on 12/25/15.
 *
 * @author Joshua Kahn
 */
public class BitfinexTrader implements TickListener {

    /**
     * The currency pair that {@link trader.exchanges.BitfinexTrader this}
     * trader will be using.
     */
    private static final CurrencyPair CURRENCY_PAIR = CurrencyPair.BTC_USD;

    /**
     * A constant value to represent 95%.
     */
    private static final BigDecimal NINETY_FIVE_PERCENT = new BigDecimal("0" +
            ".95");

    /**
     * A constant that represents the minimum order value for Bitfinex.
     */
    private static final BigDecimal MINIMUM_ORDER = new BigDecimal("0.01");

    /**
     * The strategy to use.
     */
    private static Strategy strategy;

    /**
     * The time series for {@link eu.verdelhan.ta4j.Strategy strategy}.
     */
    private static TimeSeries timeSeries;

    /**
     * A state variable to represent the last order that was made.
     */
    private static LastOrder lastOrder;

    private enum LastOrder {
        BOUGHT, SELL, NO_TRADES
    }

    private static BitfinexTradeService bitfinexTradeService;

    private static PollingMarketDataService marketDataService;

    private static Exchange bitfinex;

    private static TradingRecord tradingRecord;

    /**
     * Singleton instance of {@link trader.exchanges.BitfinexTrader this}.
     */
    private static BitfinexTrader INSTANCE;

    private BitfinexTrader() {
        if (BitfinexTrader.INSTANCE != null) {
            throw new InstantiationError("Creating of this object is not " +
                    "allowed.");
        }
        INSTANCE = this;
    }

    public void runTrader() {
        try {
            bitfinex = BitfinexUtils.createExchange();
            marketDataService = bitfinex.getPollingMarketDataService();
            bitfinexTradeService = new BitfinexTradeService(bitfinex);
        } catch (IOException e) {
            e.printStackTrace();
        }
        lastOrder = LastOrder.NO_TRADES;
        tradingRecord = new TradingRecord();
        List<Tick> tickList = new ArrayList<>();
        timeSeries = new TimeSeries("Bitfinex", tickList);
        timeSeries.setMaximumTickCount(BasicStrategy.TICKS_NEEDED);

        BitfinexTickGenerator.addListener(this);
    }

    public void stopTrader() {
        INSTANCE = null;
        BitfinexTickGenerator.removeListener(this);
    }

    /**
     * Gets the singleton instance of this. If this doesn't exist, create a
     * new instance and return it.
     *
     * @return the singleton instance of this
     */
    public static BitfinexTrader getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new BitfinexTrader();
        }
        return INSTANCE;
    }

    /**
     * Cancel any existing orders.
     *
     * @return true iff the orders were successfully canceled
     */
    private boolean cancelOrders() {
        try {
            List<LimitOrder> orders = bitfinexTradeService.getOpenOrders
                    ().getOpenOrders();
            for (LimitOrder order : orders) {
                bitfinexTradeService.cancelOrder(order.getId());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * Goes (almost) all in, either for a bid or ask order. Buys and sells
     * 95% of balance in either direction.
     *
     * @param type BID or ASK, depending
     * @return the balance used to buy in
     */
    private BigDecimal getAmountToOrder(Order.OrderType type) {
        BigDecimal toOrder;
        try {
            if (type == Order.OrderType.ASK) {
                // Sell BTC
                // Get the number of BTC in the wallet, then get 95% of the
                // value
                toOrder = bitfinex.getPollingAccountService()
                        .getAccountInfo().getWallet("BTC").getBalance();
                toOrder = toOrder.multiply(NINETY_FIVE_PERCENT);
            } else {
                // Buy BTC
                // Get the amount of USD in the wallet
                toOrder = bitfinex.getPollingAccountService()
                        .getAccountInfo().getWallet("USD").getBalance();
                // Convert the amount of USD to BTC (using best current ASK
                // price), then get 95% of the value
                toOrder = toOrder.divide(marketDataService.getTicker
                        (CURRENCY_PAIR).getBid(), RoundingMode.FLOOR);
                toOrder = toOrder.multiply(NINETY_FIVE_PERCENT);
            }
            if (toOrder.compareTo(MINIMUM_ORDER) < 0) {
                return BigDecimal.ZERO;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return BigDecimal.ZERO;
        }
        return toOrder;
    }

    /**
     * A method to actually place the order.
     *
     * @param order the order to place.
     */
    private void placeOrder(MarketOrder order) {
        try {
            bitfinexTradeService.placeMarketOrder(order);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void tickReceived(Tick tick) {
        timeSeries.addTick(tick);

        /*
         * Trader is still warming up DO NOT TRADE
         *
         * This needs to be done because as of yet, the program isn't
         * connected to a massive database to look trades
         * up in.
         */
        if (timeSeries.getTickCount() < BasicStrategy.TICKS_NEEDED) {
            System.out.println("Received " + timeSeries.getTickCount() +
                    "/" + BasicStrategy.TICKS_NEEDED + " " +
                    "needed ticks.");
            return;
        }

        if (strategy == null) {
            strategy = new BasicStrategy(timeSeries);
        }

        // There's a new tick
        // Therefore we should re-evaluate the strategy
        int endIndex = timeSeries.getEnd();
        if (strategy.shouldEnter(endIndex)) {
            if (lastOrder != LastOrder.BOUGHT) {
                lastOrder = LastOrder.BOUGHT;
                cancelOrders();
                // Buy Bitcoins
                BigDecimal amount = getAmountToOrder(Order.OrderType.BID);
                if (amount.compareTo(MINIMUM_ORDER) >= 0) {
                    System.out.println("Entered the position.");
                    MarketOrder order = new MarketOrder(Order.OrderType.BID,
                            amount, CURRENCY_PAIR);
                    placeOrder(order);
                    tradingRecord.enter(endIndex, tick.getClosePrice(),
                            Decimal.valueOf(amount.toString()));
                }
            }
        } else if (strategy.shouldExit(endIndex)) {
            if (lastOrder != LastOrder.SELL) {
                lastOrder = LastOrder.SELL;
                cancelOrders();
                // Sell Bitcoins
                BigDecimal amount = getAmountToOrder(Order.OrderType.ASK);
                if (amount.compareTo(MINIMUM_ORDER) >= 0) {
                    System.out.println("Exited the position.");
                    MarketOrder order = new MarketOrder(Order.OrderType.ASK,
                            amount, CURRENCY_PAIR);
                    placeOrder(order);
                    tradingRecord.exit(endIndex, tick.getClosePrice(),
                            Decimal.valueOf(amount.toString()));
                }
            }
        }
    }

}


text:
//------------------------------------------------------------------------------
// <copyright file="UInt32Converter.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 */
namespace System.ComponentModel {
    using Microsoft.Win32;
    using System.Diagnostics;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Runtime.Remoting;
    using System.Runtime.Serialization.Formatters;
    using System.Security.Permissions;

    /// <devdoc>
    ///    <para>Provides a type converter to convert 32-bit unsigned integer objects to and
    ///       from various other representations.</para>
    /// </devdoc>
    [HostProtection(SharedState = true)]
    public class UInt32Converter : BaseNumberConverter {

        /// <devdoc>
        /// The Type this converter is targeting (e.g. Int16, UInt32, etc.)
        /// </devdoc>
        internal override Type TargetType {
                get {
                    return typeof(UInt32);
                }
        }

        /// <devdoc>
        /// Convert the given value to a string using the given radix
        /// </devdoc>
        internal override object FromString(string value, int radix) {
                return Convert.ToUInt32(value, radix);
        }

        /// <devdoc>
        /// Convert the given value to a string using the given formatInfo
        /// </devdoc>
        internal override object FromString(string value, NumberFormatInfo formatInfo) {
                return UInt32.Parse(value, NumberStyles.Integer, formatInfo);
        }

        /// <devdoc>
        /// Convert the given value to a string using the given CultureInfo
        /// </devdoc>
        internal override object FromString(string value, CultureInfo culture){
                 return UInt32.Parse(value, culture);
        }

        /// <devdoc>
        /// Convert the given value from a string using the given formatInfo
        /// </devdoc>
        internal override string ToString(object value, NumberFormatInfo formatInfo) {
                return ((UInt32)value).ToString("G", formatInfo);
        }

    }
}


text:
<?php
namespace Clusterpoint\Contracts;

interface ConnectionInterface
{
    public function resetSelf();
}


text:
    <form novalidate class="search-form" ng-submit="applyFilters()">

                <input class="search-text" type="text" ng-model="filters.zipcode"/>

                Academia
                <input id="input-academy" type="radio" ng-model="filters.type" value="academy"/>

                Personal Trainer
                <input id="input-trainer" type="radio" ng-model="filters.type" value="trainer"/>

                    {{groupFilter.name}}

                    Limpar

    </form>

            <button ng-click="addFilter(groupFilter.type, option.slug)" ng-repeat="option in groupFilter.options">
                {{ option.name }}
            </button>


text:
- Updated the Docker image to: *demisto/python3:3.10.8.37233*.
##### Expanse Expander Feed
- Updated the Docker image to: *demisto/python3:3.10.8.37233*.


text:
title: "drpx-updateable"
tags:
  - angularjs-extensions
  - services
  - projects
  - angularjs
  - updateable
  - component
  - npm
  - bower
  - contributions
date: 2015-02-12
source: https://github.com/drpicox/drpx-updateable
description: >
    Small library with a service
    to implement
    the MVS architecture with updateable events.
snippet: |
    ```javascript
    app.factory('yourService', function(drpxUpdateable) {
        var service = {
            change: function(...) {
                ...
                service.update();
            },
            update: drpxUpdateable('yourUpdate')
        }
        return service;
    }
    ```
---

## Setup

Install the dependence with bower or npm:

```bash
$ npm install --save drpx-updateable
```

Include the javascript library into your application.

```html
<script src="bower_components/drpx-updateable/drpx-updateable.js"></script>
```

Add the module to your module.

```javascript
angular.module('yourModule', [ 'drpxUpdateable' ]);
```

See Github project for more information about usage.


text:
(function () {
  'use strict';

  // ==================== Public ===============================================

  var freefocus = window.freefocus = {
    move: move,

    getDimensions: getDimensions,

    populateDimensionsCache: populateDimensionsCache,
    invalidateDimensionsCache: invalidateDimensionsCache,

    setHint: setHint,
    clearHint: clearHint,

    // Will be set later in code
    configuration: undefined
  };

  function getDimensions(element) {
    if (!element) {
      console.error('Can\'t get freefocus dimensions for nothing');
      return { left: 0, top: 0, width: 0, height: 0 };
    }

    var box = getElementBox(element, true, false);
    return {
      left: box.x1,
      top: box.y1,
      width: box.x2 - box.x1,
      height: box.y2 - box.y1
    };
  }

  function populateDimensionsCache(element) {
    if (!element) {
      console.error('Can\'t populate freefocus cache for nothing');
      return;
    }
    getElementBox(element, true, true);
  }

  function invalidateDimensionsCache(element) {
    if (!element) {
      console.error('Can\'t invalidate freefocus cache for nothing');
      return;
    }
    delete element.freefocusDimensions;
  }

  function clearHint(element) {
    if (!element) {
      console.error('Can\'t clear freefocus hint for nothing');
      return;
    }
    for (var move in directions) {
      element.removeAttribute('data-nav-' + move);
    }
  }

  function setHint(element, hint, overwrite) {
    if (!element) {
      console.error('Can\'t set freefocus hints for nothing');
      return;
    }
    for (var move in hint) {
      if (overwrite !== false || !element.getAttribute('data-nav-' + move)) {
        element.setAttribute('data-nav-' + move, hint[move]);
      }
    }
  }

  function move(fromElement, direction, candidatesFn) {
    var target;

    if (!fromElement) {
      console.error('Can\'t move freefocus from nothing');
      return target;
    }

    if (!directions[direction]) {
      console.error('Unknown freefocus direction "' + direction + '"');
      return target;
    }

    if (!candidatesFn) {
      console.error('Can\'t move freefocus without candidates function');
      return target;
    }

    updateFocusPoint(fromElement, direction, configuration.cache);

    var targets = findTargetsFromHint(fromElement, direction, candidatesFn);
    if (targets) {
      if (targets.length <= 1) {
        // If targets is empty, return nothing, it's the result of a `none` hint
        target = targets[0];
      } else {
        // Find the nearest target from ones set by hint
        var targetsFn = function () { return targets; };
        target = findNearestTarget(fromElement, direction, targetsFn);
      }
    } else {
      // If no hint found, find the nearest target from all available candidates
      target = findNearestTarget(fromElement, direction, candidatesFn);
    }

    if (target) {
      moveFocusPoint(target, direction, configuration.cache);
    }

    return target;
  }

  var directions = {
    left: {
      toUnified: function (coords) {
        return { fwd: -coords.x, ort: -coords.y };
      },
      fromUnified: function (coords) {
        return { x: -coords.fwd, y: -coords.ort };
      }
    },
    right: {
      toUnified: function (coords) {
        return { fwd:  coords.x, ort:  coords.y };
      },
      fromUnified: function (coords) {
        return { x:  coords.fwd, y:  coords.ort };
      }
    },
    up: {
      toUnified: function (coords) {
        return { fwd: -coords.y, ort:  coords.x };
      },
      fromUnified: function (coords) {
        return { x:  coords.ort, y: -coords.fwd };
      }
    },
    down: {
      toUnified: function (coords) {
        return { fwd:  coords.y, ort: -coords.x };
      },
      fromUnified: function (coords) {
        return { x: -coords.ort, y:  coords.fwd };
      }
    }
  };

  var hintSources = [
    function (el, direction) {
      return el.getAttribute('data-nav-' + direction);
    }
  ];

  var configuration = freefocus.configuration = {
    maxDistance: Infinity,
    cache: false,

    directions: directions,
    hintSources: hintSources
  };

  // ==================== Private ==============================================

  var focusPoint = {
    freefocusId: -1
  };

  function findTargetsFromHint(element, direction, candidatesFn) {
    var hint = firstMatch(hintSources, function (source) {
      var hint = source(element, direction);
      return hint && hint.trim();
    });

    if (hint) {
      hint = hint.trim();
    }

    if (!hint) {
      return undefined;
    }

    if (hint === 'none') {
      // Empty set => no movement
      return [];
    }

    // Allow to set explicit order by enumerating selectors
    return firstMatch(hint.split(/\s*;\s*/), function (hintSelector) {
      if (!hintSelector) {
        // A `hint` with a trailing `;` creates an empty hintSelector.
        return undefined;
      }
      var candidates = candidatesFn(hintSelector);

      if (!candidates.length) {
        // Avoid firstMatch ending with an empty array
        return undefined;
      }
      return candidates;
    });
  }

  function findNearestTarget(fromElement, direction, candidatesFn) {
    var fromBox = boxInDirection(getElementBox(fromElement, configuration.cache, configuration.cache), direction);

    var candidates = candidatesFn();
    var minDistance = configuration.maxDistance;

    var target;

    for (var i = 0, len = candidates.length; i < len; i++) {
      var candidate = candidates[i];

      // Skip currently focused element
      if (candidate === fromElement) {
        continue;
      }

      var toBox = boxInDirection(getElementBox(candidate, configuration.cache, configuration.cache), direction);

      // Skip elements that are not in the direction of movement
      if (toBox.fwd1 < fromBox.fwd2) {
        continue;
      }

      var dist = distance(fromBox, toBox);

      if (dist < minDistance) {
        target = candidate;
        minDistance = dist;
      }
    }

    return target;
  }

  function distance(fromBox, toBox) {
    var fromPoint = focusPoint.updatedInDirection;

    var toPoint = {
      fwd: toBox.fwd1,
      ort: bound(fromPoint.ort, toBox.ort1, toBox.ort2)
    };

    var fwdDist = Math.abs(toPoint.fwd - fromPoint.fwd);
    var ortDist = Math.abs(toPoint.ort - fromPoint.ort);

    // The Euclidian distance between the current focus point position and
    // its potential position in the candidate.
    // If the two positions have the same coordinate on the axis orthogonal
    // to the navigation direction, dotDist is forced to 0 in order to favor
    // elements in direction of navigation
    var dotDist;
    if (toPoint.ort === fromPoint.ort) {
      dotDist = 0;
    } else {
      dotDist = Math.sqrt(fwdDist * fwdDist + ortDist * ortDist);
    }

    // The overlap between the opposing edges of currently focused element and the candidate.
    // Elements are rewarded for having high overlap with the currently focused element.
    var overlap = boxOverlap(fromBox, toBox);

    return dotDist + fwdDist + 2 * ortDist - Math.sqrt(overlap);
  }

  function boxOverlap(box1, box2) {
    var orts = {
      ort1: box1.ort1,
      ort2: box1.ort2
    };

    if (box2.ort1 > orts.ort1)
      orts.ort1 = box2.ort1;
    if (box2.ort2 < orts.ort2)
      orts.ort2 = box2.ort2;

    var result = orts.ort2 - orts.ort1;
    if (result < 0)
      result = 0;

    return result;
  }

  function computeElementBox(el) {
    var rect = el.getBoundingClientRect();
    return {
      x1: rect.left,
      y1: rect.top,
      x2: rect.right,
      y2: rect.bottom
    };
  }

  function getElementBox(element, readCache, writeCache) {
    var box;

    if (readCache) {
      box = element.freefocusDimensions;
    }
    if (!box) {
      box = computeElementBox(element);
    }
    if (writeCache) {
      element.freefocusDimensions = box;
    }

    return box;
  }

  function boxInDirection(box, direction) {
    var p1 = directions[direction].toUnified({ x: box.x1, y: box.y1 });
    var p2 = directions[direction].toUnified({ x: box.x2, y: box.y2 });
    return {
      fwd1: Math.min(p1.fwd, p2.fwd),
      ort1: Math.min(p1.ort, p2.ort),
      fwd2: Math.max(p1.fwd, p2.fwd),
      ort2: Math.max(p1.ort, p2.ort)
    };
  }

  function boxCoordsToClient(coords, box) {
    return {
      x: coords.x + box.x1,
      y: coords.y + box.y1
    };
  }

  function clientCoordsToBox(coords, box) {
    return {
      x: coords.x - box.x1,
      y: coords.y - box.y1
    };
  }

  function updateFocusPoint(element, direction, cache) {
    var box = getElementBox(element, cache, cache);

    // If the element wasn't focused by freefocus, calculate it
    if (!element.freefocusId || element.freefocusId !== focusPoint.elementId) {
      focusPoint.elementId = assignId(element);
      focusPoint.box = {
        x: (box.x2 - box.x1) / 2,
        y: (box.y2 - box.y1) / 2
      };
    }
    focusPoint.updatedInDirection = directions[direction].toUnified(boxCoordsToClient(focusPoint.box, box));
    focusPoint.updatedInDirection.fwd = boxInDirection(box, direction).fwd2;
  }

  function moveFocusPoint(element, direction, cache) {
    var box = getElementBox(element, cache, cache);

    // Hold reference only for numeric id instead of a full DOM node
    focusPoint.elementId = assignId(element);

    var boxInDir = boxInDirection(box, direction);
    var movedInDirection = {
      fwd: boxInDir.fwd1,
      ort: bound(focusPoint.updatedInDirection.ort, boxInDir.ort1, boxInDir.ort2)
    };
    focusPoint.box = clientCoordsToBox(directions[direction].fromUnified(movedInDirection), box);
  }

  // ==================== Utilities ============================================

  function bound(val, min, max) {
    return Math.min(Math.max(val, min), max);
  }

  function firstMatch(array, fn) {
    for (var i = 0, len = array.length; i < len; i++) {
      var result = fn(array[i]);
      if (result) {
        return result;
      }
    }
  }

  var lastElementId = 0;
  function assignId(element) {
    var elementId = element.freefocusId;
    if (!elementId) {
      elementId = element.freefocusId = ++lastElementId;
    }
    return elementId;
  }
})();


text:
var Scroller = require('./Scroller');
//var ScrollBar = require('./ScrollBar');

/**
 * ScrollContainer (not implemented yet)
 *
 * @class ScrollContainer
 * @extends GOWN.Scroller
 * @memberof GOWN
 * @constructor
 * @param [theme] theme for the scroll container {GOWN.Theme}
 */
function ScrollContainer(theme) {
    Scroller.call(this, theme);
}

ScrollContainer.prototype = Object.create( Scroller.prototype );
ScrollContainer.prototype.constructor = ScrollContainer;
module.exports = ScrollContainer;


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.Storage;
using Orleans.EventSourcing.Common;

namespace Orleans.EventSourcing.CustomStorage
{
    /// <summary>
    /// A log consistency adaptor that uses the user-provided storage interface <see cref="ICustomStorageInterface{T,E}"/>.
    /// This interface must be implemented by any grain that uses this log view adaptor.
    /// </summary>
    /// <typeparam name="TLogView">log view type</typeparam>
    /// <typeparam name="TLogEntry">log entry type</typeparam>
    internal class CustomStorageAdaptor<TLogView, TLogEntry> : PrimaryBasedLogViewAdaptor<TLogView, TLogEntry, SubmissionEntry<TLogEntry>>
        where TLogView : class, new()
        where TLogEntry : class
    {
        /// <summary>
        /// Initialize a new instance of CustomStorageAdaptor class
        /// </summary>
        public CustomStorageAdaptor(ILogViewAdaptorHost<TLogView, TLogEntry> host, TLogView initialState,
            ILogConsistencyProtocolServices services, string primaryCluster)
            : base(host, initialState, services)
        {
            if (!(host is ICustomStorageInterface<TLogView, TLogEntry>))
                throw new BadProviderConfigException("Must implement ICustomStorageInterface<TLogView,TLogEntry> for CustomStorageLogView provider");
            this.primaryCluster = primaryCluster;
        }

        private string primaryCluster;

        private TLogView cached;
        private int version;

        /// <inheritdoc/>
        protected override TLogView LastConfirmedView()
        {
            return cached;
        }

        /// <inheritdoc/>
        protected override int GetConfirmedVersion()
        {
            return version;
        }

        /// <inheritdoc/>
        protected override void InitializeConfirmedView(TLogView initialstate)
        {
            cached = initialstate;
            version = 0;
        }

        /// <inheritdoc/>
        protected override bool SupportSubmissions
        {
            get
            {
                return true;
            }
        }

        /// <inheritdoc/>
        protected override SubmissionEntry<TLogEntry> MakeSubmissionEntry(TLogEntry entry)
        {
           // no special tagging is required, thus we create a plain submission entry
           return new SubmissionEntry<TLogEntry>() { Entry = entry };
        }

        [Serializable]
        [GenerateSerializer]
        internal sealed class ReadRequest : ILogConsistencyProtocolMessage
        {
            [Id(0)]
            public int KnownVersion { get; set; }
        }

        [Serializable]
        [GenerateSerializer]
        internal sealed class ReadResponse<ViewType> : ILogConsistencyProtocolMessage
        {
            [Id(0)]
            public int Version { get; set; }

            [Id(1)]
            public ViewType Value { get; set; }
        }

        /// <inheritdoc/>
        protected override Task<ILogConsistencyProtocolMessage> OnMessageReceived(ILogConsistencyProtocolMessage payload)
        {
            var request = (ReadRequest) payload;

            var response = new ReadResponse<TLogView>() { Version = version };

            // optimization: include value only if version is newer
            if (version > request.KnownVersion)
                response.Value = cached;

            return Task.FromResult<ILogConsistencyProtocolMessage>(response);
        }

        /// <inheritdoc/>
        protected override async Task ReadAsync()
        {
            enter_operation("ReadAsync");

            while (true)
            {
                try
                {
                    // read from storage
                    var result = await ((ICustomStorageInterface<TLogView, TLogEntry>)Host).ReadStateFromStorage();
                    version = result.Key;
                    cached = result.Value;

                    Services.Log(LogLevel.Debug, "read success v{0}", version);

                    LastPrimaryIssue.Resolve(Host, Services);

                    break; // successful
                }
                catch (Exception e)
                {
                    // unwrap inner exception that was forwarded - helpful for debugging
                    if ((e as ProtocolTransportException)?.InnerException != null)
                        e = ((ProtocolTransportException)e).InnerException;

                    LastPrimaryIssue.Record(new ReadFromPrimaryFailed() { Exception = e }, Host, Services);
                }

                Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue);

                await LastPrimaryIssue.DelayBeforeRetry();
            }

            exit_operation("ReadAsync");
        }

        /// <inheritdoc/>
        protected override async Task<int> WriteAsync()
        {
            enter_operation("WriteAsync");

            var updates = GetCurrentBatchOfUpdates().Select(submissionentry => submissionentry.Entry).ToList();
            bool writesuccessful = false;
            bool transitionssuccessful = false;

            try
            {
                writesuccessful = await ((ICustomStorageInterface<TLogView,TLogEntry>) Host).ApplyUpdatesToStorage(updates, version);

                LastPrimaryIssue.Resolve(Host, Services);
            }
            catch (Exception e)
            {
                // unwrap inner exception that was forwarded - helpful for debugging
                if ((e as ProtocolTransportException)?.InnerException != null)
                    e = ((ProtocolTransportException)e).InnerException;

                LastPrimaryIssue.Record(new UpdatePrimaryFailed() { Exception = e }, Host, Services);
            }

            if (writesuccessful)
            {
                Services.Log(LogLevel.Debug, "write ({0} updates) success v{1}", updates.Count, version + updates.Count);

                // now we update the cached state by applying the same updates
                // in case we encounter any exceptions we will re-read the whole state from storage
                try
                {
                    foreach (var u in updates)
                    {
                        version++;
                        Host.UpdateView(this.cached, u);
                    }

                    transitionssuccessful = true;
                }
                catch (Exception e)
                {
                    Services.CaughtUserCodeException("UpdateView", nameof(WriteAsync), e);
                }
            }

            if (!writesuccessful || !transitionssuccessful)
            {
                Services.Log(LogLevel.Debug, "{0} failed {1}", writesuccessful ? "transitions" : "write", LastPrimaryIssue);

                while (true) // be stubborn until we can re-read the state from storage
                {
                    await LastPrimaryIssue.DelayBeforeRetry();

                    try
                    {
                        var result = await ((ICustomStorageInterface<TLogView, TLogEntry>)Host).ReadStateFromStorage();
                        version = result.Key;
                        cached = result.Value;

                        Services.Log(LogLevel.Debug, "read success v{0}", version);

                        LastPrimaryIssue.Resolve(Host, Services);

                        break;
                    }
                    catch (Exception e)
                    {
                        // unwrap inner exception that was forwarded - helpful for debugging
                        if ((e as ProtocolTransportException)?.InnerException != null)
                            e = ((ProtocolTransportException)e).InnerException;

                        LastPrimaryIssue.Record(new ReadFromPrimaryFailed() { Exception = e }, Host, Services);
                    }

                    Services.Log(LogLevel.Debug, "read failed {0}", LastPrimaryIssue);
                }
            }

            exit_operation("WriteAsync");

            return writesuccessful ? updates.Count : 0;
        }

        /// <summary>
        /// Describes a connection issue that occurred when updating the primary storage.
        /// </summary>
        [Serializable]
        [GenerateSerializer]
        public sealed class UpdatePrimaryFailed : PrimaryOperationFailed
        {
            /// <inheritdoc/>
            public override string ToString()
            {
                return $"update primary failed: caught {Exception.GetType().Name}: {Exception.Message}";
            }
        }

        /// <summary>
        /// Describes a connection issue that occurred when reading from the primary storage.
        /// </summary>
        [Serializable]
        [GenerateSerializer]
        public sealed class ReadFromPrimaryFailed : PrimaryOperationFailed
        {
            /// <inheritdoc/>
            public override string ToString()
            {
                return $"read from primary failed: caught {Exception.GetType().Name}: {Exception.Message}";
            }
        }

        /// <summary>
        /// A notification message that is sent to remote instances of this grain after the primary has been
        /// updated, to let them know the latest version. Contains all the updates that were applied.
        /// </summary>
        [Serializable]
        [GenerateSerializer]
        protected internal sealed class UpdateNotificationMessage : INotificationMessage
        {
            /// <inheritdoc/>
            [Id(0)]
            public int Version { get; set; }

            /// <summary> The list of updates that were applied. </summary>
            [Id(1)]
            public List<TLogEntry> Updates { get; set; }

            /// <summary>
            /// A representation of this notification message suitable for tracing.
            /// </summary>
            public override string ToString()
            {
                return string.Format("v{0} ({1} updates)", Version, Updates.Count);
            }
        }

        private SortedList<long, UpdateNotificationMessage> notifications = new SortedList<long,UpdateNotificationMessage>();

        /// <inheritdoc/>
        protected override void OnNotificationReceived(INotificationMessage payload)
        {
           var um = payload as UpdateNotificationMessage;
            if (um != null)
                notifications.Add(um.Version - um.Updates.Count, um);
            else
                base.OnNotificationReceived(payload);
        }

        /// <inheritdoc/>
        protected override void ProcessNotifications()
        {

            // discard notifications that are behind our already confirmed state
            while (notifications.Count > 0 && notifications.ElementAt(0).Key < version)
            {
                Services.Log(LogLevel.Debug, "discarding notification {0}", notifications.ElementAt(0).Value);
                notifications.RemoveAt(0);
            }

            // process notifications that reflect next global version
            while (notifications.Count > 0 && notifications.ElementAt(0).Key == version)
            {
                var updatenotification = notifications.ElementAt(0).Value;
                notifications.RemoveAt(0);

                // Apply all operations in pending
                foreach (var u in updatenotification.Updates)
                    try
                    {
                        Host.UpdateView(cached, u);
                    }
                    catch (Exception e)
                    {
                        Services.CaughtUserCodeException("UpdateView", nameof(ProcessNotifications), e);
                    }

                version = updatenotification.Version;

                Services.Log(LogLevel.Debug, "notification success ({0} updates) v{1}", updatenotification.Updates.Count, version);
            }

            Services.Log(LogLevel.Trace, "unprocessed notifications in queue: {0}", notifications.Count);

            base.ProcessNotifications();

        }

        [Conditional("DEBUG")]
        private void enter_operation(string name)
        {
            Services.Log(LogLevel.Trace, "/-- enter {0}", name);
        }

        [Conditional("DEBUG")]
        private void exit_operation(string name)
        {
            Services.Log(LogLevel.Trace, "\\-- exit {0}", name);
        }

    }
}


text:
<?php

/**
 * Class RootLocator_SearchHandler
 *
 * @author James Wigger <james@rootstudio.co.uk>
 */
class RootLocator_SearchHandler implements PerchAPI_SearchHandler
{
    /**
     * Output search SQL for Perch Runway
     *
     * @param string $key
     *
     * @return string
     */
    public static function get_admin_search_sql($key)
    {
        $API = new PerchAPI(1.0, 'root_locator');
        $db = $API->get('DB');

        $sql = '
            SELECT \'' . __CLASS__ . '\' AS source,
            MATCH(addressTitle, addressBuilding, addressStreet, addressPostcode)
            AGAINST(' . $db->pdb($key) . ') AS score, addressTitle, addressBuilding, addressStreet, addressPostcode, addressID, "", "", ""
            FROM ' . PERCH_DB_PREFIX . 'root_locator_addresses
            WHERE MATCH(addressTitle, addressBuilding, addressStreet, addressPostcode) AGAINST(' . $db->pdb($key) . ')';

        return $sql;
    }

    /**
     * Output search SQL for runtime search queries
     *
     * @param string $key
     *
     * @return string
     */
    public static function get_search_sql($key)
    {
        $API = new PerchAPI(1.0, 'root_locator');
        $db = $API->get('DB');

        $sql = '
            SELECT \'' . __CLASS__ . '\' AS source,
            MATCH(addressTitle, addressBuilding, addressStreet, addressPostcode)
            AGAINST(' . $db->pdb($key) . ') AS score, addressTitle, addressBuilding, addressStreet, addressPostcode, addressID, "", "", ""
            FROM ' . PERCH_DB_PREFIX . 'root_locator_addresses
            WHERE MATCH(addressTitle, addressBuilding, addressStreet, addressPostcode) AGAINST(' . $db->pdb($key) . ')
            AND addressLatitude IS NOT NULL AND addressLongitude IS NOT NULL';

        return $sql;
    }

    /**
     * Perform a basic search if no results are returned from primary search
     *
     * @param string $key
     *
     * @return string
     */
    public static function get_backup_search_sql($key)
    {
        $API = new PerchAPI(1.0, 'root_locator');
        $db = $API->get('DB');

        $sql = '
            SELECT \'' . __CLASS__ . '\' AS source, addressTitle AS score, addressTitle, addressBuilding, addressStreet, addressPostcode, addressID, "", "", ""
            FROM ' . PERCH_DB_PREFIX . 'root_locator_addresses
            WHERE addressLatitude IS NOT NULL AND addressLongitude IS NOT NULL
            AND (
                concat("  ", addressTitle, "  ") REGEXP ' . $db->pdb('[[:<:]]' . $key . '[[:>:]]') . '
                OR  concat("  ", addressBuilding, "  ") REGEXP ' . $db->pdb('[[:<:]]' . $key . '[[:>:]]') . '
                OR  concat("  ", addressStreet, "  ") REGEXP ' . $db->pdb('[[:<:]]' . $key . '[[:>:]]') . '
                OR  concat("  ", addressPostcode, "  ") REGEXP ' . $db->pdb('[[:<:]]' . $key . '[[:>:]]') .
            ')';

        return $sql;
    }

    /**
     * Format results for display in search results template
     *
     * @param $key
     * @param $opts
     * @param $result
     *
     * @return array
     */
    public static function format_result($key, $opts, $result)
    {
        $result['addressTitle'] = $result['col1'];
        $result['addressBuilding'] = $result['col2'];
        $result['addressStreet'] = $result['col3'];
        $result['addressPostcode'] = $result['col4'];
        $result['addressID'] = $result['col5'];
        $result['_id'] = $result['col5'];

        $html = implode(', ', [
            $result['addressTitle'],
            $result['addressBuilding'],
            $result['addressStreet'],
            $result['addressPostcode'],
            $result['addressPostcode']
        ]);

        $html = preg_replace('/(' . $key . ')/i', '$1', $html);

        $match = [];
        $match['title'] = $result['addressTitle'];
        $match['excerpt'] = $html;
        $match['key'] = $key;
        $match['url'] = false;

        return $match;
    }

    /**
     * Format results for display in Perch admin sidebar
     *
     * @param $key
     * @param $options
     * @param $result
     *
     * @return mixed
     */
    public static function format_admin_result($key, $options, $result)
    {
        $result['addressID'] = $result['col5'];

        $self = __CLASS__;

        $out = $self::format_result($key, $options, $result);

        $out['url'] = PERCH_LOGINPATH . '/addons/apps/root_locator/edit/?id=' . $result['addressID'];

        return $out;
    }
}


text:
<?php
class Kwc_Basic_ImageEnlarge_ApiContent implements Kwf_Component_ApiContent_Interface
{
    public function getContent(Kwf_Component_Data $data)
    {
        $imageApiContent = new Kwc_Basic_Image_ApiContent();
        return array(
            "link" => $data->getChildComponent('-linkTag'),
            "content" => array(
                "type" => "image",
                "id" => "no_id",
                "data" => $imageApiContent->getContent($data)
            )
        );
    }
}


text:
from __future__ import absolute_import

import six

from sentry.models import ExternalIssue, GroupLink, Integration
from sentry.testutils import APITestCase
from sentry.utils.http import absolute_uri

class GroupIntegrationDetailsTest(APITestCase):
    def test_simple_get_link(self):
        self.login_as(user=self.user)
        org = self.organization
        group = self.create_group()
        integration = Integration.objects.create(
            provider='example',
            name='Example',
        )
        integration.add_organization(org.id)

        path = '/api/0/issues/{}/integrations/{}/?action=link'.format(group.id, integration.id)

        response = self.client.get(path)
        provider = integration.get_provider()

        assert response.data == {
            'id': six.text_type(integration.id),
            'name': integration.name,
            'icon': integration.metadata.get('icon'),
            'domainName': integration.metadata.get('domain_name'),
            'accountType': integration.metadata.get('account_type'),
            'status': integration.get_status_display(),
            'provider': {
                'key': provider.key,
                'name': provider.name,
                'canAdd': provider.can_add,
                'canAddProject': provider.can_add_project,
                'features': [f.value for f in provider.features],
                'aspects': provider.metadata.aspects,
            },
            'linkIssueConfig': [{
                'default': '',
                'type': 'string',
                'name': 'externalIssue',
                'label': 'Issue',
            }]
        }

    def test_simple_get_create(self):
        self.login_as(user=self.user)
        org = self.organization
        group = self.create_group()
        self.create_event(group=group)
        integration = Integration.objects.create(
            provider='example',
            name='Example',
        )
        integration.add_organization(org.id)

        path = '/api/0/issues/{}/integrations/{}/?action=create'.format(group.id, integration.id)

        response = self.client.get(path)
        provider = integration.get_provider()

        assert response.data == {
            'id': six.text_type(integration.id),
            'name': integration.name,
            'icon': integration.metadata.get('icon'),
            'domainName': integration.metadata.get('domain_name'),
            'accountType': integration.metadata.get('account_type'),
            'status': integration.get_status_display(),
            'provider': {
                'key': provider.key,
                'name': provider.name,
                'canAdd': provider.can_add,
                'canAddProject': provider.can_add_project,
                'features': [f.value for f in provider.features],
                'aspects': provider.metadata.aspects,
            },
            'createIssueConfig': [
                {
                    'default': 'message',
                    'type': 'string',
                    'name': 'title',
                    'label': 'Title',
                }, {
                    'default': ('%s\n\n```\n'
                                'Stacktrace (most recent call last):\n\n  '
                                'File "sentry/models/foo.py", line 29, in build_msg\n    '
                                'string_max_length=self.string_max_length)\n\nmessage\n```'
                                ) % (absolute_uri(group.get_absolute_url()),),
                    'type': 'textarea',
                    'name': 'description',
                    'label': 'Description',
                }
            ]
        }

    def test_simple_put(self):
        self.login_as(user=self.user)
        org = self.organization
        group = self.create_group()
        integration = Integration.objects.create(
            provider='example',
            name='Example',
        )
        integration.add_organization(org.id)

        path = '/api/0/issues/{}/integrations/{}/'.format(group.id, integration.id)

        response = self.client.put(path, data={
            'externalIssue': 'APP-123'
        })

        assert response.status_code == 201
        external_issue = ExternalIssue.objects.get(
            key='APP-123',
            integration_id=integration.id,
            organization_id=org.id,
        )
        assert external_issue.title == 'This is a test external issue title'
        assert external_issue.description == 'This is a test external issue description'
        assert GroupLink.objects.filter(
            linked_type=GroupLink.LinkedType.issue,
            group_id=group.id,
            linked_id=external_issue.id,
        ).exists()

    def test_simple_post(self):
        self.login_as(user=self.user)
        org = self.organization
        group = self.create_group()
        integration = Integration.objects.create(
            provider='example',
            name='Example',
        )
        integration.add_organization(org.id)

        path = '/api/0/issues/{}/integrations/{}/'.format(group.id, integration.id)

        response = self.client.post(path, data={})
        assert response.status_code == 400
        assert response.data['non_field_errors'] == 'Assignee is required'

        response = self.client.post(path, data={'assignee': 'foo@sentry.io'})
        assert response.status_code == 201

        external_issue = ExternalIssue.objects.get(
            key='APP-123',
            integration_id=integration.id,
            organization_id=org.id,
        )
        assert external_issue.description == u'This is a test external issue description'
        assert external_issue.title == u'This is a test external issue title'

        assert GroupLink.objects.filter(
            linked_type=GroupLink.LinkedType.issue,
            group_id=group.id,
            linked_id=external_issue.id,
        ).exists()

    def test_simple_delete(self):
        self.login_as(user=self.user)
        org = self.organization
        group = self.create_group()
        integration = Integration.objects.create(
            provider='example',
            name='Example',
        )
        integration.add_organization(org.id)

        external_issue = ExternalIssue.objects.get_or_create(
            organization_id=org.id,
            integration_id=integration.id,
            key='APP-123',
        )[0]

        group_link = GroupLink.objects.get_or_create(
            group_id=group.id,
            project_id=group.project_id,
            linked_type=GroupLink.LinkedType.issue,
            linked_id=external_issue.id,
            relationship=GroupLink.Relationship.references,
        )[0]

        path = '/api/0/issues/{}/integrations/{}/?externalIssue={}'.format(
            group.id, integration.id, external_issue.id,
        )

        response = self.client.delete(path)

        assert response.status_code == 204
        assert not ExternalIssue.objects.filter(id=external_issue.id).exists()
        assert not GroupLink.objects.filter(id=group_link.id).exists()


text:
require 'rails_helper'

RSpec.describe 'SuperAdmins Merge Orgs', type: :feature do
  before do
    Org.destroy_all
    @scheme = create(:identifier_scheme)
    tpt = create(:token_permission_type)
    @from_org = create(:org, :organisation, templates: 1, plans: 2, managed: true,
                                            feedback_enabled: true,
                                            token_permission_types: [tpt])
    create(:annotation, org: @from_org)
    create(:department, org: @from_org)
    gg = @from_org.guidance_groups.first if @from_org.guidance_groups.any?
    gg = create(:guidance_group, org: @from_org) unless gg.present?
    create(:guidance, guidance_group: gg)
    create(:identifier, identifiable: @from_org, identifier_scheme: nil)
    create(:identifier, identifiable: @from_org, identifier_scheme: @scheme)
    create(:plan, funder: @from_org)
    create(:tracker, org: @from_org)
    create(:user, org: @from_org)

    @to_org = create(:org, :institution, plans: 2, managed: false)

    @user = create(:user, :super_admin, org: create(:org))
    sign_in(@user)
  end

  scenario 'Super admin merges an Org into another Org', :js do
    org_name = @from_org.name
    click_link 'Admin'
    sleep(0.5)
    click_link 'Organisations'

    fill_in(:search, with: @from_org.name)
    click_button 'Search'
    sleep(0.5)

    first("#org-#{@from_org.id}-actions").click
    first("a[href=\"/org/admin/#{@from_org.id}/admin_edit\"]").click

    click_link 'Merge'
    sleep(0.3)
    expect(page).to have_text('Merge Organisations')
    choose_suggestion('org_org_name', @to_org)

    click_button 'Analyze'
    # Wait for response
    sleep(0.3)
    expect(page).to have_text('Summary:')

    click_button 'Merge records'
    # Wait for redirect
    sleep(0.3)
    expect(page).to have_text('Organisations')
    expect(page).to have_text('Successfully merged')

    # Make sure that the correct org was deleted
    expect(Org.where(name: org_name).any?).to eql(false)
    expect(Org.where(name: @to_org.name).any?).to eql(true)

    # Make sure the Org we merged is no longer findable
    find('#search').click
    fill_in(:search, with: org_name)
    click_button 'Search'
    sleep(0.3)
    expect(page).to have_text('There are no records associated')

    # Make sure the Org we merged into is findable
    find('#search').click
    fill_in(:search, with: @to_org.name)
    click_button 'Search'
    sleep(0.3)
    expect(page).to have_text(@to_org.name)
  end
end


text:
using MoodPicker.ApiHelper;
using System;
using System.Drawing;
using System.Net.Http;
using System.Windows.Forms;

namespace MoodPicker.Box
{
    public partial class ConnectionTestBox : Form
    {

        private const int steps = 10;
        private Api api;

        public ConnectionTestBox(string server, string key, string token)
        {
            InitializeComponent();

            if (server == null || server == String.Empty)
            {
                MessageBox.Show("The server URL is empty.", "Holy crap!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
            else
            {
                this.api = new Api(server, key, token);

                closeButton.Enabled = false;
                this.Show();
                TestConnection();

                closeButton.Enabled = true;
            }
        }

        private void TestConnection()
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                Title("Checking URL...");
                Historize("Checking URL...", 1);
                if (!api.CheckUri())
                    throw new Exception(String.Format("The URL '{0}' is not valid.", api.Server));
                Historize(String.Format("The URL '{0}' is valid.", api.Server), 2);

                Title("Checking connection to server...");
                Historize("Checking connection to server...", 3);
                if (!api.CheckServer())
                    throw new Exception(String.Format("The server '{0}' is not responding.", new Uri(api.Server).DnsSafeHost));
                Historize(String.Format("The server '{0}' is responding.", new Uri(api.Server).DnsSafeHost), 4);

                Title("Checking API connection...");
                Historize("Checking API connection...", 5);
                if (!api.CheckApi())
                    throw new Exception("Unable to get connected to the API.");
                Historize("The API is responding.", 6);

                Title("Checking API version...");
                Historize("Checking API version...", 7);
                try
                {
                    Historize(String.Format("The API works under version {0}.", api.GetVersion().api_version), 8);
                }
                catch (ApiException ex)
                {
                    throw new Exception(ex.Message);
                }

                Title("Checking API credentials...");
                Historize("Checking API credentials...", 9);
                try
                {
                    Historize(String.Format("Credentials accepted, token {0} recieved.", api.GetToken().token), 10);
                }
                catch (ApiException ex)
                {
                    throw new Exception(String.Format("{0} (Error {1}).", ex.Message, ex.Error));
                }

                stepLabel.ForeColor = Color.Green;
                Title("Successful connection");
                Historize("Successful connection :-)", steps);
            }
            catch (Exception ex)
            {
                stepLabel.ForeColor = Color.Red;
                Title("Connection failed");
                //Historize(ex.Message, (progressBar.Value * steps / 100));
                Historize(ex.Message, steps);
            }
            finally {
                this.Cursor = Cursors.Default;
            }
        }

        private void Historize(string message, int step)
        {
            if (step > 1) { messageTextBox.AppendText(Environment.NewLine); }
            messageTextBox.AppendText(message);
            progressBar.Value = (int)step * 100 / steps;
        }

        private void Title(string message)
        {
            stepLabel.Text = message;
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}


text:
package com.hazelcast.query.impl.predicates;

import com.hazelcast.internal.serialization.BinaryInterface;
import com.hazelcast.query.impl.Index;
import com.hazelcast.query.impl.QueryContext;

@BinaryInterface
public abstract class AbstractIndexAwarePredicate<K, V> extends AbstractPredicate<K, V> implements IndexAwarePredicate<K, V> {

    protected AbstractIndexAwarePredicate() {
    }

    protected AbstractIndexAwarePredicate(String attributeName) {
        super(attributeName);
    }

    protected Index getIndex(QueryContext queryContext) {
        return matchIndex(queryContext, QueryContext.IndexMatchHint.NONE);
    }

    protected Index matchIndex(QueryContext queryContext, QueryContext.IndexMatchHint matchHint) {
        return queryContext.matchIndex(attributeName, matchHint);
    }

    @Override
    public boolean isIndexed(QueryContext queryContext) {
        return getIndex(queryContext) != null;
    }

}


text:
This project contains the data and presentation for [use of force](http://apps.mypalmbeachpost.com/lineoffire/#/) project.

## Setup

### Backend
- Clone this repo to your machine.
- Open ```/setup/password``` file and enter your mysql database password
- Open terminal and navigate to the ```/setup``` directory
- Run ```./setup.sh```

### Frontend
TKTKTK

## Assumptions
- POSIX environment
- Mysql server running with a username same as the shell username


text:
package org.apache.flink.table.plan.rules.logical

import com.google.common.collect.{ImmutableList, Maps}
import org.apache.calcite.plan.RelOptRule.{any, operand}
import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall, RelOptUtil}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.core.Aggregate.Group
import org.apache.calcite.rel.core.{Aggregate, AggregateCall, Calc, Project, RelFactories}
import org.apache.calcite.rex.{RexInputRef, RexNode, RexProgram, RexUtil}
import org.apache.calcite.runtime.Utilities
import org.apache.calcite.util.ImmutableBitSet
import org.apache.calcite.util.mapping.Mappings

import java.util

import scala.collection.JavaConversions._

/**
  * Planner rule that removes unreferenced AggregateCall from Aggregate
  */
abstract class PruneAggregateCallRule[T <: RelNode](topClass: Class[T]) extends RelOptRule(
  operand(topClass,
    operand(classOf[Aggregate], any)),
  RelFactories.LOGICAL_BUILDER,
  s"PruneAggregateCallRule_${topClass.getCanonicalName}") {

  protected def getInputRefs(relOnAgg: T): ImmutableBitSet

  override def matches(call: RelOptRuleCall): Boolean = {
    val relOnAgg: T = call.rel(0)
    val agg: Aggregate = call.rel(1)
    if (agg.indicator || agg.getGroupType != Group.SIMPLE || agg.getAggCallList.isEmpty ||
      // at least output one column
      (agg.getGroupCount == 0 && agg.getAggCallList.size() == 1)) {
      return false
    }
    val inputRefs = getInputRefs(relOnAgg)
    val unrefAggCallIndices = getUnrefAggCallIndices(inputRefs, agg)
    unrefAggCallIndices.nonEmpty
  }

  private def getUnrefAggCallIndices(
      inputRefs: ImmutableBitSet,
      agg: Aggregate): Array[Int] = {
    val groupCount = agg.getGroupCount
    agg.getAggCallList.indices.flatMap { index =>
      val aggCallOutputIndex = groupCount + index
      if (inputRefs.get(aggCallOutputIndex)) {
        Array.empty[Int]
      } else {
        Array(index)
      }
    }.toArray[Int]
  }

  override def onMatch(call: RelOptRuleCall): Unit = {
    val relOnAgg: T = call.rel(0)
    val agg: Aggregate = call.rel(1)
    val inputRefs = getInputRefs(relOnAgg)
    var unrefAggCallIndices = getUnrefAggCallIndices(inputRefs, agg)
    require(unrefAggCallIndices.nonEmpty)

    val newAggCalls: util.List[AggregateCall] = new util.ArrayList(agg.getAggCallList)
    // remove unreferenced AggCall from original aggCalls
    unrefAggCallIndices.sorted.reverse.foreach(i => newAggCalls.remove(i))

    if (newAggCalls.isEmpty && agg.getGroupCount == 0) {
      // at least output one column
      newAggCalls.add(agg.getAggCallList.get(0))
      unrefAggCallIndices = unrefAggCallIndices.slice(1, unrefAggCallIndices.length)
    }

    val newAgg = agg.copy(
      agg.getTraitSet,
      agg.getInput,
      agg.indicator,
      agg.getGroupSet,
      ImmutableList.of(agg.getGroupSet),
      newAggCalls
    )

    var newFieldIndex = 0
    // map old agg output index to new agg output index
    val mapOldToNew = Maps.newHashMap[Integer, Integer]()
    val fieldCountOfOldAgg = agg.getRowType.getFieldCount
    val unrefAggCallOutputIndices = unrefAggCallIndices.map(_ + agg.getGroupCount)
    (0 until fieldCountOfOldAgg).foreach { i =>
      if (!unrefAggCallOutputIndices.contains(i)) {
        mapOldToNew.put(i, newFieldIndex)
        newFieldIndex += 1
      }
    }
    require(mapOldToNew.size() == newAgg.getRowType.getFieldCount)

    val mapping = Mappings.target(mapOldToNew, fieldCountOfOldAgg, newAgg.getRowType.getFieldCount)
    val newRelOnAgg = createNewRel(mapping, relOnAgg, newAgg)
    call.transformTo(newRelOnAgg)
  }

  protected def createNewRel(
      mapping: Mappings.TargetMapping,
      project: T,
      newAgg: RelNode): RelNode
}

class ProjectPruneAggregateCallRule extends PruneAggregateCallRule(classOf[Project]) {
  override protected def getInputRefs(relOnAgg: Project): ImmutableBitSet = {
    RelOptUtil.InputFinder.bits(relOnAgg.getProjects, null)
  }

  override protected def createNewRel(
      mapping: Mappings.TargetMapping,
      project: Project,
      newAgg: RelNode): RelNode = {
    val newProjects = RexUtil.apply(mapping, project.getProjects).toList
    if (projectsOnlyIdentity(newProjects, newAgg.getRowType.getFieldCount) &&
      Utilities.compare(project.getRowType.getFieldNames, newAgg.getRowType.getFieldNames) == 0) {
      newAgg
    } else {
      project.copy(project.getTraitSet, newAgg, newProjects, project.getRowType)
    }
  }

  private def projectsOnlyIdentity(
      projects: util.List[RexNode],
      inputFieldCount: Int): Boolean = {
    if (projects.size != inputFieldCount) {
      return false
    }
    projects.zipWithIndex.forall {
      case (project, index) =>
        project match {
          case r: RexInputRef => r.getIndex == index
          case _ => false
        }
    }
  }
}

class CalcPruneAggregateCallRule extends PruneAggregateCallRule(classOf[Calc]) {
  override protected def getInputRefs(relOnAgg: Calc): ImmutableBitSet = {
    val program = relOnAgg.getProgram
    val condition = if (program.getCondition != null) {
      program.expandLocalRef(program.getCondition)
    } else {
      null
    }
    val projects = program.getProjectList.map(program.expandLocalRef)
    RelOptUtil.InputFinder.bits(projects, condition)
  }

  override protected def createNewRel(
      mapping: Mappings.TargetMapping,
      calc: Calc,
      newAgg: RelNode): RelNode = {
    val program = calc.getProgram
    val newCondition = if (program.getCondition != null) {
      RexUtil.apply(mapping, program.expandLocalRef(program.getCondition))
    } else {
      null
    }
    val projects = program.getProjectList.map(program.expandLocalRef)
    val newProjects = RexUtil.apply(mapping, projects).toList
    val newProgram = RexProgram.create(
      newAgg.getRowType,
      newProjects,
      newCondition,
      program.getOutputRowType.getFieldNames,
      calc.getCluster.getRexBuilder
    )
    if (newProgram.isTrivial &&
      Utilities.compare(calc.getRowType.getFieldNames, newAgg.getRowType.getFieldNames) == 0) {
      newAgg
    } else {
      calc.copy(calc.getTraitSet, newAgg, newProgram)
    }
  }
}

object PruneAggregateCallRule {
  val PROJECT_ON_AGGREGATE = new ProjectPruneAggregateCallRule
  val CALC_ON_AGGREGATE = new CalcPruneAggregateCallRule
}


text:
using System;
using System.Linq;
using NinjaNye.SearchExtensions.Levenshtein;
using Xunit;

namespace NinjaNye.SearchExtensions.Tests.Integration.Fluent
{
    [Collection("Database tests")]
    public class FluentLevenshteinTests
    {
        private readonly TestContext _context;

        public FluentLevenshteinTests(DatabaseIntegrationTests @base)
        {
            _context = @base._context;
        }

        [Fact]
        public void LevenshteinDistanceOf_GetDistanceToString_ReturnAllRecords()
        {
            //Arrange
            int totalRecords = _context.TestModels.Count();

            //Act
            var result = _context.TestModels.LevenshteinDistanceOf(x => x.StringOne).ComparedTo("test");

            //Assert
            Assert.Equal(totalRecords, result.Count());
        }

        [Fact]
        public void LevenshteinDistanceOf_GetDistanceToString_DistancesAreCorrect()
        {
            //Arrange

            //Act
            var result = _context.TestModels.LevenshteinDistanceOf(x => x.StringOne).ComparedTo("test");

            //Assert
            Assert.True(result.All(x => x.Distance == LevenshteinProcessor.LevenshteinDistance(x.Item.StringOne, "test")));
        }

        [Fact]
        public void LevenshteinDistanceOf_GetDistanceToProperty_ReturnAllRecords()
        {
            //Arrange
            int totalRecords = _context.TestModels.Count();

            //Act
            var result = _context.TestModels.LevenshteinDistanceOf(x => x.StringOne).ComparedTo(x => x.StringTwo);

            //Assert
            Assert.Equal(totalRecords, result.Count());
        }

        [Fact]
        public void LevenshteinDistanceOf_GetDistanceToProperty_DistancesAreCorrect()
        {
            //Arrange

            //Act
            var result = _context.TestModels.LevenshteinDistanceOf(x => x.StringOne).ComparedTo(x => x.StringTwo);

            //Assert
            Assert.True(result.All(x => x.Distance == LevenshteinProcessor.LevenshteinDistance(x.Item.StringOne, x.Item.StringTwo)));
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareAgainstTwoStrings_AllDistancesReturned()
        {
            var result = _context.TestModels.Search(x => x.StringOne).EqualTo("abcd")
                                            .LevenshteinDistanceOf(x => x.StringOne)
                                            .ComparedTo("abce", "efgh");

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(1, firstResult.Distances[0]);
            Assert.Equal(4, firstResult.Distances[1]);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareAgainstTwoProperties_AllDistancesReturned()
        {
            var result = _context.TestModels.Search(x => x.Id).EqualTo(new Guid("2F75BE28-CEC8-46D8-852E-E6DAE5C8F0A3"))
                                            .LevenshteinDistanceOf(x => x.StringOne)
                                            .ComparedTo(x => x.StringTwo, x => x.StringThree);

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(9, firstResult.Distances[0]);
            Assert.Equal(5, firstResult.Distances[1]);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareAgainstTwoStrings_MinimumDistanceReturned()
        {
            var result = _context.TestModels.Search(x => x.StringOne).EqualTo("abcd")
                                            .LevenshteinDistanceOf(x => x.StringOne)
                                            .ComparedTo("abce", "efgh");

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(1, firstResult.MinimumDistance);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareAgainstTwoStrings_MaximumDistanceReturned()
        {
            var result = _context.TestModels.Search(x => x.StringOne).EqualTo("abcd")
                                            .LevenshteinDistanceOf(x => x.StringOne)
                                            .ComparedTo("abce", "efghsdfsdfadgv");

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(13, firstResult.MaximumDistance);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareTwoPropertiesToString()
        {
            var result = _context.TestModels.Search(x => x.StringOne).EqualTo("abcd")
                                            .LevenshteinDistanceOf(x => x.StringOne, x => x.StringTwo)
                                            .ComparedTo("abce");

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(1, firstResult.Distances[0]);
            Assert.Equal(4, firstResult.Distances[1]);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareTwoPropertiesToProperty()
        {
            var result = _context.TestModels.Search(x => x.Id).EqualTo(new Guid("2F75BE28-CEC8-46D8-852E-E6DAE5C8F0A3"))
                                            .LevenshteinDistanceOf(x => x.StringOne, x => x.StringTwo)
                                            .ComparedTo(x => x.StringThree);

            var firstResult = result.First();
            Assert.Equal(2, firstResult.Distances.Length);
            Assert.Equal(5, firstResult.Distances[0]);
            Assert.Equal(9, firstResult.Distances[1]);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareTwoPropertiesToTwoStrings()
        {
            var result = _context.TestModels.Search(x => x.StringOne).EqualTo("abcd")
                                            .LevenshteinDistanceOf(x => x.StringOne, x => x.StringTwo)
                                            .ComparedTo("abce", "absdfb");

            var firstResult = result.First();
            Assert.Equal(4, firstResult.Distances.Length);
            Assert.Equal(1, firstResult.Distances[0]);
            Assert.Equal(4, firstResult.Distances[1]);
            Assert.Equal(3, firstResult.Distances[2]);
            Assert.Equal(6, firstResult.Distances[3]);
        }

        [Fact]
        public void LevenschteinDistanceOf_CompareTwoPropertiesToProperties()
        {
            var result = _context.TestModels.Search(x => x.Id).EqualTo(new Guid("2F75BE28-CEC8-46D8-852E-E6DAE5C8F0A3"))
                                            .LevenshteinDistanceOf(x => x.StringOne, x => x.StringTwo)
                                            .ComparedTo(x => x.StringThree, x => x.Id.ToString());

            var firstResult = result.First();
            Assert.Equal(4, firstResult.Distances.Length);
            Assert.Equal(5, firstResult.Distances[0]);
            Assert.Equal(9, firstResult.Distances[1]);
            Assert.Equal(33, firstResult.Distances[2]);
            Assert.Equal(34, firstResult.Distances[3]);
        }
    }
}


text:
importScripts("/resources/testharness.js");

test(function() { assert_true("storage" in navigator); },
    "These worker tests require navigator.storage");

test(function() { assert_false("requestPersistent" in navigator.storage); },
    "navigator.storage.requestPersistent should not exist in workers");

promise_test(function() {
    var promise = navigator.storage.persistentPermission();
    assert_true(promise instanceof Promise,
        "navigator.storage.persistentPermission() returned a Promise.")
    return promise.then(function (result) {
        // Layout tests get canned results, not the value per spec. So testing
        // their values here would only be testing our test plumbing. But we can
        // test that the type of the returned value is correct.
        assert_equals(typeof result, "string", result + " should be a string");
        assert_greater_than(result.length, 0, "result should have length >0");
    });
}, "navigator.storage.persistentPermission returns a promise that resolves.");

done();


text:
#ifndef SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_VM_INTERFACE_KSYNC_H_
#define SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_VM_INTERFACE_KSYNC_H_

#include <ovsdb_entry.h>
#include <ovsdb_object.h>

class VmInterface;

namespace OVSDB {
class VMInterfaceKSyncObject : public OvsdbDBObject {
public:
    VMInterfaceKSyncObject(OvsdbClientIdl *idl, DBTable *table);
    virtual ~VMInterfaceKSyncObject();

    void OvsdbNotify(OvsdbClientIdl::Op, struct ovsdb_idl_row*);
    KSyncEntry *Alloc(const KSyncEntry *key, uint32_t index);
    KSyncEntry *DBToKSyncEntry(const DBEntry*);
    OvsdbDBEntry* AllocOvsEntry(struct ovsdb_idl_row*);
    DBFilterResp OvsdbDBEntryFilter(const DBEntry *entry,
                                    const OvsdbDBEntry *ovsdb_entry);

private:
    DISALLOW_COPY_AND_ASSIGN(VMInterfaceKSyncObject);
};

class VMInterfaceKSyncEntry : public OvsdbDBEntry {
public:
    VMInterfaceKSyncEntry(VMInterfaceKSyncObject *table,
            const VMInterfaceKSyncEntry *key);
    VMInterfaceKSyncEntry(VMInterfaceKSyncObject *table,
            const VmInterface *entry);
    VMInterfaceKSyncEntry(VMInterfaceKSyncObject *table,
            boost::uuids::uuid uuid);

    // ovs_entry ref is not valid for VM interface, override IsDataResolved
    // to return always true
    bool IsDataResolved() {return true;}
    void AddMsg(struct ovsdb_idl_txn *);
    void ChangeMsg(struct ovsdb_idl_txn *);
    void DeleteMsg(struct ovsdb_idl_txn *);
    bool Sync(DBEntry*);
    bool IsLess(const KSyncEntry&) const;
    std::string ToString() const {return "VM Interface Ksync";}
    KSyncEntry* UnresolvedReference();

    const std::string &vn_name() const;

private:
    friend class VMInterfaceKSyncObject;
    boost::uuids::uuid uuid_;
    std::string vn_name_;
    SecurityGroupList sg_list_;
    DISALLOW_COPY_AND_ASSIGN(VMInterfaceKSyncEntry);
};
};

#endif //SRC_VNSW_AGENT_OVS_TOR_AGENT_OVSDB_CLIENT_VM_INTERFACE_KSYNC_H_


text:
var express    = require('express'); 		// call express
var app        = express(); 				// define our app using express
var bodyParser = require('body-parser');
var routes     = require('./routes/routes.js');

// configure app to use bodyParser()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
var port = 5555;
routes(app);
app.listen(5555);
console.log('Magic happens on port ' + port);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.OData;
using TestRestfulAPI.Infrastructure.Repositories;
using TestRestfulAPI.RestApi.odata.v1.Users.Entities;
using TestRestfulAPI.RestApi.odata.v1.Users.Exceptions;
using ResourceContext = TestRestfulAPI.Infrastructure.Database.ResourceContext;

namespace TestRestfulAPI.RestApi.odata.v1.Users.Repositories
{
    public class ResourceRepository : SingleBaseRepository<Resource>, ISingleRepository<Resource, int>
    {
        public ResourceRepository(ResourceContext resourceContext) : base(resourceContext)
        {
        }

        public IQueryable<Resource> All()
        {
            return this.ResourceContext.Context.Set<Resource>();
        }

        public Resource Get(int id)
        {
            var result = this.All().FirstOrDefault(r => r.Id == id);
            if (result == null)
            {
                throw new ResourceDoesNotExistException("Resource with ID " + id + " does not exist.");
            }
            return result;
        }

        public Resource Create(Resource entity)
        {
            var role = this.All().FirstOrDefault(r => r.Name == entity.Name);
            if (role != null)
            {
                throw new ResourceAlreadyExistException("Resource with name " + entity.Name + " does already exist.");
            }
            ResourceContext.Context.Set<Resource>().Add(entity);
            ResourceContext.Context.SaveChanges();

            return entity;
        }

        public Resource Update(Resource entity)
        {
            var dbEntry = this.Get(entity.Id);

            ResourceContext.Context.Entry(dbEntry).CurrentValues.SetValues(entity);
            ResourceContext.Context.Entry(dbEntry).Property("CreatedAt").IsModified = false;

            ResourceContext.Context.SaveChanges();

            return dbEntry;
        }

        public Resource PartialUpdate(int id, Delta<Resource> entity)
        {
            var dbEntry = this.Get(id);

            entity.Patch(dbEntry);
            ResourceContext.Context.Entry(dbEntry).Property("CreatedAt").IsModified = false;

            ResourceContext.Context.SaveChanges();

            return dbEntry;
        }

        public void Delete(int id)
        {
            var dbEntry = this.Get(id);

            ResourceContext.Context.Set<Resource>().Remove(dbEntry);
            ResourceContext.Context.SaveChanges();
        }
    }
}


text:
/*************************************************************************/
/*  crypto_mbedtls.h                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef CRYPTO_MBEDTLS_H
#define CRYPTO_MBEDTLS_H

#include "core/crypto/crypto.h"
#include "core/resource.h"

#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
#include <mbedtls/ssl.h>

class CryptoMbedTLS;
class SSLContextMbedTLS;
class CryptoKeyMbedTLS : public CryptoKey {
private:
	mbedtls_pk_context pkey;
	int locks = 0;
	bool public_only = true;

public:
	static CryptoKey *create();
	static void make_default() { CryptoKey::_create = create; }
	static void finalize() { CryptoKey::_create = nullptr; }

	virtual Error load(String p_path, bool p_public_only);
	virtual Error save(String p_path, bool p_public_only);
	virtual String save_to_string(bool p_public_only);
	virtual Error load_from_string(String p_string_key, bool p_public_only);
	virtual bool is_public_only() const { return public_only; };

	CryptoKeyMbedTLS() {
		mbedtls_pk_init(&pkey);
		locks = 0;
	}
	~CryptoKeyMbedTLS() {
		mbedtls_pk_free(&pkey);
	}

	_FORCE_INLINE_ void lock() { locks++; }
	_FORCE_INLINE_ void unlock() { locks--; }

	friend class CryptoMbedTLS;
	friend class SSLContextMbedTLS;
};

class X509CertificateMbedTLS : public X509Certificate {
private:
	mbedtls_x509_crt cert;
	int locks;

public:
	static X509Certificate *create();
	static void make_default() { X509Certificate::_create = create; }
	static void finalize() { X509Certificate::_create = nullptr; }

	virtual Error load(String p_path);
	virtual Error load_from_memory(const uint8_t *p_buffer, int p_len);
	virtual Error save(String p_path);

	X509CertificateMbedTLS() {
		mbedtls_x509_crt_init(&cert);
		locks = 0;
	}
	~X509CertificateMbedTLS() {
		mbedtls_x509_crt_free(&cert);
	}

	_FORCE_INLINE_ void lock() { locks++; }
	_FORCE_INLINE_ void unlock() { locks--; }

	friend class CryptoMbedTLS;
	friend class SSLContextMbedTLS;
};

class CryptoMbedTLS : public Crypto {
private:
	mbedtls_entropy_context entropy;
	mbedtls_ctr_drbg_context ctr_drbg;
	static X509CertificateMbedTLS *default_certs;
	mbedtls_md_type_t _md_type_from_hashtype(HashingContext::HashType p_hash_type, int &r_size);

public:
	static Crypto *create();
	static void initialize_crypto();
	static void finalize_crypto();
	static X509CertificateMbedTLS *get_default_certificates();
	static void load_default_certificates(String p_path);

	virtual PackedByteArray generate_random_bytes(int p_bytes);
	virtual Ref<CryptoKey> generate_rsa(int p_bytes);
	virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after);
	virtual Vector<uint8_t> sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key);
	virtual bool verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key);
	virtual Vector<uint8_t> encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext);
	virtual Vector<uint8_t> decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext);

	CryptoMbedTLS();
	~CryptoMbedTLS();
};

#endif // CRYPTO_MBEDTLS_H


text:
<?php

  namespace Vaszev\SelfAdvertBundle\DependencyInjection;

  use Symfony\Component\Config\Definition\Builder\TreeBuilder;
  use Symfony\Component\Config\Definition\ConfigurationInterface;

  /**
   * This is the class that validates and merges configuration from your app/config files
   * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
   */
  class Configuration implements ConfigurationInterface {
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder() {
      $treeBuilder = new TreeBuilder();
      $rootNode = $treeBuilder->root('vaszev_self_advert');

      $rootNode
          ->children()
            ->variableNode('logo_image')->defaultValue(null)->end()
            ->variableNode('email_subject')->defaultValue('website')->end()
            ->variableNode('email_secret')->defaultValue('thisIsNotsecret')->end()
            ->variableNode('from_email')->defaultValue('creator@noreply.me')->end()
            ->variableNode('from_name')->defaultValue('creator')->end()
          ->end();

      // Here you should define the parameters that are allowed to
      // configure your bundle. See the documentation linked above for
      // more information on that topic.

      return $treeBuilder;
    }
  }