text:
namespace ogl_utils
{
    decltype(GET_PROC_ADDRESS_TYPE)* GET_PROC_ADDRESS_FUNC = nullptr;

    decltype(glFlush)*       ogl_flush         = nullptr;
    decltype(glGetString)*   ogl_get_string    = nullptr;
    decltype(glGetIntegerv)* ogl_get_integer_v = nullptr;
    decltype(glGetError)*    ogl_get_error     = nullptr;
    PFNGLGETSTRINGIPROC      ogl_get_string_i  = nullptr;

    PFNGLGETQUERYOBJECTIVPROC       ogl_get_query_objective_iv       = nullptr;
    PFNGLGENQUERIESPROC             ogl_gen_queries                  = nullptr;
    PFNGLDELETEQUERIESPROC          ogl_delete_queries               = nullptr;
    PFNGLQUERYCOUNTERPROC           ogl_query_counter                = nullptr;
    PFNGLGETQUERYOBJECTUI64VEXTPROC ogl_get_query_object_ui_64_v_ext = nullptr;

    /// AMD perf monitor extensions.
    PFNGLGETPERFMONITORGROUPSAMDPROC        ogl_get_perf_monitor_groups_amd         = nullptr;
    PFNGLGETPERFMONITORCOUNTERSAMDPROC      ogl_get_perf_monitor_counters_amd       = nullptr;
    PFNGLGETPERFMONITORGROUPSTRINGAMDPROC   ogl_get_perf_monitor_group_string_amd   = nullptr;
    PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC ogl_get_perf_monitor_counter_string_amd = nullptr;
    PFNGLGETPERFMONITORCOUNTERINFOAMDPROC   ogl_get_perf_monitor_counter_info_amd   = nullptr;
    PFNGLGENPERFMONITORSAMDPROC             ogl_gen_perf_monitors_amd               = nullptr;
    PFNGLDELETEPERFMONITORSAMDPROC          ogl_delete_perf_monitors_amd            = nullptr;
    PFNGLSELECTPERFMONITORCOUNTERSAMDPROC   ogl_select_perf_monitor_counters_amd    = nullptr;
    PFNGLBEGINPERFMONITORAMDPROC            ogl_begin_perf_monitor_amd              = nullptr;
    PFNGLENDPERFMONITORAMDPROC              ogl_end_perf_monitor_amd                = nullptr;
    PFNGLGETPERFMONITORCOUNTERDATAAMDPROC   ogl_get_perf_monitor_counter_data_amd   = nullptr;

#ifdef DEBUG_GL_ERRORS
    // Function pointers for the GL_ARB_debug_output extension - used to improve error reporting.
    PFN_OGL_GLDEBUGMESSAGECONTROLARB  ogl_debug_message_control_arb  = nullptr;
    PFN_OGL_GLDEBUGMESSAGEINSERTARB   ogl_debug_message_insert_arb   = nullptr;
    PFN_OGL_GLDEBUGMESSAGECALLBACKARB ogl_debug_message_callback_arb = nullptr;
    PFN_OGL_GLGETDEBUGMESSAGELOGARB   ogl_get_debug_message_log_arb  = nullptr;
#endif

    // Function pointers for GLX_MESA_query_renderer extension.
    PFN_GLX_QUERYCURRENTRENDERERINTEGERMESA ogl_x_query_current_renderer_integer_mesa = nullptr;

    PFN_GL_SETGPADEVICECLOCKMODEAMDX ogl_set_gpa_device_clock_mode_amd_x = nullptr;

    const char* kAmdRendererString           = "AMD";
    const char* kRadeonRendererString        = "Radeon";
    const char* kAtiRendererString           = "ATI";
    const char* kNvidiaRendererString        = "NVIDIA";
    const char* kIntelRendererString         = "Intel";
    bool        are_gl_functions_initialized = false;
    LibHandle   gl_lib_handle                = nullptr;
#ifdef GLES
    LibHandle gl_es_lib_handle = nullptr;
#endif
    bool are_supported_extensions_queried = false;

    std::map<GLExtension, Supported> gl_extensions_map = {{std::string("GL_AMD_performance_monitor"), false},
                                                          {std::string("GL_ARB_timer_query"), false},
                                                          {std::string("GL_EXT_disjoint_timer_query"), false},
                                                          {std::string("GL_AMD_debug_output"), false},
                                                          {std::string("GLX_MESA_query_renderer"), false},
                                                          {std::string("WGL_AMD_gpu_association"), false},
                                                          {std::string("GLX_AMD_GPU_association"), false}};

    const int kGlDriverVerWithOnlyGcnSupport          = 13452;  ///< GL driver version where pre-GCN hardware was dropped.
    const int kGlDriverVerWithLinuxStableClockSupport = 13562;  ///< GL driver version where stable clocks are working on Linux.
    const int kGlDriverVerWithGpinCounters            = 13565;  ///< GL driver version where GPIN counters have been validated.

    bool CheckForGlError(const std::string& error_message)
    {
        bool   error_found = false;
        GLenum gl_error    = ogl_utils::ogl_get_error();

        if (gl_error != GL_NO_ERROR)
        {
            switch (gl_error)
            {
            case GL_INVALID_ENUM:
            case GL_INVALID_VALUE:
            case GL_INVALID_OPERATION:
            case GL_STACK_OVERFLOW:
            case GL_STACK_UNDERFLOW:
            case GL_OUT_OF_MEMORY:
                error_found = true;
                GPA_LOG_ERROR(error_message.c_str());
                break;

            default:
                assert(gl_error == GL_NO_ERROR);
                break;
            }
        }

        return error_found;
    }
}

bool ogl_utils::LoadGl()
{
    if (nullptr == gl_lib_handle)
    {
#ifdef _WIN32
#ifndef GLES
        gl_lib_handle = LoadLibraryA("opengl32.dll");
#else
        gl_lib_handle = LoadLibraryA("libEGL.dll");
#endif
#else
#ifndef GLES
        gl_lib_handle = dlopen("libGL.so", RTLD_LAZY);
#else
        gl_es_lib_handle = dlopen("libEGL.so", RTLD_NOW);

        if (nullptr == gl_lib_handle)
        {
            gl_lib_handle = dlopen("libGLESv3.so", RTLD_NOW);

            if (nullptr == gl_lib_handle)
            {
                gl_lib_handle = dlopen("libGLESv2.so", RTLD_NOW);

                if (nullptr == gl_lib_handle)
                {
                    gl_lib_handle = dlopen("libGLES.so", RTLD_NOW);
                }
            }
        }
#endif
#endif
    }

#ifndef GLES
    return nullptr != gl_lib_handle;
#else
    return nullptr != gl_lib_handle && nullptr != gl_es_lib_handle;
#endif
}

void ogl_utils::QuerySupportedExtensions()
{
    if (nullptr != ogl_get_string && !are_supported_extensions_queried)
    {
        GPA_LOG_MESSAGE("Using OpenGL 1.x method to query extensions.");
        GLint num_extensions = 0;
        ogl_get_integer_v(GL_NUM_EXTENSIONS, &num_extensions);

        if (nullptr != ogl_get_string_i)
        {
            for (GLint i = 0; i < num_extensions; i++)
            {
                const char* extension = reinterpret_cast<const char*>(ogl_get_string_i(GL_EXTENSIONS, i));

                if ((nullptr != extension) && (gl_extensions_map.find(extension) != gl_extensions_map.end()))
                {
                    gl_extensions_map[extension] = true;
                }
            }
        }

        are_supported_extensions_queried = true;
    }
}

bool ogl_utils::InitializeGlCoreFunctions()
{
    if (LoadGl())
    {
        // Load GL core functions.
        LOAD_LIBRARY_SYMBOL(ogl_flush, glFlush);
        LOAD_LIBRARY_SYMBOL(ogl_get_string, glGetString);
        LOAD_LIBRARY_SYMBOL(ogl_get_integer_v, glGetIntegerv);
        LOAD_LIBRARY_SYMBOL(ogl_get_error, glGetError);

        if (nullptr == ogl_flush || nullptr == ogl_get_string || nullptr == ogl_get_integer_v || nullptr == ogl_get_error)
        {
            GPA_LOG_MESSAGE("Unable to Initialize GL core functions.");
            return false;
        }

        return true;
    }

    return false;
}

bool ogl_utils::InitCtxAmdPerfExtFunctions()
{
    if (LoadGl())
    {
        if (nullptr == GET_PROC_ADDRESS_FUNC)
        {
#ifndef GLES
            GET_PROC_ADDRESS_FUNC = reinterpret_cast<decltype(GET_PROC_ADDRESS_TYPE)*>(LOAD_SYMBOL(gl_lib_handle, GPA_STRINGIFY(GET_PROC_ADDRESS_TYPE)));
#else
            GET_PROC_ADDRESS_FUNC = reinterpret_cast<decltype(GET_PROC_ADDRESS_TYPE)*>(LOAD_SYMBOL(gl_es_lib_handle, GPA_STRINGIFY(GET_PROC_ADDRESS_TYPE)));
#endif
        }

        // Load AMD Perf extension functions.
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_groups_amd, PFNGLGETPERFMONITORGROUPSAMDPROC, "glGetPerfMonitorGroupsAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_counters_amd, PFNGLGETPERFMONITORCOUNTERSAMDPROC, "glGetPerfMonitorCountersAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_group_string_amd, PFNGLGETPERFMONITORGROUPSTRINGAMDPROC, "glGetPerfMonitorGroupStringAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_counter_string_amd, PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC, "glGetPerfMonitorCounterStringAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_counter_info_amd, PFNGLGETPERFMONITORCOUNTERINFOAMDPROC, "glGetPerfMonitorCounterInfoAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_gen_perf_monitors_amd, PFNGLGENPERFMONITORSAMDPROC, "glGenPerfMonitorsAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_delete_perf_monitors_amd, PFNGLDELETEPERFMONITORSAMDPROC, "glDeletePerfMonitorsAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_select_perf_monitor_counters_amd, PFNGLSELECTPERFMONITORCOUNTERSAMDPROC, "glSelectPerfMonitorCountersAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_begin_perf_monitor_amd, PFNGLBEGINPERFMONITORAMDPROC, "glBeginPerfMonitorAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_end_perf_monitor_amd, PFNGLENDPERFMONITORAMDPROC, "glEndPerfMonitorAMD");
        GET_CONTEXT_PROC_ADDRESS(ogl_get_perf_monitor_counter_data_amd, PFNGLGETPERFMONITORCOUNTERDATAAMDPROC, "glGetPerfMonitorCounterDataAMD");

        return (nullptr != ogl_get_perf_monitor_groups_amd && nullptr != ogl_get_perf_monitor_counters_amd &&
                nullptr != ogl_get_perf_monitor_group_string_amd && nullptr != ogl_get_perf_monitor_counter_string_amd &&
                nullptr != ogl_get_perf_monitor_counter_info_amd && nullptr != ogl_gen_perf_monitors_amd && nullptr != ogl_delete_perf_monitors_amd &&
                nullptr != ogl_select_perf_monitor_counters_amd && nullptr != ogl_begin_perf_monitor_amd && nullptr != ogl_end_perf_monitor_amd &&
                nullptr != ogl_get_perf_monitor_counter_data_amd);
    }

    return false;
}

bool ogl_utils::InitializeGlFunctions()
{
    if (are_gl_functions_initialized)
    {
        return true;
    }

    bool ret_val = true;

    if (!LoadGl())
    {
        GPA_LOG_ERROR("Unable to get handle of OpenGL module.");
        return false;
    }

#ifndef GLES
    GET_PROC_ADDRESS_FUNC = reinterpret_cast<decltype(GET_PROC_ADDRESS_TYPE)*>(LOAD_SYMBOL(gl_lib_handle, GPA_STRINGIFY(GET_PROC_ADDRESS_TYPE)));
#else
    GET_PROC_ADDRESS_FUNC = reinterpret_cast<decltype(GET_PROC_ADDRESS_TYPE)*>(LOAD_SYMBOL(gl_es_lib_handle, GPA_STRINGIFY(GET_PROC_ADDRESS_TYPE)));
#endif

    if (!InitializeGlCoreFunctions())
    {
        GPA_LOG_ERROR("Unable to Initialize required GL functions.");
        return false;
    }

    GET_CONTEXT_PROC_ADDRESS(ogl_get_string_i, PFNGLGETSTRINGIPROC, "glGetStringi");

    QuerySupportedExtensions();

    bool perf_mon_ext_found    = gl_extensions_map["GL_AMD_performance_monitor"];
    bool timer_query_ext_found = gl_extensions_map["GL_ARB_timer_query"] || gl_extensions_map["GL_EXT_disjoint_timer_query"];

    if (!InitCtxAmdPerfExtFunctions())
    {
        if (perf_mon_ext_found)
        {
            GPA_LOG_ERROR("The GL_AMD_performance_monitor extension is exposed by the driver, but not all entry points are available.");
        }
        else
        {
            GPA_LOG_ERROR("The GL_AMD_performance_monitor extension is not exposed by the driver.");
        }

        const GLubyte* renderer = ogl_get_string(GL_RENDERER);

        if (nullptr == renderer)
        {
            // Return error if unable to retrieve renderer.
            ret_val = false;
        }
        else if (strstr(reinterpret_cast<const char*>(renderer), kAtiRendererString) == 0 ||
                 strstr(reinterpret_cast<const char*>(renderer), kAmdRendererString) == 0)
        {
            // Return error if AMD extension is missing on AMD hardware.
            ret_val = false;
        }
    }

    GET_CONTEXT_PROC_ADDRESS(ogl_set_gpa_device_clock_mode_amd_x, PFN_GL_SETGPADEVICECLOCKMODEAMDX, "glSetGpaDeviceClockModeAMDX");
    GET_CONTEXT_PROC_ADDRESS(ogl_get_query_object_ui_64_v_ext, PFNGLGETQUERYOBJECTUI64VPROC, "glGetQueryObjectui64v");

#if defined(GLES) && !defined(WIN32)
    GET_CONTEXT_PROC_ADDRESS(ogl_get_query_objective_iv, PFNGLGETQUERYOBJECTIVPROC, "glGetQueryObjectivEXT");
    GET_CONTEXT_PROC_ADDRESS(ogl_gen_queries, PFNGLGENQUERIESPROC, "glGenQueriesEXT");
    GET_CONTEXT_PROC_ADDRESS(ogl_delete_queries, PFNGLDELETEQUERIESPROC, "glDeleteQueriesEXT");
    GET_CONTEXT_PROC_ADDRESS(ogl_query_counter, PFNGLQUERYCOUNTERPROC, "glQueryCounterEXT");
#else
    GET_CONTEXT_PROC_ADDRESS(ogl_get_query_objective_iv, PFNGLGETQUERYOBJECTIVPROC, "glGetQueryObjectiv");
    GET_CONTEXT_PROC_ADDRESS(ogl_gen_queries, PFNGLGENQUERIESPROC, "glGenQueries");
    GET_CONTEXT_PROC_ADDRESS(ogl_delete_queries, PFNGLDELETEQUERIESPROC, "glDeleteQueries");
    GET_CONTEXT_PROC_ADDRESS(ogl_query_counter, PFNGLQUERYCOUNTERPROC, "glQueryCounter");
#endif

#ifdef GLES
#ifndef GL_TIMESTAMP
#define GL_TIMESTAMP GL_TIMESTAMP_EXT
#endif
#endif

    if (nullptr == ogl_get_query_objective_iv)
    {
        GPA_LOG_MESSAGE("glGetQueryObjectiv entry point not exposed by the driver.");
    }

    if (nullptr == ogl_gen_queries)
    {
        GPA_LOG_MESSAGE("glGenQueries entry point not exposed by the driver.");
    }

    if (nullptr == ogl_delete_queries)
    {
        GPA_LOG_MESSAGE("glDeleteQueries entry point not exposed by the driver.");
    }

    if (nullptr == ogl_query_counter)
    {
        GPA_LOG_MESSAGE("glQueryCounter entry point not exposed by the driver.");
    }

    if (nullptr == ogl_get_query_object_ui_64_v_ext)
    {
        GPA_LOG_MESSAGE("glGetQueryObjectui64vEXT entry point not exposed by the driver.");
    }

    if (nullptr == ogl_get_string_i || nullptr == ogl_get_query_object_ui_64_v_ext || nullptr == ogl_get_query_objective_iv || nullptr == ogl_gen_queries ||
        nullptr == ogl_delete_queries || nullptr == ogl_query_counter)
    {
        if (timer_query_ext_found)
        {
#ifndef GLES
            GPA_LOG_ERROR("The GL_ARB_timer_query extension is exposed by the driver, but the not all entry points are available.");
#else
            GPA_LOG_ERROR("The GL_EXT_disjoint_timer_query extension is exposed by the driver, but the entry points are not available.");
#endif
        }
        else
        {
#ifndef GLES
            GPA_LOG_ERROR("The GL_ARB_timer_query extension is not exposed by the driver.");
#else
            GPA_LOG_ERROR("The GL_EXT_disjoint_timer_query extension is not exposed by the driver.");
#endif
        }

        ret_val = false;
    }

#ifdef DEBUG_GL_ERRORS
    bool debug_output_ext_found = gl_extensions_map["GL_AMD_debug_output"];
    // GL_AMD_debug_output extension.
    GET_CONTEXT_PROC_ADDRESS(ogl_debug_message_control_arb, PFN_OGL_GLDEBUGMESSAGECONTROLARB, "glDebugMessageControlAMD");
    GET_CONTEXT_PROC_ADDRESS(ogl_debug_message_insert_arb, PFN_OGL_GLDEBUGMESSAGEINSERTARB, "glDebugMessageInsertAMD");
    GET_CONTEXT_PROC_ADDRESS(ogl_debug_message_callback_arb, PFN_OGL_GLDEBUGMESSAGECALLBACKARB, "glDebugMessageCallbackAMD");
    GET_CONTEXT_PROC_ADDRESS(ogl_get_debug_message_log_arb, PFN_OGL_GLGETDEBUGMESSAGELOGARB, "glGetDebugMessageLogAMD");

    if (nullptr == ogl_debug_message_control_arb || nullptr == ogl_debug_message_insert_arb || nullptr == ogl_debug_message_callback_arb ||
        nullptr == ogl_get_debug_message_log_arb)
    {
        if (debug_output_ext_found)
        {
            GPA_LOG_MESSAGE("The GL_AMD_debug_output extension is exposed by the driver, but not all entry points are available.");
        }
        else
        {
            // This interface is not required, but does help improve error logging, so allow the code
            // to continue if this is not available.
            GPA_LOG_MESSAGE("The GL_AMD_debug_output extension is not exposed by the driver.");
        }
    }

#endif

#ifndef WIN32
    bool mesa_query_renderer_ext_found = gl_extensions_map["GLX_MESA_query_renderer"];

    if (nullptr == ogl_x_query_current_renderer_integer_mesa)
    {
        if (mesa_query_renderer_ext_found)
        {
            GPA_LOG_MESSAGE("The GLX_MESA_query_renderer extension is exposed by the driver, but not all entry points are available.");
        }
        else
        {
            GPA_LOG_MESSAGE("The GLX_MESA_query_renderer extension is not exposed by the driver.");
        }
    }

#endif

    if (nullptr == ogl_set_gpa_device_clock_mode_amd_x)
    {
        GPA_LOG_MESSAGE("The glSetGpaDeviceClockModeAMDX extension entry point is not exposed by the driver.");
    }

    are_gl_functions_initialized = ret_val;
    return ret_val;
}


text:
package org.auraframework.impl.expression;

import java.io.IOException;
import java.util.Set;

import org.auraframework.def.DefDescriptor;
import org.auraframework.def.TypeDef;
import org.auraframework.expression.ExpressionType;
import org.auraframework.expression.Literal;
import org.auraframework.expression.PropertyReference;
import org.auraframework.instance.ValueProvider;
import org.auraframework.system.Location;
import org.auraframework.util.json.Json;
import org.auraframework.util.json.JsonSerializer.NoneSerializer;

/**
 * a literal number, string, boolean, or null
 */
public class LiteralImpl implements Literal {

    /**
     */
    private static final long serialVersionUID = 2255827488061408651L;
    private final Object value;
    private final Location l;

    public LiteralImpl(Object value, Location l) {
        this.value = value;
        // TODO: get typedef from value
        this.l = l;
    }

    @Override
    public final Location getLocation() {
        return l;
    }

    @Override
    public Object evaluate(ValueProvider vp) {
        return getValue();
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public ExpressionType getExpressionType() {
        return ExpressionType.LITERAL;
    }

    @Override
    public DefDescriptor<TypeDef> getReturnTypeDef() {
        return null;
    }

    @Override
    public void gatherPropertyReferences(Set<PropertyReference> propRefs) {
        // none here.
    }

    public static final Serializer SERIALIZER = new Serializer();

    private static class Serializer extends NoneSerializer<LiteralImpl> {
        @Override
        public void serialize(Json json, LiteralImpl value) throws IOException {
            json.writeValue(value.getValue());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>

#include "checkpoints.h"

#include "db.h"
#include "main.h"
#include "uint256.h"

namespace Checkpoints
{
    typedef std::map<int, uint256> MapCheckpoints;
    static MapCheckpoints mapCheckpoints =
        boost::assign::map_list_of
        (     0, hashGenesisBlockOfficial )
        (     1, uint256("0x00000629d6f31cac82862fc60c24f01d2a1332130f7a36512d19d6634f23b7ed"))
        (    10, uint256("0x00000f5f6a6b57334ec595ec513062b3d12d013ae025d23c19da2f4c29f3a793"))
        (   100, uint256("0x00000f8e3d2ac0f221b6fb96c68ff2a6789fca8be54fb2a58fc0e1d36529970a"))
        (   300, uint256("0x00000edf69cbd2e96d87bef6e400c08e268f2bfe4d1c253d010872fc9318f827"))
        (   600, uint256("0x00000b04fe74e30f2a8d952618fa8150838236737599c88a6b82989296fe53a7"))
        (   900, uint256("0x0000036a6e01fb636180bdeabe659b99545d3dd634ea1070622584484bc53157"))
        (  1000, uint256("0x00000807d7eb2c65ccfed766cbd8fcaf3b8748971a883bda5104b4dad4600225"))
        (  5000, uint256("0x0000071cdef610101490e2cd920da1da605c74191df6042b6ddde22386fdd497"))
        ( 10000, uint256("0x0000020cfb9bf5edc089990eb5f88da15958e82f33920342b14efadbaef11f67"))
        ( 20000, uint256("0x0000004c9182bd60870c78bc5a8e7f4c4641716a16cce1a6b3230a3e112a2754"))
        ( 30000, uint256("0x0000000df99ad9a3d01b76800d5e50a7429ab883e2c3f1f2d50e45f00c43335c"))
        ( 40000, uint256("0x00000002413e0321a92631b79cf7cb31045a02ea02a17c8961d17f473803b0a2"))
        ( 50000, uint256("0x00000001726c3ca0e134a210e807d058c61a059d844cd5223428e4ee2382de84"))
        ( 50600, uint256("0x000000007337b3cfe20125c76deba439d8bd41488ef948d11ef21b8cfcbac9b8"))
        ( 50650, uint256("0x000000016d0091b0d33a5b59e9c491cff3bd5aee451e352c8cdd8496d1d35367"))
        ( 50700, uint256("0x000000017da0b1f73b83409e405aa0a98f4eb37f3efc1a340927b978f766ee02"))
        ( 60000, uint256("0x000000038df060011602f03edf2687673a9c481b57ecf630fca2a49d63a54835"))
        ( 70000, uint256("0x00000000a20bddbaafb15f5c51547d5babca6bf43b5a1b5b1d8a19ce88c5faa2"))
        ( 80000, uint256("0x000000176b70a7fddd5d9fe9cde6ace6fbbaf1cd92f93fbe0a5cdfc668822530"))
        ( 90000, uint256("0x000000bcc234682a562500bab244d18c5fd90585f562192f41ef92d0f97105b4"))
        (100000, uint256("0x0000004abff9346b6b1c2a716d95ea7bec86fed7b196924c3875ada3a9105b8e"))
        (120000, uint256("0x0000004923b3b8c126346d33cf30cb6fe3d646c631ae7885e2c71560dd8b36fc"))
        (140000, uint256("0x7b866924978e8ad085003c603f42e80b5b215e391dc0d170c08306c54a74b5c7"))
        (160000, uint256("0x0000084697be26791727bfa0ef74022a64f1fb0ab48632507a26b2ccb0f3c1f9"))
        (180000, uint256("0xb39811b9af3241fd48aa5a8e46fd7e9b9d05bb5dccb62c3b52e235f0aca1bc73"))
        (200000, uint256("0x12a5fcf254d8608ca082bcaa2a3a729b8f5711d0b1467fbfcc56e9e547fca543"))
        (210000, uint256("0xc8fbf120afaa1e8012b02db228c3a35203e78bde16bdd9c402ac34479932131f"))
        (220000, uint256("0xd53c8b31605e980fb8c0d9dc1d0b8dc2719dd18144602750714cfe0c8ff66c3c"))
        (230000, uint256("0x4c0a72b6768c04e16a9264bb55eff5a2f0d5529650099917f0221ce0d48173ab"))
        (240000, uint256("0x92174bba90d1ad4ba6b2587b208afecbe38b1108cae6da422efafa1fd737c821"))
        (241000, uint256("0x16c9ae654c3a3dd4ac2e815b62f0df3842d0d0bef822324fbcf5b71cbc6010fb"))
        (242000, uint256("0x6d179b407746bd7d1410d53be0fb87c2c03ac8ce891eaccf7b0f3c6d00c0e905"))
        (242100, uint256("0xc432a72ba6176d18a9664b60c6c8b0c413b87ddcec4a7865b05ac8bfb3ced8cb"))
        (242200, uint256("0x96172a7e0df8115832bfff249dc98a14f14930e8dbe0c9ddc8ed2afc9ccbb0e4"))
        (242300, uint256("0x4df85997ef54b0df7b8dbd9d4c4d8855e858af3af370c5301762d84d8d6aa6c1"))
        (242400, uint256("0xdc262ed4b5d3632f8fd1f204a5ab5bb765959bd0164e134ad332ae2652f84eb0"))
        (242500, uint256("0x1ae61928534deeb62b775dde5fe8f26e2c0c158e2d5e4844ab39d7a7c7647862"))
        (242600, uint256("0x32f0f1b856a2ab6e6ce980f4d3dee3d97e807dda29f159d3fc71f58b137414ed"))
        (242700, uint256("0x9afc2bd1c5fa3f2a3a0e29d94d162f9e8aa984d57c7e5554e4f138cbc0d73acb"))
        (242800, uint256("0xb29ad877e994c5aa7bfe4009af52b7f97a10721d0f75da38d340fcdb1518d348"))
        (242900, uint256("0x8fd7d45e55965b317ec54ac6401ccfcff9256ecd060b242f9930a63c7afcfb4a"))
        (243000, uint256("0xaa486abe425ded9d0ed7dc6e0423fc55f60c0956e15393be63f8a8d823623d2d"))
        (244000, uint256("0x109d03582ec8f055a395e5e3f2341fc917491d06238f6cd6460b9a1d1fe0a2b0"))
        (245000, uint256("0x3831e13c95404e27f54672c2b8516a2192ac421ee70797ac27153eab9b87d62f"))
        (246000, uint256("0x0f22190425752f5960b7e8b47f0398bd1a66d99b22092931a2435fea43ce291e"))
        (247000, uint256("0x5d8fcc0f72a51dbb0cc97e80b7b2a7bc9a6ee5b182db8227a766f4c9c1f552bf"))
        (248000, uint256("0x04f5fa963a1f8cda46c1cf576d1bd84637d3f16081bfcbd7c3b393482af58279"))
        (249000, uint256("0x6e00748f972d80a0e944ec6c8dea9273d60b177a85976e14b4c27f1f00fe0f5b"))
        (250000, uint256("0x48e2813897c16a2e263008cbdb2c2086bf03ce5e52ef8a34f762d33aa4a36164"))
        (251000, uint256("0xbb4f997c0e44567370abc6c883f974c4410a2933349dfc1a2aea8c24164393cf"))
        (252000, uint256("0x7e5572ff83cc1f250b330155f7761941927b6bab94079fb513d9f877be71b830"))
        (253000, uint256("0xce67a93249432f9b8b391c2259ed35a2c67d46cc60552775f7c1d9de7d239eeb"))
        (254000, uint256("0x597d12cadb379abfabb101c46454a5cfaf2d70d7eccad27d2c18a3a6fdb91dce"))
        (255000, uint256("0xa717ff45982665175599632492a767a66b4cd7d6d54593f9ed68fc8c547d9a7b"))
        (256000, uint256("0x5e931186fd3959d87a4a0ac283def10452fd4f66e542e910872eed4ad858e88b"))
        (257000, uint256("0xd3122346b5afc74f2c7e267041ebb20ecfd3e8d38683d78ad47bebb178a7e71e"))
        (258000, uint256("0xacb9b002a46db0bbb62502e839bdded86dff4adbb591000e6a10f143597dcf60"))
        (259000, uint256("0x469b7266b60aac74a9ac57b6d92b223e711f260247c59525eaff3447f4aab98e"))
        (260000, uint256("0x1777996fe7dcbfac3c3aa66ebdb8720ccf18c9fe2e5f73521b1e58b76016c777"))
        (261000, uint256("0xbd3dd2dde4294c75e490ac8f6ec01e4eaba936a7371daf66738a89752da0290c"))
        (400446, uint256("0x5e5c3a3bffc9a447090753ac510cfdef5a9dfdd4cea7a5e0402829b788e871f0"))
        ;

    static MapCheckpoints mapCheckpointsTestnet =
        boost::assign::map_list_of
        ( 0, hashGenesisBlockOfficial )
        ;

    bool CheckHardened(int nHeight, const uint256& hash)
    {
        MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);

        MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
        if (i == checkpoints.end()) return true;
        return hash == i->second;
    }

    int GetTotalBlocksEstimate()
    {
        MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);

        return checkpoints.rbegin()->first;
    }

    CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
    {
        MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
        {
            const uint256& hash = i.second;
            std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
            if (t != mapBlockIndex.end())
                return t->second;
        }
        return NULL;
    }

    // ppcoin: synchronized checkpoint (centrally broadcasted)
    uint256 hashSyncCheckpoint = 0;
    uint256 hashPendingCheckpoint = 0;
    CSyncCheckpoint checkpointMessage;
    CSyncCheckpoint checkpointMessagePending;
    uint256 hashInvalidCheckpoint = 0;
    CCriticalSection cs_hashSyncCheckpoint;

    // ppcoin: get last synchronized checkpoint
    CBlockIndex* GetLastSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        if (!mapBlockIndex.count(hashSyncCheckpoint))
            error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
        else
            return mapBlockIndex[hashSyncCheckpoint];
        return NULL;
    }

    // ppcoin: only descendant of current sync-checkpoint is allowed
    bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
    {
        if (!mapBlockIndex.count(hashSyncCheckpoint))
            return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
        if (!mapBlockIndex.count(hashCheckpoint))
            return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());

        CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
        CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];

        if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
        {
            // Received an older checkpoint, trace back from current checkpoint
            // to the same height of the received checkpoint to verify
            // that current checkpoint should be a descendant block
            CBlockIndex* pindex = pindexSyncCheckpoint;
            while (pindex->nHeight > pindexCheckpointRecv->nHeight)
                if (!(pindex = pindex->pprev))
                    return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
            if (pindex->GetBlockHash() != hashCheckpoint)
            {
                hashInvalidCheckpoint = hashCheckpoint;
                return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
            }
            return false; // ignore older checkpoint
        }

        // Received checkpoint should be a descendant block of the current
        // checkpoint. Trace back to the same height of current checkpoint
        // to verify.
        CBlockIndex* pindex = pindexCheckpointRecv;
        while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
            if (!(pindex = pindex->pprev))
                return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
        if (pindex->GetBlockHash() != hashSyncCheckpoint)
        {
            hashInvalidCheckpoint = hashCheckpoint;
            return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
        }
        return true;
    }

    bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
    {
        CTxDB txdb;
        txdb.TxnBegin();
        if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
        {
            txdb.TxnAbort();
            return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
        }
        if (!txdb.TxnCommit())
            return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
        txdb.Close();

        Checkpoints::hashSyncCheckpoint = hashCheckpoint;
        return true;
    }

    bool AcceptPendingSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
        {
            if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
            {
                hashPendingCheckpoint = 0;
                checkpointMessagePending.SetNull();
                return false;
            }

            CTxDB txdb;
            CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
            if (!pindexCheckpoint->IsInMainChain())
            {
                CBlock block;
                if (!block.ReadFromDisk(pindexCheckpoint))
                    return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
                if (!block.SetBestChain(txdb, pindexCheckpoint))
                {
                    hashInvalidCheckpoint = hashPendingCheckpoint;
                    return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
                }
            }
            txdb.Close();

            if (!WriteSyncCheckpoint(hashPendingCheckpoint))
                return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
            hashPendingCheckpoint = 0;
            checkpointMessage = checkpointMessagePending;
            checkpointMessagePending.SetNull();
            printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
            // relay the checkpoint
            if (!checkpointMessage.IsNull())
            {
                BOOST_FOREACH(CNode* pnode, vNodes)
                    checkpointMessage.RelayTo(pnode);
            }
            return true;
        }
        return false;
    }

    // Automatically select a suitable sync-checkpoint
    uint256 AutoSelectSyncCheckpoint()
    {
        // Proof-of-work blocks are immediately checkpointed
        // to defend against 51% attack which rejects other miners block

        // Select the last proof-of-work block
        const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
        // Search forward for a block within max span and maturity window
        while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
            pindex = pindex->pnext;
        return pindex->GetBlockHash();
    }

    // Check against synchronized checkpoint
    bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
    {
        if (fTestNet) return true; // Testnet has no checkpoints
        int nHeight = pindexPrev->nHeight + 1;
		if(fDebug)
		{
			printf("checksync, hashBlock:%s, hashSyncCheckPoint:%s\n",
				hashBlock.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
		}

        LOCK(cs_hashSyncCheckpoint);
        // sync-checkpoint should always be accepted block
        assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];

        if (nHeight > pindexSync->nHeight)
        {
            // trace back to same height as sync-checkpoint
            const CBlockIndex* pindex = pindexPrev;
            while (pindex->nHeight > pindexSync->nHeight)
                if (!(pindex = pindex->pprev))
                    return error("CheckSync: pprev null - block index structure failure");
            if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
                return false; // only descendant of sync-checkpoint can pass check
        }
        if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
            return false; // same height with sync-checkpoint
        if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
            return false; // lower height than sync-checkpoint
        return true;
    }

    bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
    {
        LOCK(cs_hashSyncCheckpoint);
        if (hashPendingCheckpoint == 0)
            return false;
        if (hashBlock == hashPendingCheckpoint)
            return true;
        if (mapOrphanBlocks.count(hashPendingCheckpoint)
            && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
            return true;
        return false;
    }

    // ppcoin: reset synchronized checkpoint to last hardened checkpoint
    bool ResetSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        const uint256& hash = mapCheckpoints.rbegin()->second;
        if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
        {
            // checkpoint block accepted but not yet in main chain
            printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
            CTxDB txdb;
            CBlock block;
            if (!block.ReadFromDisk(mapBlockIndex[hash]))
                return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
            if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
            {
                return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
            }
            txdb.Close();
        }
        else if(!mapBlockIndex.count(hash))
        {
            // checkpoint block not yet accepted
            hashPendingCheckpoint = hash;
            checkpointMessagePending.SetNull();
            printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
        }

        BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
        {
            const uint256& hash = i.second;
            if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
            {
                if (!WriteSyncCheckpoint(hash))
                    return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
                printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
                return true;
            }
        }

        return false;
    }

    void AskForPendingSyncCheckpoint(CNode* pfrom)
    {
        LOCK(cs_hashSyncCheckpoint);
        if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
            pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
    }

    bool SetCheckpointPrivKey(std::string strPrivKey)
    {
        // Test signing a sync-checkpoint with genesis block
        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = hashGenesisBlock;
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
        CKey key;
        key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return false;

        // Test signing successful, proceed
        CSyncCheckpoint::strMasterPrivKey = strPrivKey;
        return true;
    }

    bool SendSyncCheckpoint(uint256 hashCheckpoint)
    {
        CSyncCheckpoint checkpoint;
        checkpoint.hashCheckpoint = hashCheckpoint;
        CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
        sMsg << (CUnsignedSyncCheckpoint)checkpoint;
        checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());

        if (CSyncCheckpoint::strMasterPrivKey.empty())
            return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
        std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
        CKey key;
        key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
        if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
            return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");

        if(!checkpoint.ProcessSyncCheckpoint(NULL))
        {
            printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint:%s\n", hashCheckpoint.ToString().c_str());
            return false;
        }

        // Relay checkpoint
        {
            LOCK(cs_vNodes);
            BOOST_FOREACH(CNode* pnode, vNodes)
                checkpoint.RelayTo(pnode);
        }
        return true;
    }

    // Is the sync-checkpoint outside maturity window?
    bool IsMatureSyncCheckpoint()
    {
        LOCK(cs_hashSyncCheckpoint);
        // sync-checkpoint should always be accepted block
        assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
        return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
                pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
    }

    // Is the sync-checkpoint too old?
    bool IsSyncCheckpointTooOld(unsigned int nSeconds)
    {

// WM - Defeat the "checkpoint too old" check, not needed now that Pennies is launched and stable.
/*
        LOCK(cs_hashSyncCheckpoint);
        // sync-checkpoint should always be accepted block
        assert(mapBlockIndex.count(hashSyncCheckpoint));
        const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
        return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
*/

        return false;
    }

}

// ppcoin: sync-checkpoint master key
const std::string CSyncCheckpoint::strMasterPubKey = "04c7a688107077107d7e5f0d1699a36933a98ed0cbced6ca97ccb36ecfb3fd5d0b1907ffa39d285b44d86c4b81251ace83c8f971c03cb40a4b491b057a2256bcab";

std::string CSyncCheckpoint::strMasterPrivKey = "";

// ppcoin: verify signature of sync-checkpoint message
bool CSyncCheckpoint::CheckSignature()
{
    CKey key;
    if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
        return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
    if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
        return error("CSyncCheckpoint::CheckSignature() : verify signature failed");

    // Now unserialize the data
    CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
    sMsg >> *(CUnsignedSyncCheckpoint*)this;
    return true;
}

// ppcoin: process synchronized checkpoint
bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
{
    if (!CheckSignature())
        return false;

    LOCK(Checkpoints::cs_hashSyncCheckpoint);
    if (!mapBlockIndex.count(hashCheckpoint))
    {
        // We haven't received the checkpoint chain, keep the checkpoint as pending
        Checkpoints::hashPendingCheckpoint = hashCheckpoint;
        Checkpoints::checkpointMessagePending = *this;
        printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
        // Ask this guy to fill in what we're missing
        if (pfrom)
        {
            pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
            // ask directly as well in case rejected earlier by duplicate
            // proof-of-stake because getblocks may not get it this time
            pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
        }
        return false;
    }

    if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
        return false;

    CTxDB txdb;
    CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
    if (!pindexCheckpoint->IsInMainChain())
    {
        // checkpoint chain received but not yet main chain
        CBlock block;
        if (!block.ReadFromDisk(pindexCheckpoint))
            return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
        if (!block.SetBestChain(txdb, pindexCheckpoint))
        {
            Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
            return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
        }
    }
    txdb.Close();

    if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
        return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
    Checkpoints::checkpointMessage = *this;
    Checkpoints::hashPendingCheckpoint = 0;
    Checkpoints::checkpointMessagePending.SetNull();
    printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
    return true;
}


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

$period = Request::getString('period', '1999-12');

$date = $period;

$dataurl = Route::url('index.php?option='.$this->option.'&task='.$this->task.'&type='.$this->type.'&no_html=1&data=markers&local=us');
$dataurl = str_replace('&', '&', $dataurl);
?>
<!DOCTYPE html>
<html dir="<?php echo Document::getDirection(); ?>" lang="<?php echo Document::getLanguage(); ?>" class="no-js">
	<head>
		<script type="text/javascript" src="https://maps.google.com/maps?file=api&v=2&key=<?php echo $this->key; ?>"></script>
		<script type="text/javascript" src="<?php echo rtrim(Request::base(), '/'); ?>/core/plugins/usage/maps/assets/js/elabel.js"></script>
		<script type="text/javascript" src="<?php echo rtrim(Request::base(), '/'); ?>/core/plugins/usage/maps/assets/js/us-maps.js"></script>
		<link rel="stylesheet" href="<?php echo rtrim(Request::base(), '/'); ?>/core/plugins/usage/maps/assets/css/maps.css" type="text/css" />
	</head>
	<body>
		<div id="map_canvas"
			data-url="<?php echo $dataurl; ?>"
			data-date="<?php echo $date; ?>"
			data-plotdt="<?php echo substr($date, 0, 7); ?>"
			data-map="<?php echo $this->mappath; ?>"
			data-path="<?php echo rtrim(Request::base(), '/'); ?>/core/plugins/usage/maps"
			data-lat="<?php echo $this->lat; ?>"
			data-long="<?php echo $this->long; ?>"
			data-zoom="<?php echo $this->zoom; ?>">
		</div>
	</body>
</html>


text:
function hash(str)
{
	var hash = crypto
      .createHash("md5")
      .update(str)
      .digest('hex');
    console.log(hash);
	return hash;
}

var authenticate = function()
{
	var self = this;

	self.login = function(req,res)
	{
		var ses = req.session;
		if(ses.logged == 1)
		{
			if(ses.user_type == 1)
				res.redirect('/catalogue/');
			else
				res.redirect('/inventory/')
		}
		else
		{
			console.log("I was here");
			return res.render('login',{error : ""});
		}
	};

	self.signup = function(req,res)
	{
		var username = req.body.username;
		var password = hash(req.body.password);
		var first_name = req.body.first_name;
		var last_name = req.body.last_name;
		var email = req.body.email;
		var user_type = req.body.user_type;

		console.log(htmlspecialchars(user_type));
		var string = 'INSERT INTO `User`(username,password,first_name,last_name,email,user_type) VALUES ('
			+'"'+htmlspecialchars(username)+'"'
			+',"'+htmlspecialchars(password)+'"'
			+',"'+htmlspecialchars(first_name)+'"'
			+',"'+htmlspecialchars(last_name)+'"'
			+',"'+htmlspecialchars(email)+'"'
			+','+user_type+')';
		console.log(string);
		connection.query(string,function(err,row,field)
			{
				console.log(err);
				if(err==null)
					return res.render('login',{error : "Sign Up Successfull"});
				else
					return res.render('login',{error : "Email or Username already exists"});
			});
	};

	self.loginAuth = function(req,res)
	{
		var ses = req.session;
		if(ses.logged)
		{
			if(ses.user_type == 1)
				res.redirect('/catalogue/');
			else
				res.redirect('/inventory/')
		}
		else
		{
			var username = req.body.username;
			var password = req.body.password;
			connection.query('SELECT * FROM `User` WHERE `username` = "'+
				htmlspecialchars(username)+'"',function(err,rows,field)
			{
				if( rows != undefined && rows.length==1)
				{
					if(hash(password) == rows[0].password)
					{
						ses.logged = 1;
						ses.username = username;
						ses.first_name = rows[0].first_name;
						ses.last_name = rows[0].last_name;
						ses.email = rows[0].email;
						ses.user_id = rows[0].id;
						ses.address = rows[0].address;
						ses.contact_no = rows[0].contact_no;
						ses.user_type = rows[0].user_type;
						res.session = ses;
						if(ses.user_type == 1)
							res.redirect('/catalogue/');
						else
							res.redirect('/inventory/');
					}
					else
					{
						res.render('login',{error : "Incorrect Password"});
					}
				}
				else
				{
					res.render('login',{error : "Invalid Username"});
				}
			});
		}
	};

	self.logout = function(req,res)
	{
		req.session.destroy();
		res.redirect('/');
	};

};

module.exports = authenticate


text:
using namespace caffe;  // NOLINT(build/namespaces)

int main(int argc, char** argv) {
  int total_iter = 50;
  if (argc < 2 || argc > 5) {
    LOG(ERROR) << "net_speed_benchmark net_proto [iterations=50]"
        " [CPU/GPU] [Device_id=0]";
    return 1;
  }

  if (argc >=3) {
    total_iter = atoi(argv[2]);
  }

  LOG(ERROR) << "Testing for " << total_iter << "Iterations.";

  if (argc >= 4 && strcmp(argv[3], "GPU") == 0) {
    LOG(ERROR) << "Using GPU";
    uint device_id = 0;
    if (argc >= 5 && strcmp(argv[3], "GPU") == 0) {
      device_id = atoi(argv[4]);
    }
    LOG(ERROR) << "Using Device_id=" << device_id;
    Caffe::SetDevice(device_id);
    Caffe::set_mode(Caffe::GPU);
  } else {
    LOG(ERROR) << "Using CPU";
    Caffe::set_mode(Caffe::CPU);
  }

  Caffe::set_phase(Caffe::TRAIN);
  Net<float> caffe_net(argv[1]);

  // Run the network without training.
  LOG(ERROR) << "Performing Forward";
  // Note that for the speed benchmark, we will assume that the network does
  // not take any input blobs.
  float initial_loss;
  caffe_net.Forward(vector<Blob<float>*>(), &initial_loss);
  LOG(ERROR) << "Initial loss: " << initial_loss;
  LOG(ERROR) << "Performing Backward";
  caffe_net.Backward();

  const vector<shared_ptr<Layer<float> > >& layers = caffe_net.layers();
  vector<vector<Blob<float>*> >& bottom_vecs = caffe_net.bottom_vecs();
  vector<vector<Blob<float>*> >& top_vecs = caffe_net.top_vecs();
  const vector<vector<bool> >& bottom_need_backward =
      caffe_net.bottom_need_backward();
  LOG(ERROR) << "*** Benchmark begins ***";
  Timer total_timer;
  total_timer.Start();
  Timer forward_timer;
  forward_timer.Start();
  Timer timer;
  for (int i = 0; i < layers.size(); ++i) {
    const string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < total_iter; ++j) {
      layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);
    }
    LOG(ERROR) << layername << "\tforward: " << timer.MilliSeconds() <<
        " milli seconds.";
  }
  LOG(ERROR) << "Forward pass: " << forward_timer.MilliSeconds() <<
      " milli seconds.";
  Timer backward_timer;
  backward_timer.Start();
  for (int i = layers.size() - 1; i >= 0; --i) {
    const string& layername = layers[i]->layer_param().name();
    timer.Start();
    for (int j = 0; j < total_iter; ++j) {
      layers[i]->Backward(top_vecs[i], bottom_need_backward[i],
                          &bottom_vecs[i]);
    }
    LOG(ERROR) << layername << "\tbackward: "
        << timer.MilliSeconds() << " milli seconds.";
  }
  LOG(ERROR) << "Backward pass: " << backward_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(ERROR) << "Total Time: " << total_timer.MilliSeconds() <<
      " milli seconds.";
  LOG(ERROR) << "*** Benchmark ends ***";
  return 0;
}


text:
class WelcomeController < ApplicationController
  before_filter :login_required

  def index

  end

  def joined_groups
    @expenses = Expense.find(:all, :conditions => ["group_id IN (?)", @current_user.groups.map { |g| g.id}], :order => "id DESC", :limit => 20)
    render :template => 'welcome/expenses.html', :layout => false
  end

  def managed
    groups = @current_user.groups.managed_groups
    @expenses = Expense.find(:all, :conditions => ["group_id IN (?)", groups.map { |g| g.id}], :order => "id DESC", :limit => 20)

    render :template => 'welcome/expenses.html', :layout => false
  end

  def my
    @expenses = @current_user.expenses.find(:all, :order => "id DESC")
    @expenses.delete_if { |e| !e.group }

    render :template => 'welcome/expenses.html', :layout => false
  end

end


text:
/*
Microformats Test Suite - Downloaded from github repo: microformats/tests version v0.1.26
Mocha integration test from: microformats-v2/h-card/baseurl
The test was built on Fri May 27 2016 13:35:35 GMT+0100 (BST)
*/

var chai = require('chai'),
   assert = chai.assert,
   helper = require('../test/helper.js');

describe('h-card', function() {
   var htmlFragment = "<base href=\"http://example.org\"/>\n
\n  Mitchell Baker \n  (Mozilla Foundation)\n  \n
";
   var found = helper.parseHTML(htmlFragment,'http://example.com/');
   var expected = {"items":[{"type":["h-card"],"properties":{"name":["Mitchell Baker"],"url":["http://blog.lizardwrangler.com/"],"org":[{"value":"Mozilla Foundation","type":["h-card"],"properties":{"name":["Mozilla Foundation"],"url":["http://example.org/bios/mitchell-baker/"]}}],"photo":["http://example.org/images/photo.gif"]}}],"rels":{},"rel-urls":{}};

   it('baseurl', function(){
       assert.deepEqual(found, expected);
   });
});


text:
#ifndef MOVEGROUPINTERFACE_H_
#define MOVEGROUPINTERFACE_H_

#include <moveit/move_group_interface/move_group.h>
#include <gtest/gtest.h>

/* THIS IMPLENTATION IS NOT THREAD SAFE */
namespace symbolic_planning_utils
{
	class MoveGroupInterface
	{
	private:
		static MoveGroupInterface* instance_;
		moveit::planning_interface::MoveGroup* right_arm_group_;
		moveit::planning_interface::MoveGroup* left_arm_group_;
		moveit::planning_interface::MoveGroup* arms_group_;
		moveit::planning_interface::MoveGroup* head_group_;
		moveit::planning_interface::MoveGroup* torso_group_;

		// Constructor: creating all moveit::planning_interfaces
//		FRIEND_TEST(moveGroupInterfaceTest, MoveGroupInterface);
		MoveGroupInterface();

//		// Copy constructor must be private to prevent any additional creation of the object
//		FRIEND_TEST(moveGroupInterfaceTest, copyConstructor);
//		MoveGroupInterface(const MoveGroupInterface* mgi);

		// Assignment operator must also be private to prevent any additional creation of the object
		FRIEND_TEST(moveGroupInterfaceTest, assignmentOperator);
		MoveGroupInterface* operator= (const MoveGroupInterface* mgi);

		// The destructor is private in order to prevent clients that hold a pointer to the
		// Singleton object from deleting it accidentally.
		// Is not implemented, since the object should exist until the end of execution of the
		// entire program
		virtual ~MoveGroupInterface();

	public:
		static MoveGroupInterface* getInstance();
		moveit::planning_interface::MoveGroup* getRightArmGroup();
		moveit::planning_interface::MoveGroup* getLeftArmGroup();
		moveit::planning_interface::MoveGroup* getArmsGroup();
		moveit::planning_interface::MoveGroup* getHeadGroup();
		moveit::planning_interface::MoveGroup* getTorsoGroup();

	moveit::planning_interface::MoveItErrorCode planExecuteVerify(
			moveit::planning_interface::MoveGroup* group, const std::string& rosout_name);
	};
};

#endif /* MOVEGROUPINTERFACE_H_ */


text:
#ifndef ALINOUS_BTREE_TIMESTAMPKEY_H_
#define ALINOUS_BTREE_TIMESTAMPKEY_H_
namespace alinous{namespace annotation{
class HeaderOnly;
}}
namespace alinous {namespace btree {
class IBTreeKey;}}

namespace alinous {namespace btree {
class TimestampKey;}}

namespace alinous {namespace buffer {namespace storage {
class FileStorageEntryBuilder;}}}

namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace btree {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::alinous::buffer::storage::FileStorageEntryBuilder;

class TimestampKey final : public IBTreeKey, public virtual IObject {
public:
	TimestampKey(const TimestampKey& base) = default;
public:
	TimestampKey(long long mills, ThreadContext* ctx) throw() ;
	void __construct_impl(long long mills, ThreadContext* ctx) throw() ;
	virtual ~TimestampKey() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
private:
	long long value;
public:
	constexpr static const int BASE_SIZE{8};
public:
	int compareTo(IBTreeKey* another, ThreadContext* ctx) throw() ;
	bool equals(IObject* obj, ThreadContext* ctx) throw() ;
	bool equals(TimestampKey* obj, ThreadContext* ctx) throw() ;
	void appendToEntry(FileStorageEntryBuilder* builder, ThreadContext* ctx) throw()  final;
	int size(ThreadContext* ctx) throw()  final;
	String* toString(ThreadContext* ctx) throw() ;
public:
	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
	class ValueCompare {
	public:
		int operator() (IBTreeKey* _this, IBTreeKey* another, ThreadContext* ctx) const throw();
	};
};

}}

#endif /* end of ALINOUS_BTREE_TIMESTAMPKEY_H_ */


text:
Clazz.load(["java.util.EventListener"],"java.util.EventListenerProxy",null,function(){
c$=Clazz.decorateAsClass(function(){
this.listener=null;
Clazz.instantialize(this,arguments);
},java.util,"EventListenerProxy",null,java.util.EventListener);
Clazz.makeConstructor(c$,
function(listener){
this.listener=listener;
},"java.util.EventListener");
Clazz.defineMethod(c$,"getListener",
function(){
return this.listener;
});
});


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using FLS.Data.WebApi;
using FLS.Data.WebApi.Person;
using FLS.Server.Service;
using FLS.Server.WebApi.ActionFilters;
using System.Threading.Tasks;

namespace FLS.Server.WebApi.Controllers
{
    /// <summary>
    /// Api controller for person entities.
    /// </summary>
    [Authorize]
    [RoutePrefix("api/v1/persons")]
    public class PersonsController : ApiController
    {
        private readonly PersonService _personService;

        /// <summary>
        /// Initializes a new instance of the <see cref="PersonsController"/> class.
        /// </summary>
        public PersonsController(PersonService personService)
        {
            _personService = personService;
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("listitems")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetPersonListItems()
        {
            var persons = _personService.GetPilotPersonListItems(true);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPersons">if set to <c>true</c> only club related persons will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("listitems/{onlyClubRelatedPersons:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetPersonListItems(bool onlyClubRelatedPersons)
        {
            var persons = _personService.GetPilotPersonListItems(onlyClubRelatedPersons);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderpilots/listitems/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetGliderPilotPersonListItems(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetGliderPilotPersonListItems(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedInstuctors">if set to <c>true</c> only club related instructors will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderinstructors/listitems/{onlyClubRelatedInstuctors:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetGliderInstructorPersonListItems(bool onlyClubRelatedInstuctors)
        {
            var persons = _personService.GetGliderInstructorPersonListItems(onlyClubRelatedInstuctors);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderobserverpilots/listitems/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetGliderObserverPilotPersonListItems(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetGliderObserverPilotPersonListItems(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("towingpilots/listitems/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetTowingPilotPersonListItems(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetTowingPilotPersonListItems(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("motorpilots/listitems/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetMotorPilotPersonListItems(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetMotorPilotPersonListItems(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedInstuctors">if set to <c>true</c> only club related instructors will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("motorinstructors/listitems/{onlyClubRelatedInstuctors:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetMotorInstructorPersonListItems(bool onlyClubRelatedInstuctors)
        {
            var persons = _personService.GetMotorInstructorPersonListItems(onlyClubRelatedInstuctors);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedTrainees">if set to <c>true</c> only club related trainees will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("glidertrainees/listitems/{onlyClubRelatedTrainees:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetGliderTraineePersonListItems(bool onlyClubRelatedTrainees)
        {
            var persons = _personService.GetGliderTraineePersonListItems(onlyClubRelatedTrainees);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedWinchOperators">if set to <c>true</c> only club related winch operators will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("winchoperators/listitems/{onlyClubRelatedWinchOperators:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetWinchOperatorPersonListItems(bool onlyClubRelatedWinchOperators)
        {
            var persons = _personService.GetWinchOperatorPersonListItems(onlyClubRelatedWinchOperators);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPassengers">if set to <c>true</c> only club related passengers will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("passengers/listitems/{onlyClubRelatedPassengers:bool}")]
        [ResponseType(typeof(List<PersonListItem>))]
        public IHttpActionResult GetPassengerListItems(bool onlyClubRelatedPassengers)
        {
            var persons = _personService.GetPassengerListItems(onlyClubRelatedPassengers);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPersons">if set to <c>true</c> only club related persons will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{onlyClubRelatedPersons:bool?}")]
        [Route("overview/{onlyClubRelatedPersons:bool?}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetPersonOverviews(bool onlyClubRelatedPersons = true)
        {
            var persons = _personService.GetPilotPersonOverviews(onlyClubRelatedPersons);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderpilots/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetGliderPilotPersonOverviews(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetGliderPilotPersonOverviews(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderobserverpilots/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetGliderObserverPilotPersonOverviews(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetGliderObserverPilotPersonOverviews(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedInstuctors">if set to <c>true</c> only club related instructors will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("gliderinstructors/{onlyClubRelatedInstuctors:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetGliderInstructorPersonOverviews(bool onlyClubRelatedInstuctors)
        {
            var persons = _personService.GetGliderInstructorPersonOverviews(onlyClubRelatedInstuctors);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPilots">if set to <c>true</c> only club related pilots will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("towingpilots/{onlyClubRelatedPilots:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetTowingPilotPersonOverviews(bool onlyClubRelatedPilots)
        {
            var persons = _personService.GetTowingPilotPersonOverviews(onlyClubRelatedPilots);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedTrainees">if set to <c>true</c> only club related trainees will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("glidertrainees/{onlyClubRelatedTrainees:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetGliderTraineePersonOverviews(bool onlyClubRelatedTrainees)
        {
            var persons = _personService.GetGliderTraineePilotPersonOverviews(onlyClubRelatedTrainees);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedWinchOperators">if set to <c>true</c> only club related winch operators will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("winchoperators/{onlyClubRelatedWinchOperators:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetWinchOperatorPersonOverviews(bool onlyClubRelatedWinchOperators)
        {
            var persons = _personService.GetWinchOperatorPilotPersonOverviews(onlyClubRelatedWinchOperators);
            return Ok(persons);
        }

        /// <summary>
        /// Get the persons ordered by lastname. If all persons will be queried but the user has no system admin rights
        /// only the main data of each person is be returned (no email, no phone numbers, etc.)
        /// </summary>
        /// <param name="onlyClubRelatedPassengers">if set to <c>true</c> only club related passengers will be returned.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("passengers/{onlyClubRelatedPassengers:bool}")]
        [ResponseType(typeof(List<PersonOverview>))]
        public IHttpActionResult GetPassengerPersonOverviews(bool onlyClubRelatedPassengers)
        {
            var persons = _personService.GetPassengerOverviews(onlyClubRelatedPassengers);
            return Ok(persons);
        }

        /// <summary>
        /// Gets the person overviews.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("page/{pageStart:int?}/{pageSize:int?}")]
        [ResponseType(typeof(PagedList<PersonOverview>))]
        public IHttpActionResult GetPagedPersonOverview([FromBody]PageableSearchFilter<PersonOverviewSearchFilter> pageableSearchFilter, int? pageStart = 0, int? pageSize = 100)
        {
            var persons = _personService.GetPagedPersonOverview(pageStart, pageSize, pageableSearchFilter);
            return Ok(persons);
        }

        /// <summary>
        /// Gets the person details.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{personId}")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult GetPersonDetails(Guid personId)
        {
            var personDetails = _personService.GetPersonDetails(personId);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets my person details.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("my")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult GetMyPersonDetails()
        {
            var personDetails = _personService.GetMyPersonDetails();
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person full details.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("fulldetails/{personId}")]
        [ResponseType(typeof(PersonFullDetails))]
        public IHttpActionResult GetPersonFullDetails(Guid personId)
        {
            var personDetails = _personService.GetPilotPersonFullDetails(personId);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person details.
        /// </summary>
        /// <param name="memberNumber">The persons club member number.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("membernumber/{memberNumber}")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult GetPersonDetailsByMemberNumber(string memberNumber)
        {
            var personDetails = _personService.GetPilotPersonDetails(memberNumber);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person full details.
        /// </summary>
        /// <param name="memberNumber">The persons club member number.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("fulldetails/membernumber/{memberNumber}")]
        [ResponseType(typeof(PersonFullDetails))]
        public IHttpActionResult GetPersonFullDetailsByMemberNumber(string memberNumber)
        {
            var personDetails = _personService.GetPilotPersonFullDetails(memberNumber);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person details which are new modified since.
        /// </summary>
        /// <param name="modifiedSince">The modified since.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("modified/{modifiedSince:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
        [Route("modified/{*modifiedSince:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
        [ResponseType(typeof(List<PersonDetails>))]
        public IHttpActionResult GetPersonDetailsModifiedSince(DateTime modifiedSince)
        {
            var personDetails = _personService.GetPersonDetailsModifiedSince(modifiedSince);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person details deleted since.
        /// </summary>
        /// <param name="deletedSince">The deleted since.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("deleted/{deletedSince:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
        [Route("deleted/{*deletedSince:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
        [ResponseType(typeof(List<PersonDetails>))]
        public IHttpActionResult GetPersonDetailsDeletedSince(DateTime deletedSince)
        {
            var personDetails = _personService.GetPersonDetailsDeletedSince(deletedSince);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person details which are new modified since.
        /// </summary>
        /// <param name="modifiedSince">The modified since.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("fulldetails/modified/{modifiedSince:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
        [Route("fulldetails/modified/{*modifiedSince:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
        [ResponseType(typeof(List<PersonFullDetails>))]
        public IHttpActionResult GetPersonFullDetailsModifiedSince(DateTime modifiedSince)
        {
            var personDetails = _personService.GetPersonFullDetailsModifiedSince(modifiedSince);
            return Ok(personDetails);
        }

        /// <summary>
        /// Gets the person details deleted since.
        /// </summary>
        /// <param name="deletedSince">The deleted since.</param>
        /// <returns></returns>
        [HttpGet]
        [Route("fulldetails/deleted/{deletedSince:datetime:regex(\\d{4}-\\d{2}-\\d{2})}")]
        [Route("fulldetails/deleted/{*deletedSince:datetime:regex(\\d{4}/\\d{2}/\\d{2})}")]
        [ResponseType(typeof(List<PersonFullDetails>))]
        public IHttpActionResult GetPersonFullDetailsDeletedSince(DateTime deletedSince)
        {
            var personDetails = _personService.GetPersonFullDetailsDeletedSince(deletedSince);
            return Ok(personDetails);
        }

        /// <summary>
        /// Inserts the person details.
        /// </summary>
        /// <param name="personDetails">The person details.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult InsertPersonDetails([FromBody] PersonDetails personDetails)
        {
            _personService.InsertPersonDetails(personDetails);
            return Ok(personDetails);
        }

        /// <summary>
        /// Inserts the passenger details.
        /// </summary>
        /// <param name="passengerDetails">The passenger details.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("passengers")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult InsertPassengerDetails([FromBody] PersonDetails passengerDetails)
        {
            _personService.InsertPassengerDetails(passengerDetails);
            return Ok(passengerDetails);
        }

        /// <summary>
        /// Inserts the person details.
        /// </summary>
        /// <param name="personFullDetails">The person full details.</param>
        /// <returns></returns>
        [HttpPost]
        [Route("fulldetails")]
        [ResponseType(typeof(PersonFullDetails))]
        public IHttpActionResult InsertPersonFullDetails([FromBody] PersonFullDetails personFullDetails)
        {
            _personService.InsertPersonFullDetails(personFullDetails);
            return Ok(personFullDetails);
        }

        /// <summary>
        /// Updates the person details.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <param name="personDetails">The person details.</param>
        /// <returns></returns>
        [HttpPut]
        [Route("{personId}")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult UpdatePersonDetails(Guid personId, [FromBody]PersonDetails personDetails)
        {
            _personService.UpdatePersonDetails(personDetails);
            return Ok(personDetails);
        }

        /// <summary>
        /// Updates the passenger details.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <param name="passengerDetails">The passenger details.</param>
        /// <returns></returns>
        [HttpPut]
        [Route("passengers/{personId}")]
        [ResponseType(typeof(PersonDetails))]
        public IHttpActionResult UpdatePassengerDetails(Guid personId, [FromBody]PersonDetails passengerDetails)
        {
            _personService.UpdatePassengerDetails(passengerDetails);
            return Ok(passengerDetails);
        }

        /// <summary>
        /// Updates the person details.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <param name="personFullDetails">The person full details.</param>
        /// <returns></returns>
        [HttpPut]
        [Route("fulldetails/{personId}")]
        [ResponseType(typeof(PersonFullDetails))]
        public IHttpActionResult UpdatePersonFullDetails(Guid personId, [FromBody]PersonFullDetails personFullDetails)
        {
            _personService.UpdatePersonFullDetails(personFullDetails);
            return Ok(personFullDetails);
        }

        /// <summary>
        /// Deletes the specified person.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("{personId}")]
        [ResponseType(typeof(void))]
        public IHttpActionResult Delete(Guid personId)
        {
            _personService.DeletePerson(personId);
            return Ok();
        }

        /// <summary>
        /// Deletes the specified person identifier.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <param name="deletedOn">The deleted timestamp.</param>
        /// <returns></returns>
        [HttpDelete]
        [Route("fulldetails/{personId}")]
        [ResponseType(typeof(void))]
        public IHttpActionResult DeletePersonFullDetails(Guid personId, [FromBody]DateTime deletedOn)
        {
            _personService.DeletePersonFullDetails(personId, deletedOn);
            return Ok();
        }

        /// <summary>
        /// Sends address list of clubs pilots as excel to logged in user's notification email address
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("addresslist/excel/email")]
        [ResponseType(typeof(void))]
        public IHttpActionResult SendAddressListByEmail()
        {
            _personService.SendPersonListExcelToUsersEmailAddress();

            return Ok();
        }

        ///// <summary>
        ///// Gets address list of clubs pilots as excel
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[Route("addresslist/excel")]
        //[ResponseType(typeof(void))]
        //public IHttpActionResult GetAddressList()
        //{
        //    return Ok();
        //    //var mediaType =
        //    //    MediaTypeHeaderValue.Parse("application/octet-stream");
        //    //var fileName = "Addresslist.xlsx";
        //    //var memoryStream = _personService.GetPersonListExcelPackageMemoryStream();
        //    //var response = Request.CreateResponse(HttpStatusCode.OK);
        //    //response.Content = new StreamContent(memoryStream);
        //    //response.Content.Headers.ContentType = mediaType;
        //    //response.Content.Headers.ContentDisposition =
        //    //    new ContentDispositionHeaderValue("fileName") { FileName = fileName };
        //    //return Ok(response);
        //}
    }
}


text:
Microservice design, architecture and API design can be found in design_updated.pdf. I have changed some design from last design.pdf, mainly realized the MQ should be used between input payment and validate payment, not between validate and output paid order.

In short, 6 microservices are used,

1. restaurant service: provides CRUD operation on restaurant and food_item(menu) information
2. order service: provides generation of order, search order based on restaurant, and view confirmed order if payment is accepted.
3. payment distributor service: receives the input payment information from payment UI and provides source of payment validator
4. payment validator suervice: consumer of distributor, validate received payment info, then return validation status to order service
5. eureka: used for service registration and discovery
6. hystrix: used for circuit breaker, mainly for fall back method of payment-validator service

mySQL is used for data persistency for order service and restaurant service.
rabbitMQ is used to decouple and asynchronize the payment input and validation.
Both of them are launched using docker configured in docker-compose.yml

The test cases include: unit test and integration tests and MVC tests for order service, restaurant service and validation service.

There are 4 UI designed, unfortuanetely I am not able to implement it yet. Those UI are:
1. UI of view menu based on restaurant ( corresponds to back-end service in restaurant-service)
2. UI of select item from menu (corresponds to back-end service in restaurant-service and order-service)
3. UI of input payment infomation (corresponds to back-end service in payment distributor-service)
4. UI of view the paid order information if payment is accepted. (correponds to back-end service in order-service)


text:
package com.oxygenxml.translation.progress.worker;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.xml.bind.JAXBException;

import com.oxygenxml.translation.progress.ProgressChangeListener;
import com.oxygenxml.translation.progress.StoppedByUserException;
import com.oxygenxml.translation.support.TranslationPackageBuilderExtension;
import com.oxygenxml.translation.support.core.PackageBuilder;
import com.oxygenxml.translation.support.util.ArchiveBuilder;

/**
 * Creates an AbstractWorker for packing a directory.
 *
 * @author Bivolan Dalina
 *
 */
public class ZipWorker extends AbstractWorker {
  /**
   *  The file we want to zip.
   */
  private File rootDir;
  /**
   *  Where to put the created package.
   */
  private File zipDir;

  public ZipWorker(File rootDir, File zipDir, ArrayList<ProgressChangeListener> listeners) {
    super(listeners);
    this.rootDir = rootDir;
    this.zipDir = zipDir;
  }

  /**
   * Main task. Executed in background thread.
   *
   * @throws JAXBException  Problems with JAXB, serialization/deserialization of a file.
   * @throws NoSuchAlgorithmException  The MD5 algorithm is not available.
   * @throws StoppedByUserException  The user pressed the Cancel button.
   * @throws  IOException Problems reading the file.
   */
  @Override
  public Void doInBackground() throws IOException, StoppedByUserException, NoSuchAlgorithmException, JAXBException {
    if(TranslationPackageBuilderExtension.isPackAll()){
      ArchiveBuilder archiveBuilder = new ArchiveBuilder();
      for (ProgressChangeListener l : listeners) {
        archiveBuilder.addListener(l);
      }

      archiveBuilder.zipDirectory(rootDir, zipDir);
    }
    else{
      PackageBuilder packageBuilder = new PackageBuilder();
      for (ProgressChangeListener l : listeners) {
        packageBuilder.addListener(l);
      }
      packageBuilder.generateChangedFilesPackage(rootDir, zipDir);
    }
    return null;
  }
}


text:
/***********************************************************
* Developer: Minhas Kamal (minhaskamal024@gmail.com)       *
* Date: Sep-2016                                           *
* License: MIT License                                     *
***********************************************************/

package com.minhaskamal.egami.utilityAlgorithms;

import java.util.ArrayList;
import java.util.Random;

public class ClusterMaker {

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

	public static int[][] kMeansClustering(int[][] dataPoints, int k){
		int[][] clusterMeans = new int[k][dataPoints[0].length];
		Random random = new Random();
		for(int i=0; i<k; i++){
			clusterMeans[i] = dataPoints[random.nextInt(dataPoints.length-1)].clone();
		}

		int[][] newClusterMeans;
		do{
			int[] pointInClusters = assignPointToCluster(dataPoints, clusterMeans);
			newClusterMeans = calculateClusterMeans(dataPoints, pointInClusters, k);
		}while(change(clusterMeans, newClusterMeans));

		return clusterMeans;
	}

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

	public static int[][] meanShiftClustering(int[][] dataPoints, int radious, int n){
		int[][] clusterMeans = new int[n][dataPoints[0].length];
		Random random = new Random();
		for(int i=0; i<n; i++){
			clusterMeans[i] = dataPoints[random.nextInt(dataPoints.length-1)].clone();
		}

		int[][] newClusterMeans;
		do{
			double[][] distaces = calculateAllDistances(dataPoints, clusterMeans);
			newClusterMeans = calculateClusterMeans(dataPoints, distaces, radious);
		}while(change(clusterMeans, newClusterMeans));

		return cleanDuplicacy(clusterMeans);
	}

	private static int[][] cleanDuplicacy(int[][] clusterMeans){
		ArrayList<int[]> cleanClusterMeans = new ArrayList<int[]>();
		cleanClusterMeans.add(clusterMeans[0]);

		boolean arrayMatched;
		for(int i=1; i<clusterMeans.length; i++){
			arrayMatched = false;

			for(int[] clusterMean: cleanClusterMeans){
				boolean matched=true;
				for(int p=0; p<clusterMean.length; p++){
					if(clusterMean[p]!=clusterMeans[i][p]){
						matched = false;
						break;
					}
				}
				if(matched){
					arrayMatched = true;
					break;
				}
			}

			if(!arrayMatched){
				cleanClusterMeans.add(clusterMeans[i]);
			}
		}

		return cleanClusterMeans.toArray(new int[][]{{}});
	}

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

	public static int[] assignPointToCluster(int[][] dataPoints, int[][] clusterMeans){
		double[][] distaces = calculateAllDistances(dataPoints, clusterMeans);
		int[] pointInCluster = findPointInCluster(distaces);

		return pointInCluster;
	}

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

	private static double[][] calculateAllDistances(int[][] dataPoints, int[][] clusterMeans){
		double[][] distaces = new double[dataPoints.length][clusterMeans.length];

		for(int i=0; i<dataPoints.length; i++){
			for(int j=0; j<clusterMeans.length; j++){
				distaces[i][j] = calculateDistance(dataPoints[i], clusterMeans[j]);
			}
		}

		return distaces;
	}

	private static double calculateDistance(int[] point1, int[] point2){
		double distance = 0;

		for(int i=0; i<point1.length; i++){
			distance += Math.pow(point1[i]-point2[i], 2);
		}
		distance = Math.sqrt(distance);

		return distance;
	}

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

	private static int[] findPointInCluster(double[][] distaces){
		int[] pointInCluster = new int[distaces.length];

		for(int i=0; i<pointInCluster.length; i++){
			pointInCluster[i] = findIndexOfMinValue(distaces[i]);
		}

		return pointInCluster;
	}

	private static int findIndexOfMinValue(double[] values){
		int minIndex = 0;
		double minValue = values[minIndex];

		for(int i=1; i<values.length; i++){
			if(minValue>values[i]){
				minIndex=i;
				minValue=values[minIndex];
			}
		}

		return minIndex;
	}

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

	private static int[][] calculateClusterMeans(int[][] dataPoints, int[] pointInClusters, int k){
		int[][] clusterMeans = new int[k][dataPoints[0].length];

		double [][] clusterSum = new double[clusterMeans.length][clusterMeans[0].length];
		int[] clusterMembers = new int[clusterMeans.length];
		for(int i=0; i<dataPoints.length; i++){
			for(int j=0; j<dataPoints[0].length; j++){
				clusterSum[pointInClusters[i]][j] += dataPoints[i][j];
			}
			clusterMembers[pointInClusters[i]] ++;
		}

		for(int i=0; i<clusterMeans.length; i++){
			for(int j=0; j<clusterMeans[0].length; j++){
				clusterMeans[i][j] = (int) (clusterSum[i][j]/clusterMembers[i]);
			}
		}

		return clusterMeans;
	}

	private static int[][] calculateClusterMeans(int[][] dataPoints, double[][] distaces, int radious){
		int[][] clusterMeans = new int[distaces[0].length][dataPoints[0].length];

		double [][] clusterSum = new double[clusterMeans.length][clusterMeans[0].length];
		int[] clusterMembers = new int[clusterMeans.length];

		for(int i=0; i<clusterMeans.length; i++){
			for(int j=0; j<distaces.length; j++){
				if(distaces[j][i]<=radious){
					for(int k=0; k<dataPoints[0].length; k++){
						clusterSum[i][k] += dataPoints[j][k];
					}
					clusterMembers[i] ++;
				}
			}
		}

		for(int i=0; i<clusterMeans.length; i++){
			for(int j=0; j<clusterMeans[0].length; j++){
				clusterMeans[i][j] = (int) (clusterSum[i][j]/clusterMembers[i]);
			}
		}

		return clusterMeans;
	}

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

	private static boolean change(int[][] clusterMeans, int[][] newClusterMeans){
		boolean isChanged = false;

		for(int i=0; i<clusterMeans.length; i++){
			for(int j=0; j<clusterMeans[0].length; j++){
				if(clusterMeans[i][j] != newClusterMeans[i][j]){
					clusterMeans[i][j] = newClusterMeans[i][j];
					isChanged = true;
				}
			}
		}

		return isChanged;
	}

}