<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
#if defined(_MSC_VER)
// turn off bogus `this used in base member initialization list'
#  pragma warning(disable: 4786)
#endif

#include "global.h"

const struct GlobalDBItem globalDBItems[] = {
  { "_agilityAdVel",		"2.25",				false, StateDatabase::Locked},
  { "_agilityTimeWindow",	"1.0",				false, StateDatabase::Locked},
  { "_agilityVelDelta",	        "0.3",				false, StateDatabase::Locked},
  { "_angleTolerance",		"0.05",				false, StateDatabase::Locked},
  { "_angularAd",		"1.5",				false, StateDatabase::Locked},
  { "_avenueSize",		"2.0*_boxBase",			false, StateDatabase::Locked},
  { "_baseSize",		"60.0",                         false, StateDatabase::Locked},
  { "_boxBase",			"30.0",				false, StateDatabase::Locked},
  { "_boxHeight",		"6.0*_muzzleHeight",		false, StateDatabase::Locked},
  { "_burrowAngularAd",		"0.55",				false, StateDatabase::Locked},
  { "_burrowDepth",		"-1.32",			false, StateDatabase::Locked},
  { "_burrowSpeedAd",		"0.80",				false, StateDatabase::Locked},
  { "_coldetDepth",		"6",			        false, StateDatabase::Locked},
  { "_coldetElements",		"4",			        false, StateDatabase::Locked},
  { "_cullDepth",		"0",			        false, StateDatabase::Locked},
  { "_cullElements",		"16",			        false, StateDatabase::Locked},
  { "_cullOccluders",		"0",			        false, StateDatabase::Locked},
  { "_deadUnder",		"-32767.0",			false, StateDatabase::Locked},
  { "_explodeTime",		"5.0",				false, StateDatabase::Locked},
  { "_fakeLag",			"0.5",				false, StateDatabase::Locked},
  { "_flagAltitude",		"11.0",				false, StateDatabase::Locked},
  { "_flagHeight",		"10.0",				false, StateDatabase::Locked},
  { "_flagPoleWidth",		"0.025",                        false, StateDatabase::Locked},
  { "_flagPoleSize",		"0.8",				false, StateDatabase::Locked},
  { "_flagRadius",		"2.5",				false, StateDatabase::Locked},
  { "_friction",		"0",				false, StateDatabase::Locked},
  { "_gMissileAng",		"0.628319",			false, StateDatabase::Locked},
  { "_gMissileAdLife",		"0.95",				false, StateDatabase::Locked},
  { "_gravity",			"-9.8",				false, StateDatabase::Locked},
  { "_identifyRange",		"50.0",				false, StateDatabase::Locked},
  { "_jumpVelocity",		"19.0",				false, StateDatabase::Locked},
  { "_laserAdLife",		"0.1",				false, StateDatabase::Locked},
  { "_laserAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_laserAdVel",		"1000.0",			false, StateDatabase::Locked},
  { "_lockOnAngle",		"0.15",				false, StateDatabase::Locked},
  { "_lRAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_maxBumpHeight",		"0.33",				false, StateDatabase::Locked},
  { "_maxFlagGrabs",		"4.0",				false, StateDatabase::Locked},
  { "_maxLOD",			"32767.0",			false, StateDatabase::Locked},
  { "_momentumAngAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumLinAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumFriction",	"0",				false, StateDatabase::Locked},
  { "_mGunAdLife",		"1.0 / _mGunAdRate",		false, StateDatabase::Locked},
  { "_mGunAdRate",		"10.0",				false, StateDatabase::Locked},
  { "_mGunAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_muzzleFront",		"_tankRadius + 0.1",		false, StateDatabase::Locked},
  { "_muzzleHeight",		"1.57",				false, StateDatabase::Locked},
  { "_noSmallPackets",		"1",				false, StateDatabase::Locked},
  { "_notRespondingTime",	"5.0",				false, StateDatabase::Locked},
  { "_obeseFactor",		"2.5",				false, StateDatabase::Locked},
  { "_pauseDropTime",		"15.0",				false, StateDatabase::Locked},
  { "_positionTolerance",	"0.09",				false, StateDatabase::Locked},
  { "_pyrBase",			"4.0*_tankHeight",		false, StateDatabase::Locked},
  { "_pyrHeight",		"5.0*_tankHeight",		false, StateDatabase::Locked},
  { "_rejoinTime",		"_explodeTime",			false, StateDatabase::Locked},
  { "_reloadTime",		"_shotRange / _shotSpeed",	false, StateDatabase::Locked},
  { "_rFireAdLife",		"1.0 / _rFireAdRate",		false, StateDatabase::Locked},
  { "_rFireAdRate",		"2.0",				false, StateDatabase::Locked},
  { "_rFireAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_shieldFlight",		"2.7",				false, StateDatabase::Locked},
  { "_shockAdLife",		"0.2",				false, StateDatabase::Locked},
  { "_shockInRadius",		"_tankLength",			false, StateDatabase::Locked},
  { "_shockOutRadius",		"60.0",				false, StateDatabase::Locked},
  { "_shotTailLength",		"4.0",				false, StateDatabase::Locked},
  { "_shotRadius",		"0.5",				false, StateDatabase::Locked},
  { "_shotRange",		"350.0",			false, StateDatabase::Locked},
  { "_shotSpeed",		"100.0",			false, StateDatabase::Locked},
  { "_shotsKeepVerticalVelocity",	"0",			false, StateDatabase::Locked},
  { "_srRadiusMult",		"2.0",				false, StateDatabase::Locked},
  { "_syncTime",		"0",				false, StateDatabase::Locked},
  { "_tankExplosionSize",	"3.5 * _tankLength", 		false, StateDatabase::Locked},
  { "_tankAngVel",		"0.785398", 			false, StateDatabase::Locked},
  { "_tankHeight",		"2.05",				false, StateDatabase::Locked},
  { "_tankLength",		"6.0",				false, StateDatabase::Locked},
  { "_tankRadius",		"0.72 * _tankLength",		false, StateDatabase::Locked},
  { "_tankSpeed",		"25.0",				false, StateDatabase::Locked},
  { "_tankWidth",		"2.8",				false, StateDatabase::Locked},
  { "_targetingAngle",		"0.3",				false, StateDatabase::Locked},
  { "_teleportBreadth",		"4.48",				false, StateDatabase::Locked},
  { "_teleportHeight",		"10.08",			false, StateDatabase::Locked},
  { "_teleportTime",		"1.0",				false, StateDatabase::Locked},
  { "_teleportWidth",		"1.12",				false, StateDatabase::Locked},
  { "_thiefAdLife",		"0.05",				false, StateDatabase::Locked},
  { "_thiefAdRate",		"12.0",				false, StateDatabase::Locked},
  { "_thiefAdShotVel",		"8.0",				false, StateDatabase::Locked},
  { "_thiefTinyFactor",		"0.5",				false, StateDatabase::Locked},
  { "_thiefVelAd",		"1.67",				false, StateDatabase::Locked},
  { "_thiefDropTime",		"_reloadTime * 0.5",		false, StateDatabase::Locked},
  { "_tinyFactor",		"0.4",				false, StateDatabase::Locked},
  { "_updateThrottleRate",	"30.0",				false, StateDatabase::Locked},
  { "_velocityAd",		"1.5",				false, StateDatabase::Locked},
  { "_wallHeight",		"3.0*_tankHeight",		false, StateDatabase::Locked},
  { "_wideAngleAng",		"1.745329", 			false, StateDatabase::Locked},
  { "_wingsGravity",		"_gravity",			false, StateDatabase::Locked},
  { "_wingsJumpCount",		"1",				false, StateDatabase::Locked},
  { "_wingsJumpVelocity",	"_jumpVelocity",		false, StateDatabase::Locked},
  { "_worldSize",		"800.0",			false, StateDatabase::Locked}
};
const unsigned int	numGlobalDBItems = countof(globalDBItems);

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>start using small packets<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
#if defined(_MSC_VER)
// turn off bogus `this used in base member initialization list'
#  pragma warning(disable: 4786)
#endif

#include "global.h"

const struct GlobalDBItem globalDBItems[] = {
  { "_agilityAdVel",		"2.25",				false, StateDatabase::Locked},
  { "_agilityTimeWindow",	"1.0",				false, StateDatabase::Locked},
  { "_agilityVelDelta",	        "0.3",				false, StateDatabase::Locked},
  { "_angleTolerance",		"0.05",				false, StateDatabase::Locked},
  { "_angularAd",		"1.5",				false, StateDatabase::Locked},
  { "_avenueSize",		"2.0*_boxBase",			false, StateDatabase::Locked},
  { "_baseSize",		"60.0",                         false, StateDatabase::Locked},
  { "_boxBase",			"30.0",				false, StateDatabase::Locked},
  { "_boxHeight",		"6.0*_muzzleHeight",		false, StateDatabase::Locked},
  { "_burrowAngularAd",		"0.55",				false, StateDatabase::Locked},
  { "_burrowDepth",		"-1.32",			false, StateDatabase::Locked},
  { "_burrowSpeedAd",		"0.80",				false, StateDatabase::Locked},
  { "_coldetDepth",		"6",			        false, StateDatabase::Locked},
  { "_coldetElements",		"4",			        false, StateDatabase::Locked},
  { "_cullDepth",		"0",			        false, StateDatabase::Locked},
  { "_cullElements",		"16",			        false, StateDatabase::Locked},
  { "_cullOccluders",		"0",			        false, StateDatabase::Locked},
  { "_deadUnder",		"-32767.0",			false, StateDatabase::Locked},
  { "_explodeTime",		"5.0",				false, StateDatabase::Locked},
  { "_fakeLag",			"0.5",				false, StateDatabase::Locked},
  { "_flagAltitude",		"11.0",				false, StateDatabase::Locked},
  { "_flagHeight",		"10.0",				false, StateDatabase::Locked},
  { "_flagPoleWidth",		"0.025",                        false, StateDatabase::Locked},
  { "_flagPoleSize",		"0.8",				false, StateDatabase::Locked},
  { "_flagRadius",		"2.5",				false, StateDatabase::Locked},
  { "_friction",		"0",				false, StateDatabase::Locked},
  { "_gMissileAng",		"0.628319",			false, StateDatabase::Locked},
  { "_gMissileAdLife",		"0.95",				false, StateDatabase::Locked},
  { "_gravity",			"-9.8",				false, StateDatabase::Locked},
  { "_identifyRange",		"50.0",				false, StateDatabase::Locked},
  { "_jumpVelocity",		"19.0",				false, StateDatabase::Locked},
  { "_laserAdLife",		"0.1",				false, StateDatabase::Locked},
  { "_laserAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_laserAdVel",		"1000.0",			false, StateDatabase::Locked},
  { "_lockOnAngle",		"0.15",				false, StateDatabase::Locked},
  { "_lRAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_maxBumpHeight",		"0.33",				false, StateDatabase::Locked},
  { "_maxFlagGrabs",		"4.0",				false, StateDatabase::Locked},
  { "_maxLOD",			"32767.0",			false, StateDatabase::Locked},
  { "_momentumAngAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumLinAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumFriction",	"0",				false, StateDatabase::Locked},
  { "_mGunAdLife",		"1.0 / _mGunAdRate",		false, StateDatabase::Locked},
  { "_mGunAdRate",		"10.0",				false, StateDatabase::Locked},
  { "_mGunAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_muzzleFront",		"_tankRadius + 0.1",		false, StateDatabase::Locked},
  { "_muzzleHeight",		"1.57",				false, StateDatabase::Locked},
  { "_noSmallPackets",		"0",				false, StateDatabase::Locked},
  { "_notRespondingTime",	"5.0",				false, StateDatabase::Locked},
  { "_obeseFactor",		"2.5",				false, StateDatabase::Locked},
  { "_pauseDropTime",		"15.0",				false, StateDatabase::Locked},
  { "_positionTolerance",	"0.09",				false, StateDatabase::Locked},
  { "_pyrBase",			"4.0*_tankHeight",		false, StateDatabase::Locked},
  { "_pyrHeight",		"5.0*_tankHeight",		false, StateDatabase::Locked},
  { "_rejoinTime",		"_explodeTime",			false, StateDatabase::Locked},
  { "_reloadTime",		"_shotRange / _shotSpeed",	false, StateDatabase::Locked},
  { "_rFireAdLife",		"1.0 / _rFireAdRate",		false, StateDatabase::Locked},
  { "_rFireAdRate",		"2.0",				false, StateDatabase::Locked},
  { "_rFireAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_shieldFlight",		"2.7",				false, StateDatabase::Locked},
  { "_shockAdLife",		"0.2",				false, StateDatabase::Locked},
  { "_shockInRadius",		"_tankLength",			false, StateDatabase::Locked},
  { "_shockOutRadius",		"60.0",				false, StateDatabase::Locked},
  { "_shotTailLength",		"4.0",				false, StateDatabase::Locked},
  { "_shotRadius",		"0.5",				false, StateDatabase::Locked},
  { "_shotRange",		"350.0",			false, StateDatabase::Locked},
  { "_shotSpeed",		"100.0",			false, StateDatabase::Locked},
  { "_shotsKeepVerticalVelocity",	"0",			false, StateDatabase::Locked},
  { "_srRadiusMult",		"2.0",				false, StateDatabase::Locked},
  { "_syncTime",		"0",				false, StateDatabase::Locked},
  { "_tankExplosionSize",	"3.5 * _tankLength", 		false, StateDatabase::Locked},
  { "_tankAngVel",		"0.785398", 			false, StateDatabase::Locked},
  { "_tankHeight",		"2.05",				false, StateDatabase::Locked},
  { "_tankLength",		"6.0",				false, StateDatabase::Locked},
  { "_tankRadius",		"0.72 * _tankLength",		false, StateDatabase::Locked},
  { "_tankSpeed",		"25.0",				false, StateDatabase::Locked},
  { "_tankWidth",		"2.8",				false, StateDatabase::Locked},
  { "_targetingAngle",		"0.3",				false, StateDatabase::Locked},
  { "_teleportBreadth",		"4.48",				false, StateDatabase::Locked},
  { "_teleportHeight",		"10.08",			false, StateDatabase::Locked},
  { "_teleportTime",		"1.0",				false, StateDatabase::Locked},
  { "_teleportWidth",		"1.12",				false, StateDatabase::Locked},
  { "_thiefAdLife",		"0.05",				false, StateDatabase::Locked},
  { "_thiefAdRate",		"12.0",				false, StateDatabase::Locked},
  { "_thiefAdShotVel",		"8.0",				false, StateDatabase::Locked},
  { "_thiefTinyFactor",		"0.5",				false, StateDatabase::Locked},
  { "_thiefVelAd",		"1.67",				false, StateDatabase::Locked},
  { "_thiefDropTime",		"_reloadTime * 0.5",		false, StateDatabase::Locked},
  { "_tinyFactor",		"0.4",				false, StateDatabase::Locked},
  { "_updateThrottleRate",	"30.0",				false, StateDatabase::Locked},
  { "_velocityAd",		"1.5",				false, StateDatabase::Locked},
  { "_wallHeight",		"3.0*_tankHeight",		false, StateDatabase::Locked},
  { "_wideAngleAng",		"1.745329", 			false, StateDatabase::Locked},
  { "_wingsGravity",		"_gravity",			false, StateDatabase::Locked},
  { "_wingsJumpCount",		"1",				false, StateDatabase::Locked},
  { "_wingsJumpVelocity",	"_jumpVelocity",		false, StateDatabase::Locked},
  { "_worldSize",		"800.0",			false, StateDatabase::Locked}
};
const unsigned int	numGlobalDBItems = countof(globalDBItems);

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>//
// Created by Ivan Shynkarenka on 01.09.2016.
//

#include "catch.hpp"

#include "math/math.h"

using namespace CppCommon;

TEST_CASE("Math", "[CppCommon][Math]")
{
    REQUIRE(Math::MulDiv64(4984198405165151231ull, 6132198419878046132ull, 9156498145135109843ull) == 3337967539561099935ull);
    REQUIRE(Math::MulDiv64(11540173641653250113ull, 10150593219136339683ull, 13592284235543989460ull) == 8618095846487663363ull);
    REQUIRE(Math::MulDiv64(449033535071450778ull, 3155170653582908051ull, 4945421831474875872ull) == 286482625873293138ull);
    REQUIRE(Math::MulDiv64(303601908757ull, 829267376026ull, 659820219978ull) == 381569328444ull);
    REQUIRE(Math::MulDiv64(449033535071450778ull, 829267376026ull, 659820219978ull) == 564348969767547451ull);
    REQUIRE(Math::MulDiv64(1234568ull, 829267376026ull, 1ull) == 1023786965885666768ull);
    REQUIRE(Math::MulDiv64(6991754535226557229ull, 7798003721120799096ull, 4923601287520449332ull) == 11073546515850664288ull);
    REQUIRE(Math::MulDiv64(9223372036854775808ull, 2147483648ull, 18446744073709551615ull) == 1073741824ull);
    REQUIRE(Math::MulDiv64(9223372032559808512ull, 9223372036854775807ull, 9223372036854775807ull) == 9223372032559808512ull);
    // Might overflow
    uint64_t overflow = Math::MulDiv64(9223372032559808512ull, 9223372036854775807ull, 12ull);
    REQUIRE(((overflow == 11529215046426383701ull) || (overflow == 0xFFFFFFFFFFFFFFFFull)));
    REQUIRE(Math::MulDiv64(9223372032559808512ull, 9223372036854775807ull, 12ull) == 18446744073709551615ull);
    REQUIRE(Math::MulDiv64(18446744073709551615ull, 18446744073709551615ull, 9223372036854775808ull) == 18446744073709551615ull);
}
<commit_msg>Bugfix<commit_after>//
// Created by Ivan Shynkarenka on 01.09.2016.
//

#include "catch.hpp"

#include "math/math.h"

using namespace CppCommon;

TEST_CASE("Math", "[CppCommon][Math]")
{
    REQUIRE(Math::MulDiv64(4984198405165151231ull, 6132198419878046132ull, 9156498145135109843ull) == 3337967539561099935ull);
    REQUIRE(Math::MulDiv64(11540173641653250113ull, 10150593219136339683ull, 13592284235543989460ull) == 8618095846487663363ull);
    REQUIRE(Math::MulDiv64(449033535071450778ull, 3155170653582908051ull, 4945421831474875872ull) == 286482625873293138ull);
    REQUIRE(Math::MulDiv64(303601908757ull, 829267376026ull, 659820219978ull) == 381569328444ull);
    REQUIRE(Math::MulDiv64(449033535071450778ull, 829267376026ull, 659820219978ull) == 564348969767547451ull);
    REQUIRE(Math::MulDiv64(1234568ull, 829267376026ull, 1ull) == 1023786965885666768ull);
    REQUIRE(Math::MulDiv64(6991754535226557229ull, 7798003721120799096ull, 4923601287520449332ull) == 11073546515850664288ull);
    REQUIRE(Math::MulDiv64(9223372036854775808ull, 2147483648ull, 18446744073709551615ull) == 1073741824ull);
    REQUIRE(Math::MulDiv64(9223372032559808512ull, 9223372036854775807ull, 9223372036854775807ull) == 9223372032559808512ull);
    // Might overflow
    uint64_t overflow = Math::MulDiv64(9223372032559808512ull, 9223372036854775807ull, 12ull);
    REQUIRE(((overflow == 11529215046426383701ull) || (overflow == 0xFFFFFFFFFFFFFFFFull)));
    REQUIRE(Math::MulDiv64(18446744073709551615ull, 18446744073709551615ull, 9223372036854775808ull) == 18446744073709551615ull);
}
<|endoftext|>


<commit_before>#include "node.h"
#include "container.h"
#include "tree.h"
#include "space.h"
#include "window.h"

#include "axlib/axlib.h"

extern std::map<CFStringRef, space_info> WindowTree;
extern ax_application *FocusedApplication;

extern kwm_settings KWMSettings;

tree_node *CreateRootNode()
{
    tree_node Clear = {0};
    tree_node *RootNode = (tree_node*) malloc(sizeof(tree_node));
    *RootNode = Clear;

    RootNode->WindowID = 0;
    RootNode->Type = NodeTypeTree;
    RootNode->Parent = NULL;
    RootNode->LeftChild = NULL;
    RootNode->RightChild = NULL;
    RootNode->SplitRatio = KWMSettings.SplitRatio;
    RootNode->SplitMode = SPLIT_OPTIMAL;

    return RootNode;
}

link_node *CreateLinkNode()
{
    link_node Clear = {0};
    link_node *Link = (link_node*) malloc(sizeof(link_node));
    *Link = Clear;

    Link->WindowID = 0;
    Link->Prev = NULL;
    Link->Next = NULL;

    return Link;
}

tree_node *CreateLeafNode(ax_display *Display, tree_node *Parent, int WindowID, int ContainerType)
{
    tree_node Clear = {0};
    tree_node *Leaf = (tree_node*) malloc(sizeof(tree_node));
    *Leaf = Clear;

    Leaf->Parent = Parent;
    Leaf->WindowID = WindowID;
    Leaf->Type = NodeTypeTree;

    CreateNodeContainer(Display, Leaf, ContainerType);

    Leaf->LeftChild = NULL;
    Leaf->RightChild = NULL;

    return Leaf;
}

void CreateLeafNodePair(ax_display *Display, tree_node *Parent, int FirstWindowID, int SecondWindowID, split_type SplitMode)
{
    Parent->WindowID = 0;
    Parent->SplitMode = SplitMode;
    Parent->SplitRatio = KWMSettings.SplitRatio;

    node_type ParentType = Parent->Type;
    link_node *ParentList = Parent->List;
    Parent->Type = NodeTypeTree;
    Parent->List = NULL;

    int LeftWindowID = KWMSettings.SpawnAsLeftChild ? SecondWindowID : FirstWindowID;
    int RightWindowID = KWMSettings.SpawnAsLeftChild ? FirstWindowID : SecondWindowID;

    if(SplitMode == SPLIT_VERTICAL)
    {
        Parent->LeftChild = CreateLeafNode(Display, Parent, LeftWindowID, 1);
        Parent->RightChild = CreateLeafNode(Display, Parent, RightWindowID, 2);

        tree_node *Node = KWMSettings.SpawnAsLeftChild ?  Parent->RightChild : Parent->LeftChild;
        Node->Type = ParentType;
        Node->List = ParentList;
        ResizeLinkNodeContainers(Node);
    }
    else if(SplitMode == SPLIT_HORIZONTAL)
    {
        Parent->LeftChild = CreateLeafNode(Display, Parent, LeftWindowID, 3);
        Parent->RightChild = CreateLeafNode(Display, Parent, RightWindowID, 4);

        tree_node *Node = KWMSettings.SpawnAsLeftChild ?  Parent->RightChild : Parent->LeftChild;
        Node->Type = ParentType;
        Node->List = ParentList;
        ResizeLinkNodeContainers(Node);
    }
    else
    {
        Parent->Parent = NULL;
        Parent->LeftChild = NULL;
        Parent->RightChild = NULL;
        Parent = NULL;
    }
}

void CreatePseudoNode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(Node)
    {
        split_type SplitMode = KWMSettings.SplitMode == SPLIT_OPTIMAL ? GetOptimalSplitMode(Node) : KWMSettings.SplitMode;
        CreateLeafNodePair(Display, Node, Node->WindowID, 0, SplitMode);
        ApplyTreeNodeContainer(Node);
    }
}

void RemovePseudoNode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(Node && Node->Parent)
    {
        tree_node *Parent = Node->Parent;
        tree_node *PseudoNode = IsLeftChild(Node) ? Parent->RightChild : Parent->LeftChild;
        if(!PseudoNode || !IsLeafNode(PseudoNode) || PseudoNode->WindowID != 0)
            return;

        Parent->WindowID = Node->WindowID;
        Parent->LeftChild = NULL;
        Parent->RightChild = NULL;
        free(Node);
        free(PseudoNode);
        ApplyTreeNodeContainer(Parent);
    }
}

bool IsLeafNode(tree_node *Node)
{
    return Node->LeftChild == NULL && Node->RightChild == NULL ? true : false;
}

bool IsPseudoNode(tree_node *Node)
{
    return Node && Node->WindowID == 0 && IsLeafNode(Node);
}

bool IsLeftChild(tree_node *Node)
{
    if(Node && IsLeafNode(Node))
    {
        tree_node *Parent = Node->Parent;
        return Parent->LeftChild == Node;
    }

    return false;
}

bool IsRightChild(tree_node *Node)
{
    if(Node && IsLeafNode(Node))
    {
        tree_node *Parent = Node->Parent;
        return Parent->RightChild == Node;
    }

    return false;
}

void ToggleFocusedNodeSplitMode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(!Node)
        return;

    tree_node *Parent = Node->Parent;
    if(!Parent || IsLeafNode(Parent))
        return;

    Parent->SplitMode = Parent->SplitMode == SPLIT_VERTICAL ? SPLIT_HORIZONTAL : SPLIT_VERTICAL;
    CreateNodeContainers(Display, Parent, false);
    ApplyTreeNodeContainer(Parent);
}

void ToggleTypeOfFocusedNode()
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *TreeNode = GetTreeNodeFromWindowIDOrLinkNode(SpaceInfo->RootNode, Window->ID);
    if(TreeNode && TreeNode != SpaceInfo->RootNode)
        TreeNode->Type = TreeNode->Type == NodeTypeTree ? NodeTypeLink : NodeTypeTree;
}

void ChangeTypeOfFocusedNode(node_type Type)
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *TreeNode = GetTreeNodeFromWindowIDOrLinkNode(SpaceInfo->RootNode, Window->ID);
    if(TreeNode && TreeNode != SpaceInfo->RootNode)
        TreeNode->Type = Type;
}

void SwapNodeWindowIDs(tree_node *A, tree_node *B)
{
    if(A && B)
    {
        DEBUG("SwapNodeWindowIDs() " << A->WindowID << " with " << B->WindowID);
        int TempWindowID = A->WindowID;
        A->WindowID = B->WindowID;
        B->WindowID = TempWindowID;

        node_type TempNodeType = A->Type;
        A->Type = B->Type;
        B->Type = TempNodeType;

        link_node *TempLinkList = A->List;
        A->List = B->List;
        B->List = TempLinkList;

        ResizeLinkNodeContainers(A);
        ResizeLinkNodeContainers(B);
        ApplyTreeNodeContainer(A);
        ApplyTreeNodeContainer(B);
    }
}

void SwapNodeWindowIDs(link_node *A, link_node *B)
{
    if(A && B)
    {
        DEBUG("SwapNodeWindowIDs() " << A->WindowID << " with " << B->WindowID);
        int TempWindowID = A->WindowID;
        A->WindowID = B->WindowID;
        B->WindowID = TempWindowID;
        ResizeWindowToContainerSize(A);
        ResizeWindowToContainerSize(B);
    }
}

split_type GetOptimalSplitMode(tree_node *Node)
{
    return (Node->Container.Width / Node->Container.Height) >= KWMSettings.OptimalRatio ? SPLIT_VERTICAL : SPLIT_HORIZONTAL;
}

void ResizeWindowToContainerSize(tree_node *Node)
{
    ax_window *Window = GetWindowByID((unsigned int)Node->WindowID);
    if(Window)
    {
        SetWindowDimensions(Window, Node->Container.X, Node->Container.Y,
                            Node->Container.Width, Node->Container.Height);
    }
}

void ResizeWindowToContainerSize(link_node *Link)
{
    ax_window *Window = GetWindowByID((unsigned int)Link->WindowID);
    if(Window)
    {
        SetWindowDimensions(Window, Link->Container.X, Link->Container.Y,
                            Link->Container.Width, Link->Container.Height);
    }
}

void ResizeWindowToContainerSize(ax_window *Window)
{
    if(Window)
    {
        ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
        if(!Window)
            return;

        ax_display *Display = AXLibWindowDisplay(Window);
        if(!Display)
            return;

        space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
        tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
        if(Node)
            ResizeWindowToContainerSize(Node);

        if(!Node)
        {
            link_node *Link = GetLinkNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
            if(Link)
                ResizeWindowToContainerSize(Link);
        }
    }
}

void ResizeWindowToContainerSize()
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ResizeWindowToContainerSize(Window);
}

void ModifyContainerSplitRatio(double Offset)
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *Root = SpaceInfo->RootNode;
    if(IsLeafNode(Root) || Root->WindowID != 0)
        return;

    tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(Root, Window->ID);
    if(Node && Node->Parent)
    {
        if(Node->Parent->SplitRatio + Offset > 0.0 &&
           Node->Parent->SplitRatio + Offset < 1.0)
        {
            Node->Parent->SplitRatio += Offset;
            ResizeNodeContainer(Display, Node->Parent);
            ApplyTreeNodeContainer(Node->Parent);
        }
    }
}

void ModifyContainerSplitRatio(double Offset, int Degrees)
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *Root = SpaceInfo->RootNode;
    if(IsLeafNode(Root) || Root->WindowID != 0)
        return;

    tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(Root, Window->ID);
    if(Node)
    {
        ax_window *ClosestWindow = NULL;
        if(FindClosestWindow(Degrees, &ClosestWindow, false))
        {
            tree_node *Target = GetTreeNodeFromWindowIDOrLinkNode(Root, ClosestWindow->ID);
            tree_node *Ancestor = FindLowestCommonAncestor(Node, Target);
            if(Ancestor &&
               Ancestor->SplitRatio + Offset > 0.0 &&
               Ancestor->SplitRatio + Offset < 1.0)
            {
                Ancestor->SplitRatio += Offset;
                ResizeNodeContainer(Display, Ancestor);
                ApplyTreeNodeContainer(Ancestor);
            }
        }
    }
}

tree_node *FindLowestCommonAncestor(tree_node *A, tree_node *B)
{
    if(!A || !B)
        return NULL;

    std::stack<tree_node*> PathToRootFromA;
    std::stack<tree_node*> PathToRootFromB;

    tree_node *PathA = A;
    while(PathA->Parent)
    {
        PathToRootFromA.push(PathA->Parent);
        PathA = PathA->Parent;
    }

    tree_node *PathB = B;
    while(PathB->Parent)
    {
        PathToRootFromB.push(PathB->Parent);
        PathB = PathB->Parent;
    }

    tree_node *LCA = NULL;
    while(!PathToRootFromA.empty() && !PathToRootFromB.empty())
    {
        tree_node *RootA = PathToRootFromA.top();
        PathToRootFromA.pop();

        tree_node *RootB = PathToRootFromB.top();
        PathToRootFromB.pop();

        if(RootA == RootB)
            LCA = RootA;
        else
            break;
    }

    return LCA;
}
<commit_msg>fix issue with container split<commit_after>#include "node.h"
#include "container.h"
#include "tree.h"
#include "space.h"
#include "window.h"

#include "axlib/axlib.h"

extern std::map<CFStringRef, space_info> WindowTree;
extern ax_application *FocusedApplication;

extern kwm_settings KWMSettings;

tree_node *CreateRootNode()
{
    tree_node Clear = {0};
    tree_node *RootNode = (tree_node*) malloc(sizeof(tree_node));
    *RootNode = Clear;

    RootNode->WindowID = 0;
    RootNode->Type = NodeTypeTree;
    RootNode->Parent = NULL;
    RootNode->LeftChild = NULL;
    RootNode->RightChild = NULL;
    RootNode->SplitRatio = KWMSettings.SplitRatio;
    RootNode->SplitMode = SPLIT_OPTIMAL;

    return RootNode;
}

link_node *CreateLinkNode()
{
    link_node Clear = {0};
    link_node *Link = (link_node*) malloc(sizeof(link_node));
    *Link = Clear;

    Link->WindowID = 0;
    Link->Prev = NULL;
    Link->Next = NULL;

    return Link;
}

tree_node *CreateLeafNode(ax_display *Display, tree_node *Parent, int WindowID, int ContainerType)
{
    tree_node Clear = {0};
    tree_node *Leaf = (tree_node*) malloc(sizeof(tree_node));
    *Leaf = Clear;

    Leaf->Parent = Parent;
    Leaf->WindowID = WindowID;
    Leaf->Type = NodeTypeTree;

    CreateNodeContainer(Display, Leaf, ContainerType);

    Leaf->LeftChild = NULL;
    Leaf->RightChild = NULL;

    return Leaf;
}

void CreateLeafNodePair(ax_display *Display, tree_node *Parent, int FirstWindowID, int SecondWindowID, split_type SplitMode)
{
    Parent->WindowID = 0;
    Parent->SplitMode = SplitMode;
    Parent->SplitRatio = KWMSettings.SplitRatio;

    node_type ParentType = Parent->Type;
    link_node *ParentList = Parent->List;
    Parent->Type = NodeTypeTree;
    Parent->List = NULL;

    int LeftWindowID = KWMSettings.SpawnAsLeftChild ? SecondWindowID : FirstWindowID;
    int RightWindowID = KWMSettings.SpawnAsLeftChild ? FirstWindowID : SecondWindowID;

    if(SplitMode == SPLIT_VERTICAL)
    {
        Parent->LeftChild = CreateLeafNode(Display, Parent, LeftWindowID, 1);
        Parent->RightChild = CreateLeafNode(Display, Parent, RightWindowID, 2);

        tree_node *Node = KWMSettings.SpawnAsLeftChild ?  Parent->RightChild : Parent->LeftChild;
        Node->Type = ParentType;
        Node->List = ParentList;
        ResizeLinkNodeContainers(Node);
    }
    else if(SplitMode == SPLIT_HORIZONTAL)
    {
        Parent->LeftChild = CreateLeafNode(Display, Parent, LeftWindowID, 3);
        Parent->RightChild = CreateLeafNode(Display, Parent, RightWindowID, 4);

        tree_node *Node = KWMSettings.SpawnAsLeftChild ?  Parent->RightChild : Parent->LeftChild;
        Node->Type = ParentType;
        Node->List = ParentList;
        ResizeLinkNodeContainers(Node);
    }
    else
    {
        Parent->Parent = NULL;
        Parent->LeftChild = NULL;
        Parent->RightChild = NULL;
        Parent = NULL;
    }
}

void CreatePseudoNode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(Node)
    {
        split_type SplitMode = KWMSettings.SplitMode == SPLIT_OPTIMAL ? GetOptimalSplitMode(Node) : KWMSettings.SplitMode;
        CreateLeafNodePair(Display, Node, Node->WindowID, 0, SplitMode);
        ApplyTreeNodeContainer(Node);
    }
}

void RemovePseudoNode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(Node && Node->Parent)
    {
        tree_node *Parent = Node->Parent;
        tree_node *PseudoNode = IsLeftChild(Node) ? Parent->RightChild : Parent->LeftChild;
        if(!PseudoNode || !IsLeafNode(PseudoNode) || PseudoNode->WindowID != 0)
            return;

        Parent->WindowID = Node->WindowID;
        Parent->LeftChild = NULL;
        Parent->RightChild = NULL;
        free(Node);
        free(PseudoNode);
        ApplyTreeNodeContainer(Parent);
    }
}

bool IsLeafNode(tree_node *Node)
{
    return Node->LeftChild == NULL && Node->RightChild == NULL ? true : false;
}

bool IsPseudoNode(tree_node *Node)
{
    return Node && Node->WindowID == 0 && IsLeafNode(Node);
}

bool IsLeftChild(tree_node *Node)
{
    if(Node && IsLeafNode(Node))
    {
        tree_node *Parent = Node->Parent;
        return Parent->LeftChild == Node;
    }

    return false;
}

bool IsRightChild(tree_node *Node)
{
    if(Node && IsLeafNode(Node))
    {
        tree_node *Parent = Node->Parent;
        return Parent->RightChild == Node;
    }

    return false;
}

void ToggleFocusedNodeSplitMode()
{
    ax_display *Display = AXLibMainDisplay();
    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    if(!FocusedApplication)
        return;

    ax_window *Window = FocusedApplication->Focus;
    if(!Window)
        return;

    tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
    if(!Node)
        return;

    tree_node *Parent = Node->Parent;
    if(!Parent || IsLeafNode(Parent))
        return;

    Parent->SplitMode = Parent->SplitMode == SPLIT_VERTICAL ? SPLIT_HORIZONTAL : SPLIT_VERTICAL;
    CreateNodeContainers(Display, Parent, false);
    ApplyTreeNodeContainer(Parent);
}

void ToggleTypeOfFocusedNode()
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *TreeNode = GetTreeNodeFromWindowIDOrLinkNode(SpaceInfo->RootNode, Window->ID);
    if(TreeNode && TreeNode != SpaceInfo->RootNode)
        TreeNode->Type = TreeNode->Type == NodeTypeTree ? NodeTypeLink : NodeTypeTree;
}

void ChangeTypeOfFocusedNode(node_type Type)
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *TreeNode = GetTreeNodeFromWindowIDOrLinkNode(SpaceInfo->RootNode, Window->ID);
    if(TreeNode && TreeNode != SpaceInfo->RootNode)
        TreeNode->Type = Type;
}

void SwapNodeWindowIDs(tree_node *A, tree_node *B)
{
    if(A && B)
    {
        DEBUG("SwapNodeWindowIDs() " << A->WindowID << " with " << B->WindowID);
        int TempWindowID = A->WindowID;
        A->WindowID = B->WindowID;
        B->WindowID = TempWindowID;

        node_type TempNodeType = A->Type;
        A->Type = B->Type;
        B->Type = TempNodeType;

        link_node *TempLinkList = A->List;
        A->List = B->List;
        B->List = TempLinkList;

        ResizeLinkNodeContainers(A);
        ResizeLinkNodeContainers(B);
        ApplyTreeNodeContainer(A);
        ApplyTreeNodeContainer(B);
    }
}

void SwapNodeWindowIDs(link_node *A, link_node *B)
{
    if(A && B)
    {
        DEBUG("SwapNodeWindowIDs() " << A->WindowID << " with " << B->WindowID);
        int TempWindowID = A->WindowID;
        A->WindowID = B->WindowID;
        B->WindowID = TempWindowID;
        ResizeWindowToContainerSize(A);
        ResizeWindowToContainerSize(B);
    }
}

split_type GetOptimalSplitMode(tree_node *Node)
{
    return (Node->Container.Width / Node->Container.Height) >= KWMSettings.OptimalRatio ? SPLIT_VERTICAL : SPLIT_HORIZONTAL;
}

void ResizeWindowToContainerSize(tree_node *Node)
{
    ax_window *Window = GetWindowByID((unsigned int)Node->WindowID);
    if(Window)
    {
        SetWindowDimensions(Window, Node->Container.X, Node->Container.Y,
                            Node->Container.Width, Node->Container.Height);
    }
}

void ResizeWindowToContainerSize(link_node *Link)
{
    ax_window *Window = GetWindowByID((unsigned int)Link->WindowID);
    if(Window)
    {
        SetWindowDimensions(Window, Link->Container.X, Link->Container.Y,
                            Link->Container.Width, Link->Container.Height);
    }
}

void ResizeWindowToContainerSize(ax_window *Window)
{
    if(Window)
    {
        ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
        if(!Window)
            return;

        ax_display *Display = AXLibWindowDisplay(Window);
        if(!Display)
            return;

        space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
        tree_node *Node = GetTreeNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
        if(Node)
            ResizeWindowToContainerSize(Node);

        if(!Node)
        {
            link_node *Link = GetLinkNodeFromWindowID(SpaceInfo->RootNode, Window->ID);
            if(Link)
                ResizeWindowToContainerSize(Link);
        }
    }
}

void ResizeWindowToContainerSize()
{
    ax_window *Window = FocusedApplication ? FocusedApplication->Focus : NULL;
    if(!Window)
        return;

    ResizeWindowToContainerSize(Window);
}

void ModifyContainerSplitRatio(double Offset)
{
    ax_application *Application = AXLibGetFocusedApplication();
    if(!Application)
        return;

    ax_window *Window = Application->Focus;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *Root = SpaceInfo->RootNode;
    if(!Root || IsLeafNode(Root) || Root->WindowID != 0)
        return;

    tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(Root, Window->ID);
    if(Node && Node->Parent)
    {
        if(Node->Parent->SplitRatio + Offset > 0.0 &&
           Node->Parent->SplitRatio + Offset < 1.0)
        {
            Node->Parent->SplitRatio += Offset;
            ResizeNodeContainer(Display, Node->Parent);
            ApplyTreeNodeContainer(Node->Parent);
        }
    }
}

void ModifyContainerSplitRatio(double Offset, int Degrees)
{
    ax_application *Application = AXLibGetFocusedApplication();
    if(!Application)
        return;

    ax_window *Window = Application->Focus;
    if(!Window)
        return;

    ax_display *Display = AXLibWindowDisplay(Window);
    if(!Display)
        return;

    space_info *SpaceInfo = &WindowTree[Display->Space->Identifier];
    tree_node *Root = SpaceInfo->RootNode;
    if(!Root || IsLeafNode(Root) || Root->WindowID != 0)
        return;

    tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(Root, Window->ID);
    if(Node)
    {
        ax_window *ClosestWindow = NULL;
        if(FindClosestWindow(Degrees, &ClosestWindow, false))
        {
            tree_node *Target = GetTreeNodeFromWindowIDOrLinkNode(Root, ClosestWindow->ID);
            tree_node *Ancestor = FindLowestCommonAncestor(Node, Target);
            if(Ancestor &&
               Ancestor->SplitRatio + Offset > 0.0 &&
               Ancestor->SplitRatio + Offset < 1.0)
            {
                Ancestor->SplitRatio += Offset;
                ResizeNodeContainer(Display, Ancestor);
                ApplyTreeNodeContainer(Ancestor);
            }
        }
    }
}

tree_node *FindLowestCommonAncestor(tree_node *A, tree_node *B)
{
    if(!A || !B)
        return NULL;

    std::stack<tree_node*> PathToRootFromA;
    std::stack<tree_node*> PathToRootFromB;

    tree_node *PathA = A;
    while(PathA->Parent)
    {
        PathToRootFromA.push(PathA->Parent);
        PathA = PathA->Parent;
    }

    tree_node *PathB = B;
    while(PathB->Parent)
    {
        PathToRootFromB.push(PathB->Parent);
        PathB = PathB->Parent;
    }

    tree_node *LCA = NULL;
    while(!PathToRootFromA.empty() && !PathToRootFromB.empty())
    {
        tree_node *RootA = PathToRootFromA.top();
        PathToRootFromA.pop();

        tree_node *RootB = PathToRootFromB.top();
        PathToRootFromB.pop();

        if(RootA == RootB)
            LCA = RootA;
        else
            break;
    }

    return LCA;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements.  See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee &cfgmap; Configuration Mapping Test
///
/// @author Nick LeRoy <nleroy@qualys.com>
//////////////////////////////////////////////////////////////////////////////

#include <ironbee/hash.h>

#include "ironbee_config_auto.h"

#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"

#include <ironbee/types.h>
#include <ironbee/clock.h>

#include <stdexcept>
#include <sys/time.h>
#include <math.h>

double TvToSecs(const struct timeval &tv)
{
    return tv.tv_sec + (tv.tv_usec * 1e-6);
}
double TvToSecs(const ib_timeval_t &tv)
{
    return tv.tv_sec + (tv.tv_usec * 1e-6);
}

double GetTime(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return TvToSecs(tv);
}

bool CheckUsecDiff(int64_t t1, int64_t t2, unsigned int usecs)
{
    int64_t diff = (int64_t)llabs(t2 - t1);
    int64_t mean = (int64_t)llabs( (t2 + t1) / 2);
    int64_t limit = mean ? mean / 5 : 100000;

    return (diff >= 0) && (abs(diff - usecs) < limit);
}
bool CheckSecDiff(double t1, double t2, double secs, double limit=-1.0)
{
    double diff = fabs(t2 - t1);
    double mean = fabs( (t1 + t2) * 0.5);

    if (limit < 0.0) {
        limit = (mean > 0.0001) ? mean * 0.2 : 1e-5;
    }
    return (diff >= 0.0) && (fabs(diff - secs) < limit);
}

bool Compare(const struct timeval &tv,
             const ib_timeval_t &itv,
             double limit=-1.0)
{
    return CheckSecDiff(TvToSecs(tv), TvToSecs(itv), 0, limit);
}

bool CheckDelta(const ib_timeval_t &tv1,
                const ib_timeval_t &tv2,
                ib_time_t expected_usecs)
{
    return CheckSecDiff(TvToSecs(tv1), TvToSecs(tv2), expected_usecs * 1e-6);
}

bool CheckDelta(const ib_timeval_t &tv1,
                const ib_timeval_t &tv2,
                double expected_secs)
{
    return CheckSecDiff(TvToSecs(tv1), TvToSecs(tv2), expected_secs);
}

bool CheckDelta(ib_time_t t1,
                ib_time_t t2,
                ib_time_t expected_usecs)
{
    return CheckUsecDiff(t1, t2, expected_usecs);
}

TEST(TestClock, test_get_time)
{
    ib_time_t time1;
    ib_time_t time2;
    unsigned int usecs;
    bool rv;

    usecs = 1000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 10000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 100000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 1000000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_gettimeofday)
{
    struct timeval tv;
    ib_timeval_t   itv;
    bool           rv;

    ASSERT_EQ(0, gettimeofday(&tv, NULL) );
    ib_clock_gettimeofday(&itv);
    rv = Compare(tv, itv);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_gettimeofday_diffs)
{
    ib_timeval_t tv1;
    ib_timeval_t tv2;
    unsigned int usecs;
    bool         rv;
    double       t1;
    double       t2;

    usecs = 100000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);

    usecs = 500000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);

    usecs = 1000000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);
}

const size_t bufsize = 32;

void TestTimestamp(bool relative, int seconds)
{
    struct timeval tv;
    struct tm      tm;
    ib_timeval_t   itv;
    char           buf[bufsize + 1];
    bool           rv;

    ib_clock_gettimeofday(&itv);
    if (relative) {
        ib_time_t offset = seconds * 1000000;
        ib_clock_relative_timestamp(buf, &itv, offset);
    }
    else {
        seconds = 0;
        ib_clock_timestamp(buf, &itv);
    }

    ASSERT_STRNE(NULL, strptime(buf, "%Y-%m-%dT%H:%M:%S", &tm));
    tv.tv_sec = mktime(&tm) - seconds;
    ASSERT_EQ( (uint32_t)itv.tv_sec, (uint32_t)tv.tv_sec);
    tv.tv_usec = atoi(buf+20) * 100;
    rv = Compare(tv, itv, 0.001);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_timestamp)
{
    {
        SCOPED_TRACE("test_timestamp");
        TestTimestamp(false, 0);
    }
}

TEST(TestClock, test_relative_timestamp)
{
    {
        SCOPED_TRACE("test_relative_timestamp: 0s");
        TestTimestamp(true, 0);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: 1s");
        TestTimestamp(true, 1);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: -1s");
        TestTimestamp(true, -1);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: 60s");
        TestTimestamp(true, 60);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: -60s");
        TestTimestamp(true, -60);
    }
}
<commit_msg>Fixed author of clock test<commit_after>//////////////////////////////////////////////////////////////////////////////
// Licensed to Qualys, Inc. (QUALYS) under one or more
// contributor license agreements.  See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// QUALYS licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////
/// @file
/// @brief IronBee &clock; Clock utility tests
///
/// @author Nick LeRoy <nleroy@qualys.com>
//////////////////////////////////////////////////////////////////////////////

#include <ironbee/hash.h>

#include "ironbee_config_auto.h"

#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"

#include <ironbee/types.h>
#include <ironbee/clock.h>

#include <stdexcept>
#include <sys/time.h>
#include <math.h>

double TvToSecs(const struct timeval &tv)
{
    return tv.tv_sec + (tv.tv_usec * 1e-6);
}
double TvToSecs(const ib_timeval_t &tv)
{
    return tv.tv_sec + (tv.tv_usec * 1e-6);
}

double GetTime(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return TvToSecs(tv);
}

bool CheckUsecDiff(int64_t t1, int64_t t2, unsigned int usecs)
{
    int64_t diff = (int64_t)llabs(t2 - t1);
    int64_t mean = (int64_t)llabs( (t2 + t1) / 2);
    int64_t limit = mean ? mean / 5 : 100000;

    return (diff >= 0) && (abs(diff - usecs) < limit);
}
bool CheckSecDiff(double t1, double t2, double secs, double limit=-1.0)
{
    double diff = fabs(t2 - t1);
    double mean = fabs( (t1 + t2) * 0.5);

    if (limit < 0.0) {
        limit = (mean > 0.0001) ? mean * 0.2 : 1e-5;
    }
    return (diff >= 0.0) && (fabs(diff - secs) < limit);
}

bool Compare(const struct timeval &tv,
             const ib_timeval_t &itv,
             double limit=-1.0)
{
    return CheckSecDiff(TvToSecs(tv), TvToSecs(itv), 0, limit);
}

bool CheckDelta(const ib_timeval_t &tv1,
                const ib_timeval_t &tv2,
                ib_time_t expected_usecs)
{
    return CheckSecDiff(TvToSecs(tv1), TvToSecs(tv2), expected_usecs * 1e-6);
}

bool CheckDelta(const ib_timeval_t &tv1,
                const ib_timeval_t &tv2,
                double expected_secs)
{
    return CheckSecDiff(TvToSecs(tv1), TvToSecs(tv2), expected_secs);
}

bool CheckDelta(ib_time_t t1,
                ib_time_t t2,
                ib_time_t expected_usecs)
{
    return CheckUsecDiff(t1, t2, expected_usecs);
}

TEST(TestClock, test_get_time)
{
    ib_time_t time1;
    ib_time_t time2;
    unsigned int usecs;
    bool rv;

    usecs = 1000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 10000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 100000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);

    usecs = 1000000;
    time1 = ib_clock_get_time( );
    usleep(usecs);
    time2 = ib_clock_get_time( );
    rv = CheckDelta(time1, time2, usecs);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_gettimeofday)
{
    struct timeval tv;
    ib_timeval_t   itv;
    bool           rv;

    ASSERT_EQ(0, gettimeofday(&tv, NULL) );
    ib_clock_gettimeofday(&itv);
    rv = Compare(tv, itv);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_gettimeofday_diffs)
{
    ib_timeval_t tv1;
    ib_timeval_t tv2;
    unsigned int usecs;
    bool         rv;
    double       t1;
    double       t2;

    usecs = 100000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);

    usecs = 500000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);

    usecs = 1000000;
    ib_clock_gettimeofday(&tv1);
    t1 = GetTime( );
    usleep(usecs);
    ib_clock_gettimeofday(&tv2);
    t2 = GetTime( );
    rv = CheckDelta(tv1, tv2, t2 - t1);
    ASSERT_TRUE(rv);
}

const size_t bufsize = 32;

void TestTimestamp(bool relative, int seconds)
{
    struct timeval tv;
    struct tm      tm;
    ib_timeval_t   itv;
    char           buf[bufsize + 1];
    bool           rv;

    ib_clock_gettimeofday(&itv);
    if (relative) {
        ib_time_t offset = seconds * 1000000;
        ib_clock_relative_timestamp(buf, &itv, offset);
    }
    else {
        seconds = 0;
        ib_clock_timestamp(buf, &itv);
    }

    ASSERT_STRNE(NULL, strptime(buf, "%Y-%m-%dT%H:%M:%S", &tm));
    tv.tv_sec = mktime(&tm) - seconds;
    ASSERT_EQ( (uint32_t)itv.tv_sec, (uint32_t)tv.tv_sec);
    tv.tv_usec = atoi(buf+20) * 100;
    rv = Compare(tv, itv, 0.001);
    ASSERT_TRUE(rv);
}

TEST(TestClock, test_timestamp)
{
    {
        SCOPED_TRACE("test_timestamp");
        TestTimestamp(false, 0);
    }
}

TEST(TestClock, test_relative_timestamp)
{
    {
        SCOPED_TRACE("test_relative_timestamp: 0s");
        TestTimestamp(true, 0);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: 1s");
        TestTimestamp(true, 1);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: -1s");
        TestTimestamp(true, -1);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: 60s");
        TestTimestamp(true, 60);
    }
    {
        SCOPED_TRACE("test_relative_timestamp: -60s");
        TestTimestamp(true, -60);
    }
}
<|endoftext|>


<commit_before>//
// BatchEncoder - GetProgress FaacEnc
// Copyright (C) 2005-2017 Wiesław Šoltés <wieslaw.soltes@gmail.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include "GetProgress.h"

int GetProgress(char *szLineBuff, int nLineLen)
{
    // NOTE: this is same code as LameEnc

    int nStart;
    int nEnd;
    char szPercentage[32];
    int j;
    int nProgress;

    memset(szPercentage, 0x00, sizeof(szPercentage));

    // check for percentage progress from console output (stdout)
    // '( 6%)'

    nStart = 0;
    nEnd = 0;

    for (j = 0; j < (int)nLineLen; j++)
    {
        if (szLineBuff[j] == '(')
        {
            nStart = j;
        }
        if (szLineBuff[j] == ')')
        {
            nEnd = j;
            break;
        }
    }

    if (nEnd > 0)
    {
        if ((nEnd - nStart) == 3)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
        else if ((nEnd - nStart) == 4)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = szLineBuff[nStart + 2];
            szPercentage[2] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
        else if ((nEnd - nStart) == 5)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = szLineBuff[nStart + 2];
            szPercentage[2] = szLineBuff[nStart + 3];
            szPercentage[3] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
    }

    return -1;
}
<commit_msg>Update GetProgress.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>

#include "GetProgress.h"

int GetProgress(char *szLineBuff, int nLineLen)
{
    // NOTE: this is same code as LameEnc

    int nStart;
    int nEnd;
    char szPercentage[32];
    int j;
    int nProgress;

    memset(szPercentage, 0x00, sizeof(szPercentage));

    // check for percentage progress from console output (stdout)
    // '( 6%)'

    nStart = 0;
    nEnd = 0;

    for (j = 0; j < (int)nLineLen; j++)
    {
        if (szLineBuff[j] == '(')
        {
            nStart = j;
        }
        if (szLineBuff[j] == ')')
        {
            nEnd = j;
            break;
        }
    }

    if (nEnd > 0)
    {
        if ((nEnd - nStart) == 3)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
        else if ((nEnd - nStart) == 4)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = szLineBuff[nStart + 2];
            szPercentage[2] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
        else if ((nEnd - nStart) == 5)
        {
            szPercentage[0] = szLineBuff[nStart + 1];
            szPercentage[1] = szLineBuff[nStart + 2];
            szPercentage[2] = szLineBuff[nStart + 3];
            szPercentage[3] = '\0';
            nProgress = atoi(szPercentage);

            return nProgress;
        }
    }

    return -1;
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include <simdee/util/allocator.hpp>
#include <vector>
#include <memory>

struct alignas(64)T {
    T(int64_t val) { v1 = val; v2 = val; }
    T(const T&) = default;
    T& operator=(const T&) = default;
    int64_t v1, v2;
};

TEST_CASE("sd::detail::alloc::malloc/free", "[allocator]") {
    SECTION("alloc T") {
        auto ptr = sd::detail::alloc<T>::malloc(sizeof(T));
        REQUIRE(uintptr_t(ptr) % alignof(T) == 0);
        ptr->v1 = -1;
        ptr->v2 = -1;
        sd::detail::alloc<T>::free(ptr);
    }
    SECTION("alloc double") {
        auto ptr = sd::detail::alloc<double>::malloc(sizeof(double));
        REQUIRE(uintptr_t(ptr) % alignof(double) == 0);
        *ptr = 1.23;
        sd::detail::alloc<double>::free(ptr);
    }
}

TEST_CASE("allocator", "[allocator]") {
    SECTION("vector<T>") {
        std::vector<T, sd::allocator<T>> vec;
        for (int i = 0; i < 123; i++) {
            vec.push_back(T{i});
        }
        for (int i : {0, 1, 10, 100, 122}) {
            REQUIRE(vec[i].v1 == i);
        }
    }
    SECTION("vector<double>") {
        std::vector<double, sd::allocator<double>> vec;
        for (int i = 0; i < 123; i++) {
            vec.push_back(i);
        }
        for (int i : {0, 1, 10, 100, 122}) {
            REQUIRE(vec[i] == i);
        }
    }
}

TEST_CASE("deleter", "[allocator]") {
    SECTION("unique_ptr<T>") {
        auto obj = sd::detail::alloc<T>::malloc(sizeof(T));
        new (obj)T{42};
        std::unique_ptr<T, sd::deleter<T>> ptr(obj);
        REQUIRE(ptr->v1 == 42);
        REQUIRE(ptr->v2 == 42);
    }
    SECTION("unique_ptr<double>") {
        auto obj = sd::detail::alloc<double>::malloc(sizeof(T));
        new (obj)double;
        std::unique_ptr<double, sd::deleter<double>> ptr(obj);
    }
}
<commit_msg>Add pad to suppress MSVC warning<commit_after>#include "catch.hpp"

#include <simdee/util/allocator.hpp>
#include <vector>
#include <memory>

struct alignas(64)T {
    T(int64_t val) { v1 = val; v2 = val; }
    T(const T&) = default;
    T& operator=(const T&) = default;
    int64_t v1, v2;
    char pad[48];
};

TEST_CASE("sd::detail::alloc::malloc/free", "[allocator]") {
    SECTION("alloc T") {
        auto ptr = sd::detail::alloc<T>::malloc(sizeof(T));
        REQUIRE(uintptr_t(ptr) % alignof(T) == 0);
        ptr->v1 = -1;
        ptr->v2 = -1;
        sd::detail::alloc<T>::free(ptr);
    }
    SECTION("alloc double") {
        auto ptr = sd::detail::alloc<double>::malloc(sizeof(double));
        REQUIRE(uintptr_t(ptr) % alignof(double) == 0);
        *ptr = 1.23;
        sd::detail::alloc<double>::free(ptr);
    }
}

TEST_CASE("allocator", "[allocator]") {
    SECTION("vector<T>") {
        std::vector<T, sd::allocator<T>> vec;
        for (int i = 0; i < 123; i++) {
            vec.push_back(T{i});
        }
        for (int i : {0, 1, 10, 100, 122}) {
            REQUIRE(vec[i].v1 == i);
        }
    }
    SECTION("vector<double>") {
        std::vector<double, sd::allocator<double>> vec;
        for (int i = 0; i < 123; i++) {
            vec.push_back(i);
        }
        for (int i : {0, 1, 10, 100, 122}) {
            REQUIRE(vec[i] == i);
        }
    }
}

TEST_CASE("deleter", "[allocator]") {
    SECTION("unique_ptr<T>") {
        auto obj = sd::detail::alloc<T>::malloc(sizeof(T));
        new (obj)T{42};
        std::unique_ptr<T, sd::deleter<T>> ptr(obj);
        REQUIRE(ptr->v1 == 42);
        REQUIRE(ptr->v2 == 42);
    }
    SECTION("unique_ptr<double>") {
        auto obj = sd::detail::alloc<double>::malloc(sizeof(T));
        new (obj)double;
        std::unique_ptr<double, sd::deleter<double>> ptr(obj);
    }
}
<|endoftext|>


<commit_before>#include "CrowApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"

#include "CHChemPotential.h"
#include "CHTemp.h"
#include "ACSinteringGrowth.h"
#include "PFDiffusion.h"
#include "PFDiffusionGrowthConst.h"
#include "PFDiffusionGrowth.h"
#include "PFDiffusionGrowth1.h"
#include "PFParticleGrowth.h"
#include "PFEigenStrainMaterial.h"
#include "PFEigenStrainMaterial1.h"
#include "TwoParticleGrainsIC.h"
#include "PFTempMobility.h"

#include "PolycrystalSinteringKernelAction.h"
#include "PolycrystalSinteringMaterialAction.h"
#include "TwoParticleGrainsICAction.h"
#include "TwoParticleDensityIC.h"

//#include "MobilityFn.h"

template<>
InputParameters validParams<CrowApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

CrowApp::CrowApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  ModulesApp::registerObjects(_factory);
  CrowApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  ModulesApp::associateSyntax(_syntax, _action_factory);
  CrowApp::associateSyntax(_syntax, _action_factory);
}

CrowApp::~CrowApp()
{
}

void
CrowApp::registerApps()
{
  registerApp(CrowApp);
}

void
CrowApp::registerObjects(Factory & factory)
{
  // Register any custom objects you have built on the MOOSE Framework
  registerKernel(CHChemPotential);  // <- registration
  registerKernel(CHTemp);
  registerKernel(ACSinteringGrowth);

  registerMaterial(PFDiffusion);
  registerMaterial(PFDiffusionGrowthConst);
  registerMaterial(PFDiffusionGrowth);
  registerMaterial(PFDiffusionGrowth1);
  registerMaterial(PFEigenStrainMaterial);
  registerMaterial(PFEigenStrainMaterial1);
  registerMaterial(PFParticleGrowth);
  registerMaterial(PFTempMobility);

  registerInitialCondition(TwoParticleGrainsIC);
  registerInitialCondition(TwoParticleDensityIC);

  //registerFunction(MobilityFn);
}

void
CrowApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
  syntax.registerActionSyntax("PolycrystalSinteringKernelAction", "Kernels/PolycrystalSinteringKernel");
  syntax.registerActionSyntax("PolycrystalSinteringMaterialAction", "Materials/PolycrystalSinteringMaterial");
  syntax.registerActionSyntax("TwoParticleGrainsICAction", "ICs/PolycrystalICs/TwoParticleGrainsIC");

  registerAction(PolycrystalSinteringKernelAction, "add_kernel");
  registerAction(PolycrystalSinteringMaterialAction, "add_material");
  registerAction(TwoParticleGrainsICAction, "add_ic");
}
<commit_msg>Adding support for dynamic multiapps (see https://github.com/idaholab/moose/issues/4643)<commit_after>#include "CrowApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"

#include "CHChemPotential.h"
#include "CHTemp.h"
#include "ACSinteringGrowth.h"
#include "PFDiffusion.h"
#include "PFDiffusionGrowthConst.h"
#include "PFDiffusionGrowth.h"
#include "PFDiffusionGrowth1.h"
#include "PFParticleGrowth.h"
#include "PFEigenStrainMaterial.h"
#include "PFEigenStrainMaterial1.h"
#include "TwoParticleGrainsIC.h"
#include "PFTempMobility.h"

#include "PolycrystalSinteringKernelAction.h"
#include "PolycrystalSinteringMaterialAction.h"
#include "TwoParticleGrainsICAction.h"
#include "TwoParticleDensityIC.h"

//#include "MobilityFn.h"

template<>
InputParameters validParams<CrowApp>()
{
  InputParameters params = validParams<MooseApp>();
  return params;
}

CrowApp::CrowApp(const std::string & name, InputParameters parameters) :
    MooseApp(name, parameters)
{
  srand(processor_id());

  Moose::registerObjects(_factory);
  ModulesApp::registerObjects(_factory);
  CrowApp::registerObjects(_factory);

  Moose::associateSyntax(_syntax, _action_factory);
  ModulesApp::associateSyntax(_syntax, _action_factory);
  CrowApp::associateSyntax(_syntax, _action_factory);
}

CrowApp::~CrowApp()
{
}

extern "C" void CrowApp__registerApps() { CrowApp::registerApps(); }
void
CrowApp::registerApps()
{
  registerApp(CrowApp);
}

void
CrowApp::registerObjects(Factory & factory)
{
  // Register any custom objects you have built on the MOOSE Framework
  registerKernel(CHChemPotential);  // <- registration
  registerKernel(CHTemp);
  registerKernel(ACSinteringGrowth);

  registerMaterial(PFDiffusion);
  registerMaterial(PFDiffusionGrowthConst);
  registerMaterial(PFDiffusionGrowth);
  registerMaterial(PFDiffusionGrowth1);
  registerMaterial(PFEigenStrainMaterial);
  registerMaterial(PFEigenStrainMaterial1);
  registerMaterial(PFParticleGrowth);
  registerMaterial(PFTempMobility);

  registerInitialCondition(TwoParticleGrainsIC);
  registerInitialCondition(TwoParticleDensityIC);

  //registerFunction(MobilityFn);
}

void
CrowApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
  syntax.registerActionSyntax("PolycrystalSinteringKernelAction", "Kernels/PolycrystalSinteringKernel");
  syntax.registerActionSyntax("PolycrystalSinteringMaterialAction", "Materials/PolycrystalSinteringMaterial");
  syntax.registerActionSyntax("TwoParticleGrainsICAction", "ICs/PolycrystalICs/TwoParticleGrainsIC");

  registerAction(PolycrystalSinteringKernelAction, "add_kernel");
  registerAction(PolycrystalSinteringMaterialAction, "add_material");
  registerAction(TwoParticleGrainsICAction, "add_ic");
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
    using std::strlen;
#endif

#include <osg/Notify>

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
	    return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<fileName<<")"<<std::endl;

    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<new_fileName<<")"<<std::endl;

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    std::string ext = osgDB::getFileExtension(filename);
    for(std::string::iterator itr=ext.begin();
        itr!=ext.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return ext;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for http://
    if (filename.size()<7) return false;
    if (filename.compare(0,7,"http://")==0) return true;
    return false;
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(7,pos_slash-7);
        }
        else
        {
            return filename.substr(7,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
//     std::string test("/here/we/are.exe");
//     std::string test2("\\there\\you\\go.dll");
//     std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
//     std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
//     std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
//     std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
//     std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
//     std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<commit_msg>Removed debugging messages<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
    using std::strlen;
#endif

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
	    return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    std::string ext = osgDB::getFileExtension(filename);
    for(std::string::iterator itr=ext.begin();
        itr!=ext.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return ext;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for http://
    if (filename.size()<7) return false;
    if (filename.compare(0,7,"http://")==0) return true;
    return false;
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(7,pos_slash-7);
        }
        else
        {
            return filename.substr(7,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',7);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
//     std::string test("/here/we/are.exe");
//     std::string test2("\\there\\you\\go.dll");
//     std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
//     std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
//     std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
//     std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
//     std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
//     std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<|endoftext|>


<commit_before>
#include "benchmark/benchmark.h"

#define BASIC_BENCHMARK_TEST(x) BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192)

void BM_empty(benchmark::State& state) {
  for (auto _ : state) {
    benchmark::DoNotOptimize(state.iterations());
  }
}
BENCHMARK(BM_empty);
BENCHMARK(BM_empty)->ThreadPerCpu();

void BM_spin_empty(benchmark::State& state) {
  for (auto _ : state) {
    for (auto x = 0; x < state.range(0); ++x) {
      benchmark::DoNotOptimize(x);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_empty);
BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu();

void BM_spin_pause_before(benchmark::State& state) {
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_before);
BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu();

void BM_spin_pause_during(benchmark::State& state) {
  for (auto _ : state) {
    state.PauseTiming();
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
    state.ResumeTiming();
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_during);
BASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu();

void BM_pause_during(benchmark::State& state) {
  for (auto _ : state) {
    state.PauseTiming();
    state.ResumeTiming();
  }
}
BENCHMARK(BM_pause_during);
BENCHMARK(BM_pause_during)->ThreadPerCpu();
BENCHMARK(BM_pause_during)->UseRealTime();
BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu();

void BM_spin_pause_after(benchmark::State& state) {
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_after);
BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu();

void BM_spin_pause_before_and_after(benchmark::State& state) {
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after);
BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu();

void BM_empty_stop_start(benchmark::State& state) {
  for (auto _ : state) {
  }
}
BENCHMARK(BM_empty_stop_start);
BENCHMARK(BM_empty_stop_start)->ThreadPerCpu();

void BM_KeepRunning(benchmark::State& state) {
  benchmark::IterationCount iter_count = 0;
  assert(iter_count == state.iterations());
  while (state.KeepRunning()) {
    ++iter_count;
  }
  assert(iter_count == state.iterations());
}
BENCHMARK(BM_KeepRunning);

void BM_KeepRunningBatch(benchmark::State& state) {
  // Choose a batch size >1000 to skip the typical runs with iteration
  // targets of 10, 100 and 1000.  If these are not actually skipped the
  // bug would be detectable as consecutive runs with the same iteration
  // count.  Below we assert that this does not happen.
  const benchmark::IterationCount batch_size = 1009;

  static benchmark::IterationCount prior_iter_count = 0;
  benchmark::IterationCount iter_count = 0;
  while (state.KeepRunningBatch(batch_size)) {
    iter_count += batch_size;
  }
  assert(state.iterations() == iter_count);

  // Verify that the iteration count always increases across runs (see
  // comment above).
  assert(iter_count == batch_size            // max_iterations == 1
         || iter_count > prior_iter_count);  // max_iterations > batch_size
  prior_iter_count = iter_count;
}
// Register with a fixed repetition count to establish the invariant that
// the iteration count should always change across runs.  This overrides
// the --benchmark_repetitions command line flag, which would otherwise
// cause this test to fail if set > 1.
BENCHMARK(BM_KeepRunningBatch)->Repetitions(1);

void BM_RangedFor(benchmark::State& state) {
  benchmark::IterationCount iter_count = 0;
  for (auto _ : state) {
    ++iter_count;
  }
  assert(iter_count == state.max_iterations);
}
BENCHMARK(BM_RangedFor);

#ifdef BENCHMARK_HAS_CXX11
template <typename T>
void BM_OneTemplateFunc(benchmark::State& state) {
  auto arg = state.range(0);
  T sum = 0;
  for (auto _ : state) {
    sum += arg;
  }
}
BENCHMARK(BM_OneTemplateFunc<int>)->Arg(1);
BENCHMARK(BM_OneTemplateFunc<double>)->Arg(1);

template <typename A, typename B>
void BM_TwoTemplateFunc(benchmark::State& state) {
  auto arg = state.range(0);
  A sum = 0;
  B prod = 1;
  for (auto _ : state) {
    sum += arg;
    prod *= arg;
  }
}
BENCHMARK(BM_TwoTemplateFunc<int, double>)->Arg(1);
BENCHMARK(BM_TwoTemplateFunc<double, int>)->Arg(1);

#endif  // BENCHMARK_HAS_CXX11

// Ensure that StateIterator provides all the necessary typedefs required to
// instantiate std::iterator_traits.
static_assert(
    std::is_same<typename std::iterator_traits<
                     benchmark::State::StateIterator>::value_type,
                 typename benchmark::State::StateIterator::value_type>::value,
    "");

BENCHMARK_MAIN();
<commit_msg>Avoid potential truncation issues for the integral type parameterized tests. (#1341)<commit_after>
#include "benchmark/benchmark.h"

#define BASIC_BENCHMARK_TEST(x) BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192)

void BM_empty(benchmark::State& state) {
  for (auto _ : state) {
    benchmark::DoNotOptimize(state.iterations());
  }
}
BENCHMARK(BM_empty);
BENCHMARK(BM_empty)->ThreadPerCpu();

void BM_spin_empty(benchmark::State& state) {
  for (auto _ : state) {
    for (auto x = 0; x < state.range(0); ++x) {
      benchmark::DoNotOptimize(x);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_empty);
BASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu();

void BM_spin_pause_before(benchmark::State& state) {
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_before);
BASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu();

void BM_spin_pause_during(benchmark::State& state) {
  for (auto _ : state) {
    state.PauseTiming();
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
    state.ResumeTiming();
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_during);
BASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu();

void BM_pause_during(benchmark::State& state) {
  for (auto _ : state) {
    state.PauseTiming();
    state.ResumeTiming();
  }
}
BENCHMARK(BM_pause_during);
BENCHMARK(BM_pause_during)->ThreadPerCpu();
BENCHMARK(BM_pause_during)->UseRealTime();
BENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu();

void BM_spin_pause_after(benchmark::State& state) {
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_after);
BASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu();

void BM_spin_pause_before_and_after(benchmark::State& state) {
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
  for (auto _ : state) {
    for (auto i = 0; i < state.range(0); ++i) {
      benchmark::DoNotOptimize(i);
    }
  }
  for (auto i = 0; i < state.range(0); ++i) {
    benchmark::DoNotOptimize(i);
  }
}
BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after);
BASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu();

void BM_empty_stop_start(benchmark::State& state) {
  for (auto _ : state) {
  }
}
BENCHMARK(BM_empty_stop_start);
BENCHMARK(BM_empty_stop_start)->ThreadPerCpu();

void BM_KeepRunning(benchmark::State& state) {
  benchmark::IterationCount iter_count = 0;
  assert(iter_count == state.iterations());
  while (state.KeepRunning()) {
    ++iter_count;
  }
  assert(iter_count == state.iterations());
}
BENCHMARK(BM_KeepRunning);

void BM_KeepRunningBatch(benchmark::State& state) {
  // Choose a batch size >1000 to skip the typical runs with iteration
  // targets of 10, 100 and 1000.  If these are not actually skipped the
  // bug would be detectable as consecutive runs with the same iteration
  // count.  Below we assert that this does not happen.
  const benchmark::IterationCount batch_size = 1009;

  static benchmark::IterationCount prior_iter_count = 0;
  benchmark::IterationCount iter_count = 0;
  while (state.KeepRunningBatch(batch_size)) {
    iter_count += batch_size;
  }
  assert(state.iterations() == iter_count);

  // Verify that the iteration count always increases across runs (see
  // comment above).
  assert(iter_count == batch_size            // max_iterations == 1
         || iter_count > prior_iter_count);  // max_iterations > batch_size
  prior_iter_count = iter_count;
}
// Register with a fixed repetition count to establish the invariant that
// the iteration count should always change across runs.  This overrides
// the --benchmark_repetitions command line flag, which would otherwise
// cause this test to fail if set > 1.
BENCHMARK(BM_KeepRunningBatch)->Repetitions(1);

void BM_RangedFor(benchmark::State& state) {
  benchmark::IterationCount iter_count = 0;
  for (auto _ : state) {
    ++iter_count;
  }
  assert(iter_count == state.max_iterations);
}
BENCHMARK(BM_RangedFor);

#ifdef BENCHMARK_HAS_CXX11
template <typename T>
void BM_OneTemplateFunc(benchmark::State& state) {
  auto arg = state.range(0);
  T sum = 0;
  for (auto _ : state) {
    sum += static_cast<T>(arg);
  }
}
BENCHMARK(BM_OneTemplateFunc<int>)->Arg(1);
BENCHMARK(BM_OneTemplateFunc<double>)->Arg(1);

template <typename A, typename B>
void BM_TwoTemplateFunc(benchmark::State& state) {
  auto arg = state.range(0);
  A sum = 0;
  B prod = 1;
  for (auto _ : state) {
    sum += static_cast<A>(arg);
    prod *= static_cast<B>(arg);
  }
}
BENCHMARK(BM_TwoTemplateFunc<int, double>)->Arg(1);
BENCHMARK(BM_TwoTemplateFunc<double, int>)->Arg(1);

#endif  // BENCHMARK_HAS_CXX11

// Ensure that StateIterator provides all the necessary typedefs required to
// instantiate std::iterator_traits.
static_assert(
    std::is_same<typename std::iterator_traits<
                     benchmark::State::StateIterator>::value_type,
                 typename benchmark::State::StateIterator::value_type>::value,
    "");

BENCHMARK_MAIN();
<|endoftext|>


<commit_before>
#include "../src/AtomicStack.h"
#include "../src/LocalWriteEM.h"

// This must be instanciated in the translation unit where it is
// used. Otherwise the compiler is not able to know its existence
// which causes the linker to complain
template <uint64_t core_num, typename GarbageNode>
std::unordered_map<void *, void *>
LocalWriteEMFactory<core_num, GarbageNode>::instance_map{};

// Since the EM type is defined by the EMFactory type, we could
// make it easier
using EMFactory = LocalWriteEMFactory<4, char>;
using EM = typename EMFactory::TargetType;

int main() {
  // This instance must be created by the factory
  EM *p = EMFactory::GetInstance();

  dbg_printf("pointer = %p\n", p);
  dbg_printf("Multiple of 64? %d\n", (int)!((uint64_t)p % 64));
  // Otherwise it fails 64 bit alignment test
  assert(((uint64_t)p % 64) == 0);

  // Enjoy the beauty of C++11!!!!!!!
  dbg_printf("ElementType size = %lu\n",
             sizeof(typename std::remove_pointer<decltype(p)>::type::ElementType));

  EMFactory::FreeInstance(p);

  return 0;
}
<commit_msg>Adding hardware_concurrency() call into benchmark<commit_after>
#include "../src/AtomicStack.h"
#include "../src/LocalWriteEM.h"

// This must be instanciated in the translation unit where it is
// used. Otherwise the compiler is not able to know its existence
// which causes the linker to complain
template <uint64_t core_num, typename GarbageNode>
std::unordered_map<void *, void *>
LocalWriteEMFactory<core_num, GarbageNode>::instance_map{};

// Since the EM type is defined by the EMFactory type, we could
// make it easier
using EMFactory = LocalWriteEMFactory<4, char>;
using EM = typename EMFactory::TargetType;

int main() {
  // This prints the number of threads supported by CPU
  // including hyper-threading, i.e. if HP is present then the actual number
  // of cores is half
  dbg_printf("Hardware concurrency = %u\n", std::thread::hardware_concurrency());

  // This instance must be created by the factory
  EM *p = EMFactory::GetInstance();

  dbg_printf("pointer = %p\n", p);
  dbg_printf("Multiple of 64? %d\n", (int)!((uint64_t)p % 64));
  // Otherwise it fails 64 bit alignment test
  assert(((uint64_t)p % 64) == 0);

  // Enjoy the beauty of C++11!!!!!!!
  dbg_printf("ElementType size = %lu\n",
             sizeof(typename std::remove_pointer<decltype(p)>::type::ElementType));

  EMFactory::FreeInstance(p);

  return 0;
}
<|endoftext|>