text:
What's new?

You can get a taste for the new stuff in the 0.9.0 release from the ChangeLog
    page. In general, this is a very stable, well-tested release. The beta is being actively
   used in a number of production sites, including this one, with no reported ill effects. The Yesod
   team feels very strongly that this is an upgrade worth making as soon as possible.

The purpose of the release candidate is to try to get any last-minute input on bugs or bad
   decisions before they are set in stone with the official release. I highly encourage everyone
   using Yesod to install the release candidate and test it out on a few of your sites.

Get set up for Yackage

The 0.9 release candidate is available on the Yesod Yackage server. Note that the version numbers are
   the same as will be released with the final release. That means that, if you install the RC, it's
   highly recommended to wipe your .ghc folder after the official release comes out.

In order to install the release candidate, follow these steps:

Add the following line to your ~/.cabal/config
    file:
remote-repo: yesod-yackage:http://yackage.yesodweb.com

Run cabal update

Run cabal install yesod-0.9.0

Get a beer and congratulate yourself on a job well done.

Migration guide: Yesod 0.8 to 0.9

As has become a bit of a custom, we're going to go through the necessary changes to the
   Haskellers codebase to get it to work with the new release. Fortunately, there are many less
   steps in this release. You can see the entire commit on Github. To give you an idea of time
   investment, it took me about two hours to migrate Haskellers, write this guide, and apply a few
   minor tweaks to the framework in the process.

Fix up your cabal file. For the most part, just change yesod to version 0.9 and watch the
    fallout. Pay particular attention to the version bounds on related packages like hamlet and
    persistent. Also:

hamlet has been split out into multiple packages. You'll likely get build errors telling
      you to add shakespeare-css and shakespeare-js

Due to issues with the newest aeson and Template Haskell, we had to create a fork. The API
      is identical, the only difference is in how doubles are rendered. Just updated any references
      to aeson to be aeson-native.

Goodbye "Helpers" module namespace. This affects Yesod.Helpers.Static, Yesod.Helpers.Auth.*,
    Yesod.Helpers.Feed.* and others. All you need to do is remove the word Helpers.

The datatypes from hamlet have been renamed. This likely doesn't affect much code, but just
    be aware of it.

Old name
      New name

Hamlet
      HtmlUrl

Cassius/Lucius
      CssUrl

Julius
      JavascriptUrl

IHamlet
      HtmlUrlI18n

Forms have had a significant overhaul. This will be the most labor-intensive part of the
    migration. I'll address this later.

In your Model.hs file, mkPersist now takes an extra parameter to give it settings. For now
    use sqlSettings, we'll have some more options in the future.

Model.hs needs the GADTs language extension enabled.

In your application file (e.g., Haskellers.hs), remove the type synonyms for Handler and
    Widget. This is now provided by the TH code. Also, instead of Widget (), just say Widget.

In the YesodPersist instance, change "YesodDB" to "YesodPersistBackend".

The other big change: the filter API for persistent became much simpler. Instead of
    using constructors like "PersonNameEq", we now just use operators. (Thanks to Boris for the
     groundhog inspiration here.) Some simple examples:

Old code
      New code

PersonNameEq "Michael"
      PersonName ==. "Michael"

PersonAgeLe 30
      PersonAge <=. 30

UserEmailNe $ Just "foo@bar.com"
      UserEmail !=. Just "foo@bar.com"

There will be a bit of manual effort involved in this transition, but the result
    is well worth it.

select syntax has changed. Instead of having those two hanging integers at the end, we have a
    list of options. An example should suffice:

Old

selectList [PersonNameEq "Michael"] [PersonAgeDesc] 5 10

New

selectList [PersonName ==. "Michael"] [Desc PersonAge, LimitTo 5, OffsetBy 10]

If you had a 0 for either of those trailing integers, they can just be ignored.

Updates are similarly changed.

Old

update personId [PersonName "Michael"]

New

update personId [PersonName =. "Michael"]

And a great sigh of relief was heard: polymorphic hamlet is gone. For the most part, this
    just means you'll need to preface a few hamlet calls with toWidget. Unfortunately, the error
    messages are confusing; just email the list if you get stuff on somthing.

There have been some renames in the templates. It's best to just read the chapter for details.

We added i18n support for form messages. You'll need to add this to your application file
    (e.g.,
    Haskellers.hs)
instance RenderMessage Haskellers FormMessage where
    renderMessage _ _ = defaultFormMessage
This
    uses the default values, which are all English. You can modify these yourself if you want,
    expect some blog posts in the next few weeks focusing on how i18n works.

Under some strange conditions, you'll have to give your ID variables explicit type
    signatures. This is exceedingly rare.

Forms

Forms got a huge cleanup in this release. I'm hoping to get the chapter up-to-date soon, but
    the migration guide isn't enough to fully explain what's happened. I'll just give a few quick
    translations that I've used in Haskellers:

Old code
     New code

runFormPost'
     runInputPost

maybeStringInput
     iopt textField

stringInput
     ireq textField

runFormGet'
     runInputGet

maybeIntInput
     iopt intField

maybeStringField
     aopt textField

fieldsToTable
     renderTable


text:
This app uses the web audio API to synthesize sounds.  The code includes synthesized sounds for the following instruments:

1. Organ
2. Piano
3. EDM
4. Acoustics

The web audio API can easily handle the processing power to deal with synthesizing and playing multiple sounds.  Since it is native to the browser, it is quick, and many of the processes run asynchronously.  For this reason, the web audio API was a good choice for this app. It is also a fascinating API.  It gives the browser the ability to create, edit, and play sounds.  In the past, developers would have to use an outside library or the audio element, which was slow in comparison to the native audio API.

Here are a few good intros to the web audio API.  These can be quickly read, and are easy to skim through:

1. http://middleearmedia.com/web-audio-api-basics/ - provides a great analogy to understand the philosophy of the API

2. http://middleearmedia.com/web-audio-api-audio-buffer/ - a great explanation of the audio buffer ( used in the code multiple times )

3. http://middleearmedia.com/web-audio-api-bufferloader/ - more info on buffers

4. http://middleearmedia.com/web-audio-api-oscillators/ - an introduction to oscillators.  Unfortunately, the code does not use oscillators.  I would like to convert the synthesized sounds to ONLY use the oscillators.  It is entirely possible since the oscillators have a Fourier function associated with them (custom oscillator).

5. http://keithwhor.com/music/ Synthesized sounds come from here

6. http://www.willvillanueva.com/the-web-audio-api-from-nodeexpress-to-your-browser/ - Check my blog post on how to use a server to efficiently server sounds to the web audio API

7. http://sendoushi.com/blog/web-audio-api-soundjs-d3/ - a superb example of how you can use the ANALYZER nodes to visualize the web audio sounds.  I would definitely like to include this feature in the future.

8. http://chimera.labs.oreilly.com/books/1234000001552 - an advanced resource on the web audio API.  IT is the best resource available anywhere.  IT is extremely thorough, and an entertaining read.

9. http://labs.dinahmoe.com/ToneCraft/ - In my opinion, the most interesting app developed through the web audio API.  This was an inspiration for our app.

# Setting up a Sound Board
In the audio library, you can create a soundBoard by doing the following:

`new SoundBoard(gridInformation)`

If you are bringing in sounds from a previous SoundBoard, you will pass the gridInformation in.  Otherwise, you can create the SoundBoard without passing any parameters in.

To add a grid to the SoundBoard, you will want to create a grid first:

`new Grid(instrument, BPM, frequency, noteScheduler)`

Our code is set to build 6 different frequencies for the grid centered around the frequency you pass in.  We have built it on the pentatonic scale.  Please do experiment with this, and try different scales!  Feel free to change this function around to take different notes.  In fact, I encourage it :)

To play an individual grids interval, you can just call the playInterval function.  To stop the scheduled sounds, just call the stop interval.

To play any sound, just call the playSounds function:

`playSounds( frequencyOrSound, volume, start)`

You may enter in ANY frequency.  This function is capable of playing any note - since the sounds are synthesized.  However, the note must exist in the Grid hash. To add it, just make sure the Grid includes the scale value.

Next, you'll want to add the grid to the soundBoard:

`SoundBoard.addGrid(Grid)`

The soundBoard has a playCurrentSound function.  It will play any sound from the current grid.  The current grid is the grid that the user is playing with/adjusting.  It will always be the last Grid in the SoundBoard's grid array.

Each individual grid has a noteScheduler object.  This object gives instructions on what sound should be played for each column.  Since the user can only adjust the currentBoard, the toggle function exists on the SoundBoard prototype.  It will only toggle (turn on and off scheduled sounds) the current board.

Once you have grids within the soundBoard, you can use the playInterval function.  This function will schedule and play all the sounds at the correct time for the loops.  This function takes a callback, but does not require a callback.  The callback simply gives information on what column is the current, activated column in the grid.  We use this callback to light up the columns in the grid view.

The stopInterval function stops the looping sounds.

The exportGrids function extracts the necessary information to create an IDENTICAL soundboard.  Once you have exported the Grids, you can pass it into a new instance of the SoundBoard to recreate it:
new SoundBoard(gridInformation).

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.developerstudio.eclipse.gmf.esb;

/**
 *
 * A representation of the model object 'Address End Point Output Connector'.
 *
 *
 *
 * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAddressEndPointOutputConnector()
 * @model
 * @generated
 */
public interface AddressEndPointOutputConnector extends OutputConnector {
} // AddressEndPointOutputConnector


text:
import * as React from "react";
import IApronDeviceGroup from "../../models/ApronDeviceGroup";
import AddNode from "./AddNode";
import DeleteNode from "./DeleteNode";

interface IListGroupProps  {
    devices: IApronDeviceGroup[];
    group: IApronDeviceGroup;
    deleteGroup(groupId: number);
    addNode(groupId: number, nodeId: number);
    deleteNode(groupId: number, nodeId: number);
}

export default class ListGroup extends React.Component<IListGroupProps, void> {
    public render() {
        const { devices, group } = this.props;
        const groupNodes = group.Nodes.map((node, index1) => {
            return (<DeleteNode group={group} node={node} deleteNode={this.props.deleteNode}/>);
        });
        return (

                                Delete

                            {group.ID}
                            <input value={group.Name}
                                className="form-control form-control-sm"
                                readOnly={true} type="text" />

                                {group.Nodes.length}

                        <AddNode group={group} devices={devices} addNode={this.props.addNode} />

                        Assoc. Devices

                            {groupNodes}

        );
    }

    private onClick = (event: React.FormEvent<HTMLAnchorElement>) => {
        event.preventDefault();

        this.props.deleteGroup(this.props.group.ID);
    }
}


text:
package com.google.jplurk;

import junit.framework.TestCase;

public class LangTest extends TestCase {

	public void testContains() throws Exception {

		assertFalse(Lang.contains("foo"));
		assertTrue(Lang.contains("en"));
		assertTrue(Lang.contains("tr_ch"));
	}
}


text:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals

import pytest

@pytest.fixture(scope='session', autouse=True)
def no_pip_environment_vars():
    import os
    for var in dict(os.environ):
        if var.startswith('PIP_'):
            del os.environ[var]

@pytest.fixture(scope='session', autouse=True)
def no_pythonpath_environment_var():
    import os
    for var in dict(os.environ):
        if var == 'PYTHONPATH':
            del os.environ[var]


text:
<?php
/**
 * www.valiton.com
 *
 * @author Uwe Jäger <uwe.jaeger@valiton.com>
 */
namespace Valiton\Bundle\MultiSiteBundle;

use Symfony\Cmf\Component\Routing\Candidates\CandidatesInterface;
use Valiton\Bundle\MultiSiteBundle\Document\Site;

class CurrentSite
{
    /** @var Site */
    protected $site;

    /** @var \Liip\ThemeBundle\ActiveTheme */
    protected $activeTheme;

    /** @var \Symfony\Cmf\Bundle\MenuBundle\Provider\PHPCRMenuProvider */
    protected $menuProvider;

    /** @var  CandidatesInterface */
    protected $routeCandidatesProvider;

    /** @var \Symfony\Cmf\Bundle\MediaBundle\Doctrine\Phpcr\MediaManager  */
    protected $mediaManager;

    /** @var \Symfony\Cmf\Bundle\MediaBundle\File\UploadFileHelperDoctrine */
    protected $uploadFileHelper;

    /** @var \Symfony\Cmf\Bundle\MediaBundle\File\UploadFileHelperDoctrine */
    protected $uploadImageHelper;

    /** @var \Symfony\Cmf\Bundle\MediaBundle\Controller\FileController */
    protected $fileController;

    /** @var \Symfony\Cmf\Bundle\MediaBundle\Controller\ImageController */
    protected $imageController;

    /**
     * @param \Liip\ThemeBundle\ActiveTheme $activeTheme
     */
    public function setActiveTheme($activeTheme)
    {
        $this->activeTheme = $activeTheme;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MenuBundle\Provider\PHPCRMenuProvider $menuProvider
     */
    public function setMenuProvider($menuProvider)
    {
        $this->menuProvider = $menuProvider;
    }

    /**
     * @param CandidatesInterface $routeCandidatesProvider
     */
    public function setRouteCandidatesProvider($routeCandidatesProvider)
    {
        $this->routeCandidatesProvider = $routeCandidatesProvider;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MediaBundle\Doctrine\Phpcr\MediaManager $mediaManager
     */
    public function setMediaManager($mediaManager)
    {
        $this->mediaManager = $mediaManager;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MediaBundle\File\UploadFileHelperDoctrine $uploadFileHelper
     */
    public function setUploadFileHelper($uploadFileHelper)
    {
        $this->uploadFileHelper = $uploadFileHelper;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MediaBundle\File\UploadFileHelperDoctrine $uploadImageHelper
     */
    public function setUploadImageHelper($uploadImageHelper)
    {
        $this->uploadImageHelper = $uploadImageHelper;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MediaBundle\Controller\FileController $fileController
     */
    public function setFileController($fileController)
    {
        $this->fileController = $fileController;
    }

    /**
     * @param \Symfony\Cmf\Bundle\MediaBundle\Controller\ImageController $imageController
     */
    public function setImageController($imageController)
    {
        $this->imageController = $imageController;
    }

    /**
     * @param mixed $site
     */
    public function setSite(Site $site)
    {
        $this->site = $site;
        if (null !== $this->activeTheme && in_array($site->getTheme(), $this->activeTheme->getThemes())) {
            $this->activeTheme->setName($site->getTheme());
        }
        if (null !== $this->menuProvider) {
            $this->menuProvider->setMenuRoot($site->getMenuRoot()->getId());
        }
        if (null !== $this->routeCandidatesProvider) {
            $this->routeCandidatesProvider->setPrefixes(array($site->getRoutesRoot()->getId()));
        }
        if (null !== $this->mediaManager) {
            $this->mediaManager->setRootPath($site->getMediaRoot()->getId());
        }
        if (null !== $this->uploadFileHelper) {
            $this->uploadFileHelper->setRootPath($site->getMediaRoot()->getId());
        }
        if (null !== $this->uploadImageHelper) {
            $this->uploadImageHelper->setRootPath($site->getMediaRoot()->getId());
        }
        if (null !== $this->fileController) {
            $this->fileController->setRootPath($site->getMediaRoot()->getId());
        }
        if (null !== $this->imageController) {
            $this->imageController->setRootPath($site->getMediaRoot()->getId());
        }
    }

    /**
     * @return Site
     */
    public function getSite()
    {
        return $this->site;
    }

}


text:
require 'fcntl'
require 'tmpdir'

class Preforker
  class TmpIO < ::File

    # for easier env["rack.input"] compatibility
    def size
      # flush if sync
      stat.size
    end
  end

  class Util
    def self.is_log?(fp)
      append_flags = File::WRONLY | File::APPEND

      ! fp.closed? &&
        fp.sync &&
        fp.path[0] == ?/ &&
        (fp.fcntl(Fcntl::F_GETFL) & append_flags) == append_flags
    end

    # creates and returns a new File object.  The File is unlinked
    # immediately, switched to binary mode, and userspace output
    # buffering is disabled
    def self.tmpio
      fp = begin
             TmpIO.open("#{Dir::tmpdir}/#{rand}",
                        File::RDWR|File::CREAT|File::EXCL, 0600)
           rescue Errno::EEXIST
             retry
           end
      File.unlink(fp.path)
      fp.binmode
      fp.sync = true
      fp
    end
  end
end


text:
aAdminMain = {
	Form = nil,
	Panel = nil,
	Tabs = {},
	Tab = nil,
	Refresh = 0,
	Hidden = false
}

g_serverConfigSettings = {}

addEvent ( "onAdminInitialize", true )
addEvent ( "onAdminRefresh", false )

addEvent ( "onAcpClientInitialSettings", true )
addEventHandler ( "onAcpClientInitialSettings", resourceRoot,
	function ( serverConfigSettings )
		g_serverConfigSettings = serverConfigSettings;
	end
)

function getServerConfigSetting(name)
	return g_serverConfigSettings[name]
end

addEvent ( "aClientAcMenu", true )
addEventHandler ( "aClientAcMenu", resourceRoot,
	function ( mode )
		if ( ( ( aAdminMain.Form ) and ( guiGetVisible ( aAdminMain.Form ) == true ) ) or ( aAdminMain.Hidden ) or mode == "close" ) then
			aAdminMain.Close ( false )
		else
			aAdminMain.Open ()
		end
	end
)

function aAdminMain.Open ()
	if ( aAdminMain.Form == nil ) then
		local x, y = guiGetScreenSize()
		aAdminMain.Form		= guiCreateWindow ( x / 2 - 310 - 20, y / 2 - 260 - 20, 620, 520, "Anti-Cheat Panel - v".._version, false )
		aAdminMain.Panel		= guiCreateTabPanel ( 0.01, 0.05, 0.98, 0.95, true, aAdminMain.Form )

		aAdminMain.AddTab ( "Status", aAntiCheatTab, "anticheat" )
		aAdminMain.AddTab ( "Status #2", aAntiCheatTab2, "anticheat" )
		aAdminMain.AddTab ( "Block Img Mods", aBlockModsTab, "mods" )
		aAdminMain.AddTab ( "Server Config", aServerConfigTab, "server" )

		addEventHandler ( "onClientGUITabSwitched", resourceRoot, aAdminMain.Switch )
		addEventHandler ( "onAdminInitialize", aAdminMain.Form, aAdminMain.Initialize )

		triggerEvent ( "onAdminInitialize", aAdminMain.Form )
	end
	guiSetAlpha ( aAdminMain.Form, 1 )
	guiSetVisible ( aAdminMain.Form, true )
	showCursor ( true )
	aAdminMain.Hidden = false
end

function aAdminMain.Close ()
	guiSetVisible ( aAdminMain.Form, false )
	showCursor ( false )
end

function aAdminMain.Initialize ()
	if ( #aAdminMain.Tabs > 0 ) then
		aAdminMain.Switch ( aAdminMain.Tabs[1].Tab )
	end
end

function aAdminMain.Switch ( tab )
	aAdminMain.Tab = tab
	local id = aAdminMain.GetTab ( tab )
	if ( id ) then
		if ( not aAdminMain.Tabs[id].Loaded ) then
			aAdminMain.Tabs[id].Class.Create ( tab )
			aAdminMain.Tabs[id].Loaded = true
		end
	end
end

function aAdminMain.AddTab ( name, class, acl )
	local tab = guiCreateTab ( name, aAdminMain.Panel, acl )
	table.insert ( aAdminMain.Tabs, { Tab = tab, Class = class, Loaded = false } )
end

function aAdminMain.GetTab ( tab )
	for k, v in ipairs ( aAdminMain.Tabs ) do
		if ( v.Tab == tab ) then return k end
	end
	return nil
end

addEventHandler ( "onClientRender", root,
	function ()
		guiSetInputMode ( "no_binds_when_editing" )
	end
)


text:
set +x
echo "Waiting for X server"
until [[ -e /var/run/appconfig/xserver_ready ]]; do sleep 1; done
echo "X server is ready"
set -x

# Forward js input control socket to shared pod volume.
if [[ -S /tmp/.uinput/js0ctl ]]; then
    echo "Forwarding socket /tmp/.uinput/js0ctl to /var/run/appconfig/js0ctl"
    sudo chown root:app /tmp/.uinput/js*ctl
    sudo chown root:app /dev/input/js* /dev/input/event* /dev/input/evdev/js*
    nohup sudo socat UNIX-RECV:/var/run/appconfig/js0ctl,reuseaddr UNIX-CLIENT:/tmp/.uinput/js0ctl &
fi

echo "Setting resolution"
RESOLUTION=${RESOLUTION:-1920x1080}
xrandr -s ${RESOLUTION}
xrandr --fb ${RESOLUTION}

# Workaround for vulkan initialization
# https://bugs.launchpad.net/ubuntu/+source/nvidia-graphics-drivers-390/+bug/1769857
[[ -c /dev/nvidiactl ]] && (cd /tmp && sudo LD_LIBRARY_PATH=${LD_LIBRARY_PATH} DISPLAY=${DISPLAY} vulkaninfo >/dev/null 2>&1 || true)

while true; do
    eval ${ENABLE_WM:-true} && xfwm4 --replace ${WM_ARGS} &
    sleep 2
    if [[ -e "${APP_PATH}" ]]; then
        echo "Starting app: ${APP_PATH}"
        cd $(dirname ${APP_PATH})
        wine64 ${APP_PATH} ${APP_ARGS}
    elif [[ -e "${ENTRYPOINT}" ]]; then
        echo "Starting env provided entrypoint: ${ENTRYPOINT}"
        eval ${ENTRYPOINT}
    else
        echo "ERROR: No APP_PATH or ENTRYPOINT env var found, nothing to execute."
        exit 1
    fi
    sleep 2
done


text:
package TrueSkill;

use strict;
use Variable;
use Gaussian;
use LikelihoodFactor;
use PriorFactor;
use SumFactor;
use TruncateFactor;

use Math::Cephes qw(:all);
use Statistics::Distrib::Normal;

my $norm = new Statistics::Distrib::Normal;

#norm = scipy_norm()
#pdf = norm.pdf
#cdf = norm.cdf
#icdf = norm.ppf    # inverse CDF

# Update rules for approximate marginals for the win and draw cases,
# respectively.

sub Vwin
{
	my $t = shift;
	my $e = shift;
  return $norm->pdf($t-$e) / Math::Cephes::ndtr($t-$e);
}

sub Wwin
{
	my $t = shift;
	my $e = shift;
  return Vwin($t, $e) * (Vwin($t, $e) + $t - $e);
}

sub Vdraw
{
	my $t = shift;
	my $e = shift;

	my $a = Math::Cephes::ndtr($e-$t);
	my $b = Math::Cephes::ndtr(-1*$e-$t);

	#print "\n$a $b";

  return ($norm->pdf(-1*$e-$t) - $norm->pdf($e-$t)) / ($a-$b );
}
sub Wdraw
{
	my $t = shift;
	my $e = shift;
  return Vdraw($t, $e) ** 2 + (($e-$t) * $norm->pdf($e-$t) + ($e+$t) * $norm->pdf($e+$t)) / (Math::Cephes::ndtr($e-$t) - Math::Cephes::ndtr(-1*$e-$t));
}

use constant INITIAL_MU => 25.0;
use constant INITIAL_SIGMA => INITIAL_MU / 3.0;

my $BETA;
my $EPSILON;
my $GAMMA;

sub SetParameters
{
	my ($beta, $epsilon, $draw_probability, $gamma) = @_;
  #"""
  #Sets three global parameters used in the TrueSkill algorithm.

  #beta is a measure of how random the game is.  You can think of it as
  #the difference in skill (mean) needed for the better player to have
  #an ~80% chance of winning.  A high value means the game is more
  #random (I need to be *much* better than you to consistently overcome
  #the randomness of the game and beat you 80% of the time); a low
  #value is less random (a slight edge in skill is enough to win
  #consistently).  The default value of beta is half of INITIAL_SIGMA
  #(the value suggested by the Herbrich et al. paper).

  #epsilon is a measure of how common draws are.  Instead of specifying
  #epsilon directly you can pass draw_probability instead (a number
  #from 0 to 1, saying what fraction of games end in draws), and
  #epsilon will be determined from that.  The default epsilon
  #corresponds to a draw probability of 0.1 (10%).  (You should pass a
  #value for either epsilon or draw_probability, not both.)

  #gamma is a small amount by which a player's uncertainty (sigma) is
  #increased prior to the start of each game.  This allows us to
  #account for skills that vary over time; the effect of old games
  #on the estimate will slowly disappear unless reinforced by evidence
  #from new games.
  #"""

	if(!defined $beta) {
		$BETA = INITIAL_SIGMA / 2.0;
	} else {
		$BETA = $beta;
	}
	if(!defined $epsilon) {
		if(!defined $draw_probability) {
			$draw_probability = 0.10;
		}
		$EPSILON = DrawMargin($draw_probability, $BETA);
	} else {
		$EPSILON = $epsilon;
	}

	if(!defined $gamma) {
		$GAMMA = INITIAL_SIGMA / 100.0;
	} else {
		$GAMMA = $gamma;
	}

	# print "\nSetup: $BETA, $EPSILON, $GAMMA";
}

#
# call set parameters with no args
#
SetParameters();

sub AdjustPlayers
{
	my @players_orig = @_;
  #"""
  #Adjust the skills of a list of players.

  #'players' is a list of player objects, for all the players who
  #participated in a single game.  A 'player object' is any object with
  #a "skill" attribute (a (mu, sigma) tuple) and a "rank" attribute.
  #Lower ranks are better; the lowest rank is the overall winner of the
  #game.  Equal ranks mean that the two players drew.

  #This function updates all the "skill" attributes of the player
  #objects to reflect the outcome of the game.  The input list is not
  #altered.
  #"""

  my @players = sort {$a->{rank}<=>$b->{rank}} @players_orig;

  # Sort players by rank, the factor graph will connect adjacent team
  # performance variables.
  # players.sort(key=lambda p: p.rank)

  # Create all the variable nodes in the graph.  "Teams" are each a
  # single player; there's a one-to-one correspondence between players
  # and teams.  (It would be straightforward to make multiplayer
  # teams, but it's not needed for my current purposes.)
	my(@ss, @ps, @ts, @ds);
	foreach my $p (@players) {
		push(@ss, new Variable());
		push(@ps, new Variable());
		push(@ts, new Variable());
		push(@ds, new Variable());
	}
	pop(@ds);

  # Create each layer of factor nodes.  At the top we have priors
  # initialized to the player's current skill estimate.
  my @skill;
  my @skill_to_perf;
  my @perf_to_team;
  for my $i (0..scalar(@ss)-1) {
	my $s = $ss[$i];
	my $p = $ps[$i];
	my $pl = $players[$i];
	my $t = $ts[$i];

	# print "\nPlayer[$i] skills: $pl->{skill}->[0], $pl->{skill}->[1]";
	push(@skill, new PriorFactor($s, new Gaussian($pl->{skill}->[0], $pl->{skill}->[1] + $GAMMA)));
	push(@skill_to_perf, new LikelihoodFactor($s, $p, $BETA**2));
	push(@perf_to_team, new SumFactor($t, [$p], [1]));
  }

  my @team_diff;
  my @t1 = @ts; pop(@t1);
  my @t2 = @ts; shift(@t2);
  for my $i (0..scalar(@ds)-1) {
	my $d = $ds[$i];
	my $t1var = $t1[$i];
	my $t2var = $t2[$i];
	push(@team_diff, new SumFactor($d, [$t1var, $t2var], [+1, -1]));
  }

  #skill = [PriorFactor(s, Gaussian(mu=pl.skill[0],
  #                                 sigma=pl.skill[1] + GAMMA))
  #         for (s, pl) in zip(ss, players)]
  #skill_to_perf = [LikelihoodFactor(s, p, BETA**2)
  #                 for (s, p) in zip(ss, ps)]
  #perf_to_team = [SumFactor(t, [p], [1])
  #                for (p, t) in zip(ps, ts)]
  #team_diff = [SumFactor(d, [t1, t2], [+1, -1])
  #             for (d, t1, t2) in zip(ds, ts[:-1], ts[1:])]
  # At the bottom we connect adjacent teams with a 'win' or 'draw'
  # factor, as determined by the rank values.
  my @trunc;
  my @pl1 = @players; pop(@pl1);
  my @pl2 = @players; shift(@pl2);
  for my $i (0..scalar(@ds)-1) {
	my $d = $ds[$i];
	my $pl1var = $pl1[$i];
	my $pl2var = $pl2[$i];

	my $v;
	if($pl1var->{rank} == $pl2var->{rank}){
		$v = \&Vdraw;
	} else{
		$v = \&Vwin;
	}

	my $w;
	if($pl1var->{rank} == $pl2var->{rank}){
		$w = \&Wdraw;
	} else{
		$w = \&Wwin;
	}

	push(@trunc, new TruncateFactor($d,
								$v,
								$w,
								$EPSILON));
  }
  #trunc = [TruncateFactor(d,
  #                        Vdraw if pl1.rank == pl2.rank else Vwin,
  #                        Wdraw if pl1.rank == pl2.rank else Wwin,
  #                        EPSILON)
  #         for (d, pl1, pl2) in zip(ds, players[:-1], players[1:])]

  # Start evaluating the graph by pushing messages 'down' from the
  # priors.

  #print "\nDoing skill";
	foreach my $f (@skill) {
		$f->Start();
	}
	#print "\nDoing skill_to_perf";
	foreach my $f (@skill_to_perf) {
		$f->UpdateValue();
	}
	#print "\nDoing perf_to_team";
	foreach my $f (@perf_to_team) {
		$f->UpdateSum();
	}

  # Because the truncation factors are approximate, we iterate,
  # adjusting the team performance (t) and team difference (d)
  # variables until they converge.  In practice this seems to happen
  # very quickly, so I just do a fixed number of iterations.
  #
  # This order of evaluation is given by the numbered arrows in Figure
  # 1 of the Herbrich paper.

	for my $i (0..4) {
		#print "\nDoing team_diff";
		foreach my $f (@team_diff) {
		  $f->UpdateSum();             # arrows (1) and (4)
		}
		#print "\nDoing trunc";
		foreach my $f (@trunc) {
		  $f->Update();                # arrows (2) and (5)
		}
		foreach my $f (@team_diff) {
		  $f->UpdateTerm(0);           # arrows (3) and (6)
		  $f->UpdateTerm(1);
		}
	}

  # Now we push messages back up the graph, from the teams back to the
  # player skills.

	foreach my $f (@perf_to_team) {
		$f->UpdateTerm(0);
	}
	foreach my $f (@skill_to_perf) {
		$f->UpdateMean();
	}

  # Finally, the players' new skills are the new values of the s
  # variables.

  for my $i (0..scalar(@ss)-1) {
	my @details = $ss[$i]->{value}->MuSigma();
	$players[$i]->{skill} = \@details;
  }
}

sub DrawProbability
{
  # """ Compute the draw probability given the draw margin (epsilon). """

  my ($epsilon, $beta, $total_players) = @_;
  $total_players = 2 if !defined $total_players;

  return 2 * Math::Cephes::ndtr($epsilon / (sqrt($total_players) * $beta)) - 1;
}

sub DrawMargin
{
  # """ Compute the draw margin (epsilon) given the draw probability. """
  my ($p, $beta, $total_players) = @_;
  $total_players = 2 if !defined $total_players;

  return Math::Cephes::ndtri(($p+1.0)/2) * sqrt($total_players) * $beta;
}


text:
Test phpinfo() displays hs info
--SKIPIF--
--FILE--
<?php
if (!extension_loaded('hs')) {
    dl('hs.' . PHP_SHLIB_SUFFIX);
}

phpinfo();
--EXPECTF--
%a
hs

heatshrink support => enabled
Extension Version => %d.%d.%d
%a


text:
using System.Diagnostics;
using System.ServiceModel.Diagnostics;

namespace System.ServiceModel.Channels
{
    public abstract class ChannelBase : CommunicationObject, IChannel, IDefaultCommunicationTimeouts
    {
        private ChannelManagerBase _channelManager;

        protected ChannelBase(ChannelManagerBase channelManager)
        {
            if (channelManager == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelManager");
            }

            _channelManager = channelManager;
        }

        TimeSpan IDefaultCommunicationTimeouts.CloseTimeout
        {
            get { return this.DefaultCloseTimeout; }
        }

        TimeSpan IDefaultCommunicationTimeouts.OpenTimeout
        {
            get { return this.DefaultOpenTimeout; }
        }

        TimeSpan IDefaultCommunicationTimeouts.ReceiveTimeout
        {
            get { return this.DefaultReceiveTimeout; }
        }

        TimeSpan IDefaultCommunicationTimeouts.SendTimeout
        {
            get { return this.DefaultSendTimeout; }
        }

        protected override TimeSpan DefaultCloseTimeout
        {
            get { return ((IDefaultCommunicationTimeouts)_channelManager).CloseTimeout; }
        }

        protected override TimeSpan DefaultOpenTimeout
        {
            get { return ((IDefaultCommunicationTimeouts)_channelManager).OpenTimeout; }
        }

        protected TimeSpan DefaultReceiveTimeout
        {
            get { return ((IDefaultCommunicationTimeouts)_channelManager).ReceiveTimeout; }
        }

        protected TimeSpan DefaultSendTimeout
        {
            get { return ((IDefaultCommunicationTimeouts)_channelManager).SendTimeout; }
        }

        protected ChannelManagerBase Manager
        {
            get
            {
                return _channelManager;
            }
        }

        public virtual T GetProperty<T>() where T : class
        {
            IChannelFactory factory = _channelManager as IChannelFactory;
            if (factory != null)
            {
                return factory.GetProperty<T>();
            }

            IChannelListener listener = _channelManager as IChannelListener;
            if (listener != null)
            {
                return listener.GetProperty<T>();
            }

            return null;
        }

        protected override void OnClosed()
        {
            base.OnClosed();
        }
    }
}


text:
#include "Interprt.h"
/*
============
Interprt.cpp
============
Implementation of Smalltalk interpreter
*/

#include "Ist.h"
#include "rc_vm.h"

#ifndef _DEBUG
	//#pragma optimize("s", on)
#pragma auto_inline(off)
#endif

#pragma code_seg(INTERPMISC_SEG)

#include "Interprt.h"
#include "InterprtProc.inl"
#include "thrdcall.h"
#include "VMExcept.h"
#include "regkey.h"
#include "VirtualMemoryStats.h"

// Smalltalk classes
#include "STProcess.h"
#include "STArray.h"
#include "STString.h"
#include "STContext.h"
#include "STMethod.h"			// To determine if in primitive when fault occurs
#include "STByteArray.h"
#include "STBlockClosure.h"

#ifdef _DEBUG
	// Execution trace
BOOL Interpreter::executionTrace = 0;
static size_t nTotalBlocksAllocated = 0;
#endif
#define VMWNDCLASS L"_VMWnd"

InterpreterRegisters16 Interpreter::m_registers = { 0, 0, 0, 0, 0, 0, 0, 0 };

SymbolOTE* Interpreter::m_oopMessageSelector = nullptr;
BOOL Interpreter::m_bStepping = FALSE;

// The only Oops ref'd by the Interpreter which are not stored in the global pointers registry (VMPointers)
ProcessOTE* Interpreter::m_oteNewProcess;

// Input Polling is initially off (negative interval) so that it doesn't interfere if not wanted
SHAREDLONG Interpreter::m_nInputPollCounter;	// When this goes to zero, its time to poll for input
LONG Interpreter::m_nInputPollInterval;		// Poll counter reset to this after each message queue poll

SHAREDLONG Interpreter::m_bAsyncPending = FALSE;
SHAREDLONG Interpreter::m_nAPCsPending = 0;

SHAREDLONG* Interpreter::m_pbAsyncPending = &m_bAsyncPending;
SHAREDLONG Interpreter::m_bAsyncPendingIOff = FALSE;

// Context related registers
ProcessorScheduler* Interpreter::m_pProcessor;

// Number of failed callback exits which have occurred since last successful callback
// These get signalled when a successful callback occurs to try again
size_t Interpreter::m_nCallbacksPending;

size_t Interpreter::m_nOTOverflows;

// Pools of reusable objects (just linked list of previously allocated and free'd objects of
// correct size and class)
ObjectMemory::OTEPool Interpreter::m_otePools[NumOtePools];

POTE* Interpreter::m_roots[] = {
	reinterpret_cast<POTE*>(&m_oteNewProcess),
	0
};

DWORD Interpreter::m_dwThreadId;
HANDLE Interpreter::m_hThread;

bool Interpreter::m_bInterruptsDisabled;
bool Interpreter::m_bAsyncGCDisabled;
bool Interpreter::m_bShutDown;

ATOM Interpreter::m_atomVMWndClass;
HWND Interpreter::m_hWndVM;

DWORD Interpreter::m_dwQueueStatusMask;

unsigned Interpreter::m_numberOfProcessors;

__declspec(align(16))
Interpreter::MethodCacheEntry Interpreter::methodCache[MethodCacheSize];

//==========
//Initialise
//==========
#ifndef _DEBUG
#pragma optimize("s", on)
#pragma auto_inline(off)
#endif

#pragma code_seg(INIT_SEG)
HRESULT Interpreter::initialize(const wchar_t* szFileName, LPVOID imageData, size_t imageSize, bool isDevSys)
{
	HRESULT hr = initializeBeforeLoad();
	if (FAILED(hr))
		return hr;

	// Load in the basic image. We do this here to avoid allocating memory
	// in the static constructor of the ObjectMemory class.
	//

#ifdef OAD
	DWORD timeStart = timeGetTime();
#endif
	hr = ObjectMemory::LoadImage(szFileName, imageData, imageSize, isDevSys);
	if (FAILED(hr))
		return hr;
#ifdef OAD
	DWORD timeEnd = timeGetTime();
	TRACESTREAM<< L"Time to load image: " << (timeEnd - timeStart)<< L" mS" << std::endl;
#endif

	ObjectMemory::HeapCompact();
	return initializeAfterLoad();
}

#pragma code_seg(INIT_SEG)
HRESULT Interpreter::initializeBeforeLoad()
{
	m_bShutDown = m_bInterruptsDisabled = m_bAsyncGCDisabled = m_bStepping = false;
	m_nOTOverflows = 0;

	InitializeCriticalSection(&m_csAsyncProtect);
	m_dwThreadId = ::GetCurrentThreadId();
	HANDLE hProc = GetCurrentProcess();
	VERIFY(::DuplicateHandle(hProc, GetCurrentThread(), hProc, &m_hThread, 0, FALSE, DUPLICATE_SAME_ACCESS));

	// We know that the static_partitioner returns the same number of chunks as there are logical cores
	m_numberOfProcessors = concurrency::static_partitioner()._Get_num_chunks(0);

	WNDCLASSW wndClass;
	wndClass.style = 0;
	wndClass.lpfnWndProc = VMWndProc;
	wndClass.cbClsExtra = 0;
	wndClass.cbWndExtra = 0;
	wndClass.hInstance = GetModuleContaining(VMWndProc);
	wndClass.hIcon = NULL;
	wndClass.hCursor = NULL;
	wndClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
	wndClass.lpszMenuName = NULL;
	wndClass.lpszClassName = VMWNDCLASS;
	m_atomVMWndClass = RegisterClass(&wndClass);

	m_hWndVM = CreateWindowW(VMWNDCLASS, L"", WS_CHILD, 0, 0, 0, 0, HWND_MESSAGE, NULL, wndClass.hInstance, NULL);
	if (m_hWndVM == NULL)	// early OSs did not support message-only windows
	{
		m_hWndVM = CreateWindowW(VMWNDCLASS, L"", 0, 0, 0, 0, 0, NULL, NULL, wndClass.hInstance, NULL);
	}
	if (m_hWndVM == NULL)
	{
		return ReportWin32Error(IDP_FAILTOCREATEVMWND, ::GetLastError());
	}

	// Use the same logic as is present in the image to determine the correct status flags for the platform
	m_dwQueueStatusMask =
		(IsWindows8OrGreater()
			? QS_MOUSE | QS_KEY | QS_RAWINPUT | QS_TOUCH | QS_POINTER
			: IsWindowsXPOrGreater()
				? QS_MOUSE | QS_KEY | QS_RAWINPUT
				: QS_MOUSE | QS_KEY)
		| (QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE);

	initializeCharMaps();

	OverlappedCall::Initialize();

	// ObjectMemory is an entirely static class, so to avoid an instance
	return ObjectMemory::Initialize();
}

HRESULT Interpreter::initializeAfterLoad()
{
	// This must now be done after load so Pointers.Nil available
	HRESULT hr = initializeTimer();
	if (FAILED(hr))
		return hr;

	m_oteNewProcess = reinterpret_cast<ProcessOTE*>(Pointers.Nil);

	hr = ObjectMemory::InitializeImage();
	if (FAILED(hr))
		return hr;

	initializeVMReferences();

#if defined(_DEBUG)
	ObjectMemory::checkReferences();	// If this fails, the saved image has a ref. count problem
#endif

	initializeCaches();

	m_registers.m_pActiveFrame = firstFrame();
	m_registers.FetchContextRegisters();

#ifdef _DEBUG
	TRACESTREAM<< L"Startup process: " << actualActiveProcessPointer() << std::endl;
#endif

	// Populate the ZCT with zero count objects in the startup process' stack
	ObjectMemory::PopulateZct(m_registers.m_stackPointer);

	// Set the callback pending count correctly to take account of any processes that were waiting
	// on the pendingReturns Semaphore when the image was saved.
	m_nCallbacksPending = countPendingCallbacks();

	hr = InitializeSampler();
	if (FAILED(hr))
		return hr;

	// Initialize the image. This must be performed after the above
	// creation of the active context.

	::SetLastError(0);

	return initializeImage();
}

HRESULT Interpreter::initializeCharMaps()
{
	char byteCharSet[256];
	for (auto i = 0u; i < 256; i++)
		byteCharSet[i] = static_cast<char>(i);

	CPINFOEX cpInfo;
	::GetCPInfoExW(::GetACP(), 0, &cpInfo);

	// First check some assumptions about the code page
	// 1. We expect code page to have a maximum character size of 1.
	// 2. Empirical evidence is that none of the standard code pages will map any of the ansi code units to more
	// than one UTF16 code unit.
	// If either assumption is not true, the implementation will not work correctly, so we switch to Windows 1252
	if (cpInfo.MaxCharSize != 1 || ::MultiByteToWideChar(cpInfo.CodePage, 0, byteCharSet, 256, nullptr, 0) > 256)
	{
		trace(IDP_UNSUPPORTED_ACP, cpInfo.CodePage);
		::GetCPInfoExW(1252, 0, &cpInfo);
	}

	m_ansiCodePage = cpInfo.CodePage;
	m_ansiReplacementChar = cpInfo.DefaultChar[0];

	::GetCPInfoExW(CP_UTF8, 0, &cpInfo);
	m_unicodeReplacementChar = cpInfo.UnicodeDefaultChar;

	// Map the ansi code units to unicode code points using the current code page.
	::MultiByteToWideChar(m_ansiCodePage, MB_PRECOMPOSED, byteCharSet, 256, m_ansiToUnicodeCharMap, 256);

	// Create the reverse map - it will be very sparse, but as it only consumes 64Kb it isn't worth using a hash table
	memset(m_unicodeToAnsiCharMap, 0, sizeof(m_unicodeToAnsiCharMap));
	WCHAR* wideChars = reinterpret_cast<WCHAR*>(_malloca(65536*sizeof(WCHAR)));
	if (wideChars == nullptr)
	{
		return E_OUTOFMEMORY;
	}

	auto i = 0u;
	for (; i < 0xd800; i++)
		wideChars[i] = static_cast<WCHAR>(i);
	for (; i <= 0xdfff; i++)
		wideChars[i] = 0;
	for (; i <= 0xffff; i++)
		wideChars[i] = static_cast<WCHAR>(i);

	VERIFY(::WideCharToMultiByte(m_ansiCodePage, WC_NO_BEST_FIT_CHARS, wideChars, 65536, m_unicodeToAnsiCharMap, 65536, "\0", nullptr) == 65536);
	_freea(wideChars);

	return S_OK;
}

#pragma code_seg(TERM_SEG)
void Interpreter::ShutDown()
{
	_ASSERTE(!m_bShutDown);
	m_bShutDown = true;
	// Nulling out the handle means that any further attempts to queue APCs, etc, will fail
	HANDLE hThread = LPVOID(InterlockedExchange(reinterpret_cast<SHAREDLONG*>(&m_hThread), 0));

	TerminateSampler();

	GuiShutdown();

	if (m_hWndVM)
	{
		DestroyWindow(m_hWndVM);
		m_hWndVM = NULL;
	}
	if (m_atomVMWndClass)
	{
		UnregisterClass(VMWNDCLASS, GetModuleContaining(initializeBeforeLoad));
		m_atomVMWndClass = NULL;
	}

	terminateTimer();
	OverlappedCall::Uninitialize();

	// Close the duplicated main thread handle
	::CloseHandle(hThread);
	::DeleteCriticalSection(&m_csAsyncProtect);

	ObjectMemory::Terminate();
}

#pragma code_seg(INIT_SEG)
inline void Interpreter::initializeCaches()
{
	// If either of these two assertions fails, update the method cache size
	// in ISTASM.INC (METHODCACHEDWORDS), change the constants, and rebuild
	// You may also need to change the cache hashing/lookup code
	ASSERT(sizeof(OTE) == 16);
	ASSERT(sizeof(MethodCacheEntry) == sizeof(OTE));
	// Bottom 4 bits of the addresses of method cache entries must be zero
	ASSERT((reinterpret_cast<uintptr_t>(methodCache) & 0xF) == 0);

	flushCaches();
}

#ifdef NDEBUG
#pragma auto_inline(on)
#endif

///////////////////////////////////

#ifdef _DEBUG
#pragma code_seg(DEBUG_SEG)

static size_t ResizeProcInContext(InterpreterRegisters& reg)
{
	ProcessOTE* oteProc = reg.m_oteActiveProcess;
	size_t size = oteProc->getSize();
	reg.ResizeProcess();
	if (size != oteProc->getSize() && Interpreter::executionTrace)
	{
		tracelock lock(TRACESTREAM);
		TRACESTREAM<< L"Check Refs: Resized proc " << oteProc<< L" from "
			<< std::dec << size<< L" to " << oteProc->getSize() << std::endl;
	}
	return size;
}

void Interpreter::checkReferences(Oop* const sp)
{
	m_registers.m_stackPointer = sp;
	checkReferences(GetRegisters());
}

// Check references without upsetting the current active process size (otherwise
// this may mask bugs in the release version)
void Interpreter::checkReferences(InterpreterRegisters& reg)
{
	HARDASSERT(ObjectMemory::isKindOf(m_registers.m_oteActiveProcess, Pointers.ClassProcess));
	size_t oldProcSize = ResizeProcInContext(reg);
	if (reg.m_pActiveProcess != m_registers.m_pActiveProcess)
	{
		// Resize active process as well as the one in the context passed
		size_t oldActiveProcSize = ResizeProcInContext(m_registers);
		ObjectMemory::checkReferences();
		m_registers.m_oteActiveProcess->setSize(oldActiveProcSize);
	}
	else
		ObjectMemory::checkReferences();
	reg.m_oteActiveProcess->setSize(oldProcSize);
}
#endif

///////////////////////////////////////////////////////////////////////////////
// Terminate Smalltalk

#pragma code_seg(TERM_SEG)

void Interpreter::exitSmalltalk(int exitCode)
{
#ifdef _DEBUG
	{
		extern void DumpPrimitiveCounts(bool);
		extern void DumpBytecodeCounts(bool);

		DumpPrimitiveCounts(false);
		DumpBytecodeCounts(false);
	}
#endif

	DolphinExit(exitCode);
}

///////////////////////////////////////////////////////////////////////////////
// Main Interpreter entry point. Handles OTE overflows and Stack overflows,
// looping through GP/FP faults in primitives too.

#pragma code_seg(INTERP_SEG)

void Interpreter::interpret()
{
#pragma warning(push)
#pragma warning(disable:4127)
	while (true)
#pragma warning(pop)
	{
		// Using Win32 structured exception handling here NOT C++
		DWORD exceptionCode;
		__try
		{
			_asm jmp byteCodeLoop
		}
		// I'd like to just test for IS_ERROR() here, but due to some macro nastiness
		// it GPFs in a release build
		__except ((exceptionCode = GetExceptionCode()) > static_cast<DWORD>(VMExceptions::CallbackUnwind)
			? interpreterExceptionFilter(GetExceptionInformation())
			: EXCEPTION_CONTINUE_SEARCH)
		{
			TRACE(L"interpret: Looping after exception %#x\n\r", exceptionCode);
		}
	}
	// We don't tend to get here as callback returns go to the enclosing exception handler
	ASSERT(FALSE);
}

//////////////////////////////////////////////////////////////////////////////////
// Save IP/SP down after a fault occurs
//
// Faults may either occur outside primitives, or in assembler primitives for which IP/SP
// have not been saved. IP is probably not so critical, since most faults result in unrecoverable
// errors, but if we don't save it down, then the picture in the debugger may be confusing.
// SP is critical, because if we don't save it down we are likely to get a crash attempting
// to produce the walkback. If the fault occurs in a primitive, then SP will already have been
// saved.
// Attempts to saved down IP/SP from CPP primitives will not often be helpful
// as these often use EDI/ESI, but I rarely use it in the assembler
// prims, so it should have the correct value in the context record
//
// CPP prims should save down IP if there is any possibility of them generating
// a trappable fault
//
#pragma code_seg(INTERPMISC_SEG)
bool Interpreter::saveContextAfterFault(const LPEXCEPTION_POINTERS info)
{
	uint8_t* ip = reinterpret_cast<uint8_t*>(info->ContextRecord->Edi);
	Oop byteCodes = m_registers.m_pMethod->m_byteCodes;
	uint8_t* pBytes = ObjectMemory::ByteAddressOfObjectContents(byteCodes);
	size_t numByteCodes = ObjectMemoryIsIntegerObject(byteCodes) ?
		sizeof(Oop) : reinterpret_cast<BytesOTE*>(byteCodes)->bytesSize();
	if (ip >= pBytes && ip < pBytes + numByteCodes)
	{
		m_registers.m_instructionPointer = ip;
	}
	// SP is saved down before primitives are executed, and we don't want to rely on primitive not
	// updating the SP register until there is no possibility of a fault
	bool inPrim = isInPrimitive(info);
	if (!inPrim)
	{
		Oop* sp = reinterpret_cast<Oop*>(info->ContextRecord->Esi);
		Process* pProc = actualActiveProcess();
		if (sp > reinterpret_cast<Oop*>(pProc))
		{
			VirtualObject* pVObj = reinterpret_cast<VirtualObject*>(pProc);
			VirtualObjectHeader* pBase = pVObj->getHeader();
			size_t cbCurrent = pBase->getCurrentAllocation();
			if (sp < reinterpret_cast<Oop*>(reinterpret_cast<uint8_t*>(pBase) + cbCurrent))
				m_registers.m_stackPointer = sp;
		}
	}
	return inPrim;
}

#pragma code_seg(INTERPMISC_SEG)
// Answer whether the interpreter is currently executing a primitive. We determine this
// by testing to see whether the new method is not the same as the active method (primitives
// do not activate until they fail). We must also ensure that the oop is still a method
//
bool Interpreter::isInPrimitive(const LPEXCEPTION_POINTERS pExInfo)
{
	uintptr_t eip = pExInfo->ContextRecord->Eip;
	return eip < reinterpret_cast<uintptr_t>(byteCodeLoop) || eip > reinterpret_cast<uintptr_t>(invalidByteCode);
}

void Interpreter::AbandonStepping()
{
	m_bStepping = false;						// We do not want to break now
	ResetInputPollCounter();
}

void Interpreter::recoverFromFault(const LPEXCEPTION_POINTERS pExInfo)
{
	AbandonStepping();
	bool inPrim = saveContextAfterFault(pExInfo);
	if (inPrim)
	{
		DWORD exceptionCode = pExInfo->ExceptionRecord->ExceptionCode;
		activatePrimitiveMethod(m_registers.m_oopNewMethod->m_location, static_cast<_PrimitiveFailureCode>(PFC_FROM_NT(exceptionCode)));
	}
}

void Interpreter::sendExceptionInterrupt(VMInterrupts oopInterrupt, const LPEXCEPTION_POINTERS pExInfo)
{
	recoverFromFault(pExInfo);
#ifdef _DEBUG
	{
		tracelock lock(TRACESTREAM);
		TRACESTREAM << std::hex << pExInfo->ExceptionRecord->ExceptionCode<< L" exception trapped in " << *m_registers.m_pMethod << std::endl;
	}
#endif
	sendVMInterrupt(oopInterrupt, reinterpret_cast<Oop>(ByteArray::NewWithRef(sizeof(EXCEPTION_RECORD), pExInfo->ExceptionRecord)));
}

static BOOL WantGPFTrap()
{
	CRegKey rk;
	return OpenDolphinKey(rk, L"DisableGPFTrap") != ERROR_SUCCESS;
}

static BOOL PleaseTrapGPFs()
{
	static BOOL TrapEm = -1;
	if (TrapEm == -1)
		TrapEm = WantGPFTrap();
	return TrapEm;
}

#pragma code_seg(INTERPMISC_SEG)
// Exception filter to handle continuable win32 exceptions for the interpreter, may return
// EXCEPTION_EXECUTE_HANDLER, in which case the interpreter loops - this is how GP faults
// and FP faults in primitives are handled.
int Interpreter::interpreterExceptionFilter(const LPEXCEPTION_POINTERS pExInfo)
{
	EXCEPTION_RECORD* pExRec = pExInfo->ExceptionRecord;
	if (pExRec->ExceptionFlags == EXCEPTION_NONCONTINUABLE)
		return EXCEPTION_CONTINUE_SEARCH;

	DWORD exceptionCode = pExRec->ExceptionCode;

	// Non-errors are supposed to have been filtered out before we get here
	// if they haven't it won't be a disaster, but it won't be as efficient
	// as it might be, as we'll end up doing a lot of work for the VM
	// callback exits.
	ASSERT(exceptionCode > static_cast<DWORD>(VMExceptions::CallbackUnwind));

	int action = EXCEPTION_CONTINUE_SEARCH;
	switch (exceptionCode)
	{
	case EXCEPTION_ACCESS_VIOLATION:
#if !defined(NO_GPF_TRAP)
		action = memoryExceptionFilter(pExInfo);

		if (action == EXCEPTION_CONTINUE_SEARCH)
		{
			void* pExceptionAddr = reinterpret_cast<void*>(pExRec->ExceptionInformation[1]);
			bool bConstWrite = pExRec->ExceptionInformation[0] != 0 &&
				ObjectMemory::IsConstObj(pExceptionAddr);

			if (bConstWrite)
			{
				sendExceptionInterrupt(VMInterrupts::ConstWrite, pExInfo);
				action = EXCEPTION_EXECUTE_HANDLER;
			}
			else if (isInPrimitive(pExInfo) && PleaseTrapGPFs())
			{
				sendExceptionInterrupt(VMInterrupts::AccessViolation, pExInfo);
				action = EXCEPTION_EXECUTE_HANDLER;
			}
			// else
			//		continue search for next handler, if any
		}
#endif
		break;

	case STATUS_NO_MEMORY:
		action = OutOfMemory(pExInfo);
		break;

	case EXCEPTION_INT_DIVIDE_BY_ZERO:
	{
		bool inPrim = saveContextAfterFault(pExInfo);
		if (inPrim)
		{
			activatePrimitiveMethod(m_registers.m_oopNewMethod->m_location, _PrimitiveFailureCode::IntegerDivideByZero);
		}
#ifdef _DEBUG
		{
			tracelock lock(TRACESTREAM);
			TRACESTREAM<< L"Divide by zero in " << *m_registers.m_pMethod << std::endl;
		}
#endif
		sendZeroDivideInterrupt(pExInfo);
		action = EXCEPTION_EXECUTE_HANDLER;
	}
	break;

	case EXCEPTION_FLT_STACK_CHECK:
		if (PleaseTrapGPFs())
		{
			_asm fninit;
			sendExceptionInterrupt(VMInterrupts::FpStack, pExInfo);
			action = EXCEPTION_EXECUTE_HANDLER;
		}
		break;

	case EXCEPTION_INT_OVERFLOW:
	case EXCEPTION_PRIV_INSTRUCTION:
	case EXCEPTION_ILLEGAL_INSTRUCTION:
		if (isInPrimitive(pExInfo) && PleaseTrapGPFs())
		{
			sendExceptionInterrupt(VMInterrupts::Exception, pExInfo);
#ifdef _DEBUG
			{
				tracelock lock(TRACESTREAM);
				TRACESTREAM<< L"Unhandled exception " << exceptionCode<< L" in " << *m_registers.m_pMethod << std::endl;
			}
#endif
			action = EXCEPTION_EXECUTE_HANDLER;
		}
		break;

	case static_cast<DWORD>(VMExceptions::CrtFault):
		if (isInPrimitive(pExInfo))
		{
			sendExceptionInterrupt(VMInterrupts::CrtFault, pExInfo);
			action = EXCEPTION_EXECUTE_HANDLER;
		}
		break;

	case static_cast<DWORD>(VMExceptions::DumpStatus):
		CrashDump(pExInfo, achImagePath);
		return EXCEPTION_CONTINUE_EXECUTION;

	case static_cast<DWORD>(VMExceptions::Exit):
		break;

	case EXCEPTION_FLT_DENORMAL_OPERAND:
	case EXCEPTION_FLT_DIVIDE_BY_ZERO:
	case EXCEPTION_FLT_INEXACT_RESULT:
	case EXCEPTION_FLT_INVALID_OPERATION:
	case EXCEPTION_FLT_OVERFLOW:
	case EXCEPTION_FLT_UNDERFLOW:
	case STATUS_FLOAT_MULTIPLE_FAULTS:
	case STATUS_FLOAT_MULTIPLE_TRAPS:
		actualActiveProcess()->ResetFP();
		AbandonStepping();
		if (saveContextAfterFault(pExInfo))
		{
			activatePrimitiveMethod(m_registers.m_oopNewMethod->m_location, static_cast<_PrimitiveFailureCode>(PFC_FROM_NT(exceptionCode)));
		}
		action = _fpieee_flt(exceptionCode, pExInfo, IEEEFPHandler);
		break;
	}

	return action;
}

void Interpreter::sendZeroDivideInterrupt(const LPEXCEPTION_POINTERS pExInfo)
{
	sendVMInterrupt(VMInterrupts::ZeroDivide, Integer::NewSigned32WithRef(pExInfo->ContextRecord->Eax));
}

int Interpreter::OutOfMemory(const LPEXCEPTION_POINTERS pExInfo)
{
	VirtualMemoryStats memStats;
	if (memStats.VirtualMemoryFree < ObjectMemory::MinimumVirtualMemoryAvailable)
	{
		FatalSystemException(pExInfo);
		// Won't return to here
	}

	sendExceptionInterrupt(VMInterrupts::NoMemory, pExInfo);
	return EXCEPTION_EXECUTE_HANDLER;
}

int __cdecl Interpreter::IEEEFPHandler(_FPIEEE_RECORD *pIEEEFPException)
{
#ifdef _DEBUG
	{
		tracelock lock(TRACESTREAM);
		TRACESTREAM<< L"FP Fault in " << *m_registers.m_pMethod << std::endl;
	}
#endif
	sendVMInterrupt(VMInterrupts::FpFault, reinterpret_cast<Oop>(ByteArray::NewWithRef(sizeof(_FPIEEE_RECORD), pIEEEFPException)));
	return EXCEPTION_EXECUTE_HANDLER;
}

#if !defined(NO_GPF_TRAP)

#pragma code_seg(INTERPMISC_SEG)
// Exception filter to handle continuable win32 exceptions caused by object table/process
// stack overflows
int Interpreter::memoryExceptionFilter(const LPEXCEPTION_POINTERS pExInfo)
{
	LPEXCEPTION_RECORD pExRec = pExInfo->ExceptionRecord;

	// This "filter" is only designed to handle GPFs
	ASSERT(pExRec->ExceptionCode == EXCEPTION_ACCESS_VIOLATION);

	int action = EXCEPTION_CONTINUE_SEARCH;

	// Determine if the fault is a stack overflow, and if so try
	// growing the stack. If the stack has reached max. size, then
	// pass control to the exception handler
	ULONG_PTR address = pExRec->ExceptionInformation[1];

	VirtualObjectHeader* pBase = actualActiveProcess()->getHeader();
	uintptr_t activeProcAlloc = pBase->getCurrentAllocation();
	uintptr_t dwNext = reinterpret_cast<uintptr_t>(pBase) + activeProcAlloc;

#ifdef OAD
	{
		tracelock lock(TRACESTREAM);
		TRACESTREAM<< L"Access violation: " << reinterpret_cast<LPVOID>(address)<< L", stack top " << reinterpret_cast<LPVOID>(dwNext) << std::endl;
	}
#endif

	if (address >= dwNext && address <= dwNext + sizeof(StackFrame))
	{
#ifdef OAD
		{
			tracelock lock(TRACESTREAM);
			TRACESTREAM<< L"Stack overflow detected" << std::endl;
		}
#endif

		if (::VirtualAlloc(LPVOID(dwNext), dwPageSize, MEM_COMMIT, PAGE_READWRITE))
		{
			// Note that the max allocation is actually one page greater since we adjust
			// the reserved space to accomodate an overrun page for detection
			if (activeProcAlloc >= pBase->getMaxAllocation())
			{
				TRACESTREAM<< L"Stack max'd out at " << std::hex << activeProcAlloc << std::endl;
				// Even though stack has hit max. we can still continue (to handle the error)
				// We'll just add an interrupt to the queue, which'll be detected later.
				// In order for this to continue to work, the stack must be shrunk at some
				// point after the stack overflow is handled
				queueInterrupt(VMInterrupts::StackOverflow, ObjectMemoryIntegerObjectOf(activeProcAlloc));
			}
			else
			{
				TRACE(L"Stack successfully grown to %u\n\r", pBase->getCurrentAllocation());
			}

			// Whether the stack has max'd out or not, we're going to continue executing
			// and detect the overflow interrupt synchronously (if it was signalled).
			// This avoids any synchronisation issues, and means that in general, we
			// don't have to code defensively where exceptions might be raised.
			action = EXCEPTION_CONTINUE_EXECUTION;

#ifdef _DEBUG
			// Let's see whether we got the rounding correct!
			MEMORY_BASIC_INFORMATION mbi;
			Process* pActive = m_registers.m_pActiveProcess;
			VERIFY(::VirtualQuery(pActive, &mbi, sizeof(mbi)) == sizeof(mbi));
			ASSERT(mbi.AllocationBase == pActive->getHeader());
			ASSERT(mbi.BaseAddress == mbi.AllocationBase);
			ASSERT(mbi.AllocationProtect == PAGE_NOACCESS);
			ASSERT(mbi.Protect == PAGE_READWRITE);
			ASSERT(mbi.RegionSize == pBase->getCurrentAllocation());
			ASSERT(mbi.State == MEM_COMMIT);
			ASSERT(mbi.Type == MEM_PRIVATE);
#endif
		}
		else
		{
			// A crash will soon result, and there's nowt we can do but to terminate
			RaiseFatalError(IDP_STACKOVERFLOW, 4, actualActiveProcessPointer()->getWordSize(), dwNext, address, activeProcAlloc);
		}
	}
	else
	{
		// The ObjectMemory may be able to handle it
		action = ObjectMemory::gpFaultExceptionFilter(pExInfo);
	}

	return action;
}

#endif


text:
layout: post
title: Switzerland photos
comments: true
share: true
chart: true
tags: "travel photography switzerland"
published: true
mathjax: false
categories:
  - travel
---

![Swiss Alps]({{site.baseurl}}/img/post/10262232036_495e77c443_z.jpg)

I'm pretty underwhelmed with many of the [pictures I took from Switzerland](https://www.flickr.com/photos/jtvanlew/sets/72157636528671866/), but they're up on flickr. This one *almost* faithfully recreates the majesty of the Alps. This was taken on top of Rothorn, near Brienz.

I think the major issue I have with all my pictures is simply that its very, very hard for an image to represent how awesome the views are. How can a picture of a snow-capped peak give the feeling of the cool air, warm sun, and cold Swiss beer that you're absorbing at the same time? Well, I'm sure someone more talented than me can do it. As it is, I have these imposters that will just have to stand in for now.

I've uploaded them all to flickr but did none of the color processing that I normally need to do. So they'll all seem grey and flat, but they're up.


text:
Mender Integration testing
===================

####Requirements
Python 2.7, requests, pytest, fabric, docker, docker-compose

Install all Python requirements by running:  `pip2.7 install -r requirements.txt`

Running tests is straight forward, just execute `bash run.sh`

`run.sh` is simple wrapper that  grabs the latest test images, artifacts tools, and other test requirements. It also calls `py.test` with `--runfast` and `--runslow`, which runs all fast and slow tests.

####OS X

Currently, running integration tests on OS X is not straight forward due to:
https://github.com/docker/docker/issues/22753

####Known issues

Since we attempting to SSH into the virtual mender device, before the OS is up and running, you may see errors such as:

`Fatal error: Needed to prompt for a connection or sudo password (host: 172.18.0.6:8822), but abort-on-prompts was set to True Aborting.`

These can simply be ignored.


text:
namespace Stripe.Issuing
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class CardholderCreateOptions : BaseOptions, IHasMetadata
    {
        ///
        /// The cardholder's billing address.
        ///
        [JsonProperty("billing")]
        public CardholderBillingOptions Billing { get; set; }

        ///
        /// Additional information about a <c>company</c> cardholder.
        ///
        [JsonProperty("company")]
        public CardholderCompanyOptions Company { get; set; }

        ///
        /// The cardholder's email address.
        ///
        [JsonProperty("email")]
        public string Email { get; set; }

        ///
        /// Additional information about an <c>individual</c> cardholder.
        ///
        [JsonProperty("individual")]
        public CardholderIndividualOptions Individual { get; set; }

        ///
        /// Set of key-value pairs that you can
        /// attach to an object. This can be useful for storing additional information about the
        /// object in a structured format. Individual keys can be unset by posting an empty value to
        /// them. All keys can be unset by posting an empty value to <c>metadata</c>.
        ///
        [JsonProperty("metadata")]
        public Dictionary<string, string> Metadata { get; set; }

        ///
        /// The cardholder's name. This will be printed on cards issued to them. The maximum length
        /// of this field is 24 characters. This field cannot contain any special characters or
        /// numbers.
        ///
        [JsonProperty("name")]
        public string Name { get; set; }

        ///
        /// The cardholder's phone number. This will be transformed to E.164 if it is not provided in that
        /// format already. This is required for all cardholders who will be creating EU cards. See
        /// the 3D
        /// Secure documentation for more details.
        ///
        [JsonProperty("phone_number")]
        public string PhoneNumber { get; set; }

        ///
        /// Rules that control spending across this cardholder's cards. Refer to our documentation for
        /// more details.
        ///
        [JsonProperty("spending_controls")]
        public CardholderSpendingControlsOptions SpendingControls { get; set; }

        ///
        /// Specifies whether to permit authorizations on this cardholder's cards. Defaults to
        /// <c>active</c>.
        /// One of: <c>active</c>, or <c>inactive</c>.
        ///
        [JsonProperty("status")]
        public string Status { get; set; }

        ///
        /// One of <c>individual</c> or <c>company</c>.
        /// One of: <c>company</c>, or <c>individual</c>.
        ///
        [JsonProperty("type")]
        public string Type { get; set; }
    }
}


text:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { TimeLeft } from './TimeLeft';

it("does not render the time left if the status does not demand action", () => {
    render(<TimeLeft metric={{ status: "target_met" }} report={{}} />)
    expect(screen.queryAllByText(/day/).length).toBe(0)
})

it("does not render the time left if there is no status start date", () => {
    render(<TimeLeft metric={{ status: "target_not_met" }} report={{}} />)
    expect(screen.queryAllByText(/day/).length).toBe(0)
})

it("does render the time left if technical debt is accepted with an end date", () => {
    render(<TimeLeft metric={{ status: "debt_target_met", status_start: "2022-01-01", debt_end_date: "3000-01-01" }} report={{}} />)
    expect(screen.queryAllByText(/day/).length).toBe(1)
})

it("does not render the time left if technical debt is accepted without an end date", () => {
    render(<TimeLeft metric={{ status: "debt_target_met", status_start: "2022-01-01" }} report={{}} />)
    expect(screen.queryAllByText(/day/).length).toBe(0)
})

it("renders 0 days left if the deadline is in the past", () => {
    render(<TimeLeft metric={{ status: "target_not_met", status_start: "2022-01-01" }} report={{}} />)
    expect(screen.queryAllByText(/0 days/).length).toBe(1)
})

it("renders the time left if status demands action", () => {
    const now = new Date()
    render(<TimeLeft metric={{ status: "target_not_met", status_start: now.toISOString() }} report={{}} />)
    expect(screen.queryAllByText(/days/).length).toBe(1)
})


text:
require_relative 'error_codes'

module Lobster

  # Information about something that went wrong.
  class Error

    # Integer code representing the error type.
    # @return [Fixnum] Error type as an integer.
    attr_reader :code

    # Extra information associated with the error.
    # This data can be used to create a localized error string.
    # @return [Hash{Symbol => String}] Set of keys and values containing additional information about the error.
    attr_reader :data

    # Creates a new error.
    # @param code [Fixnum] Integer code representing the error type.
    # @param data [Hash{Symbol => String}] Extra information associated with the error.
    def initialize(code, data = {})
      @code = code
      @data = data.dup.freeze
    end

    # Generates a string representation of the error.
    # @return [String]
    def to_s
      symbol = Error.get_code_symbol(code)
      str = "Error: #{symbol}"
      if data.any?
        str + " #{data}"
      else
        str
      end
    end

    # Attempts to get a symbol that represents an error code.
    # This method looks through {Lobster::ErrorCodes} for matching values.
    # @param code [Fixnum] Integer code representing the error type.
    # @return [Symbol, Fixnum] A symbol representing the error type or its integer code if a symbol couldn't be found.
    def self.get_code_symbol(code)
      Lobster::ErrorCodes.constants.find do |constant|
        Lobster::ErrorCodes.const_get(constant) == code
      end || code
    end

  end

end


text:
var log = {
    debug:logMessage, warn: logMessage, info: logMessage, error:logMessage
};

function logMessage(msg){
    document.getElementById('logMessages').innerHTML += "<li>" + msg + "</li>";
    console.log(msg);
}

Oidc.Log.logger = console; // log;
Oidc.Log.level = Oidc.Log.DEBUG;

new Oidc.UserManager().signinPopupCallback().catch(function(err){
    Oidc.Log.logger.error("error: " + err && err.message);
});


text:
{
  ("use strict");

  var EventTarget = scope.wrappers.EventTarget;
  var NodeList = scope.wrappers.NodeList;
  var TreeScope = scope.TreeScope;
  var assert = scope.assert;
  var defineWrapGetter = scope.defineWrapGetter;
  var enqueueMutation = scope.enqueueMutation;
  var getTreeScope = scope.getTreeScope;
  var isWrapper = scope.isWrapper;
  var mixin = scope.mixin;
  var registerTransientObservers = scope.registerTransientObservers;
  var registerWrapper = scope.registerWrapper;
  var setTreeScope = scope.setTreeScope;
  var unsafeUnwrap = scope.unsafeUnwrap;
  var unwrap = scope.unwrap;
  var unwrapIfNeeded = scope.unwrapIfNeeded;
  var wrap = scope.wrap;
  var wrapIfNeeded = scope.wrapIfNeeded;
  var wrappers = scope.wrappers;

  function assertIsNodeWrapper(node) {
    assert(node instanceof Node);
  }

  function createOneElementNodeList(node) {
    var nodes = new NodeList();
    nodes[0] = node;
    nodes.length = 1;
    return nodes;
  }

  var surpressMutations = false;

  function enqueueRemovalForInsertedNodes(node, parent, nodes) {
    enqueueMutation(parent, "childList", {
      removedNodes: nodes,
      previousSibling: node.previousSibling,
      nextSibling: node.nextSibling
    });
  }

  function enqueueRemovalForInsertedDocumentFragment(df, nodes) {
    enqueueMutation(df, "childList", {
      removedNodes: nodes
    });
  }

  function collectNodes(node, parentNode, previousNode, nextNode) {
    if (node instanceof DocumentFragment) {
      var nodes = collectNodesForDocumentFragment(node);
      surpressMutations = true;

      for (var i = nodes.length - 1; i >= 0; i--) {
        node.removeChild(nodes[i]);
        nodes[i].parentNode_ = parentNode;
      }

      surpressMutations = false;

      for (var i = 0; i < nodes.length; i++) {
        nodes[i].previousSibling_ = nodes[i - 1] || previousNode;
        nodes[i].nextSibling_ = nodes[i + 1] || nextNode;
      }

      if (previousNode) previousNode.nextSibling_ = nodes[0];
      if (nextNode) nextNode.previousSibling_ = nodes[nodes.length - 1];
      return nodes;
    }

    var nodes = createOneElementNodeList(node);
    var oldParent = node.parentNode;

    if (oldParent) {
      oldParent.removeChild(node);
    }

    node.parentNode_ = parentNode;
    node.previousSibling_ = previousNode;
    node.nextSibling_ = nextNode;
    if (previousNode) previousNode.nextSibling_ = node;
    if (nextNode) nextNode.previousSibling_ = node;
    return nodes;
  }

  function collectNodesNative(node) {
    if (node instanceof DocumentFragment)
      return collectNodesForDocumentFragment(node);
    var nodes = createOneElementNodeList(node);
    var oldParent = node.parentNode;
    if (oldParent) enqueueRemovalForInsertedNodes(node, oldParent, nodes);
    return nodes;
  }

  function collectNodesForDocumentFragment(node) {
    var nodes = new NodeList();
    var i = 0;

    for (var child = node.firstChild; child; child = child.nextSibling) {
      nodes[i++] = child;
    }

    nodes.length = i;
    enqueueRemovalForInsertedDocumentFragment(node, nodes);
    return nodes;
  }

  function snapshotNodeList(nodeList) {
    return nodeList;
  }

  function nodeWasAdded(node, treeScope) {
    setTreeScope(node, treeScope);
    node.nodeIsInserted_();
  }

  function nodesWereAdded(nodes, parent) {
    var treeScope = getTreeScope(parent);

    for (var i = 0; i < nodes.length; i++) {
      nodeWasAdded(nodes[i], treeScope);
    }
  }

  function nodeWasRemoved(node) {
    setTreeScope(node, new TreeScope(node, null));
  }

  function nodesWereRemoved(nodes) {
    for (var i = 0; i < nodes.length; i++) {
      nodeWasRemoved(nodes[i]);
    }
  }

  function ensureSameOwnerDocument(parent, child) {
    var ownerDoc =
      parent.nodeType === Node.DOCUMENT_NODE ? parent : parent.ownerDocument;
    if (ownerDoc !== child.ownerDocument) ownerDoc.adoptNode(child);
  }

  function adoptNodesIfNeeded(owner, nodes) {
    if (!nodes.length) return;
    var ownerDoc = owner.ownerDocument;
    if (ownerDoc === nodes[0].ownerDocument) return;

    for (var i = 0; i < nodes.length; i++) {
      scope.adoptNodeNoRemove(nodes[i], ownerDoc);
    }
  }

  function unwrapNodesForInsertion(owner, nodes) {
    adoptNodesIfNeeded(owner, nodes);
    var length = nodes.length;
    if (length === 1) return unwrap(nodes[0]);
    var df = unwrap(owner.ownerDocument.createDocumentFragment());

    for (var i = 0; i < length; i++) {
      df.appendChild(unwrap(nodes[i]));
    }

    return df;
  }

  function clearChildNodes(wrapper) {
    if (wrapper.firstChild_ !== undefined) {
      var child = wrapper.firstChild_;

      while (child) {
        var tmp = child;
        child = child.nextSibling_;
        tmp.parentNode_ = tmp.previousSibling_ = tmp.nextSibling_ = undefined;
      }
    }

    wrapper.firstChild_ = wrapper.lastChild_ = undefined;
  }

  function removeAllChildNodes(wrapper) {
    if (wrapper.invalidateShadowRenderer()) {
      var childWrapper = wrapper.firstChild;

      while (childWrapper) {
        assert(childWrapper.parentNode === wrapper);
        var nextSibling = childWrapper.nextSibling;
        var childNode = unwrap(childWrapper);
        var parentNode = childNode.parentNode;
        if (parentNode) originalRemoveChild.call(parentNode, childNode);
        childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = null;
        childWrapper = nextSibling;
      }

      wrapper.firstChild_ = wrapper.lastChild_ = null;
    } else {
      var node = unwrap(wrapper);
      var child = node.firstChild;
      var nextSibling;

      while (child) {
        nextSibling = child.nextSibling;
        originalRemoveChild.call(node, child);
        child = nextSibling;
      }
    }
  }

  function invalidateParent(node) {
    var p = node.parentNode;
    return p && p.invalidateShadowRenderer();
  }

  function cleanupNodes(nodes) {
    for (var i = 0, n; i < nodes.length; i++) {
      n = nodes[i];
      n.parentNode.removeChild(n);
    }
  }

  var originalImportNode = document.importNode;
  var originalCloneNode = window.Node.prototype.cloneNode;

  function cloneNode(node, deep, opt_doc) {
    var clone;
    if (opt_doc)
      clone = wrap(originalImportNode.call(opt_doc, unsafeUnwrap(node), false));
    else clone = wrap(originalCloneNode.call(unsafeUnwrap(node), false));

    if (deep) {
      for (var child = node.firstChild; child; child = child.nextSibling) {
        clone.appendChild(cloneNode(child, true, opt_doc));
      }

      if (node instanceof wrappers.HTMLTemplateElement) {
        var cloneContent = clone.content;

        for (
          var child = node.content.firstChild;
          child;
          child = child.nextSibling
        ) {
          cloneContent.appendChild(cloneNode(child, true, opt_doc));
        }
      }
    }

    return clone;
  }

  function contains(self, child) {
    if (!child || getTreeScope(self) !== getTreeScope(child)) return false;

    for (var node = child; node; node = node.parentNode) {
      if (node === self) return true;
    }

    return false;
  }

  var OriginalNode = window.Node;

  function Node(original) {
    assert(original instanceof OriginalNode);
    EventTarget.call(this, original);
    this.parentNode_ = undefined;
    this.firstChild_ = undefined;
    this.lastChild_ = undefined;
    this.nextSibling_ = undefined;
    this.previousSibling_ = undefined;
    this.treeScope_ = undefined;
  }

  var OriginalDocumentFragment = window.DocumentFragment;
  var originalAppendChild = OriginalNode.prototype.appendChild;
  var originalCompareDocumentPosition =
    OriginalNode.prototype.compareDocumentPosition;
  var originalInsertBefore = OriginalNode.prototype.insertBefore;
  var originalRemoveChild = OriginalNode.prototype.removeChild;
  var originalReplaceChild = OriginalNode.prototype.replaceChild;
  var isIe = /Trident/.test(navigator.userAgent);
  var removeChildOriginalHelper = isIe
    ? function(parent, child) {
        try {
          originalRemoveChild.call(parent, child);
        } catch (ex) {
          if (!(parent instanceof OriginalDocumentFragment)) throw ex;
        }
      }
    : function(parent, child) {
        originalRemoveChild.call(parent, child);
      };
  Node.prototype = Object.create(EventTarget.prototype);
  mixin(Node.prototype, {
    appendChild: function(childWrapper) {
      return this.insertBefore(childWrapper, null);
    },
    insertBefore: function(childWrapper, refWrapper) {
      assertIsNodeWrapper(childWrapper);
      var refNode;

      if (refWrapper) {
        if (isWrapper(refWrapper)) {
          refNode = unwrap(refWrapper);
        } else {
          refNode = refWrapper;
          refWrapper = wrap(refNode);
        }
      } else {
        refWrapper = null;
        refNode = null;
      }

      refWrapper && assert(refWrapper.parentNode === this);
      var nodes;
      var previousNode = refWrapper
        ? refWrapper.previousSibling
        : this.lastChild;
      var useNative =
        !this.invalidateShadowRenderer() && !invalidateParent(childWrapper);
      if (useNative) nodes = collectNodesNative(childWrapper);
      else nodes = collectNodes(childWrapper, this, previousNode, refWrapper);

      if (useNative) {
        ensureSameOwnerDocument(this, childWrapper);
        clearChildNodes(this);
        originalInsertBefore.call(
          unsafeUnwrap(this),
          unwrap(childWrapper),
          refNode
        );
      } else {
        if (!previousNode) this.firstChild_ = nodes[0];

        if (!refWrapper) {
          this.lastChild_ = nodes[nodes.length - 1];
          if (this.firstChild_ === undefined)
            this.firstChild_ = this.firstChild;
        }

        var parentNode = refNode ? refNode.parentNode : unsafeUnwrap(this);

        if (parentNode) {
          originalInsertBefore.call(
            parentNode,
            unwrapNodesForInsertion(this, nodes),
            refNode
          );
        } else {
          adoptNodesIfNeeded(this, nodes);
        }
      }

      enqueueMutation(this, "childList", {
        addedNodes: nodes,
        nextSibling: refWrapper,
        previousSibling: previousNode
      });
      nodesWereAdded(nodes, this);
      return childWrapper;
    },
    removeChild: function(childWrapper) {
      assertIsNodeWrapper(childWrapper);

      if (childWrapper.parentNode !== this) {
        var found = false;
        var childNodes = this.childNodes;

        for (
          var ieChild = this.firstChild;
          ieChild;
          ieChild = ieChild.nextSibling
        ) {
          if (ieChild === childWrapper) {
            found = true;
            break;
          }
        }

        if (!found) {
          throw new Error("NotFoundError");
        }
      }

      var childNode = unwrap(childWrapper);
      var childWrapperNextSibling = childWrapper.nextSibling;
      var childWrapperPreviousSibling = childWrapper.previousSibling;

      if (this.invalidateShadowRenderer()) {
        var thisFirstChild = this.firstChild;
        var thisLastChild = this.lastChild;
        var parentNode = childNode.parentNode;
        if (parentNode) removeChildOriginalHelper(parentNode, childNode);
        if (thisFirstChild === childWrapper)
          this.firstChild_ = childWrapperNextSibling;
        if (thisLastChild === childWrapper)
          this.lastChild_ = childWrapperPreviousSibling;
        if (childWrapperPreviousSibling)
          childWrapperPreviousSibling.nextSibling_ = childWrapperNextSibling;

        if (childWrapperNextSibling) {
          childWrapperNextSibling.previousSibling_ = childWrapperPreviousSibling;
        }

        childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = undefined;
      } else {
        clearChildNodes(this);
        removeChildOriginalHelper(unsafeUnwrap(this), childNode);
      }

      if (!surpressMutations) {
        enqueueMutation(this, "childList", {
          removedNodes: createOneElementNodeList(childWrapper),
          nextSibling: childWrapperNextSibling,
          previousSibling: childWrapperPreviousSibling
        });
      }

      registerTransientObservers(this, childWrapper);
      return childWrapper;
    },
    replaceChild: function(newChildWrapper, oldChildWrapper) {
      assertIsNodeWrapper(newChildWrapper);
      var oldChildNode;

      if (isWrapper(oldChildWrapper)) {
        oldChildNode = unwrap(oldChildWrapper);
      } else {
        oldChildNode = oldChildWrapper;
        oldChildWrapper = wrap(oldChildNode);
      }

      if (oldChildWrapper.parentNode !== this) {
        throw new Error("NotFoundError");
      }

      var nextNode = oldChildWrapper.nextSibling;
      var previousNode = oldChildWrapper.previousSibling;
      var nodes;
      var useNative =
        !this.invalidateShadowRenderer() && !invalidateParent(newChildWrapper);

      if (useNative) {
        nodes = collectNodesNative(newChildWrapper);
      } else {
        if (nextNode === newChildWrapper)
          nextNode = newChildWrapper.nextSibling;
        nodes = collectNodes(newChildWrapper, this, previousNode, nextNode);
      }

      if (!useNative) {
        if (this.firstChild === oldChildWrapper) this.firstChild_ = nodes[0];
        if (this.lastChild === oldChildWrapper)
          this.lastChild_ = nodes[nodes.length - 1];
        oldChildWrapper.previousSibling_ = oldChildWrapper.nextSibling_ = oldChildWrapper.parentNode_ = undefined;

        if (oldChildNode.parentNode) {
          originalReplaceChild.call(
            oldChildNode.parentNode,
            unwrapNodesForInsertion(this, nodes),
            oldChildNode
          );
        }
      } else {
        ensureSameOwnerDocument(this, newChildWrapper);
        clearChildNodes(this);
        originalReplaceChild.call(
          unsafeUnwrap(this),
          unwrap(newChildWrapper),
          oldChildNode
        );
      }

      enqueueMutation(this, "childList", {
        addedNodes: nodes,
        removedNodes: createOneElementNodeList(oldChildWrapper),
        nextSibling: nextNode,
        previousSibling: previousNode
      });
      nodeWasRemoved(oldChildWrapper);
      nodesWereAdded(nodes, this);
      return oldChildWrapper;
    },
    nodeIsInserted_: function() {
      for (var child = this.firstChild; child; child = child.nextSibling) {
        child.nodeIsInserted_();
      }
    },
    hasChildNodes: function() {
      return this.firstChild !== null;
    },

    get parentNode() {
      return this.parentNode_ !== undefined
        ? this.parentNode_
        : wrap(unsafeUnwrap(this).parentNode);
    },

    get firstChild() {
      return this.firstChild_ !== undefined
        ? this.firstChild_
        : wrap(unsafeUnwrap(this).firstChild);
    },

    get lastChild() {
      return this.lastChild_ !== undefined
        ? this.lastChild_
        : wrap(unsafeUnwrap(this).lastChild);
    },

    get nextSibling() {
      return this.nextSibling_ !== undefined
        ? this.nextSibling_
        : wrap(unsafeUnwrap(this).nextSibling);
    },

    get previousSibling() {
      return this.previousSibling_ !== undefined
        ? this.previousSibling_
        : wrap(unsafeUnwrap(this).previousSibling);
    },

    get parentElement() {
      var p = this.parentNode;

      while (p && p.nodeType !== Node.ELEMENT_NODE) {
        p = p.parentNode;
      }

      return p;
    },

    get textContent() {
      var s = "";

      for (var child = this.firstChild; child; child = child.nextSibling) {
        if (child.nodeType != Node.COMMENT_NODE) {
          s += child.textContent;
        }
      }

      return s;
    },

    set textContent(textContent) {
      if (textContent == null) textContent = "";
      var removedNodes = snapshotNodeList(this.childNodes);

      if (this.invalidateShadowRenderer()) {
        removeAllChildNodes(this);

        if (textContent !== "") {
          var textNode = unsafeUnwrap(this).ownerDocument.createTextNode(
            textContent
          );
          this.appendChild(textNode);
        }
      } else {
        clearChildNodes(this);
        unsafeUnwrap(this).textContent = textContent;
      }

      var addedNodes = snapshotNodeList(this.childNodes);
      enqueueMutation(this, "childList", {
        addedNodes: addedNodes,
        removedNodes: removedNodes
      });
      nodesWereRemoved(removedNodes);
      nodesWereAdded(addedNodes, this);
    },

    get childNodes() {
      var wrapperList = new NodeList();
      var i = 0;

      for (var child = this.firstChild; child; child = child.nextSibling) {
        wrapperList[i++] = child;
      }

      wrapperList.length = i;
      return wrapperList;
    },

    cloneNode: function(deep) {
      return cloneNode(this, deep);
    },
    contains: function(child) {
      return contains(this, wrapIfNeeded(child));
    },
    compareDocumentPosition: function(otherNode) {
      return originalCompareDocumentPosition.call(
        unsafeUnwrap(this),
        unwrapIfNeeded(otherNode)
      );
    },
    normalize: function() {
      var nodes = snapshotNodeList(this.childNodes);
      var remNodes = [];
      var s = "";
      var modNode;

      for (var i = 0, n; i < nodes.length; i++) {
        n = nodes[i];

        if (n.nodeType === Node.TEXT_NODE) {
          if (!modNode && !n.data.length) this.removeNode(n);
          else if (!modNode) modNode = n;
          else {
            s += n.data;
            remNodes.push(n);
          }
        } else {
          if (modNode && remNodes.length) {
            modNode.data += s;
            cleanupNodes(remNodes);
          }

          remNodes = [];
          s = "";
          modNode = null;
          if (n.childNodes.length) n.normalize();
        }
      }

      if (modNode && remNodes.length) {
        modNode.data += s;
        cleanupNodes(remNodes);
      }
    }
  });
  defineWrapGetter(Node, "ownerDocument");
  registerWrapper(OriginalNode, Node, document.createDocumentFragment());
  delete Node.prototype.querySelector;
  delete Node.prototype.querySelectorAll;
  Node.prototype = mixin(Object.create(EventTarget.prototype), Node.prototype);
  scope.cloneNode = cloneNode;
  scope.nodeWasAdded = nodeWasAdded;
  scope.nodeWasRemoved = nodeWasRemoved;
  scope.nodesWereAdded = nodesWereAdded;
  scope.nodesWereRemoved = nodesWereRemoved;
  scope.originalInsertBefore = originalInsertBefore;
  scope.originalRemoveChild = originalRemoveChild;
  scope.snapshotNodeList = snapshotNodeList;
  scope.wrappers.Node = Node;
}


text:
package com.nvapp.comic.fragment;

import com.nvapp.comic.R;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;

public class HomeFragment extends Fragment implements android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener {
	// private HomeAdapter adapter;
	ListView listView;
	private CountDownTimer timer;
	ProgressBar progressbar;
	SwipeRefreshLayout swipe;
	// List<HomeBean> sections;
	// FinalDb db;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, container, false);
		initView(view);
		return view;
	}

	private void initView(View view) {
		// db = FinalDb.create(getActivity(), false);
		progressbar = (ProgressBar) view.findViewById(R.id.progress_bar);
		listView = (ListView) view.findViewById(R.id.listView);
		swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
		swipe.setOnRefreshListener(this);
		// 顶部刷新的样式
		swipe.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_green_light,
				android.R.color.holo_blue_bright, android.R.color.holo_orange_light);
		timer = new CountDownTimer(9 * 100, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				long a = millisUntilFinished / 100;
				if (a == 1) {
					// getData(APIURL.SERVER_URL + "item_a.json");
					// Log.e("APIURL:", APIURL.SERVER_URL + "item_a.json");
					// adapter = new HomeAdapter(getActivity(), listView);
					// listView.setAdapter(adapter);
				} else {
					progressbar.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onFinish() {

			}
		};
		// sections = db.findAllByWhere(HomeBean.class, "1=1", "id");
		// if (NetWorkUtil.networkCanUse(getActivity())) {
		timer.start();
		// } else {
		// progressbar.setIndeterminateDrawable(getResources().getDrawable(R.drawable.net_error_loading));
		// if (sections != null || sections.size() != 0) {
		// adapter = new HomeAdapter(getActivity(), listView);
		// listView.setAdapter(adapter);
		// adapter.resetData(sections);
		// }
		// }
	}

	@Override
	public void onRefresh() {

		new Handler().postDelayed(new Runnable() {
			public void run() {

				// if (NetWorkUtil.networkCanUse(getActivity())) {
				// getData(APIURL.SERVER_URL + "item_a.json");
				// adapter = new HomeAdapter(getActivity(), listView);
				// listView.setAdapter(adapter);
				// } else {
				// Toast.makeText(getActivity(), "网络连接失败..", 1).show();
				progressbar.setVisibility(View.GONE);
				// if (sections != null || sections.size() != 0) {
				// adapter = new HomeAdapter(getActivity(), listView);
				// listView.setAdapter(adapter);
				// adapter.resetData(sections);
				// }
				// }

				swipe.setRefreshing(false);

			}
		}, 1500);
	}
}


text:
@interface WYTableViewDataSource ()
{
    NSArray *tableSource;
    NSString *cellIdentifier;
    ConfigureCellBlock configBlock;
}

@end

@implementation WYTableViewDataSource

- (id)initWithSources:(NSArray *)sources
         cellIdentifier:(NSString *)identifier
          configureCell:(ConfigureCellBlock)block
{
    if (self = [super init]) {
        tableSource = sources;
        cellIdentifier = identifier;
        configBlock = block;
    }else{
        return nil;
    }

    return self;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableSource.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"wycell"];
    }
    configBlock(cell, indexPath);

    return cell;
}

@end


text:
//
//  Complex_Impl.hpp
//  Spektr
//
//  Created by Christian J Howard on 3/26/16.
//
//  The MIT License (MIT)
//    Copyright © 2016 Christian Howard. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
//
//

#ifndef Complex_Impl_h
#define Complex_Impl_h

#define HEADER template<typename T>
#define COMPLEX Complex<T>
#include <math.h>
#include <stdio.h>

HEADER
void COMPLEX::polar2rect( const T & mag, const T & arg ){
    double m = static_cast<double>(mag);
    double a = static_cast<double>(arg);
    re_ = static_cast<T>(m*cos(a));
    im_ = static_cast<T>(m*sin(a));
}

HEADER
void COMPLEX::rect2polar( T & mag, T & arg ) const {
    mag = static_cast<T>(sqrt( static_cast<double>(re_*re_ + im_*im_) ));
    arg = static_cast<T>(atan2( static_cast<double>(im_), static_cast<double>(re_) ));
}

HEADER
COMPLEX::Complex(){
    re_ = static_cast<T>(0);
    im_ = static_cast<T>(0);
}

HEADER
COMPLEX::Complex( const T & a, const T & b , bool useRealImaginary ){
    if( useRealImaginary ){
        re_ = a; im_ = b;
    }else{
        polar2rect(a,b);
    }
}

HEADER
COMPLEX COMPLEX::operator+( const Complex & c ) const{
    return Complex( re_ + c.re_, im_ + c.im_ );
}

HEADER
COMPLEX COMPLEX::operator-( const Complex & c ) const{
    return Complex( re_ - c.re_, im_ - c.im_ );
}

HEADER
COMPLEX COMPLEX::operator*( const Complex & c ) const{
    return Complex(re_*c.re_ - im_*c.im_,re_*c.im_ + c.re_ * im_);
}

HEADER
COMPLEX COMPLEX::operator/( const Complex & c ) const{
    T mag, phase;
    CPolar cp2 = c.polar();
    rect2polar(mag,phase);
    return Complex(mag/cp2.mag,phase-cp2.phase, false);
}

HEADER
COMPLEX COMPLEX::operator-() const{
    return Complex(-re_,-im_);
}

HEADER
void COMPLEX::operator+=( const Complex & c ) {
    re_ += c.re_;
    im_ += c.im_;
}

HEADER
void COMPLEX::operator-=( const Complex & c ) {
    re_ -= c.re_;
    im_ -= c.im_;
}

HEADER
void COMPLEX::operator*=( const Complex & c ) {
    *this = this->operator*(c);
}

HEADER
void COMPLEX::operator/=( const Complex & c ) {
    *this = this->operator/(c);
}

HEADER
typename COMPLEX::CPolar COMPLEX::polar() const{
    CPolar out;
    rect2polar(out.mag,out.phase);
    return out;
}

HEADER
T & COMPLEX::re(){
    return re_;
}

HEADER
T & COMPLEX::im(){
    return im_;
}

HEADER
const T & COMPLEX::re() const{
    return re_;
}

HEADER
const T & COMPLEX::im() const{
    return im_;
}

HEADER
T COMPLEX::abs() const{
    return static_cast<T>(sqrt( static_cast<double>(re_*re_ + im_*im_) ));
}

HEADER
T COMPLEX::phase() const{
    return static_cast<T>(atan2( static_cast<double>(im_), static_cast<double>(re_) ));
}

HEADER
COMPLEX COMPLEX::getconj() const{
    return Complex(re_,-im_);
}

HEADER
void COMPLEX::conj(){
    im_ = -im_;
}

HEADER
void COMPLEX::print() const{
    if( im_ >= 0 ){
        printf("%lf + %lfi",static_cast<double>(re_),fabs(static_cast<double>(im_)));
    }else{
        printf("%lf - %lfi",static_cast<double>(re_),fabs(static_cast<double>(im_)));
    }
}

HEADER
void COMPLEX::println() const{
    if( im_ >= 0 ){
        printf("%lf + %lfi\n",static_cast<double>(re_),fabs(static_cast<double>(im_)));
    }else{
        printf("%lf - %lfi\n",static_cast<double>(re_),fabs(static_cast<double>(im_)));
    }
}

#undef HEADER
#undef COMPLEX

#endif /* Complex_Impl_h */