text:
<?php

namespace Google\Cloud\BigQuery\Tests\Snippet;

use Google\Cloud\BigQuery\BigQueryClient;
use Google\Cloud\BigQuery\Connection\ConnectionInterface;
use Google\Cloud\BigQuery\CopyJobConfiguration;
use Google\Cloud\BigQuery\ExtractJobConfiguration;
use Google\Cloud\BigQuery\InsertResponse;
use Google\Cloud\BigQuery\Job;
use Google\Cloud\BigQuery\JobConfigurationInterface;
use Google\Cloud\BigQuery\LoadJobConfiguration;
use Google\Cloud\BigQuery\Table;
use Google\Cloud\BigQuery\ValueMapper;
use Google\Cloud\Core\Iam\Iam;
use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\Testing\Snippet\SnippetTestCase;
use Google\Cloud\Core\Testing\TestHelpers;
use Google\Cloud\Storage\Connection\Rest as StorageConnection;
use Google\Cloud\Storage\StorageClient;
use Prophecy\Argument;

/**
 * @group bigquery
 */
class TableTest extends SnippetTestCase
{
    const ID = 'foo';
    const DSID = 'bar';
    const PROJECT = 'my-awesome-project';
    const JOB_ID = '123';

    private $info;
    private $connection;
    private $table;
    private $mapper;

    public function set_up()
    {
        $this->info = [
            'rows' => [
                [
                    'f' => [
                        ['v' => 'abcd']
                    ]
                ]
            ],
            'schema' => [
                'fields' => [
                    [
                        'name' => 'name',
                        'type' => 'STRING'
                    ]
                ]
            ],
            'friendlyName' => 'Jeffrey',
            'selfLink' => 'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/mynewdataset',
        ];

        $this->mapper = new ValueMapper(false);
        $this->connection = $this->prophesize(ConnectionInterface::class);
        $this->table = TestHelpers::stub(Table::class, [
            $this->connection->reveal(),
            self::ID,
            self::DSID,
            self::PROJECT,
            $this->mapper,
            $this->info
        ]);
    }

    public function testExists()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'exists');
        $snippet->addLocal('table', $this->table);

        $this->connection->getTable(Argument::any())
            ->shouldBeCalled()
            ->willReturn([]);

        $this->table->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke();
        $this->assertEquals('Table exists!', $res->output());
    }

    public function testDelete()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'delete');
        $snippet->addLocal('table', $this->table);

        $this->connection->deleteTable(Argument::any())
            ->shouldBeCalled();

        $this->table->___setProperty('connection', $this->connection->reveal());

        $snippet->invoke();
    }

    public function testUpdate()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'update');
        $snippet->addLocal('table', $this->table);

        $this->connection->patchTable(Argument::any())
            ->shouldBeCalled();

        $this->table->___setProperty('connection', $this->connection->reveal());

        $snippet->invoke();
    }

    public function testRows()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'rows');
        $snippet->addLocal('table', $this->table);

        $this->connection->listTableData(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'rows' => $this->info['rows']
            ]);

        $this->table->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('rows');
        $this->assertInstanceOf(ItemIterator::class, $res->returnVal());
        $this->assertEquals('abcd' . PHP_EOL, $res->output());
    }

    public function testRunJob()
    {
        $jobConfig = $this->prophesize(JobConfigurationInterface::class);
        $jobConfig->toArray()
            ->willReturn([
                'projectId' => self::PROJECT,
                'jobReference' => [
                    'jobId' => self::JOB_ID,
                    'projectId' => self::PROJECT
                ]
            ]);
        $snippet = $this->snippetFromMethod(Table::class, 'runJob');
        $snippet->addLocal('table', $this->table);
        $snippet->addLocal('jobConfig', $jobConfig->reveal());
        $this->connection->insertJob(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'jobReference' => [
                    'jobId' => self::JOB_ID
                ],
                'status' => [
                    'state' => 'DONE'
                ]
            ]);
        $this->table->___setProperty('connection', $this->connection->reveal());
        $res = $snippet->invoke('job');

        $this->assertInstanceOf(Job::class, $res->returnVal());
        $this->assertEquals('1', $res->output());
    }

    public function testStartJob()
    {
        $jobConfig = $this->prophesize(JobConfigurationInterface::class);
        $jobConfig->toArray()
            ->willReturn([
                'projectId' => self::PROJECT,
                'jobReference' => [
                    'jobId' => self::JOB_ID,
                    'projectId' => self::PROJECT
                ]
            ]);
        $snippet = $this->snippetFromMethod(Table::class, 'startJob');
        $snippet->addLocal('table', $this->table);
        $snippet->addLocal('jobConfig', $jobConfig->reveal());
        $this->connection->insertJob(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'jobReference' => [
                    'jobId' => self::JOB_ID
                ]
            ]);
        $this->table->___setProperty('connection', $this->connection->reveal());
        $res = $snippet->invoke('job');

        $this->assertInstanceOf(Job::class, $res->returnVal());
    }

    public function testCopy()
    {
        $bq = TestHelpers::stub(BigQueryClient::class);
        $snippet = $this->snippetFromMethod(Table::class, 'copy');
        $snippet->addLocal('bigQuery', $bq);
        $bq->___setProperty('connection', $this->connection->reveal());
        $config = $snippet->invoke('copyJobConfig')
            ->returnVal();

        $this->assertInstanceOf(CopyJobConfiguration::class, $config);
        $this->assertEquals(
            [
                'destinationTable' => [
                    'projectId' => self::PROJECT,
                    'datasetId' => 'myDataset',
                    'tableId' => 'myDestinationTable'
                ],
                'sourceTable' => [
                    'projectId' => self::PROJECT,
                    'datasetId' => 'myDataset',
                    'tableId' => 'mySourceTable'
                ]
            ],
            $config->toArray()['configuration']['copy']
        );
    }

    public function testExtract()
    {
        $storage = TestHelpers::stub(StorageClient::class);
        $storage->___setProperty('connection', $this->prophesize(StorageConnection::class)->reveal());
        $snippet = $this->snippetFromMethod(Table::class, 'extract');
        $snippet->addLocal('storage', $storage);
        $snippet->addLocal('table', $this->table);
        $config = $snippet->invoke('extractJobConfig')
            ->returnVal();

        $this->assertInstanceOf(ExtractJobConfiguration::class, $config);
        $this->assertEquals(
            [
                'destinationUris' => ['gs://myBucket/tableOutput'],
                'sourceTable' => [
                    'projectId' => self::PROJECT,
                    'datasetId' => self::DSID,
                    'tableId' => self::ID
                ]
            ],
            $config->toArray()['configuration']['extract']
        );
    }

    public function testLoad()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'load');
        $snippet->addLocal('table', $this->table);
        $snippet->replace('fopen(\'/path/to/my/data.csv\', \'r\')', '123');
        $config = $snippet->invoke('loadJobConfig')
            ->returnVal();

        $this->assertInstanceOf(LoadJobConfiguration::class, $config);
        $this->assertEquals(
            [
                'destinationTable' => [
                    'projectId' => self::PROJECT,
                    'datasetId' => self::DSID,
                    'tableId' => self::ID
                ]
            ],
            $config->toArray()['configuration']['load']
        );
    }

    public function testLoadFromStorage()
    {
        $storage = TestHelpers::stub(StorageClient::class);
        $storage->___setProperty('connection', $this->prophesize(StorageConnection::class)->reveal());
        $snippet = $this->snippetFromMethod(Table::class, 'loadFromStorage');
        $snippet->addLocal('storage', $storage);
        $snippet->addLocal('table', $this->table);
        $config = $snippet->invoke('loadJobConfig')
            ->returnVal();

        $this->assertInstanceOf(LoadJobConfiguration::class, $config);
        $this->assertEquals(
            [
                'sourceUris' => ['gs://myBucket/important-data.csv'],
                'destinationTable' => [
                    'projectId' => self::PROJECT,
                    'datasetId' => self::DSID,
                    'tableId' => self::ID
                ]
            ],
            $config->toArray()['configuration']['load']
        );
    }

    public function testInsertRow()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'insertRow');
        $snippet->addLocal('table', $this->table);

        $this->connection->insertAllTableData(Argument::any())
            ->shouldBeCalled()
            ->willReturn([

            ]);

        $this->table->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('insertResponse');
        $this->assertInstanceOf(InsertResponse::class, $res->returnVal());
    }

    public function testInsertRows()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'insertRows');
        $snippet->addLocal('table', $this->table);

        $this->connection->insertAllTableData(Argument::any())
            ->shouldBeCalled()
            ->willReturn([

            ]);

        $this->table->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('insertResponse');
        $this->assertInstanceOf(InsertResponse::class, $res->returnVal());
    }

    public function testInfo()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'info');
        $snippet->addLocal('table', $this->table);

        $res = $snippet->invoke();
        $this->assertEquals(
            'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/mynewdataset',
            $res->output()
        );
    }

    public function testReload()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'reload');
        $snippet->addLocal('table', $this->table);

        $this->connection->getTable(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'selfLink' => 'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/myupdateddataset'
            ]);

        $this->table->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke();
        $this->assertEquals(
            'https://www.googleapis.com/bigquery/v2/projects/my-project/datasets/myupdateddataset',
            $res->output()
        );
    }

    public function testId()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'id');
        $snippet->addLocal('table', $this->table);

        $res = $snippet->invoke();
        $this->assertEquals(self::ID, $res->output());
    }

    public function testIdentity()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'identity');
        $snippet->addLocal('table', $this->table);

        $res = $snippet->invoke();
        $this->assertEquals(self::PROJECT, $res->output());
    }

    public function testIam()
    {
        $snippet = $this->snippetFromMethod(Table::class, 'iam');
        $snippet->addLocal('table', $this->table);

        $this->assertInstanceof(Iam::class, $snippet->invoke('iam')->returnVal());
    }
}


text:
package org.eclipse.jdt.internal.ui.jarpackager;

import org.eclipse.swt.widgets.Shell;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;

import org.eclipse.jdt.ui.jarpackager.IJarBuilder;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;

import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;

/**
 * Base class for all jar builders.
 *
 * @since 3.4
 */
public abstract class JarBuilder implements IJarBuilder {

	private MultiStatus fStatus;

	/**
	 * {@inheritDoc}
	 */
	public void open(JarPackageData jarPackage, Shell shell, MultiStatus status) throws CoreException {
		fStatus= status;
	}

	//some methods for convenience
	protected final void addInfo(String message, Throwable error) {
		fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
	}

	protected final void addWarning(String message, Throwable error) {
		fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
	}

	protected final void addError(String message, Throwable error) {
		fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
	}

	protected final void addToStatus(CoreException ex) {
		IStatus status= ex.getStatus();
		String message= ex.getLocalizedMessage();
		if (message == null || message.length() < 1) {
			message= JarPackagerMessages.JarFileExportOperation_coreErrorDuringExport;
			status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
		}
		fStatus.add(status);
	}
}

redpajama_set_name: RedPajamaGithub


text: <title>IEM TMS + OpenLayers Example</title>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<!--框架必需start-->
<script type="text/javascript" src="../../libs/js/jquery.js"></script>
<script type="text/javascript" src="../../libs/js/framework.js"></script>
<link href="../../libs/css/import_basic.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" id="skin" prePath="../../"/>
<link rel="stylesheet" type="text/css" id="customSkin"/>
<!--框架必需end-->
</head>
<body>
 	  <input type="button" value="查看效果"
			onclick='top.Dialog.open({URL:"../../sample_skin/normal/table-pop-content1.html",Title:"table",ID:"win1",ShowMaxButton:true,ShowMinButton:true,MinToTask:true});'/>
</body>
</html>


text:
using System;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using Tibia;
using Tibia.Objects;

namespace Tibia.Util
{
    public class MapViewer : Panel
    {
        #region Constants
        private const int MapFileDimension = 256;
        private const int FloorMax = 15;
        private const int FloorMin = 0;
        private const string MaskOT = "0??0??";
        private const string MaskReal = "1??1??";
        #endregion

        #region Settings
        // Public Delegates
        public delegate void MapFloorToImagePercentCallback(int percentageComplete);

        // Public Settings
        private bool drawCrosshair = true;
        private bool drawCoors = true;
        private bool openTibiaMaps = false;
        private string directory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Tibia\\Automap\\";
        private List<MapMarker> markers = new List<MapMarker>();

        public bool DrawCrosshair
        {
            get { return drawCrosshair; }
            set { drawCrosshair = value; }
        }

        public bool DrawCoors
        {
            get { return drawCoors; }
            set { drawCoors = value; }
        }

        public bool OpenTibiaMaps
        {
            get { return openTibiaMaps; }
            set { openTibiaMaps = value; }
        }

        public string Directory
        {
            get { return directory; }
            set { directory = value; }
        }

        public List<MapMarker> Markers
        {
            get { return markers; }
        }
        #endregion

        #region Private Variables
        private bool canDrawPercentBar = false;
        private int percent = 0;
        private Rectangle mapBoundary;
        private int currentZ = 7;
        private Bitmap[] floorImages = new Bitmap[FloorMax + 1];
        private Point startingPos;
        private Point imagePos = new Point(0, 0);
        private Size imageSize;
        private Image mapImage;
        private double zoomFactor = 1;
        #endregion

        #region Constructor
        public MapViewer()
        {
            // Set the value of the double-buffering style bits to true.
            this.SetStyle(ControlStyles.DoubleBuffer |
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint,
                true);

            this.UpdateStyles();

            markers = new List<MapMarker>();
        }
        #endregion

        #region Handlers
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            markers = new List<MapMarker>();
        }
        protected override void OnMouseWheel(MouseEventArgs e)
        {
            //SetMapCenter(PointToMapCoors(new Point(e.X, e.Y)));
            Zoom((e.Delta > 0) ? 2 : .5);
            Invalidate();
        }

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            SetMapCenter(PointToMapCoors(new Point(e.X, e.Y)));
            Invalidate();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            switch (e.Button)
            {
                case MouseButtons.Left:
                    startingPos.X = e.X;
                    startingPos.Y = e.Y;
                    break;
                case MouseButtons.Middle:
                    break;
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                imagePos.X += e.X - startingPos.X;
                imagePos.Y += e.Y - startingPos.Y;
                startingPos.X = e.X;
                startingPos.Y = e.Y;

                Invalidate();
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            RedrawMap(e.Graphics);
        }

        protected override void OnResize(EventArgs e)
        {
            Invalidate();
        }
        #endregion

        #region Static Methods
        /// <summary>
        /// Get the boundary coordinates of an array of map files
        /// </summary>
        /// <param name="mapFiles"></param>
        /// <returns></returns>
        private static Rectangle GetBoundary(FileInfo[] mapFiles)
        {
            int left = 0;
            int right = 0;
            int top = 0;
            int bottom = 0;
            bool first = true;
            foreach (FileInfo mapFile in mapFiles)
            {
                Location l = MapFileNameToLocation(mapFile.Name);
                if (first)
                {
                    left = right = l.X;
                    top = bottom = l.Y;
                    first = false;
                }
                else
                {
                    if (l.X < left)
                        left = l.X;
                    else if (l.X > right)
                        right = l.X;

                    if (l.Y < top)
                        top = l.Y;
                    else if (l.Y > bottom)
                        bottom = l.Y;
                }
            }
            return new Rectangle(left, top, right - left + MapFileDimension, bottom - top + MapFileDimension);
        }

        /// <summary>
        /// Get a map file name from coordinates
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        private static string GetMapFileName(string directory, uint x, uint y, uint z)
        {
            return directory +
                (x / MapFileDimension).ToString("000") +
                (y / MapFileDimension).ToString("000") +
                z.ToString("00") + ".map";
        }

        /// <summary>
        /// Convert a map file name to a location
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static Location MapFileNameToLocation(string fileName)
        {
            Location l = new Location(0, 0, 0);
            if (fileName.Length == 12 || fileName.Length == 8)
            {
                l.X = Int32.Parse(fileName.Substring(0, 3)) * MapFileDimension;
                l.Y = Int32.Parse(fileName.Substring(3, 3)) * MapFileDimension;
                l.Z = Int32.Parse(fileName.Substring(6, 2));
            }
            return l;
        }

        /// <summary>
        /// Read a map file into an image
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Image MapFileToImage(string path)
        {
            // All map files are 256 x 256
            Bitmap bitmap = new Bitmap(MapFileDimension, MapFileDimension);

            // Make sure the file actually exists
            if (File.Exists(path))
            {
                // Open the file in a BufferedStream
                using (BufferedStream bs = new BufferedStream(new FileStream(path, FileMode.Open)))
                {
                    // Each map file contains this many pixels
                    byte[] array = new byte[65536];

                    // Read all of them at once (much faster than byte by byte) into an array
                    bs.Read(array, 0, 65536);

                    // Loop through the array
                    int index = 0;
                    for (int x = 0; x < MapFileDimension; x++)
                    {
                        for (int y = 0; y < MapFileDimension; y++)
                        {
                            byte b = array[index];

                            // Set the pixel on the bitmap, converting the byte a color
                            bitmap.SetPixel(x, y, Misc.GetAutomapColor(b));
                            index++;
                        }
                    }
                }
            }

            return bitmap;
        }
        #endregion

        #region Map File Loading
        /// <summary>
        /// Load the map into the picturebox at the currentZ level.
        /// Uses two level caching: the generated bitmap is saved as
        /// a png file in the map directory, and the Bitmap object
        /// is saved in memory.
        /// </summary>
        public void LoadMap()
        {
            Bitmap image;

            // Check if the image is already in memory
            if (floorImages[currentZ] != null)
            {
                image = floorImages[currentZ];
            }
            else
            {
                string dir = directory;

                // Open the directory
                DirectoryInfo di = new DirectoryInfo(dir);

                // Get all the map files
                FileInfo[] mapFiles = di.GetFiles(
                    (openTibiaMaps ? MaskOT : MaskReal) +
                    currentZ.ToString("00") +
                    ".map");

                // Find the boundary
                Rectangle r = GetBoundary(mapFiles);
                mapBoundary = r;

                string imageFileName = dir +
                    (r.Left / MapFileDimension).ToString("000") +
                    (r.Top / MapFileDimension).ToString("000") +
                    currentZ.ToString("00") + ".png";

                // Check if we have an image file previously generated
                if (File.Exists(imageFileName))
                {
                    image = (Bitmap)Bitmap.FromFile(imageFileName);
                }
                else
                {
                    canDrawPercentBar = true;

                    image = MapFloorToImage(dir, currentZ, delegate(int percentage)
                    {
                        this.percent = percentage;
                        Invalidate();
                    });

                    canDrawPercentBar = false;

                    // Save the image to speed up processing next time
                    image.Save(imageFileName, ImageFormat.Png);
                }
                floorImages[currentZ] = image;
            }

            // Draw the bitmap on the picture box
            if (imageSize.Width == 0)
                imageSize = image.Size;
            mapImage = image;

            Invalidate();
        }

        /// <summary>
        /// Get an image of the entire map on the specified floor
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="floor"></param>
        /// <returns></returns>
        public Bitmap MapFloorToImage(string dir, int floor)
        {
            return MapFloorToImage(dir, floor, null);
        }

        /// <summary>
        /// Get an image of the entire map on the specified floor
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="floor"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public Bitmap MapFloorToImage(string dir, int floor, MapFloorToImagePercentCallback callback)
        {
            // Open the directory
            DirectoryInfo di = new DirectoryInfo(dir);

            // Get all the map files
            FileInfo[] mapFiles = di.GetFiles((openTibiaMaps ? MaskOT : MaskReal) + floor.ToString("00") + ".map");

            // Find the boundary
            Rectangle r = GetBoundary(mapFiles);

            // Create a new bitmap big enough to hold all the map
            Bitmap b = new Bitmap(r.Width, r.Height);

            // Get the graphics object to draw on the image
            Graphics g = Graphics.FromImage(b);

            // Set the background to be black
            g.Clear(Color.Black);

            // Keep track of how far along we are
            int counter = 0;
            int total = mapFiles.Length;

            // Loop through the map files and draw them onto the bitmap
            foreach (FileInfo mapFile in mapFiles)
            {
                Location l = MapFileNameToLocation(mapFile.Name);
                if (l.Z == currentZ)
                    g.DrawImage(MapFileToImage(dir + mapFile.Name), l.X - r.Left, l.Y - r.Top);
                counter++;
                if (callback != null)
                    callback((int)(counter * 100.0 / total));
            }

            return b;
        }
        #endregion

        #region Level
        /// <summary>
        /// Move down a level
        /// </summary>
        public void LevelUp()
        {
            if (currentZ > FloorMin)
            {
                currentZ--;
                LoadMap();
            }
        }

        /// <summary>
        /// Move up a level
        /// </summary>
        public void LevelDown()
        {
            if (currentZ < FloorMax)
            {
                currentZ++;
                LoadMap();
            }
        }

        /// <summary>
        /// Set the level of the map
        /// </summary>
        /// <param name="z"></param>
        public void SetLevel(int z)
        {
            if (z != currentZ && (currentZ < FloorMax || currentZ > FloorMin))
            {
                currentZ = z;
                LoadMap();
            }
        }
        #endregion

        #region Zoom
        /// <summary>
        /// Set the zoom factor for the map
        /// </summary>
        /// <param name="factor"></param>
        public void Zoom(double factor)
        {
            Location center = GetMapCenter();

            zoomFactor *= factor;
            imageSize.Height = (int)(imageSize.Height * factor);
            imageSize.Width = (int)(imageSize.Width * factor);

            SetMapCenter(center);
        }
        #endregion

        #region Redraw Map
        /// <summary>
        /// Redraw the map (no background redraw)
        /// </summary>
        private void RedrawMap(Graphics g)
        {
            RedrawMap(true, g);
        }

        /// <summary>
        /// Redraw the map
        /// </summary>
        /// <param name="clear">if true clears the background first (produces a flicker)</param>
        /// <param name="g"></param>
        private void RedrawMap(bool clear, Graphics g)
        {
            if (canDrawPercentBar)
            {
                DrawPercentBar(percent, g);
                return;
            }

            if (mapImage == null)
                return;

            if (clear)
                g.Clear(Color.Black);

            g.DrawImage(mapImage, new Rectangle(imagePos, imageSize));

            if (drawCrosshair)
                DrawCrosshairs(g);

            if (drawCoors)
                DrawCoordinates(g);

            if (markers != null)
            {
                foreach (MapMarker mc in markers)
                {
                    mc.Update();
                    DrawMarker(mc.Location, mc.Name,
                        mc.ColorMarkerFill, mc.ColorMarkerOutline, mc.ColorTextFill, mc.ColorTextOutline,
                        mc.DrawHPBar ? mc.HPBar : -1, g);
                }
            }
        }
        #endregion

        #region Coordinate Helpers
        /// <summary>
        /// Convert Tibia coordinates to a point on the map
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public Point MapCoorsToPoint(int x, int y)
        {
            return MapCoorsToPoint(new Location(x, y, currentZ));
        }

        /// <summary>
        /// Convert a Tibia Location to a point on the map
        /// </summary>
        /// <param name="l"></param>
        /// <returns></returns>
        public Point MapCoorsToPoint(Location l)
        {
            int x = l.X;
            int y = l.Y;
            int newX = (int)((x - mapBoundary.Left) * zoomFactor) + imagePos.X;
            int newY = (int)((y - mapBoundary.Top) * zoomFactor) + imagePos.Y;

            return new Point(newX, newY);
        }

        /// <summary>
        /// Convert a point on the map to a Tibia location
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public Location PointToMapCoors(Point p)
        {
            int newX = (int)((p.X - imagePos.X) / zoomFactor + mapBoundary.Left);
            int newY = (int)((p.Y - imagePos.Y) / zoomFactor + mapBoundary.Top);

            return new Location(newX, newY, currentZ);
        }

        /// <summary>
        /// Get the point at the center of the picturebox
        /// </summary>
        /// <returns></returns>
        public Point GetMapCenterPoint()
        {
            int x = Width / 2;
            int y = Height / 2;

            return new Point(x, y);
        }

        /// <summary>
        /// Set the center of the map to a Tibia Location
        /// </summary>
        /// <param name="l"></param>
        public void SetMapCenter(Location l)
        {
            Point center = GetMapCenterPoint();

            int newX = (int)((l.X - mapBoundary.Left) * zoomFactor * -1 + center.X);
            int newY = (int)((l.Y - mapBoundary.Top) * zoomFactor * -1 + center.Y);

            imagePos.X = newX;
            imagePos.Y = newY;

            Invalidate();
        }

        /// <summary>
        /// Get the center of the map in Tibia Coordinates
        /// </summary>
        /// <returns></returns>
        public Location GetMapCenter()
        {
            return PointToMapCoors(GetMapCenterPoint());
        }
        #endregion

        #region Draw Helpers
        /// <summary>
        /// Draw a percentage bar on the map
        /// </summary>
        /// <param name="percent"></param>
        /// <param name="g"></param>
        private void DrawPercentBar(int percent, Graphics g)
        {
            Font font = new Font("Tahoma", 10, FontStyle.Bold);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;

            int width = Width / 2;
            int height = font.Height;
            int x = (int)((Width - width) / 2);
            int y = (int)((Height - height) / 2);

            Rectangle outer = new Rectangle(x, y, width, height);

            Rectangle inner = new Rectangle(x + 1, y + 1, (int)((width - 2) * percent / 100.0), height - 2);

            g.FillRectangle(Brushes.Black, outer);
            g.FillRectangle(Brushes.DarkGray, inner);
            g.DrawString(percent + "%", font, Brushes.White, outer, sf);
        }

        /// <summary>
        /// Draw crosshairs in the middle of the map
        /// </summary>
        private void DrawCrosshairs(Graphics g)
        {
            DrawCrosshairs(GetMapCenterPoint(), g);
        }

        /// <summary>
        /// Draw crosshairs at the specified point
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="g"></param>
        private void DrawCrosshairs(int x, int y, Graphics g)
        {
            DrawCrosshairs(new Point(x, y), g);
        }

        /// <summary>
        /// Draw crosshairs at the specified point
        /// </summary>
        /// <param name="p"></param>
        /// <param name="g"></param>
        private void DrawCrosshairs(Point p, Graphics g)
        {
            int x = p.X;
            int y = p.Y;

            // Draw the vertical line
            g.DrawLine(new Pen(Color.White, 1), new Point(x - 5, y), new Point(x + 5, y));
            // Draw the horizontal line
            g.DrawLine(new Pen(Color.White, 1), new Point(x, y - 5), new Point(x, y + 5));
        }

        /// <summary>
        /// Draw the current coordinates of the center point in the upper right corner
        /// </summary>
        private void DrawCoordinates(Graphics g)
        {
            Location l = GetMapCenter();

            Font font = new Font("Tahoma", 10, FontStyle.Bold);
            Rectangle rect = new Rectangle(Width - 120, 0, 120, font.Height);

            // g.FillRectangle(new SolidBrush(Color.FromArgb(100, 255, 255, 255)), rect);
            g.FillRectangle(Brushes.Black, rect);

            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            g.DrawString("" + l.X + ", " + l.Y, font, Brushes.White, rect, sf);
        }

        /// <summary>
        /// Draw a marker with the default colors.
        /// </summary>
        /// <param name="l"></param>
        /// <param name="text"></param>
        /// <param name="g"></param>
        private void DrawMarker(Location l, string text, Graphics g)
        {
            DrawMarker(l, text, Color.Yellow, Color.Black, g);
        }

        /// <summary>
        /// Draw a marker with the default text fill and outline colors.
        /// </summary>
        /// <param name="l"></param>
        /// <param name="text"></param>
        /// <param name="markerFill"></param>
        /// <param name="markerOutline"></param>
        /// <param name="g"></param>
        private void DrawMarker(Location l, string text, Color markerFill, Color markerOutline, Graphics g)
        {
            DrawMarker(l, text, markerFill, markerOutline, Color.White, Color.Black, g);
        }

        private void DrawMarker(Location l, string text, Color markerFill, Color markerOutline, Color textFill, Color textOutline, Graphics g)
        {
            DrawMarker(l, text, markerFill, markerOutline, textFill, textOutline, -1, g);
        }

        /// <summary>
        /// Draw a marker given the specifications.
        /// </summary>
        /// <param name="l"></param>
        /// <param name="text"></param>
        /// <param name="markerFill"></param>
        /// <param name="markerOutline"></param>
        /// <param name="textFill"></param>
        /// <param name="textOutline"></param>
        /// <param name="hpBar">if hpBar >= 0 && <= 100 draw an HP bar</param>
        /// <param name="g"></param>
        private void DrawMarker(Location l, string text, Color markerFill, Color markerOutline, Color textFill, Color textOutline, int hpBar, Graphics g)
        {
            // Convert to Tibia coors
            Point p = MapCoorsToPoint(l);

            // This array of points makes the marker
            Point[] points = {
                new Point(p.X - 3, p.Y - 25),
                new Point(p.X + 3, p.Y - 25),
                new Point(p.X + 3, p.Y - 20),
                new Point(p.X + 10, p.Y - 20),
                new Point(p.X, p.Y),
                new Point(p.X - 10, p.Y - 20),
                new Point(p.X - 3, p.Y - 20)
            };

            // Anti-aliased for nice effect
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            // Draw the marker
            g.FillPolygon(new SolidBrush(markerFill), points);
            g.DrawPolygon(new Pen(markerOutline), points);

            // The text font
            Font font = new Font("Tahoma", 8, FontStyle.Bold);

            // The rectangle to hold the text
            Rectangle rect = new Rectangle(p.X - 100,
                p.Y - (((hpBar >= 0 && hpBar <= 100) ? 33 : 27) + font.Height),
                200, font.Height);

            // Center the text
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;

            // Add "up" or "down" to the name
            if (l.Z != 0 && l.Z != currentZ)
                text += " (" + (currentZ - l.Z > 0 ? "+" : "") + (currentZ - l.Z) + ")";

            // Draw the outlined text
            DrawOutlinedText(text, font, new SolidBrush(textFill), new SolidBrush(textOutline), rect, sf, g);

            // Draw HP bar if needed
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            if (hpBar >= 0 && hpBar <= 100)
            {
                Rectangle hpOuter = new Rectangle(p.X - 14, p.Y - 27 - 4, 28, 4);
                Rectangle hpInner = new Rectangle(p.X - 13, p.Y - 26 - 4,
                    (int)(hpBar / 100.0 * 26), 2);
                g.FillRectangle(Brushes.Black, hpOuter);
                g.FillRectangle(new SolidBrush(Misc.HpPercentToColor(hpBar)), hpInner);
            }
        }

        /// <summary>
        /// Draw the specified text with an outline
        /// </summary>
        /// <param name="text"></param>
        /// <param name="font"></param>
        /// <param name="fill"></param>
        /// <param name="outline"></param>
        /// <param name="rect"></param>
        /// <param name="sf"></param>
        /// <param name="g"></param>
        private void DrawOutlinedText(string text, Font font, Brush fill, Brush outline, Rectangle rect, StringFormat sf, Graphics g)
        {
            // Draw the outline by offsetting the rectangle
            rect.Offset(-1, -1);
            g.DrawString(text, font, outline, rect, sf);
            rect.Offset(2, 0);
            g.DrawString(text, font, outline, rect, sf);
            rect.Offset(0, 2);
            g.DrawString(text, font, outline, rect, sf);
            rect.Offset(-2, 0);
            g.DrawString(text, font, outline, rect, sf);

            // Return to the original position and draw the fill
            rect.Offset(1, -1);
            g.DrawString(text, font, fill, rect, sf);
        }
        #endregion

        [Serializable]
        public class MapMarker
        {
            #region Properties
            private bool drawHPBar = true;
            private Location location;
            private string name;
            private int hpBar;
            private Creature creature = null;
            private Color colorMarkerFill = Color.Yellow;
            private Color colorMarkerOutline = Color.Black;
            private Color colorTextFill = Color.White;
            private Color colorTextOutline = Color.Black;

            public bool DrawHPBar
            {
                get { return drawHPBar; }
                set { drawHPBar = value; }
            }

            public Location Location
            {
                get { return location; }
                set { location = value; }
            }

            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            public int HPBar
            {
                get { return hpBar; }
                set { hpBar = value; }
            }

            public Creature Creature
            {
                get { return creature; }
                set { creature = value; }
            }

            public Color ColorMarkerFill
            {
                get { return colorMarkerFill; }
                set { colorMarkerFill = value; }
            }

            public Color ColorMarkerOutline
            {
                get { return colorMarkerOutline; }
                set { colorMarkerOutline = value; }
            }

            public Color ColorTextFill
            {
                get { return colorTextFill; }
                set { colorTextFill = value; }
            }

            public Color ColorTextOutline
            {
                get { return colorTextOutline; }
                set { colorTextOutline = value; }
            }
            #endregion

            public MapMarker() { }

            public MapMarker(Creature c) : this(c, true) { }

            public MapMarker(Creature c, bool drawHP)
            {
                drawHPBar = drawHP;
                creature = c;
                Update();
            }

            public MapMarker(string cname, Location loc)
            {
                name = cname;
                location = loc;
                drawHPBar = false;
            }

            public MapMarker(string cname, Location loc, byte hp)
            {
                name = cname;
                location = loc;
                hpBar = hp;
                drawHPBar = true;
            }

            public void Update()
            {
                if (creature != null && creature.Client != null && creature.Client.LoggedIn)
                {
                    name = creature.Name;
                    location = creature.Location;
                    hpBar = creature.HPBar;
                }
            }

            public void Update(Creature c)
            {
                name = c.Name;
                location = c.Location;
                hpBar = c.HPBar;
            }
        }
    }
}


text:
package ch.usi.inf.l3.sana.dcct.ast

import ch.usi.inf.l3.sana
import sana.primj._
import sana.tiny.types.Type
import sana.tiny.source.Position
import sana.tiny.symbols.Symbol
import sana.tiny.names.Name
import sana.primj.ast.Implicits._
import sana.primj.types.MethodType
import sana.tiny.modifiers.Flags

import sana.tiny.ast._
import sana.calcj.ast._
import sana.primj.ast._

trait TreeFactories extends sana.ooj.ast.TreeFactories {
  // TODO Copied from primj factories. Is there a nicer way to do it?
  def mkActionDef(ret: UseTree,
    name: Name, params: List[ValDefApi],
    body: Expr, pos: Option[Position] = None,
    symbol: Option[Symbol] = None): MethodDefApi = {
    val res = new MethodDef(ret, name, params, body)
    pos.foreach(res.pos = _)
    symbol.foreach( sym => {
      res.symbol = sym
      sym.owner.foreach(res.owner = _)
    })
    val tys = params.flatMap(_.tpe)
    ret.tpe.foreach(t => res.tpe = MethodType(t, tys))
    res
  }

  def mkArrayDef(name: Name, indices: List[ValDefApi],
      properties: List[ValDefApi], symbol: Option[Symbol] = None) : ArrayDefApi = {
    val res = new ArrayDef(name, indices, properties)
    symbol.foreach ( sym => {
      res.symbol = sym
      sym.owner.foreach(res.owner = _)
    })
    res
  }

  def mkForEach(entityVar: ValDefApi, whereExpr: Expr, body: BlockApi,
    symbol: Option[Symbol] = None): ForEach = {
    val res = new ForEach(entityVar, whereExpr, body)
    symbol.foreach( sym => {
      res.symbol = sym
      sym.owner.foreach(res.owner = _)
    })
    res
  }
}

object TreeFactories extends TreeFactories


text:
use std::cmp;
use std::ops;
use std::fmt;

use num;
use num::{Num, Zero, One, Signed};

use num_ops;
use bit_ops;

use super::parse_decimal_error::ParseDecimalError;

const NUM_SIGNIFICANT_DIGITS: u32 = 7;

const MIN_EXPONENT: i32 = -101;
const MAX_EXPONENT: i32 = 90;

const MIN_COEFFICIENT: u32 = 0;
const MAX_COEFFICIENT: u32 = 9999999;

/// Represents a 32-bit decimal number according to the [IEEE 754-2008 standard]
/// (https://en.wikipedia.org/wiki/Decimal32_floating-point_format).
///
/// Decimal32 supports 7 decimal digits of precision and an exponent range of −95 to +96, i.e.
/// ±0.000000×10^−95 to ±9.999999×10^96. (Equivalently, ±0000000×10^−101 to ±9999999×10^90.)
#[allow(non_camel_case_types)]
#[derive(Clone, Copy)]
pub struct d32 {
    bits: u32,
}

pub mod consts {
    use super::d32;

    pub const ZERO: d32 = d32 { bits: 0b0_01100101_00000000000000000000000 };
    pub const ONE: d32 = d32 { bits: 0b0_01100101_00000000000000000000001 };

    pub const MAX_VALUE: d32 = d32 { bits: 0b0_11_10111111_110001001011001111111 };
    pub const MIN_VALUE: d32 = d32 { bits: 0b1_11_10111111_110001001011001111111 };

    pub const INFINITY: d32 = d32 { bits: 0b0_11110_000000_00000000000000000000 };
    pub const NEG_INFINITY: d32 = d32 { bits: 0b1_11110_000000_00000000000000000000 };
    pub const QNAN: d32 = d32 { bits: 0b0_11111_000000_00000000000000000000 };
    pub const SNAN: d32 = d32 { bits: 0b0_11111_100000_00000000000000000000 };
    pub const NAN: d32 = QNAN;
}

impl d32 {
    /// Creates and initializes a d32 representation of zero.
    pub fn new() -> d32 {
        d32::zero()
    }

    /// Creates and initialize a decimal32 from its significant parts: the sign, exponent, and
    /// coefficient, respectively.
    ///
    /// If the exponent is out of range (less than -101 or greater than 90), the data will be
    /// shifted in an attempt to be fit into the 32-bit representation. If the shifted components
    /// still do not fit, the result may end in an "unexpected" value (i.e. ±infinity or zero)
    pub fn from_data(is_negative: bool, exponent: i32, coefficient: u32) -> d32 {
        if exponent < MIN_EXPONENT {
            let shift = MIN_EXPONENT - exponent;
            let shifted_components = shift_exponent(coefficient, exponent, shift);
            match shifted_components {
                // Retry with shifted exponent
                Some((shifted_exponent, shifted_coefficient)) => {
                    d32::from_data(is_negative, shifted_exponent, shifted_coefficient)
                }
                None => consts::ZERO,
            }
        } else if exponent > MAX_EXPONENT {
            let shift = MAX_EXPONENT - exponent;
            let shifted_components = shift_exponent(coefficient, exponent, shift);
            match shifted_components {
                // Retry with shifted exponent
                Some((shifted_exponent, shifted_coefficient)) => {
                    d32::from_data(is_negative, shifted_exponent, shifted_coefficient)
                }
                None => {
                    if is_negative {
                        consts::NEG_INFINITY
                    } else {
                        consts::INFINITY
                    }
                }
            }
        } else if coefficient > MAX_COEFFICIENT {
            if is_negative {
                consts::NEG_INFINITY
            } else {
                consts::INFINITY
            }
        } else {
            let sign_field = (if is_negative { 1 } else { 0 }) << 31;
            let biased_exponent = (exponent - MIN_EXPONENT) as u32;

            let implicit_100_indicator_field;
            let exponent_field;
            let coefficient_field;
            if coefficient < 8_388_608 {
                implicit_100_indicator_field = 0;
                exponent_field = biased_exponent << 23;
                coefficient_field = coefficient;
            } else {
                // 8,388,608 is the first number that requires the implicit (100) in the coefficient
                implicit_100_indicator_field = 0b11 << 29;
                exponent_field = biased_exponent << 21;
                // remove the implicit 100 since it is not stored explicitly
                let implicit_100 = 0b100_0_0000000000_0000000000;
                coefficient_field = coefficient - implicit_100;
            }
            d32 {
                bits: sign_field + implicit_100_indicator_field + exponent_field +
                      coefficient_field,
            }
        }
    }

    /// Returns a d32 with the exact bits passed in through `data`.
    pub fn from_bin(data: u32) -> d32 {
        d32 { bits: data }
    }

    pub fn to_f64(&self) -> f64 {
        let (is_negative, exponent, coefficient) = self.get_data();
        let multiplier = if is_negative { -1.0 } else { 1.0 };
        multiplier * 10f64.powi(exponent) * (coefficient as f64)
    }

    /// Returns true if the combination field signifies infinity, and false otherwise.
    pub fn is_infinity(&self) -> bool {
        self.get_combination_field() == 0b11110
    }

    /// Returns true if the combination field signifies infinity and the sign is positive, and false
    /// otherwise.
    pub fn is_pos_infinity(&self) -> bool {
        self.is_positive() && self.is_infinity()
    }

    /// Returns true if the combination field signifies infinity and the sign is negative, and false
    /// otherwise.
    pub fn is_neg_infinity(&self) -> bool {
        self.is_negative() && self.is_infinity()
    }

    /// Returns true if the combination field signifies NaN, and false otherwise.
    pub fn is_nan(&self) -> bool {
        self.get_combination_field() == 0b11111
    }

    /// Returns the three defining pieces of the decimal - the sign (true if negative), the
    /// exponent, and the coefficient, respectively.
    ///
    /// Do not expect well-behaved results if this decimal is NaN or infinity.
    pub fn get_data(&self) -> (bool, i32, u32) {
        // While it would be nice to make this method simply return (self.get_sign(),
        // self.get_exponent(), and self.get_coefficient()), that would require two duplicate checks
        // on the combination field.
        let sign = self.get_sign_field() != 0;
        let (exponent, coefficient) = if self.get_first_two_bits_combination_field() < 3 {
            ((self.get_normal_exponent() as i32) + MIN_EXPONENT, self.get_normal_coefficient())
        } else {
            // self.get_second_two_bits_combination_field() < 3
            ((self.get_shifted_exponent() as i32) + MIN_EXPONENT, self.get_shifted_coefficient())
        };
        (sign, exponent, coefficient)
    }

    /// Returns this d32's exponent value.
    ///
    /// Do not expect well-behaved results if this decimal is NaN or infinity.
    pub fn get_exponent(&self) -> i32 {
        let exponent = if self.get_first_two_bits_combination_field() < 3 {
            self.get_normal_exponent()
        } else {
            // self.get_second_two_bits_combination_field() < 3
            self.get_shifted_exponent()
        };
        (exponent as i32) + MIN_EXPONENT
    }

    /// Returns this d32's coefficient value.
    ///
    /// Do not expect well-behaved results if this decimal is NaN or infinity.
    pub fn get_coefficient(&self) -> u32 {
        if self.get_first_two_bits_combination_field() < 3 {
            self.get_normal_coefficient()
        } else {
            // self.get_second_two_bits_combination_field() < 3
            self.get_shifted_coefficient()
        }
    }

    fn get_sign_field(&self) -> u32 {
        bit_ops::get_bit(self.bits, 31)
    }

    fn get_combination_field(&self) -> u32 {
        bit_ops::get_bits(self.bits, 26, 30)
    }

    fn get_first_two_bits_combination_field(&self) -> u32 {
        let combination_field = self.get_combination_field();
        bit_ops::get_bits(combination_field, 3, 5)
    }

    fn get_second_two_bits_combination_field(&self) -> u32 {
        let combination_field = self.get_combination_field();
        bit_ops::get_bits(combination_field, 1, 3)
    }

    fn get_normal_exponent(&self) -> u32 {
        bit_ops::get_bits(self.bits, 23, 30)
    }

    fn get_shifted_exponent(&self) -> u32 {
        bit_ops::get_bits(self.bits, 21, 28)
    }

    fn get_normal_coefficient(&self) -> u32 {
        bit_ops::get_bits(self.bits, 0, 22)
    }

    fn get_shifted_coefficient(&self) -> u32 {
        let implicit_100 = 0b100_0_00000_00000_00000_00000;
        implicit_100 + bit_ops::get_bits(self.bits, 0, 20)
    }
}

fn shift_exponent(coefficient: u32, exponent: i32, shift: i32) -> Option<(i32, u32)> {
    let shifted_exponent = exponent + shift;
    let pow_shift = num::pow(10u32, num::abs(shift) as usize);
    // TODO: not happy about using Option here
    let shifted_coefficient = if shift < 0 {
        coefficient.checked_mul(pow_shift)
    } else {
        coefficient.checked_div(pow_shift)
    };
    match shifted_coefficient {
        Some(shifted_coefficient) => Some((shifted_exponent, shifted_coefficient)),
        None => None,
    }
}

fn to_common_exponent(left: &d32, right: &d32) -> (bool, u32, bool, u32, i32) {
    use std::cmp::Ordering;

    let (left_neg, left_exponent, left_coefficient) = left.get_data();
    let (right_neg, right_exponent, right_coefficient) = right.get_data();
    match left_exponent.cmp(&right_exponent) {
        Ordering::Equal => {
            (left_neg, left_coefficient, right_neg, right_coefficient, left_exponent)
        }
        Ordering::Less => {
            let shift = num::pow(10u32, (right_exponent - left_exponent) as usize);
            (left_neg, left_coefficient, right_neg, right_coefficient * shift, left_exponent)
        }
        Ordering::Greater => {
            let shift = num::pow(10u32, (left_exponent - right_exponent) as usize);
            (left_neg, left_coefficient * shift, right_neg, right_coefficient, right_exponent)
        }
    }
}

impl Default for d32 {
    fn default() -> d32 {
        d32::zero()
    }
}

impl cmp::PartialEq for d32 {
    fn eq(&self, other: &d32) -> bool {
        if self.is_zero() && other.is_zero() {
            return true;
        }
        if self.get_sign_field() != other.get_sign_field() {
            return false;
        }
        if self.is_infinity() && other.is_infinity() {
            assert_eq!(self.get_sign_field(), other.get_sign_field());
            return true;
        }
        if self.is_nan() && other.is_nan() {
            return false;
        }
        let (left_is_neg, left_coefficient, right_is_neg, right_coefficient, _) =
            to_common_exponent(&self, &other);
        left_is_neg == right_is_neg && left_coefficient == right_coefficient
    }
}

impl cmp::PartialOrd for d32 {
    fn partial_cmp(&self, other: &d32) -> Option<cmp::Ordering> {
        // NaN special case
        if self.is_nan() || other.is_nan() {
            // if either party is NaN, then the result is None (uncomparable)
            return None;
        }
        // Zero special cases (since zero's sign bit is irrelevant)
        if self.is_zero() {
            if other.is_zero() {
                return Some(cmp::Ordering::Equal);
            } else if other.is_positive() {
                return Some(cmp::Ordering::Less);
            } else {
                return Some(cmp::Ordering::Greater);
            }
        }
        if other.is_zero() {
            assert!(!self.is_zero());
            if self.is_positive() {
                return Some(cmp::Ordering::Greater);
            } else {
                return Some(cmp::Ordering::Less);
            }
        }
        // Normal case
        let lhs_sign_field = self.get_sign_field();
        let rhs_sign_field = other.get_sign_field();
        // panic!("{:?}, {:?}, {:?}", lhs_sign_field, rhs_sign_field, lhs_sign_field.partial_cmp(&rhs_sign_field));
        if lhs_sign_field != rhs_sign_field {
            // defer to the sign field comparison
            return rhs_sign_field.partial_cmp(&lhs_sign_field);
        }
        // Infinity special cases
        if self.is_infinity() && other.is_infinity() {
            assert!(lhs_sign_field == rhs_sign_field);
            return Some(cmp::Ordering::Equal);
        }
        let diff = (*self) - (*other);
        if diff.is_zero() {
            Some(cmp::Ordering::Equal)
        } else {
            if diff.is_positive() {
                Some(cmp::Ordering::Greater)
            } else {
                Some(cmp::Ordering::Less)
            }
        }
    }
}

impl ops::Neg for d32 {
    type Output = d32;

    fn neg(self) -> d32 {
        use super::super::bit_ops;

        // Flip the MSB (most significant bit)
        let msb_flipped = bit_ops::toggle_bit(self.bits, 31);

        d32 { bits: msb_flipped }
    }
}

impl ops::Add<d32> for d32 {
    type Output = d32;

    fn add(self, other: d32) -> d32 {
        if self.is_nan() || other.is_nan() {
            // NaN + anything = NaN
            consts::NAN
        } else if self.is_infinity() {
            if self.is_positive() {
                if other.is_neg_infinity() {
                    // Infinity + -Infinity = NaN
                    consts::NAN
                } else {
                    // Infinity + normal values = Infinity
                    consts::INFINITY
                }
            } else {
                if other.is_pos_infinity() {
                    // -Infinity + Infinity = NaN
                    consts::NAN
                } else {
                    // -Infinity + normal values = -Infinity
                    consts::NEG_INFINITY
                }
            }
        } else if other.is_infinity() {
            assert!(!self.is_infinity());
            if other.is_positive() {
                // normal values + Infinity = Infinity
                consts::INFINITY
            } else {
                // normal values + -Infinity = -Infinity
                consts::NEG_INFINITY
            }
        } else {
            // Normal case
            let (left_is_neg, left_coefficient, right_is_neg, right_coefficient, exponent) =
                to_common_exponent(&self, &other);

            let signed_left_coefficient = if left_is_neg {
                -(left_coefficient as i32)
            } else {
                (left_coefficient as i32)
            };
            let signed_right_coefficient = if right_is_neg {
                -(right_coefficient as i32)
            } else {
                (right_coefficient as i32)
            };

            let signed_sum_coefficient: i32 = signed_left_coefficient + signed_right_coefficient;
            let sum_is_negative = signed_sum_coefficient < 0;
            let unsigned_sum_coefficient = num::abs(signed_sum_coefficient) as u32;
            d32::from_data(sum_is_negative, exponent, unsigned_sum_coefficient)
        }
    }
}

impl ops::Sub<d32> for d32 {
    type Output = d32;

    fn sub(self, other: d32) -> d32 {
        self + (-other)
    }
}

impl ops::Mul<d32> for d32 {
    type Output = d32;

    fn mul(self, other: d32) -> d32 {
        use num::Signed;

        if self.is_nan() || other.is_nan() {
            // NaN * anything = NaN
            consts::NAN
        } else if self.is_infinity() {
            if other.is_zero() {
                // Inf * 0 = NaN
                consts::NAN
            } else {
                if self.is_positive() {
                    if other.is_positive() {
                        // Inf * anything positive = Inf
                        consts::INFINITY
                    } else {
                        // Inf * anything negative = -Inf
                        consts::NEG_INFINITY
                    }
                } else {
                    if other.is_positive() {
                        // -Inf * anything positive = -Inf
                        consts::NEG_INFINITY
                    } else {
                        // -Inf * anything negative = Inf
                        consts::INFINITY
                    }
                }
            }
        } else if other.is_infinity() {
            if self.is_zero() {
                // 0 * Inf = NaN
                consts::NAN
            } else {
                if other.is_positive() {
                    if self.is_positive() {
                        // anything positive * Inf = Inf
                        consts::INFINITY
                    } else {
                        // anything negative * Inf = -Inf
                        consts::NEG_INFINITY
                    }
                } else {
                    if self.is_positive() {
                        // anything positive * -Inf = -Inf
                        consts::NEG_INFINITY
                    } else {
                        // anything negative * -Inf = Inf
                        consts::INFINITY
                    }
                }
            }
        } else if self.is_zero() || other.is_zero() {
            // 0 * normal values = 0
            consts::ZERO
        } else if self == consts::ONE {
            // 1 * a normal value = the normal value
            other
        } else if other == consts::ONE {
            // a normal value * 1 = the normal value
            self
        } else {
            // Normal case
            let coefficient = self.get_coefficient() * other.get_coefficient();
            let exponent = self.get_exponent() + other.get_exponent();
            let sign = self.get_sign_field() ^ other.get_sign_field();
            d32::from_data(sign != 0, exponent, coefficient)
        }
    }
}

impl ops::Div<d32> for d32 {
    type Output = d32;

    fn div(self, other: d32) -> d32 {
        let dividend = self;
        let divisor = other;

        if dividend.is_nan() || divisor.is_nan() {
            consts::NAN
        } else if divisor.is_zero() {
            // Choosing to return NaN as opposed to Infinity
            consts::NAN
        } else if dividend.is_zero() {
            consts::ZERO
        } else if dividend.is_infinity() {
            if divisor.is_infinity() {
                // infinity / infinity = undefined
                consts::NAN
            } else {
                // infinity / +anything = +infinity
                // infinity / -anything = -infinity
                let sign_field = dividend.get_sign_field() ^ divisor.get_sign_field();
                let is_negative = sign_field == 1;
                if is_negative {
                    consts::NEG_INFINITY
                } else {
                    consts::INFINITY
                }
            }
        } else if divisor.is_infinity() {
            // assert!(!dividend.is_nan() && !dividend.is_infinity());
            // anything / infinity = 0
            consts::ZERO
        } else {
            // Long division
            use num_ops::num_decimal_digits;

            let mut adjust = 0;
            let mut dividend_coefficient = dividend.get_coefficient();
            let mut divisor_coefficient = divisor.get_coefficient();
            // Adjust the coefficients such that the dividend's coefficient is greater than or equal to the divisor's coefficient
            // TODO: could this be optimized to take one calculation?
            while dividend_coefficient < divisor_coefficient {
                dividend_coefficient *= 10;
                adjust += 1;
            }
            while divisor_coefficient >= (divisor_coefficient * 10) {
                divisor_coefficient *= 10;
                adjust -= 1;
            }

            let mut result_coefficient: u32 = 0;
            let mut division_complete = false;
            while !division_complete {
                while divisor_coefficient <= dividend_coefficient {
                    dividend_coefficient -= divisor_coefficient;
                    result_coefficient += 1;
                }
                if (dividend_coefficient == 0 && adjust >= 0) ||
                    // TODO: benchmark the difference between calculating digits vs. between 1000000 and 9999999
                   (num_decimal_digits(result_coefficient as i32) == NUM_SIGNIFICANT_DIGITS) {
                    division_complete = true;
                } else {
                    result_coefficient *= 10;
                    dividend_coefficient *= 10;
                    adjust += 1;
                }
            }

            let result_exponent = dividend.get_exponent() - divisor.get_exponent() - adjust;
            let result_sign_field = dividend.get_sign_field() ^ divisor.get_sign_field();
            let result_is_negative = result_sign_field == 1;

            let remainder: f32 = (dividend_coefficient as f32) / (divisor_coefficient as f32);
            let signed_remainder = remainder * (if result_is_negative { -1.0 } else { 1.0 });
            let rounded_coefficient = num_ops::round_away(result_coefficient, signed_remainder);

            let rounded = d32::from_data(result_is_negative, result_exponent, rounded_coefficient);
            rounded
        }
    }
}

impl ops::Rem<d32> for d32 {
    type Output = d32;

    fn rem(self, other: d32) -> d32 {
        self // TODO
    }
}

impl Num for d32 {
    type FromStrRadixErr = ParseDecimalError;

    fn from_str_radix(s: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
        Ok(d32::zero()) // TODO
    }
}

impl Zero for d32 {
    fn zero() -> d32 {
        consts::ZERO
    }

    fn is_zero(&self) -> bool {
        (!self.is_infinity() && !self.is_nan()) && self.get_coefficient() == 0
    }
}

impl One for d32 {
    fn one() -> d32 {
        consts::ONE
    }
}

impl num::Signed for d32 {
    /// Returns the absolute value of this decimal, by returning a copy of this decimal with the
    /// sign bit turned off.
    fn abs(&self) -> d32 {
        let with_sign_bit_off = bit_ops::clear_bit(self.bits, 31);
        d32 { bits: with_sign_bit_off }
    }

    fn abs_sub(&self, other: &d32) -> d32 {
        // TODO
        // The positive difference of two numbers.
        // Returns zero if the number is less than or equal to other, otherwise the difference between self and other is returned.
        *self
    }

    /// Returns the sign of this decimal as a decimal.
    ///
    /// - 1.0 if the decimal is positive, +0.0 or INFINITY.
    /// - -1.0 if the decimal is negative, -0.0 or -INFINITY.
    /// - NaN if the decimal is NaN.
    fn signum(&self) -> d32 {
        if self.is_nan() {
            self.clone()
        } else if self.is_positive() {
            d32::one()
        } else {
            -d32::one()
        }
    }

    /// Returns true if this decimal is positive, false otherwise.
    ///
    /// Note: Zero and NaN are neither positive or negative.
    fn is_positive(&self) -> bool {
        !self.is_nan() && !self.is_zero() && self.get_sign_field() == 0
    }

    /// Returns true if this decimal is negative, false otherwise.
    ///
    /// Note: Zero and NaN are neither positive or negative.
    fn is_negative(&self) -> bool {
        !self.is_nan() && !self.is_zero() && self.get_sign_field() != 0
    }
}

impl fmt::Debug for d32 {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        let debug_str = if self.is_infinity() {
            if self.is_positive() {
                "d32::consts::INFINITY".to_string()
            } else {
                "d32::consts::NEG_INFINITY".to_string()
            }
        } else if self.is_nan() {
            "d32::consts::NAN".to_string()
        } else {
            let (is_negative, exponent, coefficient) = self.get_data();
            format!("d32 {{ is_negative: {}, exponent: {}, coefficient: {} }}",
                    is_negative,
                    exponent,
                    coefficient)
        };

        write!(formatter, "{}", debug_str)
    }
}

// let width = match formatter.width() {
//     Some(width) => width,
//     None => 0
// };
// let precision = match formatter.precision() {
//     Some(precision) => precision,
//     None => 0
// };
impl fmt::Display for d32 {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        use super::super::zero_pad::{pad_right, pad_left};

        let (is_negative, exponent, coefficient) = self.get_data();

        let digits = coefficient.to_string();
        let num_significant_digits = digits.len() as i32;

        let sign = if is_negative {
            "-".to_string()
        } else {
            "".to_string()
        };

        let pos_decimal_str = if exponent >= 0 {
            pad_right(&digits, exponent as usize)
        } else if exponent > -num_significant_digits {
            let num_left_digits = (num_significant_digits + exponent) as usize;
            let left = digits[0..num_left_digits].to_string();
            let right = digits[num_left_digits..].to_string();
            left + "." + &right
        } else {
            let right = pad_left(&digits, ((-exponent) - num_significant_digits) as usize);
            "0.".to_string() + &right
        };

        let decimal_str = sign + &pos_decimal_str;
        write!(formatter, "{}", decimal_str)
    }
}

impl fmt::LowerExp for d32 {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        unimplemented!() // TODO
    }
}

impl fmt::UpperExp for d32 {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        unimplemented!() // TODO
    }
}

impl fmt::Binary for d32 {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        self.bits.fmt(formatter)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_exponent() {
        let zero = d32 {
            // 0+101 = 101 =>
            //      0b01100101
            bits: 0b0_01100101_00000000000000000000000,
        };
        let expected = 0;
        let actual = zero.get_exponent();
        assert_eq!(expected, actual);

        let one = d32 {
            // 1+101 = 102 =>
            //     0b_01100110
            bits: 0b0_01100110_00000000000000000000000,
        };
        let expected = 1;
        let actual = one.get_exponent();
        assert_eq!(expected, actual);

        let neg_one = d32 {
            // -1+101 = 100
            //   => 0b01100101
            bits: 0b0_01100100_00000000000000000000000,
        };
        let expected = -1;
        let actual = neg_one.get_exponent();
        assert_eq!(expected, actual);

        let ninety = d32 {
            // 90+101 = 191 =>
            //      0b10111111
            bits: 0b0_10111111_00000000000000000000000,
        };
        let expected = 90;
        let actual = ninety.get_exponent();
        assert_eq!(expected, actual);

        let neg_101 = d32 {
            // -101+101 = 0 =>
            //      0b00000000
            bits: 0b0_00000000_00000000000000000000000,
        };
        let expected = -101;
        let actual = neg_101.get_exponent();
        assert_eq!(expected, actual);

        let shifted_exponent = d32 {
            // -37+101 = 64 =>
            //         0b01000000
            bits: 0b0_11_01000000_000000000000000000000,
        };
        let expected = -37;
        let actual = shifted_exponent.get_exponent();
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_get_coefficient() {
        let zero = d32 { bits: 0b0_0000000_00000000000000000000000 };
        let expected = 0;
        let actual = zero.get_coefficient();
        assert_eq!(expected, actual);

        let one = d32 { bits: 0b0_0000000_00000000000000000000001 };
        let expected = 1;
        let actual = one.get_coefficient();
        assert_eq!(expected, actual);

        let eighty = d32 { bits: 0b0_00000000_00000000000000001010000 };
        let expected = 80;
        let actual = eighty.get_coefficient();
        assert_eq!(expected, actual);

        let first_24th_bit = d32 { bits: 0b0_11_00000000_000000000000000000000 };
        let expected = 8388608;
        let actual = first_24th_bit.get_coefficient();
        assert_eq!(expected, actual);

        let max = d32 { bits: 0b0_11_00000000_110001001011001111111 };
        let expected = 9_999_999;
        let actual = max.get_coefficient();
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_eq() {
        let zero1 = d32::from_data(true, 0, 0);
        let zero2 = d32::from_data(false, 11, 0);
        let zero3 = d32::from_data(true, 90, 0);
        let zero4 = d32::from_data(false, -101, 0);
        assert_eq!(zero1, zero2);
        assert_eq!(zero2, zero3);
        assert_eq!(zero3, zero4);
        assert_eq!(zero4, zero1);

        let one1 = d32::from_data(false, 0, 1);
        let one2 = d32::from_data(false, -1, 10);
        let one3 = d32::from_data(false, -2, 100);
        let one4 = d32::from_data(false, -3, 1000);
        assert_eq!(one1, one2);
        assert_eq!(one2, one3);
        assert_eq!(one3, one4);
        assert_eq!(one4, one1);

        let hundred1 = d32::from_data(false, 1, 100);
        let hundred2 = d32::from_data(false, 2, 10);
        let hundred3 = d32::from_data(false, 3, 1);
        assert_eq!(hundred1, hundred2);
        assert_eq!(hundred2, hundred3);
        assert_eq!(hundred3, hundred1);

        let nan = consts::NAN;
        assert!(nan != nan);

        let pos_infinity = consts::INFINITY;
        assert_eq!(pos_infinity, pos_infinity);

        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(neg_infinity, neg_infinity);
    }

    #[test]
    fn test_from_data_overflow() {
        let expected = d32::from_data(false, 90, 10);
        let actual = d32::from_data(false, 91, 1);
        assert_eq!(expected, actual);

        let expected = d32::from_data(false, 90, 1090000);
        let actual = d32::from_data(false, 94, 109);
        assert_eq!(expected, actual);

        let expected = d32::from_data(false, -101, 1);
        let actual = d32::from_data(false, -102, 10);
        assert_eq!(expected, actual);

        let expected = d32::from_data(true, -101, 1);
        let actual = d32::from_data(true, -102, 10);
        assert_eq!(expected, actual);

        let expected = d32::from_data(false, -101, 0);
        let actual = d32::from_data(false, -102, 1);
        assert_eq!(expected, actual);

        let expected = consts::ZERO;
        let actual = d32::from_data(false, -106, 1949);
        assert_eq!(expected, actual);

        let expected = consts::INFINITY;
        let actual = d32::from_data(false, 94, 9999999);
        assert_eq!(expected, actual);

        let expected = consts::NEG_INFINITY;
        let actual = d32::from_data(true, 94, 9999999);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_sign_check() {
        use num::Signed;

        let one_hundred = d32::from_data(false, 1, 100);
        assert!(one_hundred.is_positive());
        assert!(!one_hundred.is_negative());

        let neg_one_hundred = d32::from_data(true, 1, 100);
        assert!(neg_one_hundred.is_negative());
        assert!(!neg_one_hundred.is_positive());

        let zero1 = d32::from_data(true, 0, 0);
        let zero2 = d32::from_data(false, 11, 0);
        assert!(!zero1.is_positive());
        assert!(!zero1.is_negative());
        assert!(!zero2.is_positive());
        assert!(!zero2.is_negative());

        let nan = consts::NAN;
        assert!(!nan.is_positive());
        assert!(!nan.is_negative());

        let pos_infinity = consts::INFINITY;
        assert!(pos_infinity.is_positive());
        assert!(!pos_infinity.is_negative());
        assert!(pos_infinity.is_pos_infinity());
        assert!(!pos_infinity.is_neg_infinity());

        let neg_infinity = consts::NEG_INFINITY;
        assert!(neg_infinity.is_negative());
        assert!(!neg_infinity.is_positive());
        assert!(neg_infinity.is_neg_infinity());
        assert!(!neg_infinity.is_pos_infinity());
    }

    #[test]
    fn test_ord() {
        let zero1 = d32::from_data(true, 0, 0);
        let zero2 = d32::from_data(false, 11, 0);
        assert!(!(zero1 < zero2));
        assert!(!(zero1 > zero2));
        assert!(zero1 >= zero2);
        assert!(zero1 <= zero2);
        assert!(zero1 >= zero1);

        let one_hundred = d32::from_data(false, 1, 100);
        assert!(zero1 < one_hundred);
        assert!(zero1 <= one_hundred);

        let neg_one_hundred = d32::from_data(true, 1, 100);
        assert!(zero1 > neg_one_hundred);
        assert!(zero1 >= neg_one_hundred);
        assert!(one_hundred >= neg_one_hundred);
        assert!(one_hundred > neg_one_hundred);
        assert!(neg_one_hundred < one_hundred);
        assert!(neg_one_hundred <= one_hundred);

        let nan = consts::NAN;
        assert!(!(nan < nan));
        assert!(!(nan <= nan));
        assert!(!(nan > nan));
        assert!(!(nan >= nan));

        let pos_infinity = consts::INFINITY;
        assert!(pos_infinity >= pos_infinity);

        let neg_infinity = consts::NEG_INFINITY;
        assert!(neg_infinity < pos_infinity);
        assert!(neg_infinity <= pos_infinity);
    }

    #[test]
    fn test_abs() {
        use num::Signed;

        let zero = consts::ZERO;
        assert_eq!(zero, zero.abs());

        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(pos_infinity, pos_infinity.abs());
        assert_eq!(pos_infinity, neg_infinity.abs());

        let one = consts::ONE;
        let neg_one = d32::from_data(true, 0, 1);
        assert_eq!(one, one.abs());
        assert_eq!(one, neg_one.abs());

        let one_thousand_point_four = d32::from_data(false, -1, 10004);
        let neg_one_thousand_point_four = d32::from_data(true, -1, 10004);
        assert_eq!(one_thousand_point_four, one_thousand_point_four.abs());
        assert_eq!(one_thousand_point_four, neg_one_thousand_point_four.abs());
    }

    #[test]
    fn test_neg() {
        let zero = consts::ZERO;
        assert_eq!(zero, -zero);

        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(pos_infinity, -neg_infinity);
        assert_eq!(neg_infinity, -pos_infinity);

        let one = consts::ONE;
        let neg_one = d32::from_data(true, 0, 1);
        assert_eq!(neg_one, -one);

        let one_thousand_point_four = d32::from_data(false, -1, 10004);
        let neg_one_thousand_point_four = d32::from_data(true, -1, 10004);
        assert_eq!(neg_one_thousand_point_four, -one_thousand_point_four);
    }

    #[test]
    fn test_add() {
        // TODO: test adding +0 and -0 to infinity
        let zero = consts::ZERO;
        let one = consts::ONE;
        assert_eq!(one, zero + one);

        let two1 = d32::from_data(false, -1, 20);
        assert_eq!(two1, one + one);

        let two2 = d32::from_data(false, -2, 200);
        assert_eq!(two2, one + one);

        let eighteen = d32::from_data(false, -2, 1800);
        let mut sum = consts::ZERO;
        for _ in 0..18 {
            sum = sum + one;
        }
        assert_eq!(eighteen, sum);

        assert!((consts::MAX_VALUE + consts::MAX_VALUE).is_infinity());
        assert!((consts::MIN_VALUE + consts::MIN_VALUE).is_neg_infinity());

        // special values
        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(pos_infinity, pos_infinity + pos_infinity);
        assert_eq!(neg_infinity, neg_infinity + neg_infinity);
        assert!((pos_infinity + neg_infinity).is_nan());
        assert!((neg_infinity + pos_infinity).is_nan());

        let nan = consts::NAN;
        assert!((nan + zero).is_nan());
        assert!((nan + one).is_nan());
        assert!((nan + nan).is_nan());
    }

    #[test]
    fn test_sub() {
        let zero = consts::ZERO;
        let one = consts::ONE;
        assert_eq!(one, one - zero);

        assert_eq!(zero, one - one);

        let eighteen = d32::from_data(false, -2, 1800);
        let mut acc = eighteen;
        for _ in 0..18 {
            acc = acc - one;
        }
        assert_eq!(zero, acc);

        assert_eq!(zero, consts::MAX_VALUE - consts::MAX_VALUE);
        assert_eq!(zero, consts::MIN_VALUE - consts::MIN_VALUE);

        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(pos_infinity, pos_infinity - neg_infinity);
        assert_eq!(neg_infinity, neg_infinity - pos_infinity);
        assert!((pos_infinity - pos_infinity).is_nan());
        assert!((neg_infinity - neg_infinity).is_nan());

        let nan = consts::NAN;
        assert!((nan - zero).is_nan());
        assert!((nan - one).is_nan());
        assert!((nan - nan).is_nan());
    }

    #[test]
    fn test_mul() {
        let zero = consts::ZERO;
        assert_eq!(zero, zero * zero);

        let one = consts::ONE;
        assert_eq!(zero, one * zero);
        assert_eq!(one, one * one);

        let two = d32::from_data(false, 0, 2);
        let four = d32::from_data(false, 0, 4);
        assert_eq!(four, two * two);

        let eighteen = d32::from_data(false, -2, 1800);
        assert_eq!(eighteen, one * eighteen);
        assert_eq!(eighteen, eighteen * one);

        let neg_seventy_two = d32::from_data(true, 0, 72);
        assert_eq!(neg_seventy_two, -four * eighteen);

        let three_hundred_twenty_four = d32::from_data(false, 0, 324);
        assert_eq!(three_hundred_twenty_four, eighteen * eighteen);
        assert_eq!(three_hundred_twenty_four, one * eighteen * eighteen);
        assert_eq!(three_hundred_twenty_four,
                   one * eighteen * one * eighteen * one);
        assert_eq!(zero, one * eighteen * eighteen * zero);

        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(neg_infinity, pos_infinity * neg_infinity);
        assert_eq!(neg_infinity, neg_infinity * pos_infinity);
        assert_eq!(pos_infinity, neg_infinity * neg_infinity);
        assert_eq!(pos_infinity, pos_infinity * two);
        assert_eq!(neg_infinity, pos_infinity * -two);
        assert!((pos_infinity * zero).is_nan());
        assert!((zero * neg_infinity).is_nan());

        let nan = consts::NAN;
        assert!((nan * zero).is_nan());
        assert!((nan * one).is_nan());
        assert!((nan * -four).is_nan());
        assert!((nan * nan).is_nan());
    }

    #[test]
    fn test_div() {
        use num::Zero;

        let zero = consts::ZERO;
        let one = consts::ONE;
        assert_eq!(zero, zero / one);
        assert_eq!(one, one / one);

        let two = d32::from_data(false, 0, 2);
        let four = d32::from_data(false, 0, 4);
        assert_eq!(two, four / two);

        let one_half = d32::from_data(false, -1, 05);
        assert_eq!(one_half, two / four);

        let three = d32::from_data(false, 0, 3);
        let one_third = d32::from_data(false, -7, 3333333);
        assert_eq!(one_third, one / three);

        let two_thirds_rounded = d32::from_data(false, -7, 6666667);
        assert_eq!(two_thirds_rounded, two / three);

        let thirteen = d32::from_data(false, 0, 13);
        assert_eq!(thirteen, thirteen / one);

        let one_hundred_two = d32::from_data(false, 0, 102);
        let expected = d32::from_data(false, -7, 1274510);
        assert_eq!(expected, thirteen / one_hundred_two);

        let pos_infinity = consts::INFINITY;
        let neg_infinity = consts::NEG_INFINITY;
        assert_eq!(zero, two / pos_infinity);
        assert_eq!(zero, two / neg_infinity);
        assert_eq!(neg_infinity, neg_infinity / two);
        assert_eq!(pos_infinity, neg_infinity / -two);
        assert_eq!(pos_infinity, pos_infinity / two);
        assert_eq!(neg_infinity, pos_infinity / -one);
        assert!((pos_infinity / neg_infinity).is_nan());
        assert!((neg_infinity / neg_infinity).is_nan());
        assert!((pos_infinity / zero).is_nan());
        assert!((zero / neg_infinity).is_zero());

        let nan = consts::NAN;
        assert!((nan / zero).is_nan());
        assert!((one / nan).is_nan());
        assert!((nan / -thirteen).is_nan());
        assert!((nan / nan).is_nan());
    }

    #[test]
    fn test_fmt_display() {
        let no_change = d32::from_data(false, 0, 1234567);
        let expected = "1234567".to_string();
        let actual = format!("{}", no_change);
        assert_eq!(expected, actual);

        let shift_left_one = d32::from_data(false, 1, 1234567);
        let expected = "12345670".to_string();
        let actual = format!("{}", shift_left_one);
        assert_eq!(expected, actual);

        let neg_shift_left_one = d32::from_data(true, 1, 1234567);
        let expected = "-12345670".to_string();
        let actual = format!("{}", neg_shift_left_one);
        assert_eq!(expected, actual);

        let shift_right_one = d32::from_data(false, -1, 1234567);
        let expected = "123456.7".to_string();
        let actual = format!("{}", shift_right_one);
        assert_eq!(expected, actual);

        let shift_right_four = d32::from_data(false, -4, 12345);
        let expected = "1.2345".to_string();
        let actual = format!("{}", shift_right_four);
        assert_eq!(expected, actual);

        let shift_right_seven = d32::from_data(false, -7, 1234567);
        let expected = "0.1234567".to_string();
        let actual = format!("{}", shift_right_seven);
        assert_eq!(expected, actual);

        let shift_right_ten = d32::from_data(false, -10, 1234);
        let expected = "0.0000001234".to_string();
        let actual = format!("{}", shift_right_ten);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_fmt_binary() {
        let bits = 0b0_0000000_00000000000000000000000;
        let d32 = d32 { bits: bits };
        assert_eq!(format!("{:b}", bits), format!("{:b}", d32));

        let bits = 0b0_0000000_00000000000000000000001;
        let d32 = d32 { bits: bits };
        assert_eq!(format!("{:b}", bits), format!("{:b}", d32));

        let bits = 0b0_00000000_00000000000000001010000;
        let d32 = d32 { bits: bits };
        assert_eq!(format!("{:b}", bits), format!("{:b}", d32));

        let bits = 0b0_11_00000000_110001001011001111111;
        let d32 = d32 { bits: bits };
        assert_eq!(format!("{:b}", bits), format!("{:b}", d32));
    }
}


text:
#ifndef _CCMD_SWITCH_H_
#define _CCMD_SWITCH_H_

#include "ccmd.h"

class CApplication;
class CContext;

// Switch the context
class CCmdSwitch : public CCmd
{
    Q_OBJECT

public:
    CCmdSwitch(CApplication *application, const QString &context, bool verbose);
    virtual ~CCmdSwitch();

public:
    int run();
    int run(const CContext *context, const QString &contextName);

private:
    CApplication *m_application;
    QString m_context;
    bool m_verbose;

    CCMD_HELPER;
};

#endif


text:
<?php
define ('ALLOW_EXTERNAL', FALSE);
define ('FILE_CACHE_DIRECTORY', '');
define ('MAX_FILE_SIZE', 524288); //512KB
define ('MAX_WIDTH', 768);
define ('MAX_HEIGHT', 768);
define ('NOT_FOUND_IMAGE', '/images/anim/100/004.gif');
define ('ERROR_IMAGE', '/images/anim/100/004.gif');
if(! defined('OPTIPNG_ENABLED') )       define ('OPTIPNG_ENABLED', true);
if(! defined('OPTIPNG_PATH') )          define ('OPTIPNG_PATH', '/opt/local/bin/optipng'); //This will run first because it gives better compression than pngcrush.
if(! defined('PNGCRUSH_ENABLED') )      define ('PNGCRUSH_ENABLED', true);
if(! defined('PNGCRUSH_PATH') )         define ('PNGCRUSH_PATH', '/opt/local/bin/pngcrush'); //This will only run if OPTIPNG_P
define ('MEMORY_LIMIT', '10M');


text:
"""Class to hold all light accessories."""
import logging

from pyhap.const import CATEGORY_FAN

from homeassistant.components.fan import (
    ATTR_DIRECTION,
    ATTR_OSCILLATING,
    ATTR_PERCENTAGE,
    ATTR_PERCENTAGE_STEP,
    ATTR_PRESET_MODE,
    ATTR_PRESET_MODES,
    DIRECTION_FORWARD,
    DIRECTION_REVERSE,
    DOMAIN,
    SERVICE_OSCILLATE,
    SERVICE_SET_DIRECTION,
    SERVICE_SET_PERCENTAGE,
    SERVICE_SET_PRESET_MODE,
    SUPPORT_DIRECTION,
    SUPPORT_OSCILLATE,
    SUPPORT_SET_SPEED,
)
from homeassistant.const import (
    ATTR_ENTITY_ID,
    ATTR_SUPPORTED_FEATURES,
    SERVICE_TURN_OFF,
    SERVICE_TURN_ON,
    STATE_OFF,
    STATE_ON,
)
from homeassistant.core import callback

from .accessories import TYPES, HomeAccessory
from .const import (
    CHAR_ACTIVE,
    CHAR_NAME,
    CHAR_ON,
    CHAR_ROTATION_DIRECTION,
    CHAR_ROTATION_SPEED,
    CHAR_SWING_MODE,
    MAX_NAME_LENGTH,
    PROP_MIN_STEP,
    SERV_FANV2,
    SERV_SWITCH,
)

_LOGGER = logging.getLogger(__name__)

@TYPES.register("Fan")
class Fan(HomeAccessory):
    """Generate a Fan accessory for a fan entity.

    Currently supports: state, speed, oscillate, direction.
    """

    def __init__(self, *args):
        """Initialize a new Fan accessory object."""
        super().__init__(*args, category=CATEGORY_FAN)
        chars = []
        state = self.hass.states.get(self.entity_id)

        features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
        percentage_step = state.attributes.get(ATTR_PERCENTAGE_STEP, 1)
        preset_modes = state.attributes.get(ATTR_PRESET_MODES)

        if features & SUPPORT_DIRECTION:
            chars.append(CHAR_ROTATION_DIRECTION)
        if features & SUPPORT_OSCILLATE:
            chars.append(CHAR_SWING_MODE)
        if features & SUPPORT_SET_SPEED:
            chars.append(CHAR_ROTATION_SPEED)

        serv_fan = self.add_preload_service(SERV_FANV2, chars)
        self.set_primary_service(serv_fan)
        self.char_active = serv_fan.configure_char(CHAR_ACTIVE, value=0)

        self.char_direction = None
        self.char_speed = None
        self.char_swing = None
        self.preset_mode_chars = {}

        if CHAR_ROTATION_DIRECTION in chars:
            self.char_direction = serv_fan.configure_char(
                CHAR_ROTATION_DIRECTION, value=0
            )

        if CHAR_ROTATION_SPEED in chars:
            # Initial value is set to 100 because 0 is a special value (off). 100 is
            # an arbitrary non-zero value. It is updated immediately by async_update_state
            # to set to the correct initial value.
            self.char_speed = serv_fan.configure_char(
                CHAR_ROTATION_SPEED,
                value=100,
                properties={PROP_MIN_STEP: percentage_step},
            )

        if preset_modes:
            for preset_mode in preset_modes:
                preset_serv = self.add_preload_service(SERV_SWITCH, CHAR_NAME)
                serv_fan.add_linked_service(preset_serv)
                preset_serv.configure_char(
                    CHAR_NAME,
                    value=f"{self.display_name} {preset_mode}"[:MAX_NAME_LENGTH],
                )

                self.preset_mode_chars[preset_mode] = preset_serv.configure_char(
                    CHAR_ON,
                    value=False,
                    setter_callback=lambda value, preset_mode=preset_mode: self.set_preset_mode(
                        value, preset_mode
                    ),
                )

        if CHAR_SWING_MODE in chars:
            self.char_swing = serv_fan.configure_char(CHAR_SWING_MODE, value=0)
        self.async_update_state(state)
        serv_fan.setter_callback = self._set_chars

    def _set_chars(self, char_values):
        _LOGGER.debug("Fan _set_chars: %s", char_values)
        if CHAR_ACTIVE in char_values:
            if char_values[CHAR_ACTIVE]:
                # If the device supports set speed we
                # do not want to turn on as it will take
                # the fan to 100% than to the desired speed.
                #
                # Setting the speed will take care of turning
                # on the fan if SUPPORT_SET_SPEED is set.
                if not self.char_speed or CHAR_ROTATION_SPEED not in char_values:
                    self.set_state(1)
            else:
                # Its off, nothing more to do as setting the
                # other chars will likely turn it back on which
                # is what we want to avoid
                self.set_state(0)
                return

        if CHAR_SWING_MODE in char_values:
            self.set_oscillating(char_values[CHAR_SWING_MODE])
        if CHAR_ROTATION_DIRECTION in char_values:
            self.set_direction(char_values[CHAR_ROTATION_DIRECTION])

        # We always do this LAST to ensure they
        # get the speed they asked for
        if CHAR_ROTATION_SPEED in char_values:
            self.set_percentage(char_values[CHAR_ROTATION_SPEED])

    def set_preset_mode(self, value, preset_mode):
        """Set preset_mode if call came from HomeKit."""
        _LOGGER.debug(
            "%s: Set preset_mode %s to %d", self.entity_id, preset_mode, value
        )
        params = {ATTR_ENTITY_ID: self.entity_id}
        if value:
            params[ATTR_PRESET_MODE] = preset_mode
            self.async_call_service(DOMAIN, SERVICE_SET_PRESET_MODE, params)
        else:
            self.async_call_service(DOMAIN, SERVICE_TURN_ON, params)

    def set_state(self, value):
        """Set state if call came from HomeKit."""
        _LOGGER.debug("%s: Set state to %d", self.entity_id, value)
        service = SERVICE_TURN_ON if value == 1 else SERVICE_TURN_OFF
        params = {ATTR_ENTITY_ID: self.entity_id}
        self.async_call_service(DOMAIN, service, params)

    def set_direction(self, value):
        """Set state if call came from HomeKit."""
        _LOGGER.debug("%s: Set direction to %d", self.entity_id, value)
        direction = DIRECTION_REVERSE if value == 1 else DIRECTION_FORWARD
        params = {ATTR_ENTITY_ID: self.entity_id, ATTR_DIRECTION: direction}
        self.async_call_service(DOMAIN, SERVICE_SET_DIRECTION, params, direction)

    def set_oscillating(self, value):
        """Set state if call came from HomeKit."""
        _LOGGER.debug("%s: Set oscillating to %d", self.entity_id, value)
        oscillating = value == 1
        params = {ATTR_ENTITY_ID: self.entity_id, ATTR_OSCILLATING: oscillating}
        self.async_call_service(DOMAIN, SERVICE_OSCILLATE, params, oscillating)

    def set_percentage(self, value):
        """Set state if call came from HomeKit."""
        _LOGGER.debug("%s: Set speed to %d", self.entity_id, value)
        params = {ATTR_ENTITY_ID: self.entity_id, ATTR_PERCENTAGE: value}
        self.async_call_service(DOMAIN, SERVICE_SET_PERCENTAGE, params, value)

    @callback
    def async_update_state(self, new_state):
        """Update fan after state change."""
        # Handle State
        state = new_state.state
        if state in (STATE_ON, STATE_OFF):
            self._state = 1 if state == STATE_ON else 0
            self.char_active.set_value(self._state)

        # Handle Direction
        if self.char_direction is not None:
            direction = new_state.attributes.get(ATTR_DIRECTION)
            if direction in (DIRECTION_FORWARD, DIRECTION_REVERSE):
                hk_direction = 1 if direction == DIRECTION_REVERSE else 0
                self.char_direction.set_value(hk_direction)

        # Handle Speed
        if self.char_speed is not None and state != STATE_OFF:
            # We do not change the homekit speed when turning off
            # as it will clear the restore state
            percentage = new_state.attributes.get(ATTR_PERCENTAGE)
            # If the homeassistant component reports its speed as the first entry
            # in its speed list but is not off, the hk_speed_value is 0. But 0
            # is a special value in homekit. When you turn on a homekit accessory
            # it will try to restore the last rotation speed state which will be
            # the last value saved by char_speed.set_value. But if it is set to
            # 0, HomeKit will update the rotation speed to 100 as it thinks 0 is
            # off.
            #
            # Therefore, if the hk_speed_value is 0 and the device is still on,
            # the rotation speed is mapped to 1 otherwise the update is ignored
            # in order to avoid this incorrect behavior.
            if percentage == 0 and state == STATE_ON:
                percentage = 1
            if percentage is not None:
                self.char_speed.set_value(percentage)

        # Handle Oscillating
        if self.char_swing is not None:
            oscillating = new_state.attributes.get(ATTR_OSCILLATING)
            if isinstance(oscillating, bool):
                hk_oscillating = 1 if oscillating else 0
                self.char_swing.set_value(hk_oscillating)

        current_preset_mode = new_state.attributes.get(ATTR_PRESET_MODE)
        for preset_mode, char in self.preset_mode_chars.items():
            hk_value = 1 if preset_mode == current_preset_mode else 0
            char.set_value(hk_value)


text:
Detect the mouse direction when entered on the passed element. The direction can be up, down, left or right and will be passed to the two callbacks available.
The first one is the `onIn` callback, and the second one is the `onOut`.

### Parameters
Name  |  Type  |  Description  |  Status  |  Default
------------  |  ------------  |  ------------  |  ------------  |  ------------
elm  |  **{ [HTMLElement](https://developer.mozilla.org/fr/docs/Web/API/HTMLElement) }**  |  The element to listen for mouseover and mouseout on  |  required  |
onIn  |  **{ [Function](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Function) }**  |  The onIn callback. The direction and the elm will be passed to it  |  required  |
onOut  |  **{ [Function](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Function) }**  |  The onOut callback. The direction and the elm will be passed to it  |  required  |

Return **{ [HTMLElement](https://developer.mozilla.org/fr/docs/Web/API/HTMLElement) }** The elm to maintain chainability

### Example
```js
	import detectInOutDirection from 'coffeekraken-sugar/js/dom/detectInOutDirection'
detectInOutDirection(myElm, (direction, elm) => {
    // do something on in
}, (direction, elm) => {
    // do something on out
})
```
Author : Olivier Bossel [olivier.bossel@gmail.com](mailto:olivier.bossel@gmail.com) [https://olivierbossel.com](https://olivierbossel.com)