text:
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _

from oscar.apps.basket import signals
from oscar.core.loading import get_model, get_class

from rest_framework import status, generics, exceptions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView

from oscarapi import serializers, permissions
from oscarapi.basket import operations
from oscarapi.views.mixin import PutIsPatchMixin
from oscarapi.views.utils import BasketPermissionMixin

__all__ = ('BasketView', 'LineList', 'LineDetail', 'AddProductView',
           'BasketLineDetail', 'AddVoucherView', 'shipping_methods')

Basket = get_model('basket', 'Basket')
Line = get_model('basket', 'Line')
Repository = get_class('shipping.repository', 'Repository')

class BasketView(APIView):
    """
    Api for retrieving a user's basket.

    GET:
    Retrieve your basket.
    """
    serializer_class = serializers.BasketSerializer

    def get(self, request, format=None):
        basket = operations.get_basket(request)
        ser = self.serializer_class(basket, context={'request': request})
        return Response(ser.data)

class AddProductView(APIView):
    """
    Add a certain quantity of a product to the basket.

    POST(url, quantity)
    {
        "url": "http://testserver.org/oscarapi/products/209/",
        "quantity": 6
    }

    If you've got some options to configure for the product to add to the
    basket, you should pass the optional ``options`` property:
    {
        "url": "http://testserver.org/oscarapi/products/209/",
        "quantity": 6,
        "options": [{
            "option": "http://testserver.org/oscarapi/options/1/",
            "value": "some value"
        }]
    }
    """
    add_product_serializer_class = serializers.AddProductSerializer
    serializer_class = serializers.BasketSerializer

    def validate(self, basket, product, quantity, options):
        availability = basket.strategy.fetch_for_product(
            product).availability

        # check if product is available at all
        if not availability.is_available_to_buy:
            return False, availability.message

        # check if we can buy this quantity
        allowed, message = availability.is_purchase_permitted(quantity)
        if not allowed:
            return False, message

        # check if there is a limit on amount
        allowed, message = basket.is_quantity_allowed(quantity)
        if not allowed:
            return False, message
        return True, None

    def post(self, request, format=None):
        p_ser = self.add_product_serializer_class(
            data=request.data, context={'request': request})
        if p_ser.is_valid():
            basket = operations.get_basket(request)
            product = p_ser.validated_data['url']
            quantity = p_ser.validated_data['quantity']
            options = p_ser.validated_data.get('options', [])

            basket_valid, message = self.validate(
                basket, product, quantity, options)
            if not basket_valid:
                return Response(
                    {'reason': message},
                    status=status.HTTP_406_NOT_ACCEPTABLE)

            basket.add_product(product, quantity=quantity, options=options)
            operations.apply_offers(request, basket)
            ser = self.serializer_class(
                basket, context={'request': request})
            return Response(ser.data)

        return Response(
            {'reason': p_ser.errors}, status=status.HTTP_406_NOT_ACCEPTABLE)

class AddVoucherView(APIView):
    """
    Add a voucher to the basket.

    POST(vouchercode)
    {
        "vouchercode": "kjadjhgadjgh7667"
    }

    Will return 200 and the voucher as json if succesful.
    If unsuccessful, will return 406 with the error.
    """
    add_voucher_serializer_class = serializers.VoucherAddSerializer
    serializer_class = serializers.VoucherSerializer

    def post(self, request, format=None):
        v_ser = self.add_voucher_serializer_class(
            data=request.data, context={'request': request})
        if v_ser.is_valid():
            basket = operations.get_basket(request)

            voucher = v_ser.instance
            basket.vouchers.add(voucher)

            signals.voucher_addition.send(
                sender=None, basket=basket, voucher=voucher)

            # Recalculate discounts to see if the voucher gives any
            operations.apply_offers(request, basket)
            discounts_after = basket.offer_applications

            # Look for discounts from this new voucher
            for discount in discounts_after:
                if discount['voucher'] and discount['voucher'] == voucher:
                    break
            else:
                basket.vouchers.remove(voucher)
                return Response(
                    {'reason': _(
                        "Your basket does not qualify for a voucher discount")},  # noqa
                    status=status.HTTP_406_NOT_ACCEPTABLE)

            ser = self.serializer_class(
                voucher, context={'request': request})
            return Response(ser.data)

        return Response(v_ser.errors, status=status.HTTP_406_NOT_ACCEPTABLE)

@api_view(('GET',))
def shipping_methods(request, format=None):
    """
    Get the available shipping methods and their cost for this order.

    GET:
    A list of shipping method details and the prices.
    """
    basket = operations.get_basket(request)
    shiping_methods = Repository().get_shipping_methods(
        basket=request.basket, user=request.user,
        request=request)
    ser = serializers.ShippingMethodSerializer(
        shiping_methods, many=True, context={'basket': basket})
    return Response(ser.data)

class LineList(BasketPermissionMixin, generics.ListCreateAPIView):
    """
    Api for adding lines to a basket.

    Permission will be checked,
    Regular users may only access their own basket,
    staff users may access any basket.

    GET:
    A list of basket lines.

    POST(basket, line_reference, product, stockrecord,
         quantity, price_currency, price_excl_tax, price_incl_tax):
    Add a line to the basket, example::

        {
            "basket": "http://127.0.0.1:8000/oscarapi/baskets/100/",
            "line_reference": "234_345",
            "product": "http://127.0.0.1:8000/oscarapi/products/209/",
            "stockrecord":
                "http://127.0.0.1:8000/oscarapi/stockrecords/100/",
            "quantity": 3,
            "price_currency": "EUR",
            "price_excl_tax": "100.0",
            "price_incl_tax": "121.0"
        }
    """
    serializer_class = serializers.LineSerializer
    queryset = Line.objects.all()

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        if pk is not None:  # usually we need the lines of the basket
            basket = self.check_basket_permission(self.request, basket_pk=pk)
            prepped_basket = operations.assign_basket_strategy(
                basket, self.request)
            return prepped_basket.all_lines()
        elif self.request.user.is_staff:  # admin users can view a bit more
            return super(LineList, self).get_queryset()
        else:  # non admin users can view nothing at all here.
            return self.permission_denied(self.request)

    def get(self, request, pk=None, format=None):
        if pk is not None:
            basket = self.check_basket_permission(request, pk)
            prepped_basket = operations.assign_basket_strategy(basket, request)
            self.queryset = prepped_basket.all_lines()
            self.serializer_class = serializers.BasketLineSerializer

        return super(LineList, self).get(request, format)

    def post(self, request, pk=None, format=None):
        data_basket = self.get_data_basket(request.data, format)
        self.check_basket_permission(request, basket=data_basket)

        if pk is not None:
            url_basket = self.check_basket_permission(request, basket_pk=pk)
            if url_basket != data_basket:
                raise exceptions.NotAcceptable(
                    _('Target basket inconsistent %s != %s') % (
                        url_basket.pk, data_basket.pk
                    )
                )
        elif not request.user.is_staff:
            self.permission_denied(request)

        return super(LineList, self).post(request, format=format)

class LineDetail(PutIsPatchMixin, generics.RetrieveUpdateDestroyAPIView):
    queryset = Line.objects.all()
    serializer_class = serializers.LineSerializer
    permission_classes = (permissions.IsAdminUserOrRequestContainsLine,)

    def get(self, request, pk=None, format=None):
        line = self.get_object()
        basket = operations.get_basket(request)

        # if the line is from the current basket, use the serializer that
        # computes the prices by using the strategy.
        if line.basket == basket:
            operations.assign_basket_strategy(line.basket, request)
            ser = serializers.BasketLineSerializer(
                instance=line, context={'request': request})
            return Response(ser.data)

        return super(LineDetail, self).get(request, pk, format)

class BasketLineDetail(PutIsPatchMixin, generics.RetrieveUpdateDestroyAPIView):
    queryset = Line.objects.all()
    serializer_class = serializers.BasketLineSerializer
    permission_classes = (permissions.IsAdminUserOrRequestContainsLine,)

    def get_queryset(self):
        basket_pk = self.kwargs.get('basket_pk')
        basket = get_object_or_404(operations.editable_baskets(), pk=basket_pk)
        prepped_basket = operations.prepare_basket(basket, self.request)
        if operations.request_contains_basket(self.request, prepped_basket):
            return prepped_basket.all_lines()
        else:
            return self.queryset.none()


text:
package ru0xdc.rtklib.constants;

import ru0xdc.rtkgps.R;

/**
 * Ionosphere option (IONOOPT_XXX)
 */
public enum IonosphereOption implements IHasRtklibId {

    /** correction off */
    OFF(0, R.string.ionoopt_off),
    /** broadcast model */
    BRDC(1, R.string.ionoopt_brdc),
    /** SBAS model */
    SBAS(2, R.string.ionoopt_sbas),
    /** L1/L2 or L1/L5 iono-free LC */
    IFLC(3, R.string.ionoopt_iflc),
    /** estimation */
    EST(4, R.string.ionoopt_est),
    /** IONEX TEC model */
    TEC(5, R.string.ionoopt_tec),
    /** QZSS broadcast model */
    QZS(6, R.string.ionoopt_qzs),
    /** QZSS LEX ionospehre */
    LEX(7, R.string.ionoopt_lex),
    /** SLANT TEC model */
    STEC(8, R.string.ionoopt_stec)
    ;

    private final int mRtklibId;
    private final int mNameResId;

    private IonosphereOption(int rtklibId, int nameResId) {
        mRtklibId = rtklibId;
        mNameResId = nameResId;
    }

    @Override
    public int getRtklibId() {
        return mRtklibId;
    }

    @Override
    public int getNameResId() {
        return mNameResId;
    }

    public static IonosphereOption valueOf(int rtklibId) {
        for (IonosphereOption v: values()) {
            if (v.mRtklibId == rtklibId) return v;
        }
        throw new IllegalArgumentException();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "fp_consts.h"
const union _ieee_rep __QNAN = { __DOUBLE_QNAN_REP };
const union _ieee_rep __SNAN = { __DOUBLE_SNAN_REP };
const union _ieee_rep __INF =  { __DOUBLE_INF_REP };
const union _ieee_rep __DENORM = { __DOUBLE_DENORM_REP };

/* ISO C99 */
#undef nan
/* FIXME */
double nan (const char *);
double nan (const char * tagp __attribute__((unused)) )
{
	return __QNAN.double_val;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

        <TITLE></TITLE>

MiTRAQ - Multiple iTRAQ Data Analysis

            MiTRAQ has been developed by Harald Barsnes
            from the Proteomics Unit at the University of Bergen, Norway.

Licenses:

        MiTRAQ Apache License 2.0.

        Please note that some of the JAR files used by MiTRAQ
        may not have the same license as MiTRAQ. If you
        want to use any of these in a different context, make sure to obtain the
        original license for the JAR file in question.

        The platform independent graphical user interface design is based Nimbus, but
        when Nimbus is not available
        JGoodies is used, and this has a separate
        license.

        For licenses regarding Java see www.sun.com.

Questions?

        Any further questions can be forwarded to:
        harald.barsnes@biomed.uib.no.

Supported Platforms:

            The tool has been developed on Windows 7. But should also work on older
            Windows versions and on other platforms, as long as Java 1.6 (or newer) is installed.

        Go to top of page

        The BSD License for the JGoodies Looks

        Copyright (c) 2001-2007 JGoodies Karsten Lentzsch. All rights reserved.

        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:

        o Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.

        o Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.

        o Neither the name of JGoodies Karsten Lentzsch nor the names of
        its contributors may be used to endorse or promote products derived
        from this software without specific prior written permission.

        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
        THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
        PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
        CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
        EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
        PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
        OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
        WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
        OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
        EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        Go to top of page


text:
package org.neo4j.cypher.internal.compiler.v2_3.pipes.matching

import org.neo4j.cypher.internal.compiler.v2_3._
import org.neo4j.cypher.internal.compiler.v2_3.commands.expressions.Expression
import org.neo4j.cypher.internal.compiler.v2_3.commands.predicates.{Predicate, True}
import org.neo4j.cypher.internal.compiler.v2_3.pipes.{MutableMaps, QueryState}
import org.neo4j.cypher.internal.compiler.v2_3.symbols.SymbolTable
import org.neo4j.cypher.internal.frontend.v2_3.{SemanticDirection, EntityNotFoundException}
import org.neo4j.graphdb._
import org.neo4j.helpers.ThisShouldNotHappenError

import scala.collection.mutable
import scala.collection.mutable.{Map => MutableMap}

trait ExpanderStep {
  def next: Option[ExpanderStep]

  def typ: Seq[String]

  def direction: SemanticDirection

  def id: Int

  def relPredicate: Predicate

  def nodePredicate: Predicate

  def createCopy(next: Option[ExpanderStep], direction: SemanticDirection, nodePredicate: Predicate): ExpanderStep

  def size: Option[Int]

  def expand(node: Node, parameters: ExecutionContext, state:QueryState): (Iterable[Relationship], Option[ExpanderStep])

  def shouldInclude(): Boolean

  /*
  The way we reverse the steps is by first creating a Seq out of the steps. In this Seq, the first element points to
  Some(second), the second to Some(third), und so weiter, until the last element points to None.

  By doing a fold left and creating copies along the way, we reverse the directions - we push in None and True as the
  first tuple, as what the first reversed step will end use as node predicate and next step. We then pass the reversed
  step, and it's original predicate on to the next step. The result is that the first element points to
  None, the second to Some(first), und so weiter, until we pop out the last step as our reversed expander
   */
  def reverse(): ExpanderStep = {
    val allSteps: Seq[ExpanderStep] = this.asSeq()

    val reversed = allSteps.foldLeft[(Option[ExpanderStep], Predicate)]((None, True())) {
      case ((lastStep: Option[ExpanderStep], lastPred: Predicate), step: ExpanderStep) =>
        val newStep = Some(step.createCopy(next = lastStep, direction = step.direction.reversed, nodePredicate = lastPred))
        (newStep, step.nodePredicate)
    }

    reversed match {
      case (Some(result), _) => result
      case _                 => throw new ThisShouldNotHappenError("Andres", "Reverse should always succeed")
    }
  }

  private def asSeq(): Seq[ExpanderStep] = {
    var allSteps = mutable.Seq[ExpanderStep]()
    var current: Option[ExpanderStep] = Some(this)

    while (current.nonEmpty) {
      val step = current.get
      allSteps = allSteps :+ step
      current = step.next
    }

    allSteps.toSeq
  }
}

abstract class MiniMapProperty(originalName: String, propertyKeyName: String) extends Expression {
  protected def calculateType(symbols: SymbolTable) = fail()

  def arguments = Nil

  def rewrite(f: (Expression) => Expression) = fail()

  def symbolTableDependencies = fail()

  def apply(ctx: ExecutionContext)(implicit state: QueryState) = {
    val qtx = state.query
    ctx match {
      case m: MiniMap => {
        val pc = extract(m)
        try {
          pc match {
            case n: Node         => qtx.nodeOps.getProperty(n.getId, qtx.getPropertyKeyId(propertyKeyName))
            case r: Relationship => qtx.relationshipOps.getProperty(r.getId, qtx.getPropertyKeyId(propertyKeyName))
          }
        } catch {
          case x: NotFoundException =>
            throw new EntityNotFoundException("The property '%s' does not exist on %s, which was found with the identifier: %s".format(propertyKeyName, pc, originalName), x)
        }
      }
      case _          => fail()
    }
  }

  protected def fail() = throw new ThisShouldNotHappenError("Andres", "This predicate should never be used outside of the traversal matcher")

  protected def extract(m: MiniMap): PropertyContainer
}

abstract class MiniMapIdentifier() extends Expression {
  protected def calculateType(symbols: SymbolTable) = fail()

  def arguments = Nil

  def rewrite(f: (Expression) => Expression) = fail()

  def symbolTableDependencies = fail()

  def apply(ctx: ExecutionContext)(implicit state: QueryState) = ctx match {
    case m: MiniMap => extract(m)
    case _          => fail()
  }

  protected def extract(m: MiniMap): PropertyContainer

  def fail() = throw new ThisShouldNotHappenError("Andres", "This predicate should never be used outside of the traversal matcher")
}

case class NodeIdentifier() extends MiniMapIdentifier() {
  protected def extract(m: MiniMap) = m.node
}

case class RelationshipIdentifier() extends MiniMapIdentifier() {
  protected def extract(m: MiniMap) = m.relationship
}

class MiniMap(var relationship: Relationship, var node: Node, myMap: MutableMap[String, Any] = MutableMaps.empty)
  extends ExecutionContext(m = myMap) {

  override def iterator = throw new ThisShouldNotHappenError("Andres", "This method should never be used")

  override def -(key: String) = throw new ThisShouldNotHappenError("Andres", "This method should never be used")

  override protected def createWithNewMap(newMap: mutable.Map[String, Any]) = new MiniMap(relationship, node, newMap)
}


text:
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Route.css';
import Image from '../../components/Lotus/Image'

import Menu from '../../components/Material/Menu/';
import Button from '../../components/Material/Button';
import PopOver from '../../components/Material/PopOver';
import BarDecor from '../../components/Material/BarDecor';
import ArcDecor from '../../components/Material/ArcDecor';
import Card from '../../components/Material/Card';
import CardTitle from '../../components/Material/Card/CardTitle';
import CardBody from '../../components/Material/Card/CardBody';
import CardActions from '../../components/Material/Card/CardActions';
import CardMedia from '../../components/Material/Card/CardMedia';

import Icon from '../../components/Material/Icon'
import Choice from '../../components/Material/Choice'
const title = 'React Starter Kit';

import ResponsiveUI from '../../components/Material/Sheet/ResponsiveUI'
import Tree from '../../components/Material/Tree'

function Route({}, context) {
  context.setTitle(title);
  return (
    <ResponsiveUI>

Tree

        <svg height="110" width="500"><text x="50" y="50" style={{textAnchor:"middle", color:'black', fontSize:35, fontFamily:"Verdana"}}>TEST</text></svg>
        <svg height="500" width="800">
        <Tree y={0} nodes={[{name:'0', value:0, children:[{name:'1', value:1}, {name:'2', value:2, children:[{name:'4', value:3}, {name:'5', value:4}, {name:'6', value:5}]}, {name:'3', value:6}]}]}/>
        </svg>

    </ResponsiveUI>
  );
}

Route.propTypes = {
};
Route.contextTypes = { setTitle: PropTypes.func.isRequired };

export default withStyles(s)(Route);


text:
package io.cattle.platform.core.dao;

import io.cattle.platform.core.model.Account;
import io.cattle.platform.core.model.Credential;

public interface AccountDao {

    Account getSystemAccount();

    Credential getApiKey(Account account, boolean requireActive);

    Account findByUuid(String uuid);

}


text:
#ifndef BOOST_SPIRIT_INCLUDE_KARMA_DIRECTIVE
#define BOOST_SPIRIT_INCLUDE_KARMA_DIRECTIVE
#include <boost/spirit/home/karma/directive.hpp>
#endif


text:
A .NET-based SDK for the GlassDoor API which separates HTTP request overhead from business logic and front end formatting.
Intended to become a NuGet package.

Hello World Sample:

      // Get your partnerid and key from GlassDoor
			var client = new Client(PartnerId, Key);

      // The methods all tend to have large parameter lists with most parameters having default (usually null) values,
      // So we recommend using named parameter syntax.
			var jobstats = client.GetJobsStatsAsync(returnStates: true);

      // Make sure that you specify what information you want returned. If you don't ask for Employer or City information,
      // nothing will be returned.
			var developerjobstats = client.GetJobsStatsAsync(queryPhrase: "Developer",
			    returnEmployers: true,
			    returnCities: true,
			    returnJobTitles: true,
			    returnStates: true);

      // Do other work here.

      // All calls are asychronous, so either call them in an async method, or wait for the task result.
			jobstats.Wait();
      developerjobstats.Wait();

			var result = jobstats.Result;

			foreach (var state in result.States)
				System.Diagnostics.Debug.WriteLine(state.Value.Name + " " + state.Value.NumberOfJobs);


text:
\hypertarget{class_bike_prototype}{}\section{Bike\+Prototype Class Reference}
\label{class_bike_prototype}\index{Bike\+Prototype@{Bike\+Prototype}}

\hyperlink{class_bike_prototype}{Bike\+Prototype} Class.

{\ttfamily \#include $<$bike\+\_\+prototype.\+hpp$>$}

Inheritance diagram for Bike\+Prototype\+:\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[height=2.000000cm]{class_bike_prototype}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hypertarget{class_bike_prototype_ae49515bfb795c1a9000d7168fd764cc9}{}\hyperlink{class_bike_prototype_ae49515bfb795c1a9000d7168fd764cc9}{Bike\+Prototype} ()\label{class_bike_prototype_ae49515bfb795c1a9000d7168fd764cc9}

\begin{DoxyCompactList}\small\item\em Constructor. \end{DoxyCompactList}\item
\hypertarget{class_bike_prototype_a044c34974541500ea818be723c65a64a}{}\hyperlink{class_bike_prototype_a044c34974541500ea818be723c65a64a}{Bike\+Prototype} (const \hyperlink{class_bike_prototype}{Bike\+Prototype} \&)\label{class_bike_prototype_a044c34974541500ea818be723c65a64a}

\begin{DoxyCompactList}\small\item\em Copy Constructor. \end{DoxyCompactList}\item
\hyperlink{class_equipment_prototype}{Equipment\+Prototype} $\ast$ \hyperlink{class_bike_prototype_a10732d6849be44963b62994b724605b1}{clone} () const
\begin{DoxyCompactList}\small\item\em Clone. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

\subsection{Detailed Description}
\hyperlink{class_bike_prototype}{Bike\+Prototype} Class.

Used to hold information regarding an exercise bike.

\subsection{Member Function Documentation}
\hypertarget{class_bike_prototype_a10732d6849be44963b62994b724605b1}{}\index{Bike\+Prototype@{Bike\+Prototype}!clone@{clone}}
\index{clone@{clone}!Bike\+Prototype@{Bike\+Prototype}}
\subsubsection[{clone() const }]{\setlength{\rightskip}{0pt plus 5cm}{\bf Equipment\+Prototype} $\ast$ Bike\+Prototype\+::clone (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
) const\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_bike_prototype_a10732d6849be44963b62994b724605b1}

Clone.

Returns a new object that is identical to this one

Implements \hyperlink{class_equipment_prototype_a4014d69b92c71c4c49477c657c824024}{Equipment\+Prototype}.

The documentation for this class was generated from the following files\+:\begin{DoxyCompactItemize}
\item
/\+Users/jshier/\+Development/\+Exercise\+Software/\+Exercise\+Software/bike\+\_\+prototype.\+hpp\item
/\+Users/jshier/\+Development/\+Exercise\+Software/\+Exercise\+Software/bike\+\_\+prototype.\+cpp\end{DoxyCompactItemize}


text:
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include "kinsol_impl.h"
#include <kinsol/kinsol_spgmr.h>
#include "kinsol_spils_impl.h"

#include <sundials/sundials_spgmr.h>
#include <sundials/sundials_math.h>

/*
 * -----------------------------------------------------------------
 * private constants
 * -----------------------------------------------------------------
 */

#define ZERO RCONST(0.0)

/*
 * -----------------------------------------------------------------
 * function prototypes
 * -----------------------------------------------------------------
 */

/* KINSpgmr linit, lsetup, lsolve, and lfree routines */

static int KINSpgmrInit(KINMem kin_mem);
static int KINSpgmrSetup(KINMem kin_mem);
static int KINSpgmrSolve(KINMem kin_mem, N_Vector xx,
                         N_Vector bb, realtype *sJpnorm, realtype *sFdotJp);
static void KINSpgmrFree(KINMem kin_mem);

/*
 * -----------------------------------------------------------------
 * readability replacements
 * -----------------------------------------------------------------
 */

#define nni            (kin_mem->kin_nni)
#define nnilset        (kin_mem->kin_nnilset)
#define func           (kin_mem->kin_func)
#define user_data      (kin_mem->kin_user_data)
#define printfl        (kin_mem->kin_printfl)
#define linit          (kin_mem->kin_linit)
#define lsetup         (kin_mem->kin_lsetup)
#define lsolve         (kin_mem->kin_lsolve)
#define lfree          (kin_mem->kin_lfree)
#define lmem           (kin_mem->kin_lmem)
#define inexact_ls     (kin_mem->kin_inexact_ls)
#define uu             (kin_mem->kin_uu)
#define fval           (kin_mem->kin_fval)
#define uscale         (kin_mem->kin_uscale)
#define fscale         (kin_mem->kin_fscale)
#define sqrt_relfunc   (kin_mem->kin_sqrt_relfunc)
#define jacCurrent     (kin_mem->kin_jacCurrent)
#define eps            (kin_mem->kin_eps)
#define errfp          (kin_mem->kin_errfp)
#define infofp         (kin_mem->kin_infofp)
#define setupNonNull   (kin_mem->kin_setupNonNull)
#define vtemp1         (kin_mem->kin_vtemp1)
#define vec_tmpl       (kin_mem->kin_vtemp1)
#define vtemp2         (kin_mem->kin_vtemp2)
#define strategy       (kin_mem->kin_globalstrategy)

#define pretype   (kinspils_mem->s_pretype)
#define gstype    (kinspils_mem->s_gstype)
#define nli       (kinspils_mem->s_nli)
#define npe       (kinspils_mem->s_npe)
#define nps       (kinspils_mem->s_nps)
#define ncfl      (kinspils_mem->s_ncfl)
#define njtimes   (kinspils_mem->s_njtimes)
#define nfes      (kinspils_mem->s_nfes)
#define new_uu    (kinspils_mem->s_new_uu)
#define spils_mem (kinspils_mem->s_spils_mem)

#define jtimesDQ  (kinspils_mem->s_jtimesDQ)
#define jtimes    (kinspils_mem->s_jtimes)
#define J_data    (kinspils_mem->s_J_data)

#define last_flag (kinspils_mem->s_last_flag)

/*
 * -----------------------------------------------------------------
 * Function : KINSpgmr
 * -----------------------------------------------------------------
 * This routine allocates and initializes the memory record and
 * sets function fields specific to the SPGMR linear solver module.
 * KINSpgmr sets the kin_linit, kin_lsetup, kin_lsolve, and
 * kin_lfree fields in *kinmem to be KINSpgmrInit, KINSpgmrSetup,
 * KINSpgmrSolve, and KINSpgmrFree, respectively. It allocates
 * memory for a structure of type KINSpilsMemRec and sets the
 * kin_lmem field in *kinmem to the address of this structure. It
 * also calls SpgmrMalloc to allocate memory for the module
 * SPGMR. In summary, KINSpgmr sets various fields in the
 * KINSpilsMemRec structure.
 * -----------------------------------------------------------------
 */

int KINSpgmr(void *kinmem, int maxl)
{
  KINMem kin_mem;
  KINSpilsMem kinspils_mem;
  SpgmrMem spgmr_mem;
  int maxl1;

  if (kinmem == NULL){
    KINProcessError(NULL, KINSPILS_MEM_NULL, "KINSPILS", "KINSpgmr", MSGS_KINMEM_NULL);
    return(KINSPILS_MEM_NULL);
  }
  kin_mem = (KINMem) kinmem;

  /* check for required vector operations */

  /* Note: do NOT need to check for N_VLinearSum, N_VProd, N_VScale, N_VDiv,
     or N_VWL2Norm because they are required by KINSOL */

  if ((vec_tmpl->ops->nvconst == NULL) ||
      (vec_tmpl->ops->nvdotprod == NULL) ||
      (vec_tmpl->ops->nvl1norm == NULL)) {
    KINProcessError(NULL, KINSPILS_ILL_INPUT, "KINSPILS", "KINSpgmr", MSGS_BAD_NVECTOR);
    return(KINSPILS_ILL_INPUT);
  }

  if (lfree != NULL) lfree(kin_mem);

  /* set four main function fields in kin_mem */

  linit  = KINSpgmrInit;
  lsetup = KINSpgmrSetup;
  lsolve = KINSpgmrSolve;
  lfree  = KINSpgmrFree;

  /* get memory for KINSpilsMemRec */
  kinspils_mem = NULL;
  kinspils_mem = (KINSpilsMem) malloc(sizeof(struct KINSpilsMemRec));
  if (kinspils_mem == NULL){
    KINProcessError(NULL, KINSPILS_MEM_FAIL, "KINSPILS", "KINSpgmr", MSGS_MEM_FAIL);
    return(KINSPILS_MEM_FAIL);
  }

  /* Set ILS type */
  kinspils_mem->s_type = SPILS_SPGMR;

  /* set SPGMR parameters that were passed in call sequence */

  maxl1 = (maxl <= 0) ? KINSPILS_MAXL : maxl;
  kinspils_mem->s_maxl = maxl1;

  /* Set defaults for Jacobian-related fileds */

  jtimesDQ = TRUE;
  jtimes   = NULL;
  J_data   = NULL;

  /* Set defaults for preconditioner-related fields */

  kinspils_mem->s_pset   = NULL;
  kinspils_mem->s_psolve = NULL;
  kinspils_mem->s_pfree  = NULL;
  kinspils_mem->s_P_data = kin_mem->kin_user_data;

  /* Set default values for the rest of the SPGMR parameters */

  kinspils_mem->s_pretype   = PREC_NONE;
  kinspils_mem->s_gstype    = MODIFIED_GS;
  kinspils_mem->s_maxlrst   = 0;
  kinspils_mem->s_last_flag = KINSPILS_SUCCESS;

  /* Call SpgmrMalloc to allocate workspace for SPGMR */

  /* vec_tmpl passed as template vector */
  spgmr_mem = NULL;
  spgmr_mem = SpgmrMalloc(maxl1, vec_tmpl);
  if (spgmr_mem == NULL) {
    KINProcessError(NULL, KINSPILS_MEM_FAIL, "KINSPILS", "KINSpgmr", MSGS_MEM_FAIL);
    free(kinspils_mem); kinspils_mem = NULL;
    return(KINSPILS_MEM_FAIL);
  }

  /* This is an iterative linear solver */

  inexact_ls = TRUE;

  /* Attach SPGMR memory to spils memory structure */
  spils_mem = (void *) spgmr_mem;

  /* attach linear solver memory to KINSOL memory */
  lmem = kinspils_mem;

  return(KINSPILS_SUCCESS);
}

/*
 * -----------------------------------------------------------------
 * additional readability replacements
 * -----------------------------------------------------------------
 */

#define maxl    (kinspils_mem->s_maxl)
#define maxlrst (kinspils_mem->s_maxlrst)
#define pset    (kinspils_mem->s_pset)
#define psolve  (kinspils_mem->s_psolve)
#define P_data  (kinspils_mem->s_P_data)

/*
 * -----------------------------------------------------------------
 * Function : KINSpgmrInit
 * -----------------------------------------------------------------
 * This routine initializes variables associated with the GMRES
 * linear solver. Memory allocation was done previously in
 * KINSpgmr.
 * -----------------------------------------------------------------
 */

static int KINSpgmrInit(KINMem kin_mem)
{
  KINSpilsMem kinspils_mem;

  kinspils_mem = (KINSpilsMem) lmem;

  /* initialize counters */

  npe = nli = nps = ncfl = 0;
  njtimes = nfes = 0;

  /* set preconditioner type */

  if (psolve != NULL) {
    pretype = PREC_RIGHT;
  } else {
    pretype = PREC_NONE;
  }

  /* set setupNonNull to TRUE iff there is preconditioning with setup */

  setupNonNull = (psolve != NULL) && (pset != NULL);

  /* Set Jacobian-related fields, based on jtimesDQ */

  if (jtimesDQ) {
    jtimes = KINSpilsDQJtimes;
    J_data = kin_mem;
  } else {
    J_data = user_data;
  }

  if ( (strategy == KIN_PICARD) && jtimesDQ ) {
    KINProcessError(kin_mem, KIN_ILL_INPUT, "KINSOL", "KINSpgmrInit",
		    MSG_NOL_FAIL);
    return(KIN_ILL_INPUT);
  }

  last_flag = KINSPILS_SUCCESS;
  return(0);
}

/*
 * -----------------------------------------------------------------
 * Function : KINSpgmrSetup
 * -----------------------------------------------------------------
 * This routine does the setup operations for the SPGMR linear
 * solver, that is, it is an interface to the user-supplied
 * routine pset.
 * -----------------------------------------------------------------
 */

static int KINSpgmrSetup(KINMem kin_mem)
{
  KINSpilsMem kinspils_mem;
  int ret;

  kinspils_mem = (KINSpilsMem) lmem;

  /* call pset routine */

  ret = pset(uu, uscale, fval, fscale, P_data, vtemp1, vtemp2);

  last_flag = ret;

  npe++;
  nnilset = nni;

  /* return the same value ret that pset returned */

  return(ret);
}

/*
 * -----------------------------------------------------------------
 * Function : KINSpgmrSolve
 * -----------------------------------------------------------------
 * This routine handles the call to the generic SPGMR solver
 * SpgmrSolve for the solution of the linear system Ax = b.
 *
 * Appropriate variables are passed to SpgmrSolve and the counters
 * nli, nps, and ncfl are incremented, and the return value is set
 * according to the success of SpgmrSolve. The success flag is
 * returned if SpgmrSolve converged, or if the residual was reduced.
 * Of the other error conditions, only preconditioner solver
 * failure is specifically returned. Otherwise a generic flag is
 * returned to denote failure of this routine.
 * -----------------------------------------------------------------
 */

static int KINSpgmrSolve(KINMem kin_mem, N_Vector xx, N_Vector bb,
                         realtype *sJpnorm, realtype *sFdotJp)
{
  KINSpilsMem kinspils_mem;
  SpgmrMem spgmr_mem;
  int ret, nli_inc, nps_inc;
  realtype res_norm;

  kinspils_mem = (KINSpilsMem) lmem;

  spgmr_mem = (SpgmrMem) spils_mem;

  /* Set initial guess to xx = 0. bb is set, by the routine
     calling KINSpgmrSolve, to the RHS vector for the system
     to be solved. */

  N_VConst(ZERO, xx);

  new_uu = TRUE;  /* set flag required for user Jacobian routine */

  /* call SpgmrSolve */

  ret = SpgmrSolve(spgmr_mem, kin_mem, xx, bb, pretype, gstype, eps,
                   maxlrst, kin_mem, fscale, fscale, KINSpilsAtimes,
                   KINSpilsPSolve, &res_norm, &nli_inc, &nps_inc);

  /* increment counters nli, nps, and ncfl
     (nni is updated in the KINSol main iteration loop) */

  nli = nli + (long int) nli_inc;
  nps = nps + (long int) nps_inc;

  if (printfl > 2)
    KINPrintInfo(kin_mem, PRNT_NLI, "KINSPGMR", "KINSpgmrSolve", INFO_NLI, nli_inc);

  if (ret != 0) ncfl++;
  last_flag = ret;

  if ( (ret != 0) && (ret != SPGMR_RES_REDUCED) ) {

    /* Handle all failure returns from SpgmrSolve */

    switch(ret) {
    case SPGMR_PSOLVE_FAIL_REC:
    case SPGMR_ATIMES_FAIL_REC:
      return(1);
      break;
    case SPGMR_CONV_FAIL:
    case SPGMR_QRFACT_FAIL:
    case SPGMR_MEM_NULL:
    case SPGMR_GS_FAIL:
    case SPGMR_QRSOL_FAIL:
    case SPGMR_ATIMES_FAIL_UNREC:
    case SPGMR_PSOLVE_FAIL_UNREC:
      return(-1);
      break;
    }
  }

  /*  SpgmrSolve returned either SPGMR_SUCCESS or SPGMR_RES_REDUCED.

     Compute the terms sJpnorm and sFdotJp for use in the linesearch
     routine and in KINForcingTerm.  Both of these terms are subsequently
     corrected if the step is reduced by constraints or the linesearch.

     sJpnorm is the norm of the scaled product (scaled by fscale) of the
     current Jacobian matrix J and the step vector p (= solution vector xx).

     sFdotJp is the dot product of the scaled f vector and the scaled
     vector J*p, where the scaling uses fscale.                            */

  ret = KINSpilsAtimes(kin_mem, xx, bb);
  if (ret > 0) {
    last_flag = SPGMR_ATIMES_FAIL_REC;
    return(1);
  }
  else if (ret < 0) {
    last_flag = SPGMR_ATIMES_FAIL_UNREC;
    return(-1);
  }

  *sJpnorm = N_VWL2Norm(bb, fscale);
  N_VProd(bb, fscale, bb);
  N_VProd(bb, fscale, bb);
  *sFdotJp = N_VDotProd(fval, bb);

  if (printfl > 2) KINPrintInfo(kin_mem, PRNT_EPS, "KINSPGMR",
                     "KINSpgmrSolve", INFO_EPS, res_norm, eps);

  return(0);
}

/*
 * -----------------------------------------------------------------
 * Function : KINSpgmrFree
 * -----------------------------------------------------------------
 * This routine frees memory specific to the SPGMR linear solver.
 * -----------------------------------------------------------------
 */

static void KINSpgmrFree(KINMem kin_mem)
{
  KINSpilsMem kinspils_mem;
  SpgmrMem spgmr_mem;

  kinspils_mem = (KINSpilsMem) lmem;

  spgmr_mem = (SpgmrMem) spils_mem;
  SpgmrFree(spgmr_mem);

  if (kinspils_mem->s_pfree != NULL) (kinspils_mem->s_pfree)(kin_mem);

  free(kinspils_mem); kinspils_mem = NULL;
}


text:
<?php

namespace Magento\Tax\Api;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\WebapiAbstract;
use Magento\Webapi\Model\Rest\Config as HttpConstants;

class TaxRuleRepositoryInterfaceTest extends WebapiAbstract
{
    const SERVICE_NAME = "taxTaxRuleRepositoryV1";
    const SERVICE_VERSION = "V1";
    const RESOURCE_PATH = "/V1/taxRules";

    /** @var \Magento\Tax\Model\Calculation\Rate[] */
    private $fixtureTaxRates;

    /** @var \Magento\Tax\Model\ClassModel[] */
    private $fixtureTaxClasses;

    /** @var \Magento\Tax\Model\Calculation\Rule[] */
    private $fixtureTaxRules;

    /** @var FilterBuilder */
    private $filterBuilder;

    /** @var SearchCriteriaBuilder */
    private $searchCriteriaBuilder;

    /**
     * Execute per test initialization.
     */
    public function setUp()
    {
        $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create(
            'Magento\Framework\Api\SearchCriteriaBuilder'
        );
        $this->filterBuilder = Bootstrap::getObjectManager()->create(
            'Magento\Framework\Api\FilterBuilder'
        );
        $objectManager = Bootstrap::getObjectManager();

        $this->searchCriteriaBuilder = $objectManager->create(
            'Magento\Framework\Api\SearchCriteriaBuilder'
        );
        $this->filterBuilder = $objectManager->create(
            'Magento\Framework\Api\FilterBuilder'
        );

        /** Initialize tax classes, tax rates and tax rules defined in fixture Magento/Tax/_files/tax_classes.php */
        $this->getFixtureTaxRates();
        $this->getFixtureTaxClasses();
        $this->getFixtureTaxRules();
    }

    public function tearDown()
    {
        $taxRules = $this->getFixtureTaxRules();
        if (count($taxRules)) {
            $taxRates = $this->getFixtureTaxRates();
            $taxClasses = $this->getFixtureTaxClasses();
            foreach ($taxRules as $taxRule) {
                $taxRule->delete();
            }
            foreach ($taxRates as $taxRate) {
                $taxRate->delete();
            }
            foreach ($taxClasses as $taxClass) {
                $taxClass->delete();
            }
        }
    }

    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testDeleteTaxRule()
    {
        $fixtureRule = $this->getFixtureTaxRules()[0];
        $taxRuleId = $fixtureRule->getId();
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'DeleteById',
            ],
        ];
        $requestData = ['ruleId' => $taxRuleId];
        $result = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertTrue($result);
        /** Ensure that tax rule was actually removed from DB */
        /** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
        $taxRate = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rate');
        $this->assertNull($taxRate->load($taxRuleId)->getId(), 'Tax rule was not deleted from DB.');
    }

    public function testCreateTaxRule()
    {
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => HttpConstants::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        $requestData = [
            'rule' => [
                'code' => 'Test Rule ' . microtime(),
                'position' => 10,
                'priority' => 5,
                'customer_tax_class_ids' => [3],
                'product_tax_class_ids' => [2],
                'tax_rate_ids' => [1, 2],
                'calculate_subtotal' => 1,
            ],
        ];
        $taxRuleData = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertArrayHasKey('id', $taxRuleData, "Tax rule ID is expected");
        $this->assertGreaterThan(0, $taxRuleData['id']);
        $taxRuleId = $taxRuleData['id'];
        unset($taxRuleData['id']);
        $this->assertEquals($requestData['rule'], $taxRuleData, "Tax rule is created with invalid data.");
        /** Ensure that tax rule was actually created in DB */
        /** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
        $taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
        $this->assertEquals($taxRuleId, $taxRule->load($taxRuleId)->getId(), 'Tax rule was not created in DB.');
        $taxRule->delete();
    }

    public function testCreateTaxRuleInvalidTaxClassIds()
    {
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => HttpConstants::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        $requestData = [
            'rule' => [
                'code' => 'Test Rule ' . microtime(),
                'position' => 10,
                'priority' => 5,
                'customer_tax_class_ids' => [2],
                'product_tax_class_ids' => [3],
                'tax_rate_ids' => [1, 2],
                'calculate_subtotal' => 1,
            ],
        ];

        try {
            $this->_webApiCall($serviceInfo, $requestData);
            $this->fail('Did not throw expected InputException');
        } catch (\SoapFault $e) {
            $this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage());
        } catch (\Exception $e) {
            $this->assertContains('No such entity with customer_tax_class_ids = %fieldValue', $e->getMessage());
        }
    }

    public function testCreateTaxRuleExistingCode()
    {
        $expectedMessage = '%1 already exists.';
        $requestData = [
            'rule' => [
                'code' => 'Test Rule ' . microtime(),
                'position' => 10,
                'priority' => 5,
                'customer_tax_class_ids' => [3],
                'product_tax_class_ids' => [2],
                'tax_rate_ids' => [1, 2],
                'calculate_subtotal' => 0,
            ],
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        $newTaxRuleData = $this->_webApiCall($serviceInfo, $requestData);
        try {
            $this->_webApiCall($serviceInfo, $requestData);
            $this->fail('Expected exception was not raised');
        } catch (\SoapFault $e) {
            $this->assertContains(
                $expectedMessage,
                $e->getMessage(),
                'SoapFault does not contain expected message.'
            );
        } catch (\Exception $e) {
            $errorObj = $this->processRestExceptionResult($e);
            $this->assertEquals($expectedMessage, $errorObj['message']);
            $this->assertEquals(['Code'], $errorObj['parameters']);
        }

        // Clean up the new tax rule so it won't affect other tests
        /** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
        $taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
        $taxRule->load($newTaxRuleData['id']);
        $taxRule->delete();
    }

    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testGetTaxRule()
    {
        $fixtureRule = $this->getFixtureTaxRules()[0];
        $taxRuleId = $fixtureRule->getId();

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Get',
            ],
        ];

        $expectedRuleData = [
            'id' => $taxRuleId,
            'code' => 'Test Rule Duplicate',
            'priority' => '0',
            'position' => '0',
            'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
            'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
            'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
            'calculate_subtotal' => false,
        ];
        $requestData = ['ruleId' => $taxRuleId];
        $result = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertEquals($expectedRuleData, $result);
    }
    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testSearchTaxRulesSimple()
    {
        // Find rules whose code is 'Test Rule'
        $filter = $this->filterBuilder->setField('code')
            ->setValue('Test Rule')
            ->create();

        $this->searchCriteriaBuilder->addFilters([$filter]);

        $fixtureRule = $this->getFixtureTaxRules()[1];

        $searchData = $this->searchCriteriaBuilder->create()->__toArray();
        $requestData = ['searchCriteria' => $searchData];
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'GetList',
            ],
        ];

        /** @var \Magento\Framework\Api\SearchResults $searchResults */
        $searchResults = $this->_webApiCall($serviceInfo, $requestData);

        $this->assertEquals(1, $searchResults['total_count']);

        $expectedRuleData = [
            [
                'id' => $fixtureRule->getId(),
                'code' => 'Test Rule',
                'priority' => 0,
                'position' => 0,
                'calculate_subtotal' => 0,
                'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
                'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
                'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
            ],
        ];
        $this->assertEquals($expectedRuleData, $searchResults['items']);
    }

    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testSearchTaxRulesCodeLike()
    {
        // Find rules whose code starts with 'Test Rule'
        $filter = $this->filterBuilder
            ->setField('code')
            ->setValue('Test Rule%')
            ->setConditionType('like')
            ->create();

        $sortFilter = $this->filterBuilder
            ->setField('position')
            ->setValue(0)
            ->create();

        $this->searchCriteriaBuilder->addFilters([$filter, $sortFilter]);

        $fixtureRule = $this->getFixtureTaxRules()[1];

        $searchData = $this->searchCriteriaBuilder->create()->__toArray();
        $requestData = ['searchCriteria' => $searchData];
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'GetList',
            ],
        ];

        /** @var \Magento\Framework\Api\SearchResults $searchResults */
        $searchResults = $this->_webApiCall($serviceInfo, $requestData);

        $this->assertEquals(2, $searchResults['total_count']);

        $expectedRuleData = [
            [
                'id' => $fixtureRule->getId(),
                'code' => 'Test Rule',
                'priority' => 0,
                'position' => 0,
                'calculate_subtotal' => 0,
                'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
                'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
                'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates())),
            ],
            [
                'id' => $this->getFixtureTaxRules()[0]->getId(),
                'code' => 'Test Rule Duplicate',
                'priority' => 0,
                'position' => 0,
                'calculate_subtotal' => 0,
                'customer_tax_class_ids' => array_values(array_unique($fixtureRule->getCustomerTaxClasses())),
                'product_tax_class_ids' => array_values(array_unique($fixtureRule->getProductTaxClasses())),
                'tax_rate_ids' => array_values(array_unique($fixtureRule->getRates()))
            ],
        ];
        $this->assertEquals($expectedRuleData, $searchResults['items']);
    }

    public function testGetTaxRuleNotExist()
    {
        $taxRuleId = 37865;
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . "/$taxRuleId",
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Get',
            ],
        ];
        $requestData = ['ruleId' => $taxRuleId];
        try {
            $this->_webApiCall($serviceInfo, $requestData);
            $this->fail('Expected exception was not raised');
        } catch (\Exception $e) {
            $expectedMessage = 'No such entity with %fieldName = %fieldValue';

            $this->assertContains(
                $expectedMessage,
                $e->getMessage(),
                "Exception does not contain expected message."
            );
        }
    }
    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testUpdateTaxRule()
    {
        $fixtureRule = $this->getFixtureTaxRules()[0];
        $requestData = [
            'rule' => [
                'id' => $fixtureRule->getId(),
                'code' => 'Test Rule ' . microtime(),
                'position' => 10,
                'priority' => 5,
                'customer_tax_class_ids' => [3],
                'product_tax_class_ids' => [2],
                'tax_rate_ids' => [1, 2],
                'calculate_subtotal' => 1,
            ],
        ];
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        $this->_webApiCall($serviceInfo, $requestData);
        $expectedRuleData = $requestData['rule'];
        /** Ensure that tax rule was actually updated in DB */
        /** @var \Magento\Tax\Model\Calculation $taxCalculation */
        $taxCalculation = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation');
        /** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
        $taxRule = Bootstrap::getObjectManager()->create(
            'Magento\Tax\Model\Calculation\Rule',
            ['calculation' => $taxCalculation]
        );
        $taxRuleModel = $taxRule->load($fixtureRule->getId());
        $this->assertEquals($expectedRuleData['id'], $taxRuleModel->getId(), 'Tax rule was not updated in DB.');
        $this->assertEquals(
            $expectedRuleData['code'],
            $taxRuleModel->getCode(),
            'Tax rule code was updated incorrectly.'
        );
        $this->assertEquals(
            $expectedRuleData['position'],
            $taxRuleModel->getPosition(),
            'Tax rule sort order was updated incorrectly.'
        );
        $this->assertEquals(
            $expectedRuleData['priority'],
            $taxRuleModel->getPriority(),
            'Tax rule priority was updated incorrectly.'
        );
        $this->assertEquals(
            $expectedRuleData['customer_tax_class_ids'],
            array_values(array_unique($taxRuleModel->getCustomerTaxClasses())),
            'Customer Tax classes were updated incorrectly'
        );
        $this->assertEquals(
            $expectedRuleData['product_tax_class_ids'],
            array_values(array_unique($taxRuleModel->getProductTaxClasses())),
            'Detail Tax classes were updated incorrectly.'
        );
        $this->assertEquals(
            $expectedRuleData['tax_rate_ids'],
            array_values(array_unique($taxRuleModel->getRates())),
            'Tax rates were updated incorrectly.'
        );
    }
    public function testUpdateTaxRuleNotExisting()
    {
        $requestData = [
            'rule' => [
                'id' => 12345,
                'code' => 'Test Rule ' . microtime(),
                'position' => 10,
                'priority' => 5,
                'customer_tax_class_ids' => [3],
                'product_tax_class_ids' => [2],
                'tax_rate_ids' => [1, 2],
            ],
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        try {
            $this->_webApiCall($serviceInfo, $requestData);
            $this->fail('Expected exception was not raised');
        } catch (\Exception $e) {
            $expectedMessage = 'No such entity with %fieldName = %fieldValue';

            $this->assertContains(
                $expectedMessage,
                $e->getMessage(),
                "Exception does not contain expected message."
            );
        }
    }

    /**
     * @magentoApiDataFixture Magento/Tax/_files/tax_classes.php
     */
    public function testSearchTaxRule()
    {
        $fixtureRule = $this->getFixtureTaxRules()[0];

        $filter = $this->filterBuilder->setField('code')
            ->setValue($fixtureRule->getCode())
            ->create();
        $this->searchCriteriaBuilder->addFilters([$filter]);
        $searchData = $this->searchCriteriaBuilder->create()->__toArray();
        $requestData = ['searchCriteria' => $searchData];
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/search' . '?' . http_build_query($requestData),
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'GetList',
            ],
        ];
        $searchResults = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertEquals(1, $searchResults['total_count']);
        $this->assertEquals($fixtureRule->getId(), $searchResults['items'][0]["id"]);
        $this->assertEquals($fixtureRule->getCode(), $searchResults['items'][0]['code']);
    }

    /**
     * Get tax rates created in Magento\Tax\_files\tax_classes.php
     *
     * @return \Magento\Tax\Model\Calculation\Rate[]
     */
    private function getFixtureTaxRates()
    {
        if ($this->fixtureTaxRates === null) {
            $this->fixtureTaxRates = [];
            if ($this->getFixtureTaxRules()) {
                $taxRateIds = (array)$this->getFixtureTaxRules()[0]->getRates();
                foreach ($taxRateIds as $taxRateId) {
                    /** @var \Magento\Tax\Model\Calculation\Rate $taxRate */
                    $taxRate = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rate');
                    $this->fixtureTaxRates[] = $taxRate->load($taxRateId);
                }
            }
        }
        return $this->fixtureTaxRates;
    }

    /**
     * Get tax classes created in Magento\Tax\_files\tax_classes.php
     *
     * @return \Magento\Tax\Model\ClassModel[]
     */
    private function getFixtureTaxClasses()
    {
        if ($this->fixtureTaxClasses === null) {
            $this->fixtureTaxClasses = [];
            if ($this->getFixtureTaxRules()) {
                $taxClassIds = array_merge(
                    (array)$this->getFixtureTaxRules()[0]->getCustomerTaxClasses(),
                    (array)$this->getFixtureTaxRules()[0]->getProductTaxClasses()
                );
                foreach ($taxClassIds as $taxClassId) {
                    /** @var \Magento\Tax\Model\ClassModel $taxClass */
                    $taxClass = Bootstrap::getObjectManager()->create('Magento\Tax\Model\ClassModel');
                    $this->fixtureTaxClasses[] = $taxClass->load($taxClassId);
                }
            }
        }
        return $this->fixtureTaxClasses;
    }

    /**
     * Get tax rule created in Magento\Tax\_files\tax_classes.php
     *
     * @return \Magento\Tax\Model\Calculation\Rule[]
     */
    private function getFixtureTaxRules()
    {
        if ($this->fixtureTaxRules === null) {
            $this->fixtureTaxRules = [];
            $taxRuleCodes = ['Test Rule Duplicate', 'Test Rule'];
            foreach ($taxRuleCodes as $taxRuleCode) {
                /** @var \Magento\Tax\Model\Calculation\Rule $taxRule */
                $taxRule = Bootstrap::getObjectManager()->create('Magento\Tax\Model\Calculation\Rule');
                $taxRule->load($taxRuleCode, 'code');
                if ($taxRule->getId()) {
                    $this->fixtureTaxRules[] = $taxRule;
                }
            }
        }
        return $this->fixtureTaxRules;
    }
}


text:
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

WebInspector.ApplicationCacheManager = (function (_WebInspector$Object) {
    _inherits(ApplicationCacheManager, _WebInspector$Object);

    function ApplicationCacheManager() {
        _classCallCheck(this, ApplicationCacheManager);

        _get(Object.getPrototypeOf(ApplicationCacheManager.prototype), "constructor", this).call(this);

        if (window.ApplicationCacheAgent) ApplicationCacheAgent.enable();

        WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
        WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ChildFrameWasRemoved, this._childFrameWasRemoved, this);

        this._online = true;

        this.initialize();
    }

    // Public

    _createClass(ApplicationCacheManager, [{
        key: "initialize",
        value: function initialize() {
            this._applicationCacheObjects = {};

            if (window.ApplicationCacheAgent) ApplicationCacheAgent.getFramesWithManifests(this._framesWithManifestsLoaded.bind(this));
        }
    }, {
        key: "networkStateUpdated",
        value: function networkStateUpdated(isNowOnline) {
            this._online = isNowOnline;

            this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.NetworkStateUpdated, { online: this._online });
        }
    }, {
        key: "applicationCacheStatusUpdated",
        value: function applicationCacheStatusUpdated(frameId, manifestURL, status) {
            var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId);
            if (!frame) return;

            this._frameManifestUpdated(frame, manifestURL, status);
        }
    }, {
        key: "requestApplicationCache",
        value: function requestApplicationCache(frame, callback) {
            function callbackWrapper(error, applicationCache) {
                if (error) {
                    callback(null);
                    return;
                }

                callback(applicationCache);
            }

            ApplicationCacheAgent.getApplicationCacheForFrame(frame.id, callbackWrapper);
        }

        // Private

    }, {
        key: "_mainResourceDidChange",
        value: function _mainResourceDidChange(event) {
            console.assert(event.target instanceof WebInspector.Frame);

            if (event.target.isMainFrame()) {
                // If we are dealing with the main frame, we want to clear our list of objects, because we are navigating to a new page.
                this.initialize();

                this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.Cleared);

                return;
            }

            if (window.ApplicationCacheAgent) ApplicationCacheAgent.getManifestForFrame(event.target.id, this._manifestForFrameLoaded.bind(this, event.target.id));
        }
    }, {
        key: "_childFrameWasRemoved",
        value: function _childFrameWasRemoved(event) {
            this._frameManifestRemoved(event.data.childFrame);
        }
    }, {
        key: "_manifestForFrameLoaded",
        value: function _manifestForFrameLoaded(frameId, error, manifestURL) {
            if (error) return;

            var frame = WebInspector.frameResourceManager.frameForIdentifier(frameId);
            if (!frame) return;

            if (!manifestURL) this._frameManifestRemoved(frame);
        }
    }, {
        key: "_framesWithManifestsLoaded",
        value: function _framesWithManifestsLoaded(error, framesWithManifests) {
            if (error) return;

            for (var i = 0; i < framesWithManifests.length; ++i) {
                var frame = WebInspector.frameResourceManager.frameForIdentifier(framesWithManifests[i].frameId);
                if (!frame) continue;

                this._frameManifestUpdated(frame, framesWithManifests[i].manifestURL, framesWithManifests[i].status);
            }
        }
    }, {
        key: "_frameManifestUpdated",
        value: function _frameManifestUpdated(frame, manifestURL, status) {
            if (status === WebInspector.ApplicationCacheManager.Status.Uncached) {
                this._frameManifestRemoved(frame);
                return;
            }

            if (!manifestURL) return;

            var manifestFrame = this._applicationCacheObjects[frame.id];
            if (manifestFrame && manifestURL !== manifestFrame.manifest.manifestURL) this._frameManifestRemoved(frame);

            var oldStatus = manifestFrame ? manifestFrame.status : -1;
            var statusChanged = manifestFrame && status !== oldStatus;
            if (manifestFrame) manifestFrame.status = status;

            if (!this._applicationCacheObjects[frame.id]) {
                var cacheManifest = new WebInspector.ApplicationCacheManifest(manifestURL);
                this._applicationCacheObjects[frame.id] = new WebInspector.ApplicationCacheFrame(frame, cacheManifest, status);

                this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestAdded, { frameManifest: this._applicationCacheObjects[frame.id] });
            }

            if (statusChanged) this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestStatusChanged, { frameManifest: this._applicationCacheObjects[frame.id] });
        }
    }, {
        key: "_frameManifestRemoved",
        value: function _frameManifestRemoved(frame) {
            if (!this._applicationCacheObjects[frame.id]) return;

            delete this._applicationCacheObjects[frame.id];

            this.dispatchEventToListeners(WebInspector.ApplicationCacheManager.Event.FrameManifestRemoved, { frame: frame });
        }
    }, {
        key: "applicationCacheObjects",
        get: function get() {
            var applicationCacheObjects = [];
            for (var id in this._applicationCacheObjects) applicationCacheObjects.push(this._applicationCacheObjects[id]);
            return applicationCacheObjects;
        }
    }, {
        key: "online",
        get: function get() {
            return this._online;
        }
    }]);

    return ApplicationCacheManager;
})(WebInspector.Object);

WebInspector.ApplicationCacheManager.Event = {
    Cleared: "application-cache-manager-cleared",
    FrameManifestAdded: "application-cache-manager-frame-manifest-added",
    FrameManifestRemoved: "application-cache-manager-frame-manifest-removed",
    FrameManifestStatusChanged: "application-cache-manager-frame-manifest-status-changed",
    NetworkStateUpdated: "application-cache-manager-network-state-updated"
};

WebInspector.ApplicationCacheManager.Status = {
    Uncached: 0,
    Idle: 1,
    Checking: 2,
    Downloading: 3,
    UpdateReady: 4,
    Obsolete: 5
};


text:
 package kafka.utils

import kafka.common._
import scala.collection._
import util.parsing.json.JSON

/**
 *  A wrapper that synchronizes JSON in scala, which is not threadsafe.
 */
object Json extends Logging {
  val myConversionFunc = {input : String => input.toInt}
  JSON.globalNumberParser = myConversionFunc
  val lock = new Object

  /**
   * Parse a JSON string into an object
   */
  def parseFull(input: String): Option[Any] = {
    lock synchronized {
      try {
        JSON.parseFull(input)
      } catch {
        case t: Throwable =>
          throw new KafkaException("Can't parse json string: %s".format(input), t)
      }
    }
  }

  /**
   * Encode an object into a JSON string. This method accepts any type T where
   *   T => null | Boolean | String | Number | Map[String, T] | Array[T] | Iterable[T]
   * Any other type will result in an exception.
   *
   * This method does not properly handle non-ascii characters.
   */
  def encode(obj: Any): String = {
    obj match {
      case null => "null"
      case b: Boolean => b.toString
      case s: String => "\"" + s + "\""
      case n: Number => n.toString
      case m: Map[_, _] =>
        "{" +
          m.map(elem =>
            elem match {
            case t: Tuple2[_,_] => encode(t._1) + ":" + encode(t._2)
            case _ => throw new IllegalArgumentException("Invalid map element (" + elem + ") in " + obj)
          }).mkString(",") +
      "}"
      case a: Array[_] => encode(a.toSeq)
      case i: Iterable[_] => "[" + i.map(encode).mkString(",") + "]"
      case other: AnyRef => throw new IllegalArgumentException("Unknown arguement of type " + other.getClass + ": " + other)
    }
  }
}


text:
import math
import sys
import time
import random
from timeit import default_timer as timer

class City:
    def __init__(self, number, xc, yc):
        self.cNum = number
        self.x = xc
        self.y = yc

    def distanceTo(self, endpoint):
        xdiff = endpoint.x - self.x
        ydiff = endpoint.y - self.y
        dist = math.sqrt(xdiff*xdiff + ydiff*ydiff)
        return int(round(dist))

def tourLength(tourArray):
    n = len(tourArray)
    dSum = tourArray[n-1].distanceTo(tourArray[0])
    for i in range(n-1):
        dSum += tourArray[i].distanceTo(tourArray[i+1])
    return dSum

def initTour(inFile):
    cities = []
    for line in inFile:
        if line != "":
            cParams = [int(n) for n in line.split()]
            cities.append(City(cParams[0], cParams[1], cParams[2]))
    return cities

def anneal(tour, Tmax, alpha, steps, attempts, changes, startTime):
    temp = Tmax
    for k in range(steps):
    # changed to loop up to
    #while temp > 1e-6:
        print("Temperature = {}, Tour Length = {}, Time Elapsed = {}".format(temp, tourLength(tour), timer() - startTime))
        tour = tSearch(tour, temp, attempts, changes)
        temp *= alpha
    return tour

def tSearch(tour, temp, attempts, changes):
    nAtt = 0
    nChg = 0

    while nAtt < attempts and nChg < changes:
        # tSelect will return the tuple ci, cj, dE
        selectionTuple = tSelect(tour)
        if accept(selectionTuple[2], temp):
            tour = tChange(tour, selectionTuple[0], selectionTuple[1])
            nChg += 1
        nAtt += 1
        if nAtt >= attempts:
            print("Max number of attempts reached, cooling...")
        if nChg >= changes:
            print("Max number of tour changes reached, cooling...")

    return tour

def tSelect(tour):
    # pick random cities in tour
    ci = random.randint(0, len(tour) - 1)
    cj = random.randint(0, len(tour) - 1)

    # find the cities directly after ci and cj
    cinx = (ci + 1) % len(tour)
    cjnx = (cj + 1) % len(tour)

    # calculate energy change , i.e. tour length change, for reversing the sequence
    # between ci and cj
    if ci != cj:
        dE = (tour[ci].distanceTo(tour[cj]) + tour[cinx].distanceTo(tour[cjnx])
              - tour[ci].distanceTo(tour[cinx]) - tour[cj].distanceTo(tour[cjnx]))
    else:
        dE = 0

    return ci, cj, float(dE)

def accept(dE, temp):
    if dE > 0:
        acceptance = (math.exp(-dE / temp) > random.random())
    else:
        acceptance = True

    return acceptance

def tChange(tour, ci, cj):
    n = len(tour)
    # snippet does not wrap around end of list
    if ci < cj:
        tSnip = tour[(ci+1):(cj+1)]
        rSnip = list(reversed(tSnip))
        tour[(ci + 1):(cj + 1)] = rSnip[:]
    else:
        # the snippet wraps around the end of the list, so ninjutsu is needed...
        tSnip = tour[(ci+1):] + tour[:(cj+1)]
        rSnip = list(reversed(tSnip))
        divider = len(tour[(ci+1):])
        tour[(ci+1):] = rSnip[:divider]
        tour[:(cj + 1)] = rSnip[divider:]

    return tour

def main():
    random.seed(time.clock())

    # set up I/O files
    inputFileName = str(sys.argv[1])
    #inputFileName = sys.path[0] + "/tsp_example_3.txt"
    inputFile = open(inputFileName, 'r')
    outputFileName = inputFileName + ".tour"
    outputFile = open(outputFileName, 'w')

    # the cityTour list will hold the current tour sequence
    cityTour = initTour(inputFile)
    random.shuffle(cityTour)

    # initialize simulation parameters per recommendations by Hansen
    n = len(cityTour)
    Tmax = round(math.sqrt(n))
    alpha = 0.95
    steps = 20 * int(round(math.log1p(n + 1)))
    attempts = 100 * n
    changes = 10 * n

    # call the annealing function with the defined parameters
    startTime = timer()
    cityTour = anneal(cityTour, Tmax, alpha, steps, attempts, changes, startTime)
    end = timer()
    print("Algorithm ran in {} seconds".format(end - startTime))

    # write output file
    outputFile.write(str(tourLength(cityTour)) + '\n')
    for k in range(n):
        outstring = str(cityTour[k].cNum) + '\n'
        outputFile.write(outstring)

    inputFile.close()
    outputFile.close()

if __name__ == '__main__':
  main()


text:
var amdOptimize = require("amd-optimize");
var clean = require('gulp-clean');
var concat = require("gulp-concat");
var cover = require('gulp-coverage');
var csslint = require('gulp-csslint');
var gulp = require('gulp');
var htmlhint = require("gulp-htmlhint");
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var minifyHTML = require('gulp-minify-html');
var mocha = require('gulp-mocha');
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');

var configuration = require('./gulp/configuration');
var homeBuilder = require('./gulp/homeBuilder');
var taskAsync = require('./gulp/taskAsync');
var templateInjector = require('./gulp/templateInjector');
var templateWrapper = require('./gulp/templateWrapper');
var testRunner = require('./gulp/testRunner');

var clientConfiguration = configuration.client;
var serverConfiguration = configuration.server;

gulp.task('dev-html-create-layout', function () {
    return gulp.src(clientConfiguration.getLayoutPath())
        .pipe(rename(clientConfiguration.getHomeFileName()))
        .pipe(gulp.dest(clientConfiguration.getDirectory()));
});

gulp.task('dev-html-layout', ['dev-html-create-layout'], function () {
    return gulp.src(clientConfiguration.getTemplateFilesPattern())
        .pipe(templateWrapper.wrap())
        .pipe(templateInjector.inject(clientConfiguration.getHomePath()));
});

gulp.task('dev-html-templates-watch', ['dev-html-layout'], function () {
    gulp.watch(clientConfiguration.getLayoutPath(), ['dev-html-layout']);

    watch({glob: clientConfiguration.getTemplateFilesPattern()})
        .pipe(plumber())
        .pipe(templateWrapper.wrap())
        .pipe(templateInjector.inject(clientConfiguration.getHomePath()));
});

gulp.task('dev-css-less-watch', function () {
    watch({glob: clientConfiguration.getLessFilesPattern()})
        .pipe(plumber())
        .pipe(less())
        .pipe(gulp.dest(clientConfiguration.getCssDirectory()));
});

gulp.task('dev-js-server-test-watch', ['test-server'], function () {
    gulp.watch(serverConfiguration.getAllJavascriptFilesPattern(), ['test-server']);
});

gulp.task('dev-js-client-test-watch', function () {
    testRunner.runClient(true);
});

gulp.task('check-js-watch', function() {
    watch({glob: configuration.getAllJavascriptFilesWithoutTestsPattern()})
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('check-html-watch', function() {
    watch({glob: clientConfiguration.getHtmlFilesPattern()})
        .pipe(plumber())
        .pipe(htmlhint({
            "doctype-first": false
        }))
        .pipe(htmlhint.reporter());
});

gulp.task('check-css-watch', function() {
    watch({glob: clientConfiguration.getCssFilesPattern()})
        .pipe(plumber())
        .pipe(csslint())
        .pipe(csslint.reporter());
});

gulp.task('check-watch', ['check-js-watch', 'check-html-watch', 'check-css-watch']);
gulp.task('test-watch', ['dev-js-server-test-watch', 'dev-js-client-test-watch']);

gulp.task('dev', ['dev-css-less-watch', 'test-watch', 'check-watch', 'dev-html-templates-watch']);

gulp.task('test-server-cover', function () {
    return gulp.src(serverConfiguration.getTestFilesPattern(), { read: false })
        .pipe(cover.instrument({
            pattern: serverConfiguration.getJavascriptFilesPattern(),
            debugDirectory: serverConfiguration.getCoverTempDirectory()
        }))
        .pipe(mocha())
        .pipe(cover.report({
            outFile: serverConfiguration.getCoverOutput()
        }));
});

gulp.task('test-server', function () {
    return testRunner.runServer(serverConfiguration.getTestDirectory());
});

gulp.task('test-server-with-report', function () {
    return testRunner.runServer(serverConfiguration.getTestDirectory(), true);
});

gulp.task('test-client', function() {
    return testRunner.runClient();
});

gulp.task('test', ['test-client', 'test-server']);

gulp.task('check-js', function() {
    return gulp.src(configuration.getAllJavascriptFilesWithoutTestsPattern())
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('check-html', function() {
    return gulp.src(clientConfiguration.getHtmlFilesPattern())
        .pipe(htmlhint({
            "doctype-first": false
        }))
        .pipe(htmlhint.reporter());
});

gulp.task('check-css', function() {
    return gulp.src(clientConfiguration.getCssFilesPattern())
        .pipe(csslint())
        .pipe(csslint.reporter());
});

gulp.task('check', ['check-css', 'check-html', 'check-js']);

gulp.task('build-css', function() {
    return gulp.src(clientConfiguration.getLessFilesPattern())
        .pipe(less())
        .pipe(concat(clientConfiguration.getBuildCssFileName()))
        .pipe(minifyCSS())
        .pipe(gulp.dest(clientConfiguration.getBuildDirectory()));
});

gulp.task('build-js', function() {
    var requireJsConfiguration = {
        optimize: "none"
    };

    var externalLibNames = clientConfiguration.getExternalLibNames();
    requireJsConfiguration.paths = {};
    for(var key in externalLibNames){
        requireJsConfiguration.paths[externalLibNames[key]] = 'empty:';
    }

    return gulp.src(clientConfiguration.getJavascriptFilesPattern())
        .pipe(amdOptimize(clientConfiguration.getRequireMainModule(), requireJsConfiguration))
        .pipe(concat(clientConfiguration.getBuildJavascriptFileName()))
        .pipe(uglify())
        .pipe(gulp.dest(clientConfiguration.getBuildDirectory()));
});

gulp.task('build-html-templates', function () {
    return gulp.src(clientConfiguration.getTemplateFilesPattern())
        .pipe(templateWrapper.wrap())
        .pipe(concat(clientConfiguration.getBuildTemplateFileName()))
        .pipe(gulp.dest(clientConfiguration.getBuildDirectory()));
});

gulp.task('build-html', ['build-html-templates'], function() {
    return gulp.src(clientConfiguration.getLayoutPath())
        .pipe(homeBuilder.injectExternalCss())
//        .pipe(homeBuilder.injectExternalJs())
        .pipe(homeBuilder.injectBuildedCss())
        .pipe(homeBuilder.injectBuildedJs())
        .pipe(homeBuilder.injectBuildedTemplates())
        .pipe(homeBuilder.addVersionOnFilesIncluded())
        .pipe(minifyHTML())
        .pipe(rename(clientConfiguration.getHomeFileName()))
        .pipe(gulp.dest(clientConfiguration.getBuildDirectory()));
});

gulp.task('build-staticFiles', function() {
    return gulp.src(clientConfiguration.getStaticFilesPattern())
        .pipe(gulp.dest(clientConfiguration.getBuildDirectory()));
});

gulp.task('build-clean', function() {
    return gulp.src(clientConfiguration.getBuildDirectory(), {read: false})
        .pipe(clean());
});

taskAsync.create('build', function(){
    return taskAsync.start('build-clean')
        .then(function(){
            return taskAsync.start('build-css')
        }).then(function(){
            return taskAsync.start('build-js')
        }).then(function(){
            return taskAsync.start('build-html')
        }).then(function(){
            return taskAsync.start('build-staticFiles')
        });
});

gulp.task('default', ['dev']);

gulp.task('jenkins', function(){
    gulp.start('test-client');
    gulp.start('test-server-with-report');
});