text:
typedef bool (_cdecl * AnalyzingData)(void *, int length);
typedef bool (_cdecl * AutoAnalyzingData)(void *, int length);
typedef void (_cdecl * SayHello)();

class ServiceDLL{
protected:
	static ServiceDLL* instance;
	ServiceDLL();

	QLibrary qLib;
	AnalyzingData analyzingData;
	AutoAnalyzingData autoAnalyzingData;
	SayHello sayHello;
public:
	~ServiceDLL();
	static ServiceDLL* getInstance();

	bool execServiceAnalyze(AI_TrajectoryAnalysis*&);
	bool execServiceAuto(AI_TrajectoryAnalysis*&);
	void releaseDLL();
	bool loadDLL(std::string path);
};

#endif

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>VM Infrastructure: stack_trace.h File Reference</title>
<link href="hydoxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Packages

Classes

Files

Related Pages

File List

File Members

stack_trace.h File Reference

Detailed Description

Mechanism for tracing the stack of Java and native code.

This module provides stack traces. A stack trace is a sequence of frames counting from the top to the bottom of the stack.

The stack trace inlcudes one frame for each managed stack frame and one frame for each M2N frame that has an associated method. For each frame, the method and the IP are provided and, optionally, the file and line number.

The current implementation supports the following types of frames:

Managed code frames corresponding to Java code

Managed-to-native frames (M2N) for transferring data and control between managed and native frames

Native frames iteration is not currently supported. To iterate over native frames, use OS-provided tools.

Classes

struct  	StackTraceFrame

Functions

VMEXPORT unsigned 	st_get_depth (VM_thread *p_vmthread)

 	Gets the depth of the stack trace for the specified thread.

VMEXPORT bool 	st_get_frame (unsigned depth, StackTraceFrame *stf)

 	Fills the stack trace frame at the given relative depth for the current thread.

VMEXPORT StackTraceFrame * 	st_alloc_frames (int num)

 	Allocates memory required for the given number of stack trace frames.

VMEXPORT void 	st_get_trace (VM_thread *p_vmthread, unsigned *depth, StackTraceFrame **stfs)

 	Fills the stack trace frames for the specified number of frames of the specified thread.

VMEXPORT void 	get_file_and_line (Method_Handle method, void *ip, bool is_ip_past, int depth, const char **file, int *line)

 	Fills the given pointer to a source file and line number by using the given method and IP.

void 	st_print_frame (ExpandableMemBlock *buf, StackTraceFrame *stf)

 	Appends data about the given frame to the expandable buffer in a human-readable form.

void 	st_print_all (FILE *f)

 	Prints stack trace of all java threads.

void 	st_print (FILE *f, hythread_t thread)

 	Prints the current java thread stack trace into specified stream.

void 	st_print ()

 	Prints the current java thread stack trace into the stderr stream.

Function Documentation

          VMEXPORT unsigned st_get_depth
          (
          VM_thread *
           p_vmthread
           )

Gets the depth of the stack trace for the specified thread.

The depth is the number of supported stack frames in the current thread stack, from most recently pushed to the first pushed. The depth also includes the number of inlined methods.

Parameters:

<tt>[in]</tt> 	p_vmthread 	- pointer to the thread

Returns:

The number of frames above the current one including the current frame and inlined methods.

          VMEXPORT bool st_get_frame
          (
          unsigned
           depth,

          StackTraceFrame *
           stf

          )

Fills the stack trace frame at the given relative depth for the current thread.

Parameters:

<tt>[in]</tt> 	depth 	- relative depth of a frame or inlined method on the stack, topmost frame has zero depth.

<tt>[out]</tt> 	stf 	- the pointer to the StackTraceFrame structure that needs to be filled with the data on the frame or inlined method corresponding to the given depth

Returns:

TRUE on success, FALSE if the depth is greater than or equal to thecurrent thread's stack trace length.

          VMEXPORT StackTraceFrame* st_alloc_frames
          (
          int
           num
           )

Allocates memory required for the given number of stack trace frames.

Used internaly by the interpreter to avoid memory allocation/de-allocation conflicts in the VM and DLLs on Windows / IA-32 systems.

Parameters:

<tt>[in]</tt> 	num 	- required number of stack trace frames

Returns:

The pointer to the allocated array of stack trace frames.

Note:

The caller is responsible for freeing the memory.

          VMEXPORT void st_get_trace
          (
          VM_thread *
           p_vmthread,

          unsigned *
           depth,

          StackTraceFrame **
           stfs

          )

Fills the stack trace frames for the specified number of frames of the specified thread.

Parameters:

<tt>[in]</tt> 	p_vmthread 	- pointer to the thread

<tt>[in]</tt> 	depth 	- the number of frames including inlined methods, information about which should be stored

<tt>[out]</tt> 	stfs 	- the pointer to the array of stack trace frames created by this function and returned via this pointer.

Note:

The caller is responsible for freeing the memory.

          VMEXPORT void get_file_and_line
          (
          Method_Handle
           method,

          void *
           ip,

          bool
           is_ip_past,

          int
           depth,

          const char **
           file,

          int *
           line

          )

Fills the given pointer to a source file and line number by using the given method and IP.

Parameters:

<tt>[in]</tt> 	method 	- the handle of the method information to identify the source file

<tt>[in]</tt> 	ip 	- the instruction pointer to identify the JIT and using the JIT line number

<tt>[in]</tt> 	depth 	- the inlined depth for inlined methods; (-1) for native methods and methods which were not inlined

<tt>[out]</tt> 	file 	- the pointer to the file reference to be filled by this function

<tt>[out]</tt> 	line 	- the pointer to the line number to be filled by this function

          void st_print_frame
          (
          ExpandableMemBlock *
           buf,

          StackTraceFrame *
           stf

          )

Appends data about the given frame to the expandable buffer in a human-readable form.

Parameters:

<tt>[in]</tt> 	buf 	- the pointer to ExpandableMemBlock, where data will be added

<tt>[in]</tt> 	stf 	- the pointer to the stack trace frame, data from which will be printed into buffer

          void st_print_all
          (
          FILE *
           f
           )

Prints stack trace of all java threads.

This function supports and prints all Java frames.

Parameters:

<tt>[in]</tt> 	f 	- the pointer to the file, where the stack trace will be printed

Note:

Intended for debugging purposes.

          void st_print
          (
          FILE *
           f,

          hythread_t
           thread

          )

Prints the current java thread stack trace into specified stream.

This function supports and prints all Java frames.

Parameters:

<tt>[in]</tt> 	f 	- the pointer to the file, where the stack trace will be printed

<tt>[in]</tt> 	thread 	- the thread wich stack should be printed

Note:

Intended for debugging purposes.

          void st_print
          (

           )

Prints the current java thread stack trace into the stderr stream.

Note:

Intended for debugging purposes.

<address style="text-align: center;">

Genereated on Tue Mar 11 19:25:58 2008 by Doxygen.

(c) Copyright 2005, 2008 The Apache Software Foundation or its licensors, as applicable.

</address>


text:
r"""

.. autofunction:: openpnm.models.phases.viscosity.water
.. autofunction:: openpnm.models.phases.viscosity.reynolds
.. autofunction:: openpnm.models.phases.viscosity.chung

"""
import numpy as np

def water(target, temperature='pore.temperature', salinity='pore.salinity'):
    r"""
    Calculates viscosity of pure water or seawater at atmospheric pressure
    using Eq. (22) given by Sharqawy et. al [1]. Values at temperature higher
    than the normal boiling temperature are calculated at the saturation
    pressure.

    Parameters
    ----------
    target : OpenPNM Object
        The object for which these values are being calculated. This
        controls the length of the calculated array, and also provides
        access to other necessary thermofluid properties.

    temperature : string
        The dictionary key containing the temperature values. Temperature must
        be in Kelvin for this emperical equation to work. Can be either a pore
        or throat array.

    salinity : string
        The dictionary key containing the salinity values. Salinity must be
        expressed in g of salt per kg of solution (ppt). Can be either a
        pore or throat array, but must be consistent with ``temperature``.

    Returns
    -------
    value : NumPy ndarray
        Array containing viscosity of water/seawater in [kg/m.s]

    Notes
    -----
     T must be in K, and S in g of salt per kg of phase, or ppt (parts per
        thousand)
    VALIDITY: 273 < T < 453 K; 0 < S < 150 g/kg;
    ACCURACY: 1.5 %

    References
    ----------
    [1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
        Water Treatment, 2010.

    """
    T = target[temperature]
    if salinity in target.keys():
        S = target[salinity]
    else:
        S = 0
    TC = T-273.15
    S = S/1000
    a1 = 1.5700386464E-01
    a2 = 6.4992620050E+01
    a3 = -9.1296496657E+01
    a4 = 4.2844324477E-05
    mu_w = a4 + 1/(a1*(TC+a2)**2+a3)
    a5 = 1.5409136040E+00
    a6 = 1.9981117208E-02
    a7 = -9.5203865864E-05
    a8 = 7.9739318223E+00
    a9 = -7.5614568881E-02
    a10 = 4.7237011074E-04
    A = a5 + a6*T + a7*T**2
    B = a8 + a9*T + a10*T**2
    mu_sw = mu_w*(1 + A*S + B*S**2)
    value = mu_sw
    return value

def reynolds(target, u0, b, temperature='pore.temperature'):
    r"""
    Uses exponential model by Reynolds [1] for the temperature dependance of
    shear viscosity

    Parameters
    ----------
    target : OpenPNM Object
        The object for which these values are being calculated.  This
        controls the length of the calculated array, and also provides
        access to other necessary thermofluid properties.

    u0, b : float, array_like
            Coefficients of the viscosity exponential model (mu = u0*Exp(-b*T)
            where T is the temperature in Kelvin

    temperature : string
        The dictionary key containing the temperature values (K).  Can be
        either a pore or throat array.

    Returns
    -------
    value : NumPy ndarray
        Array containing viscosity values based on Reynolds model.

    [1] Reynolds O. (1886). Phil Trans Royal Soc London, v. 177, p.157.

    """
    value = u0*np.exp(b*target[temperature])
    return value

def chung(target, temperature='pore.temperature',
          mol_weight='pore.molecular_weight',
          critical_temperature='pore.critical_temperature',
          critical_volume='pore.critical_volume'):
    r"""
    Uses Chung et al. [1] model to estimate viscosity for gases at low
    pressure (much less than the critical pressure) at conditions of interest.

    Parameters
    ----------
    target : OpenPNM Object
        The object for which these values are being calculated.  This
        controls the length of the calculated array, and also provides
        access to other necessary thermofluid properties.

    temperatre: string
        The dictionary key containing the temperature values (K)

    critical_temperature : string
        The dictionary key containing the temperature values (K)

    mol_weight: string
        The dictionary key containing the molecular weight values (kg/mol)

    critical_volume : string
        The dictionary key containing the critical volume values (m3/kmol)

    Returns
    -------
    value : NumPy ndarray
        Array containing viscosity values based on Chung model [kg/m.s].

    References
    ----------
    [1] Chung, T.H., Lee, L.L., and Starling, K.E., Applications of Kinetic Gas
        Theories and Multiparameter Correlation for Prediction of Dilute Gas
        Viscosity and Thermal Conductivity", Ind. Eng. Chem. Fundam.23:8, 1984.

    """
    T = target[temperature]
    MW = target[mol_weight]
    Tc = target[critical_temperature]
    Vc = target[critical_volume]
    Tr = T / Tc
    Tstar = 1.2593*Tr
    A = 1.161415
    B = 0.14874
    C = 0.52487
    D = 0.77320
    E = 2.16178
    F = 2.43787
    omega = (A*(Tstar)**(-B)) + C*(np.exp(-D*Tstar)) + E*(np.exp(-F*Tstar))
    sigma = 0.809*(Vc**(1/3))
    value = 26.69E-9*np.sqrt(MW*T)/(omega*sigma**2)
    return value


text:
@implementation AppTool

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static AppTool *applicationUtils=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        applicationUtils=[super allocWithZone:zone];
    });
    return applicationUtils;
}

+(instancetype)sharedAppTool
{
    return [[AppTool alloc]init];
}

#pragma mark -getters and setters
-(NSString *)documentPath
{
    if (_documentPath==nil) {
        _documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    }
    return _documentPath;
}

-(NSString *)userDocumentPath
{
    if (AppUser.email==nil) {
        return nil;
    }

    if (_userDocumentPath==nil) {
        //账号不区分大小写,统一用小写字母为名字目录
        _userDocumentPath=[self.documentPath stringByAppendingPathComponent:[AppUser.email lowercaseString]];

        NSFileManager *fileManager=[NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:_userDocumentPath]) {
            NSError *error=nil;
            [fileManager createDirectoryAtPath:_userDocumentPath withIntermediateDirectories:NO attributes:nil error:&error];
            if (error) {
                AppLog(@"创建userDocumentPath错误...");
                _userDocumentPath=@"";
            }
        }
    }

    return _userDocumentPath;
}

-(NSString *)userInfoPath
{
    if (_userInfoPath==nil) {
        _userInfoPath=[self.documentPath stringByAppendingPathComponent:@"curcentUser"];
        NSError *error=nil;

        if (![[NSFileManager defaultManager] createDirectoryAtPath:_userInfoPath withIntermediateDirectories:YES attributes:nil error:&error]) {
            AppLog(@"创建userDataPath错误");
            _userInfoPath= @"";
        }

    }
    return _userInfoPath;
}
@end


text:
package com.twitter.finatra.tests.conversions

import com.twitter.finatra.conversions.future._
import com.twitter.inject.Test
import com.twitter.util.{Throw, Future, Return}

class FutureConversionsTest extends Test {

  def intToString(num: Int): String = num.toString

  def intToFutureString(num: Int): Future[String] = Future(num.toString)

  def intToOptionString(num: Int): Option[String] = Some(num.toString)

  def intToFutureOptionString(num: Int): Future[Option[String]] = Future(Some(num.toString))

  def unitToFutureOptionAbc(): Future[Option[String]] = Future(Some("abc"))

  "Future[Option[T]]" should {
    "#getInnerOrFail" in {
      assertFuture(
        Future(Some(1)) getInnerOrElseFail TestException,
        Future(1))
    }
    "#getInnerOrFail when empty" in {
      assertFailedFuture[TestException](
        Future(None) getInnerOrElseFail TestException)
    }
    "#getInnerOrElseFail when already failed" in {
      assertFailedFuture[TestException](
        Future.exception(ExistingException).getInnerOrElseFail(TestException))
    }
    "#mapInner" in {
      assertFuture(
        Future(Some(1)) mapInner intToString,
        Future(Some("1")))
    }
    "#mapInnerOpt" in {
      assertFuture[Option[String]](
        Future(Some(1)) mapInnerOpt intToOptionString,
        Future(Some("1")))
    }
    "#flatMapInner" in {
      assertFuture(
        Future(Some(1)) flatMapInner intToFutureString,
        Future(Some("1")))
    }
    "#flatMapInnerOpt" in {
      assertFuture(
        Future(Some(1)) flatMapInnerOpt intToFutureOptionString,
        Future(Some("1")))
    }
    "#flatMapIfUndefined when None" in {
      assertFuture(
        Future[Option[String]](None) flatMapIfUndefined { _ =>
          Future(Some("abc"))
        },
        Future(Some("abc")))
    }
    "#flatMapInnerOpt when Some" in {
      assertFuture(
        Future(Some("xyz")) flatMapIfUndefined { _ =>
          Future(Some("abc"))
        },
        Future(Some("xyz")))
    }
  }

  "Future[Seq[T]]" should {
    "#mapInner" in {
      assertFuture(
        Future(Seq(1)) mapInner intToString,
        Future(Seq("1")))
    }
    "#mapInnerOpt" in {
      assertFuture(
        Future(Seq(1)) mapInnerOpt intToOptionString,
        Future(Seq("1")))
    }
    "#flatMapInner" in {
      assertFuture(
        Future(Seq(1)) flatMapInner intToFutureString,
        Future(Seq("1")))
    }
    "#flatMapInnerOpt" in {
      assertFuture(
        Future(Seq(1)) flatMapInnerOpt intToFutureOptionString,
        Future(Seq("1")))
    }
    "#flatMapInnerOpt when empty" in {
      assertFuture(
        Future(Seq[Int]()) flatMapInnerOpt intToFutureOptionString,
        Future(Seq[Int]()))
    }
    "#filter" in {
      assertFuture(
        Future(Seq(0, 1, 2, 3)) filterInner { _ > 1 },
        Future(Seq(2, 3)))
    }
    "#headOption when seq of size 1" in {
      assertFuture(
        Future(Seq(0)).headOption,
        Future(Some(0)))
    }
    "#headOption when seq of size > 1" in {
      assertFuture(
        Future(Seq(0, 1, 2, 3)).headOption,
        Future(Some(0)))
    }
    "#headOption when empty" in {
      assertFuture(
        Future(Seq[Int]()).headOption,
        Future(None))
    }
    "#collectInner" in {
      assertFuture(
        Future(Seq("a", 1)).collectInner { case num: Int => num + 1 },
        Future(Seq(2)))
    }
    "#groupBySingleValue" in {
      assertFuture(
        Future(Seq("a", "aa", "bb", "ccc")).groupBySingleValue { _.size },
        Future(Map(
          1 -> "a",
          2 -> "bb",
          3 -> "ccc")))
    }
  }

  "Future[Option[Seq[T]]]" should {
    "#flattenInner with Some list" in {
      assertFuture(
        Future(Some(Seq(1))).flattenInner,
        Future(Seq(1)))
    }
    "#flattenInner with None" in {
      assertFuture(
        Future(None).flattenInner,
        Future(Seq()))
    }
  }

  "Future[Seq[Future[T]]]" should {
    "#flattenInner with Some list" in {
      assertFuture(
        Future(Seq(Future(1))).flattenInner,
        Future(Seq(1)))
    }
    "#flattenInner with None" in {
      assertFuture(
        Future(Seq()).flattenInner,
        Future(Seq()))
    }
  }

  "Future[T]" should {
    "#toBoolean returns true when Return" in {
      assertFuture(
        Future("asdf").toBoolean,
        Future(true))
    }
    "#toBoolean returns false when Throw" in {
      assertFuture(
        Future.exception(ExistingException).toBoolean,
        Future(false))
    }
    "#toOption returns Some when Return" in {
      assertFuture(
        Future("asdf").toOption,
        Future(Some("asdf")))
    }
    "#toBoolean returns None when Throw" in {
      assertFuture(
        Future.exception(ExistingException).toOption,
        Future(None))
    }
    "#chainedOnFailure succeeds when Return" in {
      assertFuture(
        Future("asdf").chainedOnFailure { throwable =>
          fail("should not run when Return")
        },
        Future("asdf"))
    }
    "#chainedOnFailure succeeds when Throw" in {
      var chainedRan = false

      assertFailedFuture[ExistingException](
        Future.exception(ExistingException).chainedOnFailure { throwable =>
          assert(throwable == ExistingException)
          chainedRan = true
          Future.Unit
        })

      assert(chainedRan)
    }
    "#chainedOnFailure returns failed future when Throw" in {
      var chainedRan = false

      assertFailedFuture[ExistingException](
        Future.exception(ExistingException).chainedOnFailure { throwable =>
          assert(throwable == ExistingException)
          chainedRan = true
          Future.exception(new Exception("another exception"))
        })

      assert(chainedRan)
    }

    "#chainedOnFailure throws Exception when Throw" in {
      var chainedRan = false

      assertFailedFuture[ExistingException](
        Future.exception(ExistingException).chainedOnFailure { throwable =>
          assert(throwable == ExistingException)
          chainedRan = true
          throw new Exception("another exception")
        })

      assert(chainedRan)
    }
  }

  def chainedSuccessFunc(throwable: Throwable): Future[Unit] = {
    Future.Unit
  }

  def chainedFailedFunc(throwable: Throwable): Future[Unit] = {
    Future.exception(new Exception("oops"))
  }

  def chainedFailedThrowsFunc(throwable: Throwable): Future[Unit] = {
    throw new Exception("oops")
  }

  "Future[Boolean]" should {
    var ran = false

    def sideeffect = {
      ran = true
      Future.Unit
    }

    "#flatMapIfTrue when Return(true)" in {
      ran = false
      assertFuture(
        Future(true).flatMapIfTrue(sideeffect),
        Future.Unit)
      ran should equal(true)
    }

    "#flatMapIfTrue when Return(false)" in {
      ran = false
      assertFuture(
        Future(false).flatMapIfTrue(sideeffect),
        Future.Unit)
      ran should equal(false)
    }

    "#flatMapIfTrue when Throw" in {
      ran = false
      assertFailedFuture[ExistingException](
        Future.exception(ExistingException).flatMapIfTrue(sideeffect))
      ran should equal(false)
    }
  }

  "Future[Seq[Seq[A]]]" should {
    "flattenInnerSeq" in {
      assertFuture(
        Future(Seq(Seq(), Seq("a", "b"), Seq("c"))).flattenInnerSeq,
        Future(Seq("a", "b", "c")))
    }
  }

  "Future[T]" should {
    "chainedOnFailure when success" in {
      assertFuture(
        Future(1).chainedOnFailure { e => Future(2).unit },
        Future(1))
    }

    "chainedOnFailure when failure" in {
      assertFuture(
        Future(1).chainedOnFailure { e => Future.exception(new RuntimeException("failure in chained")) },
        Future(1))
    }

    "partialTransform when success matches" in {
      assertFailedFuture[RuntimeException](
        Future(1).partialTransform {
          case Return(r) if r == 1 =>
            Future.exception(new RuntimeException("bad"))
        })
    }

    "partialTransform when success doesn't match" in {
      assertFuture(
        Future(2).partialTransform {
          case Return(r) if r == 1 =>
            Future.exception(new RuntimeException("bad"))
        },
        Future(2))
    }

    "partialTransform when failed" in {
      assertFailedFuture[TestException](
        Future.exception[String](ExistingException).partialTransform {
          case Throw(e: ExistingException) =>
            Future.exception(TestException)
        })
    }
  }

  object TestException extends TestException

  class TestException extends Exception

  object ExistingException extends ExistingException

  class ExistingException extends Exception

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/timeplace"
        android:layout_alignParentLeft="true"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/live"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"/>

        <TextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/live"/>

        <TextView
            android:id="@+id/event"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/date"/>

        <TextView
        android:id="@+id/team1"
        android:layout_alignParentTop="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/date"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="20dp"/>

        <TextView
            android:id="@+id/team2"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginRight="5dp"/>

        <TextView
            android:id="@+id/percent1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/team1"
            android:layout_alignLeft="@id/team1"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"/>

        <TextView
            android:id="@+id/percent2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/team2"
            android:layout_alignLeft="@id/team2"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"/>

    </RelativeLayout>

</RelativeLayout>


text:
<?php $view->script('uikit-form-password') ?>

<form class="pk-user pk-user-reset uk-form uk-form-stacked uk-width-medium-1-2 uk-width-large-1-3 uk-container-center" action="<?= $view->url('@user/resetpassword/confirm', ['key' => $activation]) ?>" method="post">

    <?php if($error): ?>

        <?= $error; ?>

    <?php endif; ?>

<?= __('Password Confirmation') ?>

            <input class="uk-width-1-1" type="password" name="password" value="" placeholder="<?= __('New Password') ?>">
            <a href="" class="uk-form-password-toggle" tabindex="-1" data-uk-form-password="{ lblShow: '<?= __('Show') ?>', lblHide: '<?= __('Hide') ?>' }"><?= __('Show') ?>

        <button class="uk-button uk-button-primary uk-button-large uk-width-1-1" type="submit"><?= __('Confirm') ?></button>

    <?php $view->token()->get() ?>

</form>


text:
import os
import logging

from django.conf import settings
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import TestCase
from selenium.common.exceptions import NoSuchElementException

from .common import WebDriverMixin
from .page import PageElement

class NoLoggingMixin(object):

    def setUp(self):
        # logging.disable(logging.CRITICAL)
        super(NoLoggingMixin, self).setUp()

    def tearDown(self):
        # logging.disable(logging.NOTSET)
        super(NoLoggingMixin, self).tearDown()

class SeleniumAssertionsMixin(object):

    def assertElementExists(self, selector, sleep=None):
        self.sleep(sleep)
        try:
            elem = self.find(selector)
        except NoSuchElementException:
            raise AssertionError('No such element exists: %s'%selector)

    def assertCurrentPath(self, path, sleep=None):
        self.sleep(sleep)
        url = self.wd.current_url
        cur_path = '/' + '/'.join(url.split('/')[3:])
        if path != cur_path:
            raise AssertionError('Paths do not match: %s and %s'%(path, cur_path))

    def assertNotCurrentPath(self, path, sleep=None):
        self.sleep(sleep)
        url = self.wd.current_url
        cur_path = '/' + '/'.join(url.split('/')[3:])
        if path == cur_path:
            raise AssertionError('Paths match (when they should not): %s and %s'%(path, cur_path))

class UnitTestCaseMixin(object):
    pass

class FunctionalTestCaseMixin(object):
    pass

class IntegrationTestCaseMixin(NoLoggingMixin):

    def __init__(self, *args, **kwargs):
        super(IntegrationTestCaseMixin, self).__init__(*args, **kwargs)
        settings.DEBUG = getattr(self, 'use_debug', True)
        settings.CSRF_COOKIE_SECURE = False
        settings.SESSION_COOKIE_SECURE = False

    @classmethod
    def setUpClass(cls):
        if os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', '').lower() == 'hostname':
            import socket
            host = socket.gethostbyname(socket.getfqdn())
            os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = host + ':8081-8179'
        super().setUpClass()

class PageTestCaseMixin(SeleniumAssertionsMixin, IntegrationTestCaseMixin):

    def setUp(self, **kwargs):
        super(PageTestCaseMixin, self).setUp()
        self.setup(**kwargs)

    def tearDown(self):
        super(PageTestCaseMixin, self).tearDown()
        self.teardown()

    def get_domain(self):
        return self.live_server_url

class SeleniumTestCaseMixin(WebDriverMixin, SeleniumAssertionsMixin, IntegrationTestCaseMixin):

    def setUp(self, **kwargs):
        super(SeleniumTestCaseMixin, self).setUp()
        self.setup(**kwargs)

    def tearDown(self):
        super(SeleniumTestCaseMixin, self).tearDown()
        self.teardown()

    def get_domain(self):
        return self.live_server_url

class UnitTestCase(UnitTestCaseMixin, TestCase):
    pass

class FunctionalTestCase(FunctionalTestCaseMixin, TestCase):
    pass

class IntegrationTestCase(IntegrationTestCaseMixin, TestCase):
    pass

class SeleniumTestCase(SeleniumTestCaseMixin, StaticLiveServerTestCase):
    pass

class PageTestCase(PageTestCaseMixin, StaticLiveServerTestCase):
    pass


text:
java functional
==================

JSR 354 Java Functional Examples

same examples using Java 8 with streams, lambda with money-api

---------

- **CreateCurrencyUnit** – The currency unit, it is represented using the CurrencyUnit's interface, it's possible make a instance some forms as inform the currency code or using java.util.Locale of country of origin.

- **CreateMonetaryCurrency** – The monetary value, this class has a strong relationship with a currency. The interface is MonetaryAmount and some implementations are:
Money: implementation that uses BigDecimal to represents the value.
FastMoney: this implementation uses long instead of BigDecimal, it is faster than Money, about 15
times, however has a limited decimals places, just five.

- **FormatExample** – format the money

- **MonetaryFilterOperations** - You may do selection to just one or more currency unit, beyond from a value (greater than, lesser, than, greater and equal than, between, etc.).

- **MonetaryReducerOperations** - Reducer operations such, the greatest value, lesser value, sum.

- **MonetarySorterOperations** - Operation to do sort in a list or stream, so it's possible sort by CurrencyUnit or by value, in asc or desc way, and you can combine, in other words, I may sort by currency unit in ascending way and descending by value.

- **MonetaryGroupOperations** - From Stream or list is possible create a summary (an object that contains informations as size of list, sum, lesser value, greater value and average), a map where the key is CurrencyUnit and the value is a list of MonetaryAmount and a map where the key is CurrencyUnit and the value is a summary of this currency unit.
(currently **broken** because a vital class is no longer public, this example was disabled)

- **SimpleOperations** – simples operations using MonetaryAmount, that included arithmetic operations such sum, subtract and comparative operations such lesser equal, greater equal, etc.


text:
set -x
set -e

# mkdir /home/ubuntu/.aws
touch /home/ubuntu/.aws/config
touch /home/ubuntu/.aws/credentials
chmod 600 /home/ubuntu/.aws/config
chmod 600 /home/ubuntu/.aws/credentials
echo "[default]" > /home/ubuntu/.aws/config
echo "region = us-west-2" >> /home/ubuntu/.aws/config
echo "[default]" > /home/ubuntu/.aws/credentials
echo "aws_access_key_id=$AWS_ACCESS_KEY_ID" >> /home/ubuntu/.aws/config
echo "aws_secret_access_key=$AWS_SECRET_ACCESS_KEY" >> /home/ubuntu/.aws/config


text:
package org.jetbrains.plugins.groovy.annotator.checkers;

import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.AnnotationSession;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;

class AliasedAnnotationHolder implements AnnotationHolder {
  private final AnnotationHolder myHolder;
  private final GrAnnotation myAlias;
  private final GrCodeReferenceElement myReference;

  AliasedAnnotationHolder(@NotNull AnnotationHolder holder, @NotNull GrAnnotation alias) {
    myHolder = holder;
    myAlias = alias;
    myReference = myAlias.getClassReference();
  }

  @NotNull
  private PsiElement findCodeElement(@NotNull PsiElement elt) {
    if (PsiTreeUtil.isAncestor(myAlias, elt, true)) {
      return elt;
    }
    else {
      return myReference;
    }
  }

  @Override
  public Annotation createErrorAnnotation(@NotNull PsiElement elt, @Nullable String message) {
    PsiElement codeElement = findCodeElement(elt);
    return myHolder.createErrorAnnotation(codeElement, message);
  }

  @Override
  public Annotation createErrorAnnotation(@NotNull ASTNode node, @Nullable String message) {
    return createErrorAnnotation(node.getPsi(), message);
  }

  @Override
  public Annotation createErrorAnnotation(@NotNull TextRange range, @Nullable String message) {
    throw new UnsupportedOperationException("unsupported");
  }

  @Override
  public Annotation createWarningAnnotation(@NotNull PsiElement elt, @Nullable String message) {
    return myHolder.createWarningAnnotation(findCodeElement(elt), message);
  }

  @Override
  public Annotation createWarningAnnotation(@NotNull ASTNode node, @Nullable String message) {
    return myHolder.createWarningAnnotation(node.getPsi(), message);
  }

  @Override
  public Annotation createWarningAnnotation(@NotNull TextRange range, @Nullable String message) {
    throw new UnsupportedOperationException("unsupported");
  }

  @Override
  public Annotation createWeakWarningAnnotation(@NotNull PsiElement elt, @Nullable String message) {
    return myHolder.createWeakWarningAnnotation(findCodeElement(elt), message);
  }

  @Override
  public Annotation createWeakWarningAnnotation(@NotNull ASTNode node, @Nullable String message) {
    return myHolder.createWarningAnnotation(node.getPsi(), message);
  }

  @Override
  public Annotation createWeakWarningAnnotation(@NotNull TextRange range, @Nullable String message) {
    throw new UnsupportedOperationException("unsupported");
  }

  @Override
  public Annotation createInfoAnnotation(@NotNull PsiElement elt, @Nullable String message) {
    return myHolder.createInfoAnnotation(findCodeElement(elt), message);
  }

  @Override
  public Annotation createInfoAnnotation(@NotNull ASTNode node, @Nullable String message) {
    return myHolder.createInfoAnnotation(node.getPsi(), message);
  }

  @Override
  public Annotation createInfoAnnotation(@NotNull TextRange range, @Nullable String message) {
    throw new UnsupportedOperationException("unsupported");
  }

  @Override
  public Annotation createAnnotation(@NotNull HighlightSeverity severity, @NotNull TextRange range, @Nullable String message) {
    throw new UnsupportedOperationException("unsupported");
  }

  @Override
  public Annotation createAnnotation(@NotNull HighlightSeverity severity,
                                     @NotNull TextRange range,
                                     @Nullable String message,
                                     @Nullable String htmlTooltip) {
    throw new UnsupportedOperationException("unsupported");
  }

  @NotNull
  @Override
  public AnnotationSession getCurrentAnnotationSession() {
    return myHolder.getCurrentAnnotationSession();
  }

  @Override
  public boolean isBatchMode() {
    return myHolder.isBatchMode();
  }
}


text:
package worms.model;

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

import worms.model.equipment.weapons.*;
import worms.model.world.entity.*;
import worms.util.*;
import be.kuleuven.cs.som.annotate.*;

/**
 *
 * Defensive
 * Position DONE
 * Shape DONE
 * Mass DONE
 * Name DONE
 * Jumping
 * Moving
 *
 * Nominal
 * Direction DONE
 * Turning
 *
 * Total
 * ActionPoint DONE
 * HitPoints DONE
 */

/**
 * A class representing worms with a position, a direction it's facing, a radius, a mass,
 * 			 an amount of action points, an amount of hit points, a name, a team and a set of weapons.
 *
 * @author Derkinderen Vincent - Bachelor Informatica - R0458834
 * @author Coosemans Brent - Bachelor Informatica - R0376498
 *
 * @Repository https://github.com/FearTheDust/Worm_Part3
 *
 * @invar	This worm's action points amount is at all times less than or equal to the maximum amount of action points allowed and greater than or equal to 0.
 * 			| 0 <= this.getCurrentActionPoints() <= this.getMaximumActionPoints()
 *
 * @invar	This worm's hit points amount is at all times less than or equal to the maximum amount of hit points allowed and greater than or equal to 0.
 * 			| 0 <= this.getCurrentHitPoints() <= this.getMaximumHitPoints()
 *
 * @invar	| This worm's name is a valid name.
 * 			| isValidName(this.getName())
 *
 * @invar	This worm's radius is higher than or equal to the minimum radius.
 * 			| this.getRadius() >= this.getMinimumRadius()
 *
 * @invar	This worm's angle is at all times a valid angle.
 * 			| isValidAngle(this.getAngle())
 *
 * @invar 	The mass of this worm follows, at all times, the formula:
 * 			| getDensity() * (4.0/3.0) * Math.PI * Math.pow(this.getRadius(),3) == this.getMass()
 *
 * @invar	The position of this worm is never null.
 *			| this.getPosition() != null
 *
 * @invar	This worm is a member of the team it is in.
 *			| this.getTeam().isMember(this)
 */

public class Worm extends GameObject implements Entity {

	/**
	 * Initialize a new worm with a certain position, angle, radius, name,
	 * 	 a certain amount of action points, a certain amount of hit points and give him a set of weapons.
	 *
	 * @param world The world of the new worm.
	 * @param position The position of the new worm.
	 * @param angle The angle of the new worm.
	 * @param radius The radius of the new worm.
	 * @param name The name of the new worm.
	 * @param actionPoints The amount of action points of the new worm.
	 * @param hitPoints The amount of hit points of the new worm.
     * @param program The program of the new worm.
	 *
	 * @effect	This worm will be granted a provided position when valid.
	 * 			| super(world, position)
	 *
	 * @post	The angle of the new worm is equal to angle.
	 * 			| new.getAngle() == angle
	 * @post	The radius of the new worm is equal to radius.
	 * 			| new.getRadius() == radius
	 * @post	The name of the new worm is equal to name.
	 * 			| new.getName() == name
	 *
	 * @effect	The current amount of action points for the new worm is equal to actionPoints.
	 * 			In the case that actionPoints is greater than the amount of action points allowed, the maximum amount will be set.
	 * 			| this.setCurrentActionPoints(actionPoints)
	 * @effect The current amount of hit points for the new worm is equal to hitPoints.
	 * 			In the case that hitPoints is greater than the amount of hit points allowed, the maximum amount will be set.
	 * 			| this.setCurrentHitPoints(hitPoints)
	 * @effect This worm is added to the list of GameObjects in world.
	 * 			| world.add(this)
     * @throws IllegalArgumentException
     *          When the program is not well formed.
     *          | !program.isWellFormed()
	 */
	@Raw
	public Worm(World world, Position position, double angle, double radius,
			String name, int actionPoints, int hitPoints, Program program) throws IllegalArgumentException {
		super(world, position);
		this.setAngle(angle);
		this.setRadius(radius);
		this.setName(name);
		this.setCurrentActionPoints(actionPoints);
		this.setCurrentHitPoints(hitPoints);

                if(program != null && !program.isWellFormed())
                    throw new IllegalArgumentException("The program is not well formed.");

		world.add(this);
                this.program = program;
                if(program != null)
                    program.setWorm(this);

		// Add & set weapons.
		this.add(new Rifle(this));
		this.add(new Bazooka(this));
		//this.add(new BrentsWeaponOfDoom(this));
		this.setCurrentWeapon(this.getNextWeapon());
	}

	/**
	 * Initialize a new worm with a maximum amount of action points possible for this worm as well as the maximum amount of possible hit points for this worm.
	 *
	 * @param world The world of the new worm.
	 * @param position The position of the new worm.
	 * @param angle The angle of the new worm.
	 * @param radius The radius of the new worm.
	 * @param name The name of the new worm.
     * @param program The program of the new worm.
	 *
	 * @effect	A new worm will be initialized with a position, angle, radius, name, the maximum amount of action points possible for the new worm
	 * 				and the maximum amount of hit points possible for the new worm. As well as the program for the new worm.
	 * 			| this(world, position, angle, radius, name, Integer.MAX_VALUE, Integer.MAX_VALUE, program)
	 */
	@Raw
	public Worm(World world, Position position, double angle, double radius,
			String name, Program program) {
		this(world, position, angle, radius, name, Integer.MAX_VALUE,
				Integer.MAX_VALUE, program);
	}

	/**
	 * Initialize a new worm with a certain position, angle, radius, name,
	 * 	 a certain amount of action points, a certain amount of hit points and give him a set of weapons.
	 *
	 * @param world The world of the new worm.
	 * @param position The position of the new worm.
	 * @param angle The angle of the new worm.
	 * @param radius The radius of the new worm.
	 * @param name The name of the new worm.
	 * @param actionPoints The amount of action points of the new worm.
	 * @param hitPoints The amount of hit points of the new worm.
	 *
	 * @effect	A new worm will be initialized with a position, angle, radius, name, the maximum amount of action points possible for the new worm
	 * 				and the maximum amount of hit points possible for the new worm. The program will be null.
	 * 			| this(world, position, angle, radius, name,name, actionPoints, hitPoints, null)
	 */
	@Raw
	public Worm(World world, Position position, double angle, double radius,
			String name, int actionPoints, int hitPoints) {
		this(world, position, angle, radius, name, actionPoints,
				hitPoints, null);
	}

	/**
	 * Initialize a new worm with a maximum amount of action points possible for this worm as well as the maximum amount of possible hit points for this worm.
	 *
	 * @param world The world of the new worm.
	 * @param position The position of the new worm.
	 * @param angle The angle of the new worm.
	 * @param radius The radius of the new worm.
	 * @param name The name of the new worm.
	 *
	 * @effect	A new worm will be initialized with a position, angle, radius, name, the maximum amount of action points possible for the new worm
	 * 				and the maximum amount of hit points possible for the new worm. The program will be null.
	 * 			| this(world, position, angle, radius, name, Integer.MAX_VALUE, Integer.MAX_VALUE, null)
	 */
	@Raw
	public Worm(World world, Position position, double angle, double radius,
			String name) {
		this(world, position, angle, radius, name, Integer.MAX_VALUE,
				Integer.MAX_VALUE, null);
	}

	/**
	 * This worm jumps to a certain position calculated by a formula.
	 *
         * @param timeStep The step with which we increase the time every time.
         *
	 * @post	The current amount of action points is 0.
	 * 			| new.getCurrentActionPoints() == 0
	 *
	 * @effect The new position of this worm is calculated and set if the current amount of actionPoints is higher than 0.
	 * 			| if(this.getCurrentActionpoints() > 0)
	 * 			| this.setPosition(this.jumpStep(this.jumpTime()))
	 */
	public void jump(double timeStep) {
		if(this.getCurrentActionPoints() > 0) {
			this.setPosition(this.jumpStep(this.jumpTime(timeStep)));
			this.setCurrentActionPoints(0);
		}
	}

	/**
	 * Returns the position where this worm would be at a certain time whilst jumping.
	 *
	 * @param time The time of when we return the position.
	 *
	 * @return	When the time equals 0 the current position will be returned,
	 * 			else the position this worm has at a certain time in a jump will be returned.
	 * 			| if(time == 0) then
	 * 			| 	result == this.getPosition()
	 * 			| Else
	 * 			| 	force = 5 * this.getCurrentActionPoints() + this.getMass() * Constants.EARTH_ACCELERATION
	 * 			| 	startSpeed = (force / this.getMass()) * FORCE_TIME
	 * 			| 	startSpeedX = startSpeed * Math.cos(this.getAngle())
	 * 			| 	startSpeedY = startSpeed * Math.sin(this.getAngle())
	 * 			| 	x = this.getPosition().getX() + (startSpeedX * time)
	 * 			| 	y = this.getPosition().getY() + (startSpeedY * time - Constants.EARTH_ACCELERATION * Math.pow(time,2) / 2)
	 * 			| 	result == new Position(x,y)
	 *
	 * @throws IllegalArgumentException
	 * 			When time is a negative value.
	 * 			| (time < 0)
	 */
	public Position jumpStep(double time) throws IllegalArgumentException {
		if (time < 0)
			throw new IllegalArgumentException("The time can't be negative.");

		if (time == 0) {
			return this.getPosition();
		}

		// Calculation
		double force = 5 * this.getCurrentActionPoints() + this.getMass()
				* Constants.EARTH_ACCELERATION;
		double startSpeed = (force / this.getMass()) * this.getForceTime();

		double startSpeedX = startSpeed * Math.cos(this.getAngle());
		double startSpeedY = startSpeed * Math.sin(this.getAngle());

		double x = this.getPosition().getX() + (startSpeedX * time);
		double y = this.getPosition().getY()
				+ (startSpeedY * time - Constants.EARTH_ACCELERATION
						* Math.pow(time, 2) / 2);

		// Return
		return new Position(x, y);
	}

	/**
	 * Returns the time a force is exerted on a worm's body.
	 */
	@Basic @Immutable
	public double getForceTime() {
		return Constants.FORCE_TIME;
	}

	/**
	 * Returns the jump time if jumped with this worm's current angle.
	 *
	 * @param timeStep the time between two positions on the traject of the jump.
	 *
	 * @return the time needed to jump from the worm's current position, with the worm's current angle and in the world he is located in.
	 * 			| double loopTime = 0
	 *			| Position calculatedPosition = this.getPosition()
	 *			| while(this.getWorld().liesWithinBoundaries(calculatedPosition, this.getRadius()) && (!this.getWorld().isAdjacent(calculatedPosition, this.getRadius()) || this.getPosition().distance(calculatedPosition) <= this.getRadius()) &&
	 *			|	!this.getWorld().isImpassable(calculatedPosition, this.getRadius()))
	 *			|		loopTime += timeStep
	 *			|		calculatedPosition = this.jumpStep(loopTime)
	 *			| loopTime -= timeStep
	 *			| result == Math.max(loopTime,0)
	 */
	public double jumpTime(double timeStep) {
		double loopTime = 0;
		Position calculatedPosition = this.getPosition();

		while(this.getWorld().liesWithinBoundaries(calculatedPosition, this.getRadius()) && (!this.getWorld().isAdjacent(calculatedPosition, this.getRadius()) || this.getPosition().distance(calculatedPosition) <= this.getRadius()) &&
				!this.getWorld().isImpassable(calculatedPosition, this.getRadius())) {
			loopTime += timeStep;
			calculatedPosition = this.jumpStep(loopTime);
		}
		loopTime -= timeStep; //one step back

		return Math.max(loopTime,0);
	}

	/**
	 * Returns the cost to move for this worm if this would be a legal position to move to.
	 *
	 * @param finalPosition The position to go to.
	 *
	 * @return 	The cost to move.
	 * 			| s = Math.atan((this.getPosition().getY() - finalPosition.getY()) / (this.getPosition().getX() - finalPosition.getX()));
	 * 			| result ==  (int) (Math.ceil(Math.abs(Math.cos(s)) + Math.abs(4 * Math.sin(s))));
	 */
	public int getMoveCost(Position finalPosition) {
		double s = Math.atan((this.getPosition().getY() - finalPosition.getY())
				/ (this.getPosition().getX() - finalPosition.getX()));
		return (int) (Math.ceil(Math.abs(Math.cos(s))
				+ Math.abs(4 * Math.sin(s))));
	}

	/**
	 * Returns the angle of this worm.
	 */
	@Basic @Override
	public double getAngle() {
		return angle;
	}

	/**
	 * Returns whether or not this worm can turn with the provided angle.
	 *
	 * @param angle The angle to check for.
	 *
	 * @return	Whether the worm has more or an equal amount of AP than the cost to turn with that angle.
	 * 			| result == Worm.getTurnCost(angle) <= this.getCurrentActionPoints()
	 */
	public boolean canTurn(double angle) {
		return Worm.getTurnCost(angle) <= this.getCurrentActionPoints();
	}

	/**
	 * Turn this worm with a given angle.
	 *
	 * @param angle The angle to turn with.
	 *
	 * @pre		The absolute value of twice the angle must be valid or equal to Math.abs(Math.PI).
	 * 			| isValidAngle(Math.abs(2*angle)) || Util.fuzzyEquals(Math.abs(angle), Math.PI)
	 * @pre		The cost to turn should be less than or equal to the amount of action points we have.
	 * 			| canTurn(angle)
	 *
	 * @effect	This worm's new action points is set to the old amount of action points minus the cost to turn.
	 * 			| this.setCurrentActionPoints(this.getCurrentActionPoints() - getTurnCost(angle))
	 * @effect	This worm's new direction is set to the old angle plus the given angle plus 2*Math.PI modulo 2*Math.PI.
	 * 			| this.setAngle(Util.modulo(this.getAngle() + angle + 2*Math.PI, 2*Math.PI));
	 */
	public void turn(double angle) {
		assert isValidAngle(Math.abs(2 * angle)) || Util.fuzzyEquals(Math.abs(angle), Math.PI);
		assert canTurn(angle);
		this.setAngle(Util.modulo(this.getAngle() + angle + 2 * Math.PI,
				2 * Math.PI));
		this.setCurrentActionPoints(this.getCurrentActionPoints()
				- getTurnCost(angle));
	}

	/**
	 * Returns the cost to change the orientation to the angle formed by adding the given angle to the current orientation.
	 *
	 * @param angle The angle to turn.
	 *
	 * @return The cost to turn.
	 * 			| result == (int) Math.ceil(Math.abs(30 * (angle / Math.PI)))
	 */
	public static int getTurnCost(double angle) {
		return (int) Math.ceil(Math.abs(30 * (angle / Math.PI)));
	}

	/**
	 * The angle provided has to be greater than or equal to 0 and less than 2*Math.PI.
	 *
	 * @param angle The angle to check.
	 *
	 * @return	Whether or not the given angle is valid.
	 * 			| result == Util.fuzzyGreaterThanOrEqualTo(angle, 0) && (angle < 2*Math.PI)
	 */
	public static boolean isValidAngle(double angle) {
		return Util.fuzzyGreaterThanOrEqualTo(angle, 0)
				&& (angle < 2 * Math.PI);
	}

	/**
	 * Set the new angle of this worm.
	 *
	 * @param angle The new angle of this worm.
	 *
	 * @pre		The angle provided has to be a valid angle.
	 * 			| isValidAngle(angle)
	 *
	 * @post	The new angle of this worm is equal to the given angle.
	 * 			| (new.getAngle() == angle)
	 */
	private void setAngle(double angle) {
		assert isValidAngle(angle);
		this.angle = angle;
	}

	private double angle;

	/**
	 * Returns the radius of this worm.
	 */
	@Basic @Raw @Override
	public double getRadius() {
		return radius;
	}

	/**
	 * Set the new radius of this worm and update the action points accordingly.
	 *
	 * @param radius The new radius of this worm.
	 *
	 * @post	The radius of this worm is equal to the given radius.
	 * 			| new.getRadius() == radius
	 *
	 * @throws IllegalArgumentException
	 * 			When the given radius is less than the minimum radius.
	 * 			| radius < this.getMinimumRadius()
	 * @throws IllegalArgumentException
	 * 			When the radius isn't a number.
	 * 			| Double.isNaN(radius)
	 */
	@Raw
	public void setRadius(double radius) throws IllegalArgumentException {
		if (!Util.fuzzyGreaterThanOrEqualTo(radius, getMinimumRadius()))
			throw new IllegalArgumentException("The radius has to be greater than or equal to the minimum radius " + this.minRadius);
		if (Double.isNaN(radius))
			throw new IllegalArgumentException("The radius must be a number.");
		this.radius = radius;
	}

	/**
	 * Returns the minimum radius of this worm.
	 */
	@Basic
	@Immutable
	public double getMinimumRadius() {
		return minRadius;
	}

	private double radius;

	private final double minRadius = 0.25; // Initialize in constructor later
											// on.

	/**
	 * Returns the mass of this worm.
	 */
	@Basic @Override
	public double getMass() {
		return getDensity() * (4.0 / 3.0) * Math.PI * Math.pow(this.getRadius(), 3);
	}

	/**
	 * Returns this worm's density.
	 */
	@Basic
	@Immutable
	public static final double getDensity() {
		return DENSITY;
	}

	private static final double DENSITY = 1062;

	/**
	 * Returns this worm's name.
	 */
	@Basic @Raw
	public String getName() {
		return name;
	}

	/**
	 * Set a new name for this worm.
	 *
	 * @param name The new name of this worm.
	 *
	 * @post	The name of this worm is equal to name.
	 * 			| new.getName() == name
	 *
	 * @throws IllegalArgumentException
	 * 			When name isn't a valid name.
	 * 			| !isValidName(name)
	 */
	@Raw
	public void setName(String name) throws IllegalArgumentException {
		if (!isValidName(name))
			throw new IllegalArgumentException("Invalid name.");
		this.name = name;
	}

	/**
	 * Returns whether the name is a valid name.
	 *
	 * @param name The name to be checked.
	 *
	 * @return  True if the name is longer than or equal to 2 characters, starts with an uppercase and when every character is one from the following:
	 * 			[A-Z] || [a-z] || a space || ' || " || [0-9]
	 * 			| result != ((name == null) &&
	 * 			| (name.length() < 2) &&
	 * 			| (!Character.isUpperCase(name.charAt(0)) &&
	 * 			| (for each index i in 0..name.toCharArray().length-1:
	 *       	|   (!(Character.isLetterOrDigit(name.toCharArray[i]) || name.toCharArray[i] == ' ' || name.toCharArray[i] == '\'' || name.toCharArray[i] == '\"'))))
	 */
	public static boolean isValidName(String name) {
		if (name == null)
			return false;
		if (name.length() < 2)
			return false;
		if (!Character.isUpperCase(name.charAt(0)))
			return false;
		for (Character ch : name.toCharArray()) {
			if (!(ch == ' ' || ch == '\'' || ch == '\"' || Character.isLetterOrDigit(ch)))
				return false;
		}
		return true;
	}

	private String name;

	/**
	 * Set the current amount of hit points.
	 *
	 * @param hitPoints The amount of hit points to set the current amount to.
	 *
	 * @post	If hitPoints is greater than or equal to zero,
	 * 			the new amount of hit points will be set to the minimum of hitPoints and getMaximumHitPoints()
	 * 			| if(hitPoints >= 0)
	 * 			| new.getCurrentHitPoints() == Math.min(hitPoints, this.getMaximumHitPoints)
	 * @post	If the hitPoints is less than zero, zero will be set for the new Worm's HP.
	 * 			| if(hitPoints < 0)
	 * 			| new.getCurrentHitPoints() == 0
	 * @effect If hitPoints is less than or equal to zero, the currentHP is different and the active worm in the world is this one, call this.getWorld().nextTurn().
	 * 			| if(hitPoints <= 0 && this.getCurrentHitPoints() > hitPoints && this.getWorld() != null && this.getWorld().getActiveWorm() == this)
	 * 			|		this.getWorld().nextTurn()
	 */
	@Raw @Model
	private void setCurrentHitPoints(int hitPoints) {
		int oldHP = this.currentHitPoints;
		this.currentHitPoints = (hitPoints <= 0) ? 0 : Math.min(hitPoints, getMaximumHitPoints());
		if (hitPoints <= 0 && oldHP > hitPoints && this.getWorld() != null && this.getWorld().getActiveWorm() == this) //so this doesn't get called by this.getCurrentHP()
				this.getWorld().nextTurn();
	}

	/**
	 * Inflict damage upon this worm.
	 * @post	The new hit points amount is less than or equal to the old amount.
	 * 			| new.getCurrentHitPoints() <= this.getCurrentHitPoints()
	 */
	public void inflictHitDamage(int damage) {
		if(damage < 0)
			damage = 0;
		this.setCurrentHitPoints(this.getCurrentHitPoints() - damage);
	}

	/**
	 * Return the current amount of hit points in valid form.
	 */
	public int getCurrentHitPoints() {
		// Call setCurrentHitPoints to make sure we're in valid bounds.
		//(if the radius changed, meaning the mass changed, meaning the maximum amount of hit points changed)
		setCurrentHitPoints(currentHitPoints);
		return currentHitPoints;
	}

	/**
	 * Returns this worm's maximum amount of hit points.
	 */
	public int getMaximumHitPoints() {
		double mass = this.getMass();
		if (mass > Integer.MAX_VALUE)
			return Integer.MAX_VALUE;
		return (int) Math.round(mass);
	}

	private int currentHitPoints;

	/**
	 * Set the current action points.
	 *
	 * @param actionPoints The new amount of action points.
	 *
	 * @post If actionPoints is less than or equal to zero the new AP will be 0.
	 * 			| if(actionPoints <= 0)
	 * 			| 	new.getCurrentActionPoints() == 0
	 * @post If actionPoints is greater than zero, The new amount will be set to the minimum value of
	 * 			actionPoints and getMaximumActionPoints()
	 *      	| if(actionPoints > 0)
	 *      	| 	new.getCurrentActionPoints() == Math.min(actionPoints,this.getMaximumActionPoints)
	 *
	 * @effect If actionPoints is less than or equal to zero, the currentAP is different and the active worm is this one, call this.getWorld().nextTurn().
	 * 			| if(actionPoints <= 0 && this.getCurrentActionPoints() > actionPoints && this.getWorld() != null && this.getWorld().getActiveWorm() == this)
	 * 			|		this.getWorld().nextTurn()
	 */
	@Raw @Model
	private void setCurrentActionPoints(int actionPoints) {
		int oldAP = this.currentActionPoints;
		this.currentActionPoints = (actionPoints <= 0) ? 0 : Math.min(actionPoints, getMaximumActionPoints());

		if (actionPoints <= 0 && oldAP > actionPoints && this.getWorld() != null && this.getWorld().getActiveWorm() == this) //so this doesn't get called by this.getCurrentAP()
				this.getWorld().nextTurn();
	}

	/**
	 * Returns the current amount of action points in valid form.
	 */
	@Basic @Raw
	public int getCurrentActionPoints() {
		// Call setCurrentActionPoints to make sure we're in valid bounds.
		//(if the radius changed, meaning the mass changed, meaning the maximum amount of hit points changed)
		setCurrentActionPoints(currentActionPoints);
		return currentActionPoints;
	}

	/**
	 * Decrease the current AP of this worm.
	 *
	 * @param cost The cost to decrease the AP with.
	 *
	 * @post The amount of action points of the new worm is less than or equal to the old one.
	 * 			| new.getCurrentActionPoints() <= this.getCurrentActionPoints()
	 * @post The amount of action points of the new worm is the same as before when the cost <= 0
	 * 			| if(cost <= 0)
	 * 			|	new.getCurrentActionpoints() == this.getCurrentActionpoints()
	 */
	public void decreaseActionPointsBy(int cost) {
		if(cost < 0)
			cost = 0;
		this.setCurrentActionPoints(this.getCurrentActionPoints() - cost);
	}

	/**
	 * Returns the maximum amount of action points.
	 */
	public int getMaximumActionPoints() {
		double mass = this.getMass();
		if (mass > Integer.MAX_VALUE)
			return Integer.MAX_VALUE;
		return (int) Math.round(mass);
	}

	private int currentActionPoints;

	/**
	 * Set the team of this worm to team.
	 *
	 * @param team The team to set for this worm.
	 *
	 * @post The team of this worm will be equal to team.
	 * 		 | new.getTeam() == team
	 *
	 * @throws IllegalArgumentException
	 * 			When this worm isn't a member of team.
	 * 			| !team.isMember(this)
	 */
	@Raw
	public void setTeam(Team team) throws IllegalArgumentException {
		if (!team.isMember(this))
			throw new IllegalArgumentException("This worm also has to be a member of the team.");
		this.team = team;
	}

	/**
	 * Returns this worm's team.
	 */
	public Team getTeam() {
		return team;
	}

	private Team team;

	/**
	 * Returns whether the worm is alive.
	 *
	 * @return The worm isn't alive when the current hit points equal to 0.
	 * 			| if(this.getCurrentHitPoints() == 0)
	 * 			| 	result == false
	 * @return The worm isn't alive when its circle doesn't lie fully within the world boundaries
	 * 			| if(!this.getWorld().liesWithinBoundaries(this))
	 * 			|	result == false
	 * @return The worm isn't alive when he isn't in a world.
	 * 			| if(this.getWorld() == null)
	 * 			|	result == false
	 */
        @Override
	public boolean isAlive() {
		if (this.getWorld() == null)
			return false;
		if(!this.getWorld().liesWithinBoundaries(this))
			return false;
		if (this.getCurrentHitPoints() == 0)
			return false;
		return true;
	}

	/**
	 * Returns the Weapon the worm is currently having equipped.
	 * If it hasn't got a Weapon equipped it will return null.
	 */
	@Raw @Basic
	public Weapon getCurrentWeapon() {
		if (currentWeaponIndex == -1)
			return null;

		return weaponList.get(currentWeaponIndex);
	}

	/**
	 * Set the current weapon to weapon.
	 *
	 * @param weapon The weapon to set to.
	 *
	 * @post The current Weapon of the worm will be equal to weapon.
	 * 			| new.getCurrentWeapon() == weapon
	 *
	 * @throws IllegalArgumentException
	 * 			When the weapon provided is equal to null.
	 * 			| (weapon == null)
	 * 			When the worm doesn't have the weapon.
	 * 			| !this.getWeaponList().contains(weapon)
	 */
	@Raw
	public void setCurrentWeapon(Weapon weapon) throws IllegalArgumentException {
		if (weapon == null)
			throw new IllegalArgumentException("The weapon provided to set to isn't allowed to be a null reference.");
		if (!weaponList.contains(weapon))
			throw new IllegalArgumentException("The weapon must be in our weaponList.");
		this.currentWeaponIndex = weaponList.indexOf(weapon);
	}

	private int currentWeaponIndex = -1;

	/**
	 * Returns the next weapon available for the worm.
	 *
	 * @return The weapon next to the current weapon.
	 * 			| if(this.getCurrentWeapon() == null)
	 * 			|	result == this.getWeaponList().get(0)
	 * 			| else
	 * 			|	index = this.getWeaponList().indexOf(this.getCurrentWeapon)
	 * 			|	if(index >= this.getWeaponList().size() - 1)
	 * 			|		result == this.getWeaponList().get(0)
	 * 			|	else
	 * 			|		result == this.getWeaponList().get(index+1)
	 *
	 * @throws IllegalStateException
	 * 			When the list of weapons available is empty.
	 * 			| this.getWeaponList().size() == 0
	 */
	@Raw
	public Weapon getNextWeapon() throws IllegalStateException {
		if (currentWeaponIndex == -1 && weaponList.size() == 0)
			throw new IllegalStateException("Next Weapon isn't available since the list doesn't contain any weapons.");
		if (currentWeaponIndex == weaponList.size() - 1)
			return weaponList.get(0);
		else
			return weaponList.get(currentWeaponIndex + 1);
	}

	/**
	 * Add a weapon to the weapons available to this worm.
	 * Doesn't do anything if the worm already has this weapon.
	 *
	 * @param weapon The weapon to add.
	 *
	 * @post The weapon will be available for the worm to access.
	 * 			| this.getWeaponList().contains(weapon);
	 *
	 * @throws IllegalArgumentException
	 * 			When weapon is equal to null.
	 * 			| weapon == null
	 */
	public void add(Weapon weapon) throws IllegalArgumentException {
		if (weapon == null)
			throw new IllegalArgumentException("Can't add a weapon that is a null reference.");

		if (!this.hasGot(weapon))
			weaponList.add(weapon);
	}

	/**
	 * Returns whether the worm has access to a weapon of the same class as the class of the weapon provided.
	 * @param weapon The weapon to check the class from.
	 *
	 * @return Whether the worm has access to a weapon of the same class than weapon.getClass()
	 * 			| for each Weapon aWeapon of this.getWeaponList()
	 * 			| 	if(aWeapon.getClass() == weapon.getClass())
	 * 			| 		result == true
	 * 			| result == false
	 */
	public boolean hasGot(Weapon weapon) {
		for (Weapon aWeapon : weaponList) {
			if (aWeapon.getClass() == weapon.getClass())
				return true;
		}
		return false;
	}

	/**
	 * Returns a copy of the list of all weapon a worm has access to at this moment.
	 */
	public List<Weapon> getWeaponList() {
		return new ArrayList<Weapon>(weaponList);
	}

	private ArrayList<Weapon> weaponList = new ArrayList<Weapon>();

	/**
	 * Give this worm his turn points.
	 *
	 * @post Set the action points to the maximum action points for this worm.
	 * 		| new.getCurrentActionPoints() == this.getMaximumActionPoints()
	 * @post Set the hit points to the current amount of hit points + 10 for this worm.
	 * 		| new.getCurrentHitPoints() == this.getCurrentHitPoints() + 10
	 *
	 * @throws IllegalStateException
	 * 			When this worm isn't alive.
	 * 			| !this.isAlive()
	 */
	public void giveTurnPoints() throws IllegalStateException {
		if (!this.isAlive())
			throw new IllegalStateException("The worm must be alive in order to grant its turn points.");

		this.setCurrentActionPoints(this.getMaximumActionPoints());
		//This is to make sure Integer.MAX + 10 doesn't go to 0 HP.
		if (this.getCurrentHitPoints() + 10 < this.getCurrentHitPoints())
			this.setCurrentHitPoints(getMaximumHitPoints());
		else
			this.setCurrentHitPoints(this.getCurrentHitPoints() + 10);
	}

	/**
	 * Returns the position where the worm would be if he would move.
	 *
	 * @return check for every angle between the worm's current angle +/- 0.7875 with a step of 0.0175
	 * 			what the maximum distance is and for all angles with equal maximum distances,
	 * 			search the angle with the minimum divergence between the angle and the worm's current angle.
	 * 			| if (this.getWorld() == null)
	 *			|	result == null
	 *			| double bestAngle = this.getAngle()
	 *			| double bestDistance = 0
	 *			| Position bestPos = this.getPosition()
	 *			| for double currentAngle = this.getAngle() - 0.7875 until currentAngle <= this.getAngle() + 0.7875 with step currentAngle += 0.0175
	 *			|	double distance = 0.1
	 *			|	boolean found = false
	 *			|	while (distance <= this.getRadius() && !found)
	 *			|		double posX = distance * Math.cos(currentAngle) + this.getPosition().getX()
	 *			|		double posY = distance * Math.sin(currentAngle) + this.getPosition().getY()
	 *			|		Position pos = new Position(posX, posY)
	 *			|		if (!this.getWorld().isImpassable(pos, this.getRadius()))
	 *			|			distance += 0.1*this.getRadius()
	 *			|		else
	 *			|			found = true
	 *			|	distance -= 0.1*this.getRadius()
	 *			| 	Position newPos = new Position(distance * Math.cos(currentAngle) + this.getPosition().getX(),
	 *			|							distance * Math.sin(currentAngle) + this.getPosition().getY())
	 *			|	if (distance >= 0.1)
	 *			|		if(distance > bestDistance)
	 *			|			bestDistance = distance
	 *			|			bestAngle = currentAngle
	 *			|			bestPos = newPos
	 *			|	else if(Util.fuzzyEquals(bestDistance, distance, 1E-4))
	 *			|		if(Math.abs(this.getAngle() - currentAngle) < Math.abs(this.getAngle() - bestAngle))
	 *			|			bestDistance = distance
	 *			|			bestAngle = currentAngle
	 *			|			bestPos = newPos
	 *			| result == bestPos
	 */
	public Position getMovePosition() {
		if (this.getWorld() == null)
			return null;
		double bestAngle = this.getAngle();
		double bestDistance = 0;
		Position bestPos = this.getPosition();
		for (double currentAngle = this.getAngle() - 0.7875; currentAngle <= this.getAngle() + 0.7875; currentAngle += 0.0175) {
			double distance = 0.1;
			boolean found = false;
			while (distance <= this.getRadius() && !found) {
				double posX = distance * Math.cos(currentAngle) + this.getPosition().getX();
				double posY = distance * Math.sin(currentAngle) + this.getPosition().getY();
				Position pos = new Position(posX, posY);
				if (!this.getWorld().isImpassable(pos, this.getRadius()))
					distance += 0.1*this.getRadius();
				else
					found = true;
			}
			distance -= 0.1*this.getRadius();
			Position newPos = new Position(distance * Math.cos(currentAngle) + this.getPosition().getX(),
											distance * Math.sin(currentAngle) + this.getPosition().getY());
			if (distance >= 0.1) {
				if(distance > bestDistance) {
					bestDistance = distance;
					bestAngle = currentAngle;
					bestPos = newPos;
				} else if(Util.fuzzyEquals(bestDistance, distance, 1E-4)) {
					if(Math.abs(this.getAngle() - currentAngle) < Math.abs(this.getAngle() - bestAngle)) {
						bestDistance = distance;
						bestAngle = currentAngle;
						bestPos = newPos;
					}
				}
			}
		}
		return bestPos;
	}

	/**
	 * Move the worm to a position by checking for every angle between the worm's current angle +/- 0.7875 with a step of 0.0175
	 * what the maximum distance is and for all angles with equal maximum distances,
	 * search the angle with the minimum divergence between the angle and the worm's current angle.
	 * If the worm isn't in a world, do nothing.
	 *
	 * @effect The current action points is the previous - the cost.
	 * 			| this.setCurrentActionPoints(this.getCurrentActionpoints() - this.getMoveCost(movePosition))
	 * @effect The position is changed to the calculated position.
	 * 			| this.setPosition(this.getMovePosition())
	 *
	 * @throws IllegalArgumentException
	 * 			When this worm can not move to the calculated position because he doesn't have enough action points.
	 * 			| !canMove(movePosition)
	 */
	public void move() throws IllegalArgumentException {
		if (this.getWorld() == null)
			return;
		Position movePosition = this.getMovePosition();
		if (!canMove(movePosition))
			throw new IllegalArgumentException("You don't have enough Action Points");
		this.setCurrentActionPoints(this.getCurrentActionPoints() - this.getMoveCost(movePosition));
		this.setPosition(movePosition);
	}

	/**
	 * Returns whether this worm can move to finalPosition.
	 *
	 * @param finalPosition The position to check if we can reach.
	 *
	 * @return Whether this worm is alive and whether he has enough AP to perform the move.
	 * 			| result == this.isAlive() && this.getMoveCost(this.getMovePosition()) <= this.getCurrentActionPoints();
	 */
	public boolean canMove(Position finalPosition) {
		return this.isAlive() && this.getMoveCost(this.getMovePosition()) <= this.getCurrentActionPoints();
	}

	/**
	 * Returns whether this worm can fall.
	 *
	 * @return False if the worm has no world.
	 * 			| if(this.getWorld() == null
	 * 			| 	result == false
	 * @return False if the position of the worm with its radius is impassable.
	 * 			| if(this.getWorld().isImpassable(this.getPosition(), this.getRadius())
	 * 			|	result == false
	 * @return False if there is impassable terrain adjacent to this worm.
	 * 			| result == !this.getWorld().isAdjacent(this.getPosition(), this.getRadius())
	 */
        @Override
	public boolean canFall() {
		if (this.getWorld() == null)
			return false;
		/*
		 * This code actually checked if there was an impassable block beneath the worm only instead of adjacent in any direction.
		 *
		 * for (double x = Math.max(Math.floor(this.getPosition().getX() - this.getRadius()), 0);
				x <= Math.ceil(this.getPosition().getX() + this.getRadius())
				&& x <= this.getWorld().getWidth() && x / this.getWorld().getScale() <= Integer.MAX_VALUE;
					x++) {

			for(double testRadius = this.getRadius(); testRadius <= 1.1*this.getRadius(); testRadius += this.getWorld().getScale()) {
				if (!this.getWorld().isPassableTile(
						new Position(x, this.getPosition().getY() - testRadius)))
				return false;
			}
		}
		return true;*/
		if(this.getWorld().isImpassable(this.getPosition(), this.getRadius()))
			return false;

		return !this.getWorld().isAdjacent(this.getPosition(), this.getRadius());
	}

	/**
	 * Let this worm fall down until it leaves the world boundaries or is adjacent to impassable terrain, while falling down
	 * and give the worm hit damage.
	 *
	 * @effect Let the worm fall down.
	 * 			| super.fall()
	 *
	 * @post	The amount of hit points after the fall is equal to or less than the previous amount.
	 * 			| new.getCurrentHitPoints() <= this.getCurrentHitPoints()
	 *
	 */
        @Override
	public void fall() {
		Position oldPosition = this.getPosition();
		super.fall();
		double fallenMeters = oldPosition.getY() - this.getPosition().getY();
		int cost = (int) (3*Math.floor(fallenMeters));
		this.setCurrentHitPoints(this.getCurrentHitPoints() - cost);
	}

	/**
	 * Let this worm fall down until it leaves the world boundaries or is adjacent to impassable terrain, while falling down.
	 *
	 * @effect Let the worm fall down.
	 *          | super.fall()
	 */
	public void softFall() {
		super.fall();
	}

	/**
	 * Set the position of this worm and eat food within its reach.
	 * When this worm is outside of the world boundaries and listed as active worm for that world, execute the nextTurn()
	 * of that world.
	 *
	 * @post The new radius will be greater than or equal to the old radius.
	 * 		| new.getRadius() >= this.getRadius()
	 * @post All Food within the radius of this worm is eaten.
	 * 		| if(this.getWorld() != null)
	 * 		|	new.getWorld().eatableFood(new.getPosition(), this.getRadius()).size() == 0
	 * @post A worm outside of the world boundaries will not be the active worm in the new world.
	 * 		| if(this.getWorld() != null)
	 * 		|	new.getWorld().liesWithinBoundaries(new) || new.getWorld().getActiveWorm() != new
	 *
	 * @effect set the position for the worm.
	 * 		| super.setPosition(position)
	 */
        @Override
	public void setPosition(Position position) {
		super.setPosition(position);

		if(this.getWorld() != null) {
			for(Food food : this.getWorld().eatableFood(this.getPosition(), this.getRadius())) {
				this.setRadius(Constants.FOOD_RADIUS_GROWTH*this.getRadius());
				food.setToEaten();
			}

			if(!this.getWorld().liesWithinBoundaries(this) && this.getWorld().getActiveWorm() == this)
				this.getWorld().nextTurn();
		}
	}

	/**
	 * Shoot a projectile: create it and let it jump.
	 *
	 * @param yield The propulsionYield with which we shoot.
	 *
	 * @effect the living projectile of the world of this worm will be set to the created projectile.
	 * 			| this.getWorld().setLivingProjectile(projectile)
	 * @effect the created projectile will be added as a GameObject to the world of this worm.
	 * 			| this.getWorld.add(projectile)
	 * @effect the projectile will jump.
	 * 			| projectile.jump(GUIConstants.JUMP_TIME_STEP)
	 *
	 * @throws IllegalStateException
	 * 			When the current weapon of this worm is a null reference.
	 * 			| this.getCurrentWeapon() == null
	 */
	public void shoot(int yield) throws IllegalStateException {
		if(this.getWorld() == null)
			return;

		if(this.getCurrentWeapon() == null)
			throw new IllegalStateException("The worm hasn't got a weapon equipped.");

		WeaponProjectile projectile = this.getCurrentWeapon().createProjectile(yield);
		if(projectile != null) {
			this.getWorld().setLivingProjectile(projectile);
			this.getWorld().add(projectile);
			//When we let the src-provided jump it doesn't seem to paint the end position although it does
			//end up on the same end position it isn't painted like that.
			//this.getWorld().getLivingProjectile().jump(GUIConstants.JUMP_TIME_STEP);
		}
	}

    /**
     * This will return the current HP of this worm.
     * @return This will return the current HP of this worm as defined by getCurrentHitPoints()
     *          | result == this.getCurrentHitPoints()
     */
    @Override @Basic
    public double getHP() {
        return this.getCurrentHitPoints();
    }

    /**
     * This will return the maximum HP of this worm.
     * @return This will return the maximum HP of this worm as defined by getMaximumHitPoints()
     *          | result == this.getMaximumHitPoints()
     */
    @Override
    public double getMaxHP() {
        return this.getMaximumHitPoints();
    }

    /**
     * This will return the current AP of this worm.
     * @return The current AP of this worm as defined by getCurrentActionPoints()
     *          | result == this.getCurrentActionPoints()
     */
    @Override @Basic
    public double getAP() {
        return this.getCurrentActionPoints();
    }

    /**
     * This will return the maximum AP of this worm.
     * @return The maximum AP of this worm as defined by getMaximumActionPoints()
     *          | result == this.getMaximumActionPoints()
     */
    @Override
    public double getMaxAP() {
        return this.getMaximumActionPoints();
    }

    /**
     * Returns a representation of this worm in String.
     * Format: the name of the worm followed by its Action Points and its Hit Points.
     *
     * @return The name of this worm along with AP and HP information formatted in a certain way.
     *          | result == "Name: " + this.getName() + " ; AP: " + this.getCurrentActionPoints() + "/" + this.getMaximumActionPoints()
     *           + " ; HP: " + this.getCurrentHitPoints() + "/" + this.getMaximumHitPoints()
     */
    @Override
    public String toString() {
        return ("Name: " + this.getName() + " ; AP: " + this.getCurrentActionPoints() + "/" + this.getMaximumActionPoints()
                + " ; HP: " + this.getCurrentHitPoints() + "/" + this.getMaximumHitPoints());
    }

    /**
     * Execute the program as defined by the Program.
     * Does nothing when the program is a null reference.
     * @effect The program executes as defined by execute()
     *          | program.execute();
     */
    public void executeProgram() {
        if(program != null)
            this.program.execute();
    }

    /**
     * Return whether this worm has got a program.
     * @return True if the worm has a program else false.
     */
    @Basic
    public boolean hasProgram() {
        return this.program != null;
    }

    private Program program;

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Config.Net.Stores;
using Xunit;
using YamlDotNet.Core.Tokens;

namespace Config.Net.Tests.Stores
{
   public class JsonFileConfigStoreTest : AbstractTestFixture, IDisposable
   {
      private string _path;
      private JsonConfigStore _store;

      public JsonFileConfigStoreTest()
      {
         _path = Path.Combine(BuildDir.FullName, "TestData", "sample.json");
         _store = new JsonConfigStore(_path, true);
      }

      [Fact]
      public void Read_inline_property()
      {
         string key = _store.Read("ApplicationInsights.InstrumentationKey");

         Assert.NotNull(key);
      }

      [Fact]
      public void Write_inline_property_reads_back()
      {
         if (!_store.CanWrite) return;

         string key = "ApplicationInsights.InstrumentationKey";

         _store.Write(key, "123");

         Assert.Equal("123", _store.Read(key));
      }

      [Fact]
      public void Write_new_value_hierarchically()
      {
         if (!_store.CanWrite) return;

         string key = "One.Two.Three";

         _store.Write(key, "111");

         Assert.Equal("111", _store.Read(key));
      }

      [Fact]
      public void AliasesOnCollections()
      {
         IMyConfigUsingAliases myConfig = new ConfigurationBuilder<IMyConfigUsingAliases>()
            .UseConfigStore(_store)
            .Build();

         Assert.NotNull(myConfig.Credentials);
         foreach (ICredsWithAlias c in myConfig.Credentials)
         {
            if (c.Name == "user1")
            {
               Assert.Equal("pass1", c.Pass);
            }
            else if (c.Name == "user2")
            {
               Assert.Equal("pass2", c.Pass);
            }
            else
            {
               Assert.Equal("user1", c.Name);
            }
         }
      }

      [Fact]
      public void TestCreatingFileInMissingFolder()
      {
         _path = Path.Combine("C:\\temp", "TestData", "sample.json");

         if (Directory.Exists(_path))
         {
            Directory.Delete(_path);
         }

         string key = "One.Two.Three";

         _store = new JsonConfigStore(_path, true);
         _store.Write(key, "111");

         Assert.Equal("111", _store.Read(key));

         Assert.True(File.Exists(_path));
      }

      public void Dispose()
      {
         _store.Dispose();
      }
   }
   public interface ICredsWithAlias
   {
      [Option(Alias = "Username")]
      string Name { get; set; }
      [Option(Alias = "Password")]
      string Pass { get; set; }
   }

   public interface IMyConfigUsingAliases
   {
      [Option(Alias = "Creds")]
      IEnumerable<ICredsWithAlias> Credentials { get; }
   }
}


text:
package net.sourceforge.pmd.lang.vm.directive;

/**
 * Base class for directives which do input operations
 * (e.g. #include(), #parse(), etc.).
 *
 * @author Daniel Rall
 * @since 1.4
 */
public abstract class InputBase extends Directive
{

}


text:
const del = require('del');
const path = require('path');
const mkdirp = require('mkdirp');
const cpy = require('cpy');
const { argv } = require('./argv');
const { promisify } = require('util');
const glob = promisify(require('glob'));
const child_process = require(`child_process`);
const { memoizeTask } = require('./memoize-task');
const readFile = promisify(require('fs').readFile);
const asyncDone = promisify(require('async-done'));
const exec = promisify(require('child_process').exec);
const parseXML = promisify(require('xml2js').parseString);
const { targetAndModuleCombinations, npmPkgName } = require('./util');

const jestArgv = [`--reporters=jest-silent-reporter`];

if (argv.verbose) {
    jestArgv.push(`--verbose`);
}

if (targetAndModuleCombinations.length > 1) {
    jestArgv.push(`--detectOpenHandles`);
}

const jest = path.join(path.parse(require.resolve(`jest`)).dir, `../bin/jest.js`);
const testOptions = {
    stdio: [`ignore`, `inherit`, `inherit`],
    env: {
        ...process.env,
        // hide fs.promises/stream[Symbol.asyncIterator] warnings
        NODE_NO_WARNINGS: `1`,
    },
};

const testTask = ((cache, execArgv, testOptions) => memoizeTask(cache, function test(target, format) {
    const opts = { ...testOptions };
    const args = [...execArgv];
    if (format === 'esm' || target === 'ts' || target === 'src' || target === npmPkgName) {
        args.unshift(`--experimental-vm-modules`);
    }
    if (argv.coverage) {
        args.push(`-c`, `jestconfigs/jest.coverage.config.js`);
    } else {
        const cfgname = [target, format].filter(Boolean).join('.');
        args.push(`-c`, `jestconfigs/jest.${cfgname}.config.js`, `test/unit/`);
    }
    opts.env = {
        ...opts.env,
        TEST_TARGET: target,
        TEST_MODULE: format,
        TEST_DOM_STREAMS: (target ==='src' || format === 'umd').toString(),
        TEST_NODE_STREAMS: (target ==='src' || format !== 'umd').toString(),
        TEST_TS_SOURCE: !!argv.coverage || (target === 'src') || (opts.env.TEST_TS_SOURCE === 'true')
    };
    return asyncDone(() => child_process.spawn(`node`, args, opts));
}))({}, [jest, ...jestArgv], testOptions);

module.exports = testTask;
module.exports.testTask = testTask;
module.exports.cleanTestData = cleanTestData;
module.exports.createTestData = createTestData;

// Pull C++ and Java paths from environment vars first, otherwise sane defaults
const ARROW_HOME = process.env.ARROW_HOME || path.resolve('../');
const ARROW_JAVA_DIR = process.env.ARROW_JAVA_DIR || path.join(ARROW_HOME, 'java');
const CPP_EXE_PATH = process.env.ARROW_CPP_EXE_PATH || path.join(ARROW_HOME, 'cpp/build/debug');
const ARROW_INTEGRATION_DIR = process.env.ARROW_INTEGRATION_DIR || path.join(ARROW_HOME, 'integration');
const CPP_JSON_TO_ARROW = path.join(CPP_EXE_PATH, 'arrow-json-integration-test');
const CPP_FILE_TO_STREAM = path.join(CPP_EXE_PATH, 'arrow-file-to-stream');

const testFilesDir = path.join(ARROW_HOME, 'js/test/data');
const snapshotsDir = path.join(ARROW_HOME, 'js/test/__snapshots__');
const cppFilesDir = path.join(testFilesDir, 'cpp');
const javaFilesDir = path.join(testFilesDir, 'java');
const jsonFilesDir = path.join(testFilesDir, 'json');

async function cleanTestData() {
    return await del([
        `${cppFilesDir}/**`,
        `${javaFilesDir}/**`,
        `${jsonFilesDir}/**`,
        `${snapshotsDir}/**`
    ]);
}

async function createTestJSON() {
    await mkdirp(jsonFilesDir);
    await cpy(`cp ${ARROW_INTEGRATION_DIR}/data/*.json`, jsonFilesDir);
    await exec(`python3 ${ARROW_INTEGRATION_DIR}/integration_test.py --write_generated_json ${jsonFilesDir}`);
}

async function createTestData() {

    let JAVA_TOOLS_JAR = process.env.ARROW_JAVA_INTEGRATION_JAR;
    if (!JAVA_TOOLS_JAR) {
        const pom_version = await
            readFile(path.join(ARROW_JAVA_DIR, 'pom.xml'))
                .then((pom) => parseXML(pom.toString()))
                .then((pomXML) => pomXML.project.version[0]);
        JAVA_TOOLS_JAR = path.join(ARROW_JAVA_DIR, `/tools/target/arrow-tools-${pom_version}-jar-with-dependencies.jar`);
    }

    await cleanTestData().then(createTestJSON);
    await mkdirp(path.join(cppFilesDir, 'file'));
    await mkdirp(path.join(javaFilesDir, 'file'));
    await mkdirp(path.join(cppFilesDir, 'stream'));
    await mkdirp(path.join(javaFilesDir, 'stream'));

    const errors = [];
    const names = await glob(path.join(jsonFilesDir, '*.json'));

    for (let jsonPath of names) {
        const name = path.parse(path.basename(jsonPath)).name;
        const arrowCppFilePath = path.join(cppFilesDir, 'file', `${name}.arrow`);
        const arrowJavaFilePath = path.join(javaFilesDir, 'file', `${name}.arrow`);
        const arrowCppStreamPath = path.join(cppFilesDir, 'stream', `${name}.arrow`);
        const arrowJavaStreamPath = path.join(javaFilesDir, 'stream', `${name}.arrow`);
        try {
            await generateCPPFile(path.resolve(jsonPath), arrowCppFilePath);
            await generateCPPStream(arrowCppFilePath, arrowCppStreamPath);
        } catch (e) { errors.push(`${e.stdout}\n${e.message}`); }
        try {
            await generateJavaFile(path.resolve(jsonPath), arrowJavaFilePath);
            await generateJavaStream(arrowJavaFilePath, arrowJavaStreamPath);
        } catch (e) { errors.push(`${e.stdout}\n${e.message}`); }
    }
    if (errors.length) {
        console.error(errors.join(`\n`));
        process.exit(1);
    }

    async function generateCPPFile(jsonPath, filePath) {
        await del(filePath);
        return await exec(
            `${CPP_JSON_TO_ARROW} ${
            `--integration --mode=JSON_TO_ARROW`} ${
            `--json=${jsonPath} --arrow=${filePath}`}`,
            { maxBuffer: Math.pow(2, 53) - 1 }
        );
    }

    async function generateCPPStream(filePath, streamPath) {
        await del(streamPath);
        return await exec(
            `${CPP_FILE_TO_STREAM} ${filePath} > ${streamPath}`,
            { maxBuffer: Math.pow(2, 53) - 1 }
        );
    }

    async function generateJavaFile(jsonPath, filePath) {
        await del(filePath);
        return await exec(
            `java -cp ${JAVA_TOOLS_JAR} ${
            `org.apache.arrow.tools.Integration -c JSON_TO_ARROW`} ${
            `-j ${path.resolve(jsonPath)} -a ${filePath}`}`,
            { maxBuffer: Math.pow(2, 53) - 1 }
        );
    }

    async function generateJavaStream(filePath, streamPath) {
        await del(streamPath);
        return await exec(
            `java -cp ${JAVA_TOOLS_JAR} ${
            `org.apache.arrow.tools.FileToStream`} ${filePath} ${streamPath}`,
            { maxBuffer: Math.pow(2, 53) - 1 }
        );
    }
}


text:
package pl.touk.nussknacker.openapi.http.backend

import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory
import pl.touk.nussknacker.engine.api.test.InvocationCollectors.{CollectableAction, ServiceInvocationCollector, TransmissionNames}
import pl.touk.nussknacker.openapi.http.backend.LoggingAndCollectingSttpBackend.HttpBackend
import sttp.client.monad.MonadError
import sttp.client.ws.WebSocketResponse
import sttp.client._

import java.nio.charset.StandardCharsets
import java.util.UUID
import scala.concurrent.{ExecutionContext, Future}

object LoggingAndCollectingSttpBackend {

  type HttpBackend = SttpBackend[Future, Nothing, Nothing]

  private case class WithStringResponseBody[T](original: T, stringResponseBody: () => Option[String])

  private val transmissionNames = TransmissionNames("request", "response")

}

class LoggingAndCollectingSttpBackend(delegate: HttpBackend, baseLoggerName: String)
                                     (implicit ec: ExecutionContext, serviceInvocationCollector: ServiceInvocationCollector) extends HttpBackend {

  import LoggingAndCollectingSttpBackend._

  private val requestLogger = Logger(LoggerFactory.getLogger(s"$baseLoggerName.request"))
  private val responseLogger = Logger(LoggerFactory.getLogger(s"$baseLoggerName.response"))

  override def send[T](request: Request[T, Nothing]): Future[Response[T]] = {
    val correlationId = UUID.randomUUID()
    lazy val requestLog = RequestResponseLog(request)
    requestLogger.debug(s"[$correlationId]: ${requestLog.pretty}")
    val withLoggedStringResponseBody = request.response(withStringResponseBody(request.response))
    val reqTime = System.currentTimeMillis()
    lazy val response = delegate.send(withLoggedStringResponseBody)
      .transform(
        response => handleResponse(correlationId, request, reqTime, response),
        error => {
          responseLogger.debug(s"[$correlationId]: request failed in ${System.currentTimeMillis() - reqTime}ms: ${requestLog.pretty}")
          error
        })
    serviceInvocationCollector.collectWithResponse(requestLog, mockValue = None)(response, transmissionNames)
  }

  private def withStringResponseBody[T](responseAs: ResponseAs[T, Nothing]): ResponseAs[WithStringResponseBody[T], Nothing] = {
    responseAs match {
      case ResponseAsByteArray =>
        ResponseAsByteArray.map(byteArray => WithStringResponseBody(byteArray, () => Some(new String(byteArray, StandardCharsets.UTF_8))))
      case MappedResponseAs(raw, g) =>
        val nested = withStringResponseBody(raw)
        MappedResponseAs(nested, (withSRB: WithStringResponseBody[Any], responseMetadata: ResponseMetadata) =>
          withSRB.copy(original = g(withSRB.original, responseMetadata)))
      case other =>
        other.map(WithStringResponseBody(_, () => None))
    }
  }

  private def handleResponse[T](correlationId: UUID,
                                request: Request[T, Nothing],
                                requestTimestamp: Long,
                                response: Response[WithStringResponseBody[T]]): CollectableAction[Response[T]] = {
    def responseLog = RequestResponseLog(request, response, resBody = response.body.stringResponseBody())
    responseLogger.debug(s"[$correlationId][took ${System.currentTimeMillis() - requestTimestamp}ms]: ${responseLog.pretty}")
    val targetResponse = response.copy(body = response.body.original)
    CollectableAction(() => responseLog, targetResponse)
  }

  override def openWebsocket[T, WS_RESULT](request: Request[T, Nothing], handler: NothingT[WS_RESULT]): Future[WebSocketResponse[WS_RESULT]] = ???

  override def close(): Future[Unit] = delegate.close()

  override def responseMonad: MonadError[Future] = delegate.responseMonad
}


text:
package com.rapbattlingworld.thefarnapp;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

// Referenced classes of package com.rapbattlingworld.thefarnapp:
//            Answers

public class MainActivity extends Activity
{

    private TextView answerLabel;
    private Answers answers;
    private Button clearText;
    private Button getAnswerButton;

    public MainActivity()
    {
    }

    private void animateAnswer()
    {
        AlphaAnimation alphaanimation = new AlphaAnimation(0.0F, 1.0F);
        alphaanimation.setDuration(1500L);
        alphaanimation.setFillAfter(true);
        answerLabel.setAnimation(alphaanimation);
    }

    private void animateFarn()
    {
        ImageView imageview = (ImageView)findViewById(0x7f090001);
        imageview.setImageResource(0x7f020013);
        AnimationDrawable animationdrawable = (AnimationDrawable)imageview.getDrawable();
        if (animationdrawable.isRunning())
        {
            animationdrawable.stop();
        }
        animationdrawable.start();
    }

    private void playSound()
    {
        MediaPlayer mediaplayer = MediaPlayer.create(this, 0x7f040000);
        mediaplayer.start();
        mediaplayer.setOnCompletionListener(new android.media.MediaPlayer.OnCompletionListener() {

            final MainActivity this$0;

            public void onCompletion(MediaPlayer mediaplayer1)
            {
                mediaplayer1.release();
            }

            {
                this$0 = MainActivity.this;
                super();
            }
        });
    }

    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);
        setContentView(0x7f030000);
        answerLabel = (TextView)findViewById(0x7f090002);
        getAnswerButton = (Button)findViewById(0x7f090003);
        clearText = (Button)findViewById(0x7f090004);
        answers = new Answers();
        getAnswerButton.setOnClickListener(new android.view.View.OnClickListener() {

            final MainActivity this$0;

            public void onClick(View view)
            {
                animateFarn();
                playSound();
                String s = answers.getAnswer();
                answerLabel.setText(s);
                animateAnswer();
            }

            {
                this$0 = MainActivity.this;
                super();
            }
        });
        clearText.setOnClickListener(new android.view.View.OnClickListener() {

            final MainActivity this$0;

            public void onClick(View view)
            {
                answerLabel.setText("");
            }

            {
                this$0 = MainActivity.this;
                super();
            }
        });
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(0x7f080000, menu);
        return true;
    }

}


text:
__time = __import__('time')
from evy.patcher import slurp_properties

__patched__ = ['sleep']
slurp_properties(__time, globals(), ignore = __patched__, srckeys = dir(__time))
from evy.green.threads import sleep

sleep # silence pyflakes


text:
"""
API for the blog application
"""
from rest_framework import serializers, viewsets, filters
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response

from blog.models import BlogEntry

class BlogEntrySerializer(serializers.ModelSerializer):

    """
    Serializer for a `BlogEntry`
    """

    class Meta:
        model = BlogEntry

class BlogEntryViewSet(viewsets.ModelViewSet):

    """
    ViewSet for `BlogEntries`
    """

    queryset = BlogEntry.objects.filter(is_published=True)
    serializer_class = BlogEntrySerializer
    filter_backends = (filters.OrderingFilter, )
    ordering = ('-first_published_on', )

    def retrieve_with_slug(self, request, year, month, slug):
        """
        Retrieve a blog post given the year, month and title slug.
        """
        entry = get_object_or_404(
            self.get_queryset(),
            first_published_on__year=year,
            first_published_on__month=month,
            slug=slug)
        serializer = self.get_serializer(entry)
        return Response(serializer.data)