!ios:!if(win*:isEqual(QT_ARCH, "x86_64")): DEFINES += V4_ENABLE_JIT

# On Qt/Android/ARM release builds are thumb and debug builds arm,
# but we'll force the JIT to always generate thumb2
android:isEqual(QT_ARCH, "arm") {
    DEFINES += WTF_CPU_ARM_THUMB2
}

DEFINES += WTF_EXPORT_PRIVATE="" JS_EXPORT_PRIVATE=""

win*: DEFINES += NOMINMAX

DEFINES += ENABLE_LLINT=0
DEFINES += ENABLE_DFG_JIT=0
DEFINES += ENABLE_JIT_CONSTANT_BLINDING=0
DEFINES += ENABLE_ASSEMBLER=1
DEFINES += BUILDING_QT__
DEFINES += ENABLE_YARR_JIT=1
DEFINES += ENABLE_JIT=1

INCLUDEPATH += $$PWD/jit
INCLUDEPATH += $$PWD/assembler
INCLUDEPATH += $$PWD/runtime
INCLUDEPATH += $$PWD/wtf
INCLUDEPATH += $$PWD/stubs
INCLUDEPATH += $$PWD/stubs/wtf
INCLUDEPATH += $$PWD

if(isEqual(QT_ARCH, "i386")|isEqual(QT_ARCH, "x86_64")):!win*: DEFINES += WTF_USE_UDIS86=1
else: DEFINES += WTF_USE_UDIS86=0

INCLUDEPATH += $$PWD/disassembler
INCLUDEPATH += $$PWD/disassembler/udis86
INCLUDEPATH += $$_OUT_PWD

Disable the udis86 disassembler by default

!ios:!if(win*:isEqual(QT_ARCH, "x86_64")): DEFINES += V4_ENABLE_JIT

# On Qt/Android/ARM release builds are thumb and debug builds arm,
# but we'll force the JIT to always generate thumb2
android:isEqual(QT_ARCH, "arm") {
    DEFINES += WTF_CPU_ARM_THUMB2
}

DEFINES += WTF_EXPORT_PRIVATE="" JS_EXPORT_PRIVATE=""

win*: DEFINES += NOMINMAX

DEFINES += ENABLE_LLINT=0
DEFINES += ENABLE_DFG_JIT=0
DEFINES += ENABLE_JIT_CONSTANT_BLINDING=0
DEFINES += ENABLE_ASSEMBLER=1
DEFINES += BUILDING_QT__
DEFINES += ENABLE_YARR_JIT=1
DEFINES += ENABLE_JIT=1

INCLUDEPATH += $$PWD/jit
INCLUDEPATH += $$PWD/assembler
INCLUDEPATH += $$PWD/runtime
INCLUDEPATH += $$PWD/wtf
INCLUDEPATH += $$PWD/stubs
INCLUDEPATH += $$PWD/stubs/wtf
INCLUDEPATH += $$PWD

disassembler:if(isEqual(QT_ARCH, "i386")|isEqual(QT_ARCH, "x86_64")):!win*: DEFINES += WTF_USE_UDIS86=1
else: DEFINES += WTF_USE_UDIS86=0

INCLUDEPATH += $$PWD/disassembler
INCLUDEPATH += $$PWD/disassembler/udis86
INCLUDEPATH += $$_OUT_PWD


include(compiler_config.pri)
CONFIG(debug, debug|release) {
  TARGET_SUFFIX = .debug
} else {
  TARGET_SUFFIX = .release
}
CONFIG *= build_all debug_and_release

Use regular target suffix (_d for debug and none for release)

include(compiler_config.pri)
CONFIG(debug, debug|release) {
  TARGET_SUFFIX = _d
} else {
  TARGET_SUFFIX =
}
CONFIG *= build_all debug_and_release


# Project include file for QtPods

INCLUDEPATH += $$PWD/qtsignal

LIBS += -L../qtsignal -lqtsignal

Fix include path for QtPods

# Project include file for QtPods

INCLUDEPATH += $$PWD/src

LIBS += -L../qtsignal -lqtsignal


unittest_arguments += -graphicssystem raster

qws {
    unittest_arguments += -qws
}

QMAKE_EXTRA_TARGETS += check
check.target = check
check.commands = \
    TESTING_IN_SANDBOX=1 \
    TESTPLUGIN_PATH=../plugins \
    TESTDATA_PATH=$$IN_PWD \
    LD_LIBRARY_PATH=../../connection:../../maliit-plugins-quick/input-method:../../maliit-plugins-quick/plugin-factory:../../src:../../input-context/:../../maliit:../plugins:$(LD_LIBRARY_PATH) \
    ./$$TARGET $$unittest_arguments

check.depends += $$TARGET

QMAKE_EXTRA_TARGETS += check-xml
check-xml.target = check-xml
check-xml.commands = ../rt.sh $$TARGET
check-xml.depends += $$TARGET

# coverage flags are off per default, but can be turned on via qmake COV_OPTION=on
for(OPTION,$$list($$lower($$COV_OPTION))){
    isEqual(OPTION, on){
        QMAKE_CXXFLAGS += -ftest-coverage -fprofile-arcs
        LIBS += -lgcov
    }
}
QMAKE_CLEAN += $$OBJECTS_DIR/*.gcno $$OBJECTS_DIR/*.gcda

Fix ut_minputcontextplugin not finding libmaliit-qt4.so

unittest_arguments += -graphicssystem raster

qws {
    unittest_arguments += -qws
}

QMAKE_EXTRA_TARGETS += check
check.target = check
check.commands = \
    TESTING_IN_SANDBOX=1 \
    TESTPLUGIN_PATH=../plugins \
    TESTDATA_PATH=$$IN_PWD \
    LD_LIBRARY_PATH=../../connection:../../maliit-plugins-quick/input-method:../../maliit-plugins-quick/plugin-factory:../../src:../../input-context/input-context-plugin:../../maliit:../plugins:$(LD_LIBRARY_PATH) \
    ./$$TARGET $$unittest_arguments

check.depends += $$TARGET

QMAKE_EXTRA_TARGETS += check-xml
check-xml.target = check-xml
check-xml.commands = ../rt.sh $$TARGET
check-xml.depends += $$TARGET

# coverage flags are off per default, but can be turned on via qmake COV_OPTION=on
for(OPTION,$$list($$lower($$COV_OPTION))){
    isEqual(OPTION, on){
        QMAKE_CXXFLAGS += -ftest-coverage -fprofile-arcs
        LIBS += -lgcov
    }
}
QMAKE_CLEAN += $$OBJECTS_DIR/*.gcno $$OBJECTS_DIR/*.gcda


DEFINES += BUILDING_QMH

TEMP_DIR = tmp
OBJECTS_DIR = $$TEMP_DIR/.obj
MOC_DIR = $$TEMP_DIR/.moc

linux* {
    message(Linux specific options: (*default unless adjusted in common.pri))
    message(gstreamer)
    message(release*)
}

CONFIG += release

Make direct gstreamer usage the default rather than process wrangling

DEFINES += BUILDING_QMH

TEMP_DIR = tmp
OBJECTS_DIR = $$TEMP_DIR/.obj
MOC_DIR = $$TEMP_DIR/.moc

linux* {
    message(Linux specific options: (*default unless adjusted in common.pri))
    message(gstreamer*)
    message(release*)
    CONFIG += gstreamer
}

CONFIG += release


# Linker optimization for release build
QMAKE_LFLAGS_RELEASE+=-Wl,--as-needed
# Compiler warnings are error if the build type is debug
QMAKE_CXXFLAGS_DEBUG+=-Werror

enable-legacy {
    MALIIT_PLUGINS_DIR=$$system(pkg-config --variable pluginsdir MeegoImFramework)
    MALIIT_PLUGINS_DATA_DIR=$$system(pkg-config --variable pluginsdatadir MeegoImFramework)
} else {
    MALIIT_PLUGINS_DIR=$$system(pkg-config --variable pluginsdir maliit-plugins-0.80)
    MALIIT_PLUGINS_DATA_DIR=$$system(pkg-config --variable pluginsdatadir maliit-plugins-0.80)
}

enable-opengl {
    QT += opengl
    DEFINES += MALIIT_KEYBOARD_HAVE_OPENGL
}

Make sure that MALIIT_PLUGINS_DATA_DIR is non-empty

# Linker optimization for release build
QMAKE_LFLAGS_RELEASE+=-Wl,--as-needed
# Compiler warnings are error if the build type is debug
QMAKE_CXXFLAGS_DEBUG+=-Werror

enable-legacy {
    MALIIT_PLUGINS_DIR=$$system(pkg-config --variable pluginsdir MeegoImFramework)
    MALIIT_PLUGINS_DATA_DIR=$$system(pkg-config --variable pluginsdatadir MeegoImFramework)
} else {
    MALIIT_PLUGINS_DIR=$$system(pkg-config --variable pluginsdir maliit-plugins-0.80)
    MALIIT_PLUGINS_DATA_DIR=$$system(pkg-config --variable pluginsdatadir maliit-plugins-0.80)
}

isEmpty(MALIIT_PLUGINS_DATA_DIR) {
    MALIIT_PLUGINS_DATA_DIR=/usr/local/share/maliit/plugins
}

enable-opengl {
    QT += opengl
    DEFINES += MALIIT_KEYBOARD_HAVE_OPENGL
}


MALIIT_PLUGINS = meego-im-plugins
MALIIT_SERVER = meego-im-uiserver
MALIIT_PLUGINS_LIB = meegoimframework
MALIIT_PLUGINS_HEADER = meegoimframework
MALIIT_PLUGINS_QUICK_LIB = meegoimquick
MALIIT_PLUGINS_QUICK_HEADER = meegoimquick
MALIIT_TEST_SUITE = meego-im-framework-tests
MALIIT_PACKAGENAME = meego-im-framework
MALIIT_PACKAGE_BRIEF = Meego Touch Input Method Framework
MALIIT_ATTRIBUTE_EXTENSIONS = meegoimframework/imtoolbars
MALIIT_CONFIG_ROOT = /meegotouch/inputmethods/
MALIIT_INPUTCONTEXT_NAME = MInputContext
MALIIT_INPUTCONTEXT_TARGETNAME = minputcontext

Add MALIIT_PLUGINS_QUICK_FACTORY to legacy defines, too

MALIIT_PLUGINS = meego-im-plugins
MALIIT_SERVER = meego-im-uiserver
MALIIT_PLUGINS_LIB = meegoimframework
MALIIT_PLUGINS_HEADER = meegoimframework
MALIIT_PLUGINS_QUICK_LIB = meegoimquick
MALIIT_PLUGINS_QUICK_HEADER = meegoimquick
MALIIT_PLUGINS_QUICK_FACTORY = meegoimquickfactory-$${MALIIT_PLUGINS_QUICK_INTERFACE_VERSION}
MALIIT_TEST_SUITE = meego-im-framework-tests
MALIIT_PACKAGENAME = meego-im-framework
MALIIT_PACKAGE_BRIEF = Meego Touch Input Method Framework
MALIIT_ATTRIBUTE_EXTENSIONS = meegoimframework/imtoolbars
MALIIT_CONFIG_ROOT = /meegotouch/inputmethods/
MALIIT_INPUTCONTEXT_NAME = MInputContext
MALIIT_INPUTCONTEXT_TARGETNAME = minputcontext


!ios: DEFINES += V4_ENABLE_JIT

# On Qt/Android/ARM release builds are thumb and debug builds arm,
# but we'll force the JIT to always generate thumb2
android:isEqual(QT_ARCH, "arm") {
    DEFINES += WTF_CPU_ARM_THUMB2
}

DEFINES += WTF_EXPORT_PRIVATE="" JS_EXPORT_PRIVATE=""

win*: DEFINES += NOMINMAX

DEFINES += ENABLE_LLINT=0
DEFINES += ENABLE_DFG_JIT=0
DEFINES += ENABLE_JIT_CONSTANT_BLINDING=0
DEFINES += ENABLE_ASSEMBLER=1
DEFINES += BUILDING_QT__
DEFINES += ENABLE_YARR_JIT=1
DEFINES += ENABLE_JIT=1

INCLUDEPATH += $$PWD/jit
INCLUDEPATH += $$PWD/assembler
INCLUDEPATH += $$PWD/runtime
INCLUDEPATH += $$PWD/wtf
INCLUDEPATH += $$PWD/stubs
INCLUDEPATH += $$PWD/stubs/wtf
INCLUDEPATH += $$PWD

if(isEqual(QT_ARCH, "i386")|isEqual(QT_ARCH, "x86_64")):!win*: DEFINES += WTF_USE_UDIS86=1
else: DEFINES += WTF_USE_UDIS86=0

INCLUDEPATH += $$PWD/disassembler
INCLUDEPATH += $$PWD/disassembler/udis86
INCLUDEPATH += $$_OUT_PWD

Disable the JIT on Windows 64-bit again until the exception support is implemented

!ios:!if(win*:isEqual(QT_ARCH, "x86_64")): DEFINES += V4_ENABLE_JIT

# On Qt/Android/ARM release builds are thumb and debug builds arm,
# but we'll force the JIT to always generate thumb2
android:isEqual(QT_ARCH, "arm") {
    DEFINES += WTF_CPU_ARM_THUMB2
}

DEFINES += WTF_EXPORT_PRIVATE="" JS_EXPORT_PRIVATE=""

win*: DEFINES += NOMINMAX

DEFINES += ENABLE_LLINT=0
DEFINES += ENABLE_DFG_JIT=0
DEFINES += ENABLE_JIT_CONSTANT_BLINDING=0
DEFINES += ENABLE_ASSEMBLER=1
DEFINES += BUILDING_QT__
DEFINES += ENABLE_YARR_JIT=1
DEFINES += ENABLE_JIT=1

INCLUDEPATH += $$PWD/jit
INCLUDEPATH += $$PWD/assembler
INCLUDEPATH += $$PWD/runtime
INCLUDEPATH += $$PWD/wtf
INCLUDEPATH += $$PWD/stubs
INCLUDEPATH += $$PWD/stubs/wtf
INCLUDEPATH += $$PWD

if(isEqual(QT_ARCH, "i386")|isEqual(QT_ARCH, "x86_64")):!win*: DEFINES += WTF_USE_UDIS86=1
else: DEFINES += WTF_USE_UDIS86=0

INCLUDEPATH += $$PWD/disassembler
INCLUDEPATH += $$PWD/disassembler/udis86
INCLUDEPATH += $$_OUT_PWD


# OpenSSL support; compile in QSslSocket.
contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) {

symbian {
	INCLUDEPATH *= $$OS_LAYER_SSL_SYSTEMINCLUDE
} else {
	include($$QT_SOURCE_TREE/config.tests/unix/openssl/openssl.pri)
}

    HEADERS += ssl/qssl.h \
               ssl/qsslcertificate.h \
               ssl/qsslcertificate_p.h \
	       ssl/qsslconfiguration.h \
	       ssl/qsslconfiguration_p.h \
               ssl/qsslcipher.h \
               ssl/qsslcipher_p.h \
               ssl/qsslerror.h \
               ssl/qsslkey.h \
               ssl/qsslsocket.h \
               ssl/qsslsocket_openssl_p.h \
               ssl/qsslsocket_openssl_symbols_p.h \
               ssl/qsslsocket_p.h
    SOURCES += ssl/qssl.cpp \
               ssl/qsslcertificate.cpp \
	       ssl/qsslconfiguration.cpp \
               ssl/qsslcipher.cpp \
               ssl/qsslerror.cpp \
               ssl/qsslkey.cpp \
               ssl/qsslsocket.cpp \
               ssl/qsslsocket_openssl.cpp \
               ssl/qsslsocket_openssl_symbols.cpp

    # Include Qt's default CA bundle
    RESOURCES += network.qrc

    # Add optional SSL libs
    !contains(QT_CONFIG, system-zlib):contains(OPENSSL_LIBS, -lz) {
        # Use the zlib in QtCore
        OPENSSL_LIBS -= -lz
        OPENSSL_LIBS += -lQtCore4
    }
    LIBS_PRIVATE += $$OPENSSL_LIBS

}

Revert "remove -lz from OPENSSL_LIBS so as to respect qt-zlib"

# OpenSSL support; compile in QSslSocket.
contains(QT_CONFIG, openssl) | contains(QT_CONFIG, openssl-linked) {

symbian {
	INCLUDEPATH *= $$OS_LAYER_SSL_SYSTEMINCLUDE
} else {
	include($$QT_SOURCE_TREE/config.tests/unix/openssl/openssl.pri)
}

    HEADERS += ssl/qssl.h \
               ssl/qsslcertificate.h \
               ssl/qsslcertificate_p.h \
	       ssl/qsslconfiguration.h \
	       ssl/qsslconfiguration_p.h \
               ssl/qsslcipher.h \
               ssl/qsslcipher_p.h \
               ssl/qsslerror.h \
               ssl/qsslkey.h \
               ssl/qsslsocket.h \
               ssl/qsslsocket_openssl_p.h \
               ssl/qsslsocket_openssl_symbols_p.h \
               ssl/qsslsocket_p.h
    SOURCES += ssl/qssl.cpp \
               ssl/qsslcertificate.cpp \
	       ssl/qsslconfiguration.cpp \
               ssl/qsslcipher.cpp \
               ssl/qsslerror.cpp \
               ssl/qsslkey.cpp \
               ssl/qsslsocket.cpp \
               ssl/qsslsocket_openssl.cpp \
               ssl/qsslsocket_openssl_symbols.cpp

    # Include Qt's default CA bundle
    RESOURCES += network.qrc

    # Add optional SSL libs
    LIBS_PRIVATE += $$OPENSSL_LIBS
}


include(../config.pri)

TEMPLATE = lib
DEPENDPATH += ..

OBJECTS_DIR = .obj
MOC_DIR = .moc

include(../common/libmaliit-common.pri)
include(../maliit/libmaliit.pri)
include(../connection/libmaliit-connection.pri)

DEFINES += MALIIT_INPUTCONTEXT_NAME=\\\"$${MALIIT_INPUTCONTEXT_NAME}\\\"

QT = core gui
CONFIG += link_pkgconfig

# coverage flags are off per default, but can be turned on via qmake COV_OPTION=on
for(OPTION,$$list($$lower($$COV_OPTION))){
    isEqual(OPTION, on){
        QMAKE_CXXFLAGS += -ftest-coverage -fprofile-arcs -fno-elide-constructors
        LIBS += -lgcov
    }
}

QMAKE_CLEAN += $$OBJECTS_DIR/*.gcno $$OBJECTS_DIR/*.gcda

QT_IM_PLUGIN_PATH = $$[QT_INSTALL_PLUGINS]/inputmethods
QT_PREFIX = $$[QT_INSTALL_PREFIX]
enforce-install-prefix {
    QT_IM_PLUGIN_PATH = $$replace(QT_IM_PLUGIN_PATH, $$QT_PREFIX, $$M_IM_PREFIX)
}

QMAKE_EXTRA_TARGETS += check-xml
check-xml.target = check-xml
check-xml.depends += lib$${TARGET}.so

QMAKE_EXTRA_TARGETS += check
check.target = check
check.depends += lib$${TARGET}.so

Fix dependency issues for make check


# Mock interface for DeclarativeWebUtils. Interface is not complete.
# Currently it includes only methods needed at runtime.
# This pri is included indirectly from unit tests cases that
# are at the same level in the file hierarchy.
SOURCES += ../common/declarativewebutils.cpp
HEADERS += ../common/declarativewebutils.h

PKGCONFIG += qt5embedwidget

Fix builds error when using ./build.sh script.

# Mock interface for DeclarativeWebUtils. Interface is not complete.
# Currently it includes only methods needed at runtime.
# This pri is included indirectly from unit tests cases that
# are at the same level in the file hierarchy.
SOURCES += ../common/declarativewebutils.cpp
HEADERS += ../common/declarativewebutils.h

isEmpty(QTEMBED_LIB) {
  PKGCONFIG += qt5embedwidget
} else {
  LIBS+=$$QTEMBED_LIB
}


CONFIG      -= qt

CONFIG(debug,debug|release) {
    message("ks: Debug Build")
}

CONFIG(release,debug|release) {
    message("ks: Release Build")
}

android {
    message("ks: Platform: Android")
}
linux {
    !android {
        message("ks: Platform: Linux")
    }
}

#ks_core
include($${PATH_KS}/ks_core/ks_core.pri)

#ks_ecs
include($${PATH_KS}/ks_ecs/ks_ecs.pri)

#ks_gl
include($${PATH_KS}/ks_gl/ks_gl.pri)

#ks_draw
include($${PATH_KS}/ks_draw/ks_draw.pri)

#ks_gui
include($${PATH_KS}/ks_gui/ks_gui.pri)

#ks_platform
include($${PATH_KS}/ks_platform/ks_platform.pri)

#ks_shared
include($${PATH_KS}/ks_shared/ks_shared.pri)

Build info message is slightly nicer and more informative

CONFIG      -= qt

KS_BUILD_INFO_CONFIG = Unknown
KS_BUILD_INFO_PLATFORM = $$[QMAKE_XSPEC]
KS_BUILD_INFO_SPEC = $$[QMAKE_XSPEC]
KS_BUILD_INFO_ARCH = $${QT_ARCH}

CONFIG(debug,debug|release) {
    KS_BUILD_INFO_CONFIG = Debug
}

CONFIG(release,debug|release) {
    KS_BUILD_INFO_CONFIG = Release
}

android {
    KS_BUILD_INFO_PLATFORM = Android
}
linux {
    !android {
        KS_BUILD_INFO_PLATFORM = Linux
    }
}

message("ks: Build Info: $${KS_BUILD_INFO_PLATFORM}, $${KS_BUILD_INFO_SPEC}, $${KS_BUILD_INFO_ARCH}, $${KS_BUILD_INFO_CONFIG}")

#ks_core
include($${PATH_KS}/ks_core/ks_core.pri)

#ks_ecs
include($${PATH_KS}/ks_ecs/ks_ecs.pri)

#ks_gl
include($${PATH_KS}/ks_gl/ks_gl.pri)

#ks_draw
include($${PATH_KS}/ks_draw/ks_draw.pri)

#ks_gui
include($${PATH_KS}/ks_gui/ks_gui.pri)

#ks_platform
include($${PATH_KS}/ks_platform/ks_platform.pri)

#ks_shared
include($${PATH_KS}/ks_shared/ks_shared.pri)

#ks_text
include($${PATH_KS}/ks_text/ks_text.pri)


include(../install_prefix.pri)

QT = core
TEMPLATE = app
!isEmpty(QBS_APPS_DESTDIR):DESTDIR = $${QBS_APPS_DESTDIR}
else:DESTDIR = ../../../bin

!isEmpty(QBS_APPS_RPATH_DIR) {
    linux-*:QMAKE_LFLAGS += -Wl,-z,origin \'-Wl,-rpath,$${QBS_APPS_RPATH_DIR}\'
    macx:QMAKE_LFLAGS += -Wl,-rpath,$${QBS_APPS_RPATH_DIR}
}

CONFIG += console
CONFIG -= app_bundle
CONFIG += c++11

include($${PWD}/../lib/corelib/use_corelib.pri)
include($${PWD}/shared/logging/logging.pri)

!isEmpty(QBS_APPS_INSTALL_DIR):target.path = $${QBS_APPS_INSTALL_DIR}
else:target.path = $${QBS_INSTALL_PREFIX}/bin
INSTALLS += target

Use the same compatibility defines in qmake and qbs build

include(../install_prefix.pri)

QT = core
TEMPLATE = app
DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_PROCESS_COMBINED_ARGUMENT_START
!isEmpty(QBS_APPS_DESTDIR):DESTDIR = $${QBS_APPS_DESTDIR}
else:DESTDIR = ../../../bin

!isEmpty(QBS_APPS_RPATH_DIR) {
    linux-*:QMAKE_LFLAGS += -Wl,-z,origin \'-Wl,-rpath,$${QBS_APPS_RPATH_DIR}\'
    macx:QMAKE_LFLAGS += -Wl,-rpath,$${QBS_APPS_RPATH_DIR}
}

CONFIG += console
CONFIG -= app_bundle
CONFIG += c++11

include($${PWD}/../lib/corelib/use_corelib.pri)
include($${PWD}/shared/logging/logging.pri)

!isEmpty(QBS_APPS_INSTALL_DIR):target.path = $${QBS_APPS_INSTALL_DIR}
else:target.path = $${QBS_INSTALL_PREFIX}/bin
INSTALLS += target


CONFIG(debug, debug|release) {
  BUILD_TYPE = debug
}
else:CONFIG(release, debug|release) {
  BUILD_TYPE = release
}
else {
  warning("Unknown build type; defaulting to debug")
  BUILD_TYPE = debug
}

OBJECTS_DIR = temp
MOC_DIR = temp
UI_DIR = temp
RCC_DIR = temp

INCLUDEPATH *= \
  $$MOC_DIR \
  $$UI_DIR \
  $$RCC_DIR \
  /usr/include \
  /usr/local/include \
  /usr/include/x86_64-linux-gnu \
  /usr/include/x86_64-linux-gnu/qt5 \
  /usr/include/qt5 \

DESTDIR = $$PWD/../build/$${BUILD_TYPE}-$${QMAKE_CC}/dist

LIBS *= \
  -L/usr/lib \
  -L/usr/local/lib \
  -L/usr/local/clang-3.5.0/lib \
  -L/usr/local/clang-3.6.0/lib \
  -L/usr/local/clang-3.7.0/lib \
  -L/usr/local/clang-3.8.0/lib \

Add another directory for libraries

CONFIG(debug, debug|release) {
  BUILD_TYPE = debug
}
else:CONFIG(release, debug|release) {
  BUILD_TYPE = release
}
else {
  warning("Unknown build type; defaulting to debug")
  BUILD_TYPE = debug
}

OBJECTS_DIR = temp
MOC_DIR = temp
UI_DIR = temp
RCC_DIR = temp

INCLUDEPATH *= \
  $$MOC_DIR \
  $$UI_DIR \
  $$RCC_DIR \
  /usr/include \
  /usr/local/include \
  /usr/include/x86_64-linux-gnu \
  /usr/include/x86_64-linux-gnu/qt5 \
  /usr/include/qt5 \

DESTDIR = $$PWD/../build/$${BUILD_TYPE}-$${QMAKE_CC}/dist

LIBS *= \
  -L/usr/lib \
  -L/usr/local/lib \
  -L/usr/local/clang-3.5.0/lib \
  -L/usr/local/clang-3.6.0/lib \
  -L/usr/local/clang-3.7.0/lib \
  -L/usr/local/clang-3.8.0/lib \
  -L/usr/lib/x86_64-linux-gnu


SUPPORT_QT_MAEMO = $$(QTCREATOR_WITH_MAEMO)
!isEmpty(SUPPORT_QT_MAEMO) {
    message("Adding experimental support for Qt/Maemo applications.")
    DEFINES += QTCREATOR_WITH_MAEMO
#    DEFINES += USE_SSH_LIB
#    INCLUDEPATH += $$PWD/../../../libs/3rdparty/net7ssh/src
#    INCLUDEPATH += $$PWD/../../../libs/3rdparty/botan/build
#    LIBS += -l$$qtLibraryTarget(Net7ssh) -l$$qtLibraryTarget(Botan)
    HEADERS += $$PWD/maemorunconfiguration.h \
        $$PWD/maemomanager.h \
        $$PWD/maemotoolchain.h \
        $$PWD/maemodeviceconfigurations.h \
        $$PWD/maemosettingspage.h \
        $$PWD/maemosshconnection.h \
        $$PWD/maemosshthread.h \
        $$PWD/maemoruncontrol.h \
        $$PWD/maemorunconfigurationwidget.h
    SOURCES += $$PWD/maemorunconfiguration.cpp \
        $$PWD/maemomanager.cpp \
        $$PWD/maemotoolchain.cpp \
        $$PWD/maemodeviceconfigurations.cpp \
        $$PWD/maemosettingspage.cpp \
        $$PWD/maemosshconnection.cpp \
        $$PWD/maemosshthread.cpp \
        $$PWD/maemoruncontrol.cpp \
        $$PWD/maemorunconfigurationwidget.cpp
    FORMS += $$PWD/maemosettingswidget.ui
    RESOURCES += $$PWD/qt-maemo.qrc
}

Make use of the new ssh lib feature.

SUPPORT_QT_MAEMO = $$(QTCREATOR_WITH_MAEMO)
!isEmpty(SUPPORT_QT_MAEMO) {
    message("Adding experimental support for Qt/Maemo applications.")
    DEFINES += QTCREATOR_WITH_MAEMO
    DEFINES += USE_SSH_LIB
    INCLUDEPATH += $$PWD/../../../libs/3rdparty/net7ssh/src
    INCLUDEPATH += $$PWD/../../../libs/3rdparty/botan/build
    LIBS += -l$$qtLibraryTarget(Net7ssh) -l$$qtLibraryTarget(Botan)
    HEADERS += $$PWD/maemorunconfiguration.h \
        $$PWD/maemomanager.h \
        $$PWD/maemotoolchain.h \
        $$PWD/maemodeviceconfigurations.h \
        $$PWD/maemosettingspage.h \
        $$PWD/maemosshconnection.h \
        $$PWD/maemosshthread.h \
        $$PWD/maemoruncontrol.h \
        $$PWD/maemorunconfigurationwidget.h
    SOURCES += $$PWD/maemorunconfiguration.cpp \
        $$PWD/maemomanager.cpp \
        $$PWD/maemotoolchain.cpp \
        $$PWD/maemodeviceconfigurations.cpp \
        $$PWD/maemosettingspage.cpp \
        $$PWD/maemosshconnection.cpp \
        $$PWD/maemosshthread.cpp \
        $$PWD/maemoruncontrol.cpp \
        $$PWD/maemorunconfigurationwidget.cpp
    FORMS += $$PWD/maemosettingswidget.ui
    RESOURCES += $$PWD/qt-maemo.qrc
}


QT_DECLARATIVE_VERSION = $$QT_VERSION
QT_DECLARATIVE_MAJOR_VERSION = $$QT_MAJOR_VERSION
QT_DECLARATIVE_MINOR_VERSION = $$QT_MINOR_VERSION
QT_DECLARATIVE_PATCH_VERSION = $$QT_PATCH_VERSION

QT.declarative.name = QtDeclarative
QT.declarative.includes = $$QT_MODULE_INCLUDE_BASE $$QT_MODULE_INCLUDE_BASE/QtDeclarative
QT.declarative.sources = $$QT_MODULE_BASE/src/declarative
QT.declarative.libs = $$QT_MODULE_LIB_BASE
QT.declarative.depends = gui script network

Add the private_includes path to the modules .pri file

QT_DECLARATIVE_VERSION = $$QT_VERSION
QT_DECLARATIVE_MAJOR_VERSION = $$QT_MAJOR_VERSION
QT_DECLARATIVE_MINOR_VERSION = $$QT_MINOR_VERSION
QT_DECLARATIVE_PATCH_VERSION = $$QT_PATCH_VERSION

QT.declarative.name = QtDeclarative
QT.declarative.includes = $$QT_MODULE_INCLUDE_BASE $$QT_MODULE_INCLUDE_BASE/QtDeclarative
QT.declarative.private_includes = $$QT_MODULE_INCLUDE_BASE/QtDeclarative/private
QT.declarative.sources = $$QT_MODULE_BASE/src/declarative
QT.declarative.libs = $$QT_MODULE_LIB_BASE
QT.declarative.depends = gui script network


message("qtcontacts-tracker.pri")

!contains(DEFINES, QTCONTACTS-TRACKER_PRI) {
message(" ^ including")
DEFINES += QTCONTACTS-TRACKER_PRI

INCLUDEPATH += /usr/include/qt4/QtContacts
INCLUDEPATH += $$PWD

LIBS += -lqttracker
LIBS += -lQtContacts

HEADERS += qcontacttrackerbackend_p.h \
           qtrackercontactasyncrequest.h \
           trackerchangelistener.h

SOURCES += qcontacttrackerbackend.cpp \
           qtrackercontactasyncrequest.cpp \
           trackerchangelistener.cpp
}

Fix source and header paths.

message("qtcontacts-tracker.pri")

!contains(DEFINES, QTCONTACTS-TRACKER_PRI) {
message(" ^ including")
DEFINES += QTCONTACTS-TRACKER_PRI

INCLUDEPATH += /usr/include/qt4/QtContacts

LIBS += -lqttracker
LIBS += -lQtContacts

HEADERS += $$PWD/qcontacttrackerbackend_p.h \
           $$PWD/qtrackercontactasyncrequest.h \
           $$PWD/trackerchangelistener.h

SOURCES += $$PWD/qcontacttrackerbackend.cpp \
           $$PWD/qtrackercontactasyncrequest.cpp \
           $$PWD/trackerchangelistener.cpp
}


!qbs_do_not_link_bundled_qtscript {
    include(../../library_dirname.pri)
    isEmpty(QBSLIBDIR) {
        QBSLIBDIR = $$shadowed($$PWD/../../../$${QBS_LIBRARY_DIRNAME})
    }
    LIBS += -L$$QBSLIBDIR -lqbsscriptengine$$qtPlatformTargetSuffix()
}

INCLUDEPATH += \
    $$PWD/include \
    $$shadowed($$PWD/include)

Fix library not found for -lqbsscriptengine_debug on macOS

!qbs_do_not_link_bundled_qtscript {
    include(../../library_dirname.pri)
    isEmpty(QBSLIBDIR) {
        QBSLIBDIR = $$shadowed($$PWD/../../../$${QBS_LIBRARY_DIRNAME})
    }

    LIBS += -L$$QBSLIBDIR
    macos {
        LIBS += -lqbsscriptengine
    }
    else {
        LIBS += -lqbsscriptengine$$qtPlatformTargetSuffix()
    }

}

INCLUDEPATH += \
    $$PWD/include \
    $$shadowed($$PWD/include)


QMAKE_EXTRA_TARGETS += check
check.target = check
check.commands = TESTING_IN_SANDBOX=1 TESTPLUGIN_PATH=../plugins LD_LIBRARY_PATH=../../src:../../input-context/:../../passthroughserver/:../plugins:$(LD_LIBRARY_PATH) ./$$TARGET
check.depends += $$TARGET

QMAKE_EXTRA_TARGETS += check-xml
check-xml.target = check-xml
check-xml.commands = ../rt.sh $$TARGET
check-xml.depends += $$TARGET

# coverage flags are off per default, but can be turned on via qmake COV_OPTION=on
for(OPTION,$$list($$lower($$COV_OPTION))){
    isEqual(OPTION, on){
        QMAKE_CXXFLAGS += -ftest-coverage -fprofile-arcs
        LIBS += -lgcov
    }
}
QMAKE_CLEAN += *.gcno *.gcda

Fix make check for non-legacy mode

QMAKE_EXTRA_TARGETS += check
check.target = check
check.commands = TESTING_IN_SANDBOX=1 TESTPLUGIN_PATH=../plugins LD_LIBRARY_PATH=../../src:../../input-context/:../../passthroughserver/:../../maliit:../plugins:$(LD_LIBRARY_PATH) ./$$TARGET
check.depends += $$TARGET

QMAKE_EXTRA_TARGETS += check-xml
check-xml.target = check-xml
check-xml.commands = ../rt.sh $$TARGET
check-xml.depends += $$TARGET

# coverage flags are off per default, but can be turned on via qmake COV_OPTION=on
for(OPTION,$$list($$lower($$COV_OPTION))){
    isEqual(OPTION, on){
        QMAKE_CXXFLAGS += -ftest-coverage -fprofile-arcs
        LIBS += -lgcov
    }
}
QMAKE_CLEAN += *.gcno *.gcda


include(../compiler.pri)

TEMPLATE	= lib
CONFIG		+= plugin debug_and_release warn_on
CONFIG		-= qt
DIST		*= mumble_plugin.h

CONFIG(debug, debug|release) {
  DEFINES += PLUGIN_DEBUG
  CONFIG += console
  DESTDIR       = ../../debug/plugins
}

CONFIG(release, debug|release) {
  DESTDIR       = ../../release/plugins
}

include(../symbols.pri)

Disable PLUGIN_DEBUG as the console spams breaks up audio

include(../compiler.pri)

TEMPLATE	= lib
CONFIG		+= plugin debug_and_release warn_on
CONFIG		-= qt
DIST		*= mumble_plugin.h

CONFIG(debug, debug|release) {
  CONFIG += console
  DESTDIR       = ../../debug/plugins
}

CONFIG(release, debug|release) {
  DESTDIR       = ../../release/plugins
}

include(../symbols.pri)


INCLUDEPATH += $$PWD

SOURCES += $$PWD/qiscp.cpp \
    $$PWD/iscpmsg.cpp \
    $$PWD/deviceinforparser.cpp

HEADERS += \
    $$PWD/qiscp.h \
    $$PWD/iscpmsg.h \
    $$PWD/deviceinforparser.h


Use .pri includes in all tests instead of setting LIBS/INCLUDES

# Should normally not be used! This is a plugin.
#
# The .pro file must define TOP_DIR to be a relative path
# to the top-level source/build directory, and include config.pri

INCLUDEPATH += $$TOP_DIR/input-context/input-context-plugin
LIBS += -L$$TOP_DIR/lib/plugins \
        -l$$MALIIT_INPUTCONTEXTPLUGIN_TARGETNAME
POST_TARGETDEPS += $$TOP_DIR/lib/plugins/$$maliitDynamicLib($$MALIIT_INPUTCONTEXTPLUGIN_TARGETNAME)


Make it easy for applications to build Bacon2D into their project

# Include this file in your .pro file to statically compile the Bacon2D QML
# plugin into your project.
#
# Basic usage instructions:
#
#  #include <plugins.h>
#
#  int main(int argc, char *argv[])
#  {
#      QApplication app(argc, argv);
#
#      Plugin plugin;
#      plugin.registerTypes("Bacon2D");
#
#      ...
#  }

INCLUDEPATH += $$PWD

DEPENDPATH += .
INCLUDEPATH += ../3rdparty/qml-box2d/

DEFINES += STATIC_PLUGIN_BOX2D
include(../3rdparty/qml-box2d/box2d-static.pri)

HEADERS += \
        $$PWD/animationchangeevent.h \
        $$PWD/animationtransition.h \
        $$PWD/behavior.h \
        $$PWD/entity.h \
        $$PWD/enums.h \
        $$PWD/game.h \
        $$PWD/imagelayer.h \
        $$PWD/layer.h \
        $$PWD/plugins.h \
        $$PWD/scene.h \
        $$PWD/scriptbehavior.h \
        $$PWD/spriteanimation.h \
        $$PWD/sprite.h \
        $$PWD/spritesheet.h \
        $$PWD/viewport.h

SOURCES += \
        $$PWD/animationtransition.cpp \
        $$PWD/behavior.cpp \
        $$PWD/entity.cpp \
        $$PWD/game.cpp \
        $$PWD/imagelayer.cpp \
        $$PWD/layer.cpp \
        $$PWD/plugins.cpp \
        $$PWD/scene.cpp \
        $$PWD/scriptbehavior.cpp \
        $$PWD/spriteanimation.cpp \
        $$PWD/sprite.cpp \
        $$PWD/spritesheet.cpp \
        $$PWD/viewport.cpp


Add function to query spec file for metadata

defineReplace(rpmquery) {
  return($$system("rpmspec -q --srpm --queryformat '\"%{$$1}\"' $$2"))
}
defineReplace(rpmquery_appspec) {
  return($$rpmquery("$$1", "$$top_srcdir/rpm/harbour-communi.spec"))
}


function parse(io::IO)
    d = Decoder()
    decode(d, JSON.parse(io))
end

Add convenience function to parse strings directly.

function parse(io::IO)
    d = Decoder()
    decode(d, JSON.parse(io))
end

function parse(s::AbstractString)
    d = Decoder()
    decode(d, JSON.parse(s))
end


module EclipseREPL
function execute(statement)
  status="complete"
  mimeType="text/plain"
  try
    expression = parse(statement,1; greedy=true, raise=false)
    if isa(expression[1],Expr)
      state = expression[1].head
    else
      state = nothing
    end
    status = state==:incomplete ? "incomplete" : state==:error ? "error" : "complete"
    result=nothing
    if(status=="complete")
      result=include_string(statement)
      if result!=nothing
        if string(typeof(result))=="Gadfly.Plot"
           mimeType = "text/html"
           println(stringmime(mimeType,result))
        else
          println(result)
        end
      end
    end
  catch e
    showerror(STDOUT, e); println()
    status = "error"
    println()
  finally
    flush_all()
    println("<<<<$status>>>>")
    println("<<<<$mimeType>>>>")
    println("<<<<eox>>>>")
  end
end
function flush_all()
#    Libc.flush_cstdio()
    flush(STDOUT)
#    flush(STDERR)
end
#import Base.flush
#const StdioPipe = Base.PipeEndpoint
#function flush(io::StdioPipe)
#    invoke(flush, (supertype(StdioPipe),), io)
#    if io == STDOUT
#        oslibuv_flush()
#        send_stream("stdout")
#    elseif io == STDERR
#        oslibuv_flush()
#        send_stream("stderr")
#    end
#end
end;

Update repl io stream flushing

module EclipseREPL
function execute(statement)
  status="complete"
  mimeType="text/plain"
  try
    expression = parse(statement,1; greedy=true, raise=false)
    if isa(expression[1],Expr)
      state = expression[1].head
    else
      state = nothing
    end
    status = state==:incomplete ? "incomplete" : state==:error ? "error" : "complete"
    result=nothing
    if(status=="complete")
      result=include_string(statement)
      if result!=nothing
        if string(typeof(result))=="Gadfly.Plot"
           mimeType = "text/html"
           println(stringmime(mimeType,result))
        else
          println(result)
        end
      end
    end
  catch e
    showerror(STDOUT, e); println()
    status = "error"
    println()
  finally
    flush_all()
    println("<<<<$status>>>>")
    println("<<<<$mimeType>>>>")
    println("<<<<eox>>>>")
  end
end
function flush_all()
    Libc.flush_cstdio()
    flush(STDOUT)
    flush(STDERR)
end
end;


script, output = ARGS

using Pkg

compilerenv = abspath("compilerenv")
Pkg.activate(compilerenv)
Pkg.add([
    PackageSpec(
        name = "PackageCompiler",
        uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d",
        version = "0.6",
    )
])
using PackageCompiler

Pkg.activate(".")
Pkg.add("MacroTools")
Pkg.add("PyCall")

sysout, _curr_syso = compile_incremental("Project.toml", script)

cp(sysout, output, force=true)

Use PackageSpec when installing PyCall

script, output = ARGS

if VERSION < v"0.7-"
    error("Unsupported Julia version $VERSION")
end

using Pkg

compilerenv = abspath("compilerenv")
Pkg.activate(compilerenv)
Pkg.add([
    PackageSpec(
        name = "PackageCompiler",
        uuid = "9b87118b-4619-50d2-8e1e-99f35a4d4d9d",
        version = "0.6",
    )
])
using PackageCompiler

Pkg.activate(".")
Pkg.add([
    PackageSpec(
        name = "PyCall",
        uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0",
    )
    PackageSpec(
        name = "MacroTools",
        uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09",
    )
])

sysout, _curr_syso = compile_incremental("Project.toml", script)

cp(sysout, output, force=true)


using Base.Test

for (root, dirs, files) in walkdir("exercises")
    for exercise in dirs
        # Allow only testing specified execises
        if !isempty(ARGS) && !(exercise in ARGS)
            continue
        end

        exercise_path = joinpath("exercises", exercise)

        # Create temporary directory
        temp_path = mktempdir(root)

        # Copy tests & example to the temporary directory
        cp(joinpath(exercise_path, "example.jl"), joinpath(temp_path, "$exercise.jl"))
        cp(joinpath(exercise_path, "runtests.jl"), joinpath(temp_path, "runtests.jl"))

        # Run the tests
        result = @testset "$exercise example" begin
            include(joinpath(temp_path, "runtests.jl"))
        end

        # Delete the temporary directory
        rm(temp_path, recursive=true)

        # Print test output (this is the default behaviour for older versions of Julia)
        if VERSION > v"0.6.0-dev"
            Base.Test.print_test_results(result)
        end
    end
end

Fix removal of temp directory if tests fail

using Base.Test

for (root, dirs, files) in walkdir("exercises")
    for exercise in dirs
        # Allow only testing specified execises
        if !isempty(ARGS) && !(exercise in ARGS)
            continue
        end

        exercise_path = joinpath("exercises", exercise)

        # Create temporary directory
        temp_path = mktempdir(root)

        # Copy tests & example to the temporary directory
        cp(joinpath(exercise_path, "example.jl"), joinpath(temp_path, "$exercise.jl"))
        cp(joinpath(exercise_path, "runtests.jl"), joinpath(temp_path, "runtests.jl"))

        try
            # Run the tests
            result = @testset "$exercise example" begin
                include(joinpath(temp_path, "runtests.jl"))
            end
        finally
            # Delete the temporary directory
            rm(temp_path, recursive=true)
        end

        # Print test output (this is the default behaviour for older versions of Julia)
        if VERSION > v"0.6.0-dev"
            Base.Test.print_test_results(result)
        end
    end
end


module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop(loop=nothing)
    this                        = new()
    this.ioloop                 = loop # or ioloop.IOLoop()
    this.ioloop.make_current()
    this.periodic_callback      = nothing
    this.periodic_callback_time = 1

    this.instance                  = function() instance(this) end
    this.start                     = function() start(this) end
    this.stop                      = function() stop(this) end
    this.attach_periodic_callback  = function() attach_periodic_callback(this, this.periodic_callback, this.periodic_callback_time) end
    this.dettach_periodic_callback = function() dettach_periodic_callback(this) end

    this
  end

  function instance(self::Loop)
    # return Loop(ioloop.IOLoop.current())
  end

  function start(self::Loop)
    self.ioloop.start()
  end

  function stop(self::Loop)
    self.ioloop.stop()
  end

  function attach_periodic_callback(self::Loop, callback::Callback, callback_time::Int)
  end

  function dettach_periodic_callback(self::Loop)
  end

end

end # module loop

Implement skeleton codes for Loop.attach_periodic_callback and Loop.dettach_periodic_callback

module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop(loop=nothing)
    this                        = new()
    this.ioloop                 = loop # or ioloop.IOLoop()
    this.ioloop.make_current()
    this.periodic_callback      = nothing
    this.periodic_callback_time = 1

    this.instance                  = function() instance(this) end
    this.start                     = function() start(this) end
    this.stop                      = function() stop(this) end
    this.attach_periodic_callback  = function() attach_periodic_callback(this, this.periodic_callback, this.periodic_callback_time) end
    this.dettach_periodic_callback = function() dettach_periodic_callback(this) end

    this
  end

  function instance(self::Loop)
    # return Loop(ioloop.IOLoop.current())
  end

  function start(self::Loop)
    self.ioloop.start()
  end

  function stop(self::Loop)
    self.ioloop.stop()
  end

  function attach_periodic_callback(self::Loop, callback::Callback, callback_time::Int)
    if (self.periodic_callback != nothing)
      self.dettach_periodic_callback(self)
    end
    # self.periodic_callback = ioloop.PeriodicCallback(callback, callback_time, self._ioloop)
    # self.periodic_callback.start
  end

  function dettach_periodic_callback(self::Loop)
    # if (self.periodic_callback != nothing)
    #   self.periodic_callback.stop()
    # end
    self.periodic_callback = nothing
  end

end

end # module loop


@testset "Cli Function Tests" begin

  @test isdefined(Julz, :cli) == true

end

Add test for cli usage

@testset "Cli Function Tests" begin

  @test isdefined(Julz, :cli) == true

  originalSTDOUT = STDOUT

  (outRead, outWrite) = redirect_stdout()

  run(`julia -L $(Pkg.dir("Julz"))/src/functions/cli.jl -e 'cli()' -- hello`)

  close(outWrite)

  data = readavailable(outRead)

  close(outRead)

  redirect_stdout(originalSTDOUT)

  @test String(data) == "Hello, World!\n"

end


using Base.Test
using Tlaloc

#=

# Testing constructor
engine = TlalocEngine(string(dirname(Base.source_path()),"\\test_conf.ini"))
@test typeof(engine) == TlalocEngine
@test engine.viewPath == "thisIsTheViewPath"
@test engine.TemplatePath == "thisIsTheTemplatePath"
@test engine.ResourcePath == "thisIsTheResource"

=#

@test 1==1

Change Backslash for slash ini path

using Base.Test
using Tlaloc

# Testing constructor
engine = TlalocEngine(string(dirname(Base.source_path()),"/test_conf.ini"))
@test typeof(engine) == TlalocEngine
@test engine.viewPath == "thisIsTheViewPath"
@test engine.TemplatePath == "thisIsTheTemplatePath"
@test engine.ResourcePath == "thisIsTheResource"

@test 1==1


# Represents a subset of {1, 2, ..., 9},
# which in turn represents the leftover number that can be use to fill the corresponding cells.
typealias PossibleValue Uint

Create type `gameState`, `Index`, 'Number`, and `LeftoverNumbers`.

# Represents the number to fill into a cell, i.e. 1 to 9.
typealias Number Int

# Represents a subset of {1, 2, ..., 9},
# which in turn represents the leftover number that can be use to fill the corresponding cells.
typealias PossibleValue Uint
typealias LeftoverNumbers Uint

# Represents the index of a cell.
# The index counts from 1, starting at the top left, moving to right, then row-by-row to the bottom, ending with 81.
typealias Index Int

# The state of the game currently.
# This will evolve as the Sudoku puzzle is being solved.
type gameState
    cell::Vector{Number}

    leftoverNumbers_block::Vector{LeftoverNumbers}
    leftoverNumbers_row::Vector{LeftoverNumbers}
    leftoverNumbers_col::Vector{LeftoverNumbers}

    block_of::Vector{Index}
    row_of::Vector{Index}
    col_of::Vector{Index}

    sequence::Vector{Index}
    sequencePointer::Index

    currentCount::Int
    levelCount::Vector{Int}
end

function gameState()
    cell = Array(Number, 81)

    leftoverNumbers_block = Array(LeftoverNumbers, 9)
    leftoverNumbers_row = Array(LeftoverNumbers, 9)
    leftoverNumbers_col = Array(LeftoverNumbers, 9)

    block_of = Array(Index, 81)
    row_of = Array(Index, 81)
    col_of = Array(Index, 81)

    sequence = Array(Index, 81)
    sequencePointer = one(Index)

    currentCount = zero(Int)
    levelCount = Array(Int, 82)

    return gameState(cell,

                     leftoverNumbers_block,
                     leftoverNumbers_row,
                     leftoverNumbers_col,

                     block_of,
                     row_of,
                     col_of,

                     sequence,
                     sequencePointer,

                     currentCount,
                     levelCount)
end


include("unscentedtypes.jl")

# Predict and update functions

# Now a target for abstraction
function ap(f::AdditiveUnscentedModel,s::UnscentedState)
    σs = map(f.f,s.σ)
    x = dot(s.wm,σs)
    p = dot(s.wc,map(y->(y-x)*(y-x)',σs)) + f.q
    UnscentedState(σs,s.α,s.β,s.κ,s.wm,s.wc)
end

function covs(kf::AdditiveUnscentedKalmanFilter,y::Observation)
    yp = map(kf.z.h,kf.x.σ)
    yhat = dot(kf.x.wm,yp)

    resx = map(x->x-kf.x.x,kf.x.σ)
    resy = map(y->y-yhat,yp)

    res = y.y-yhat
    ph = dot(kf.x.wc,map((x,z)->x*z',resx,resy))
    s = dot(kf.x.wc,map(x->x*x',resy)) + kf.z.r

    return res,ph,s
end

Refactor ap for UKFs to use the new UKF API

include("unscentedtypes.jl")

# Predict and update functions

# Now a target for abstraction
function ap(f::AdditiveUnscentedModel,s::UnscentedState)
    σn,wm,wc = sigma(s)
    σs = zeros(σn)
    xn = zeros(s.x)
    for i in 1:size(σn,2)
        σs[:,i] = f.f(σn[:,i])
        xn += wm[i] * σs[:,i]
    end
    pn = zeros(s.p)
    for i in 1:size(σn,2)
        pn += wc[i] * (σs[:,i]-xn)*(σs[:,i]-xn)'
    end
    pn += f.q
    UnscentedState(xn,pn,s.α,s.β,s.κ)
end

function covs(kf::AdditiveUnscentedKalmanFilter,y::Observation)
    yp = map(kf.z.h,kf.x.σ)
    yhat = dot(kf.x.wm,yp)

    resx = map(x->x-kf.x.x,kf.x.σ)
    resy = map(y->y-yhat,yp)

    res = y.y-yhat
    ph = dot(kf.x.wc,map((x,z)->x*z',resx,resy))
    s = dot(kf.x.wc,map(x->x*x',resy)) + kf.z.r

    return res,ph,s
end


using CGP
using Base.Test

function getparameters()
    return default_parameters(3, 3, 9, 2, 3, 1)
end

funcs = default_funcs()
parameters = getparameters()
chromosome = random_chromosome(parameters, funcs)

Expand test file to exercise more code.

using CGP
using Base.Test

const numinputs = 2
const numoutputs = 1
const nodearity = 2
const numperlevel = 1
const numlevels = 10
const numlevelsback = 10

funcs = default_funcs()
parameters = default_parameters(numinputs, numoutputs, nodearity,
                                numperlevel, numlevels, numlevelsback)
chromosome = random_chromosome(parameters, funcs)
result = execute_chromosome(chromosome, [true, false])
println(result)


using Kalman
using Base.Test

include("bkftest.jl")
include("ekftest.jl")
include("ukftest.jl")

if VERSION >= v"0.4.0-"
    include("nullabletest.jl")
end

Modify run tests to run the new UKF tests

using Kalman
using Base.Test

include("bkftest.jl")
include("ekftest.jl")
include("ukf/bkfiltertest.jl")

if VERSION >= v"0.4.0-"
    include("nullabletest.jl")
end


using Documenter, DataFrames

# Build documentation.
# ====================

makedocs(
    # options
    modules = [DataFrames],
    doctest = true,
    clean = false,
    sitename = "DataFrames.jl",
    format = Documenter.Formats.HTML,
    pages = Any[
        "Introduction" => "index.md",
        "User Guide" => Any[
            "Getting Started" => "man/getting_started.md",
            "Joins" => "man/joins.md",
            "Split-apply-combine" => "man/split_apply_combine.md",
            "Reshaping" => "man/reshaping_and_pivoting.md",
            "Sorting" => "man/sorting.md",
            "Categorical Data" => "man/categorical.md",
            "Querying frameworks" => "man/querying_frameworks.md",
        ],
        "API" => Any[
            "Main types" => "lib/maintypes.md",
            "Utilities" => "lib/utilities.md",
            "Data manipulation" => "lib/manipulation.md",
        ],
        "About" => Any[
            "Release Notes" => "NEWS.md",
            "License" => "LICENSE.md",
        ]
    ]
)

# Deploy built documentation from Travis.
# =======================================

deploydocs(
    # options
    repo = "github.com/JuliaData/DataFrames.jl.git",
    target = "build",
    deps = nothing,
    make = nothing,
)

Deploy Documenter manual from Julia 0.6 rather than from nightlies

using Documenter, DataFrames

# Build documentation.
# ====================

makedocs(
    # options
    modules = [DataFrames],
    doctest = true,
    clean = false,
    sitename = "DataFrames.jl",
    format = Documenter.Formats.HTML,
    pages = Any[
        "Introduction" => "index.md",
        "User Guide" => Any[
            "Getting Started" => "man/getting_started.md",
            "Joins" => "man/joins.md",
            "Split-apply-combine" => "man/split_apply_combine.md",
            "Reshaping" => "man/reshaping_and_pivoting.md",
            "Sorting" => "man/sorting.md",
            "Categorical Data" => "man/categorical.md",
            "Querying frameworks" => "man/querying_frameworks.md",
        ],
        "API" => Any[
            "Main types" => "lib/maintypes.md",
            "Utilities" => "lib/utilities.md",
            "Data manipulation" => "lib/manipulation.md",
        ],
        "About" => Any[
            "Release Notes" => "NEWS.md",
            "License" => "LICENSE.md",
        ]
    ]
)

# Deploy built documentation from Travis.
# =======================================

deploydocs(
    # options
    repo = "github.com/JuliaData/DataFrames.jl.git",
    target = "build",
    julia = "0.6",
    deps = nothing,
    make = nothing,
)


module kalman;
import StateSpace;
import Distributions;

export newModel,initialGuess,predict,update;

function initialGuess(observationMatrix::Array{Float64,1},varianceMatrix::Array{Float64,1})
   return Distributions.MvNormal(observationMatrix,varianceMatrix)
end

function newModel(processVariance::Float64,observationVariance::Float64)
   M_p::Matrix{Float64} = eye(2);
   M_v::Matrix{Float64} = eye(2)*processVariance;
   O_p::Matrix{Float64} = eye(2);
   O_v::Matrix{Float64} = eye(2)*observationVariance;

   return StateSpace.LinearGaussianSSM(M_p,M_v,O_p,O_v);
end

function update(model,predictedState,observations)
   return StateSpace.update(model,predictedState,observations);
end

function predict(model,state)
   predictedState = StateSpace.predict(model,state)
   return predictedState.
end

end

Add accessor for state mean.

module kalman;
import StateSpace;
import Distributions;

export newModel,initialGuess,predict,update,extractMeanFromState;

function initialGuess(observationMatrix::Array{Float64,1},varianceMatrix::Array{Float64,1})
   return Distributions.MvNormal(observationMatrix,varianceMatrix)
end

function newModel(processVariance::Float64,observationVariance::Float64)
   M_p::Matrix{Float64} = eye(2);
   M_v::Matrix{Float64} = eye(2)*processVariance;
   O_p::Matrix{Float64} = eye(2);
   O_v::Matrix{Float64} = eye(2)*observationVariance;

   return StateSpace.LinearGaussianSSM(M_p,M_v,O_p,O_v);
end

function update(model,predictedState,observations)
   return StateSpace.update(model,predictedState,observations);
end

function predict(model,state)
   return StateSpace.predict(model,state)
   return predictedState.µ;
end

function extractMeanFromState(state)
   return state.µ;
end


function init_s_grid(Ns)
    if any( (Ns .% 2) .== 0 )
        error("Ns must be odd numbers")
    end
    NN = round.(Int, (Ns-1)/2)
    Npoints = prod(Ns)
    s = zeros(3,Npoints)
    ip = 0
    for n = -NN[3]:NN[3]
        for m = -NN[2]:NN[2]
            for l = -NN[1]:NN[1]
                ip = ip + 1
                s[1,ip] = l/(2*NN[1] + 1)
                s[2,ip] = m/(2*NN[2] + 1)
                s[3,ip] = n/(2*NN[3] + 1)
            end
        end
    end
    return s
end

# r = hh * s
function s_to_r(s::Array{Float64,2}, hh)
    Npoints = size(s)[2]
    r = zeros(3,Npoints)
    for ip = 1:Npoints
        for α = 1:3
            r[α,ip] = 0.0
            for β = 1:3
                r[α,ip] = r[α,ip] + hh[α,β]*s[β,ip]
            end
        end
    end
    return r
end

# Function to evaluate LF
function eval_μ_lmn(Ns, hh, s_grid, ip, s)
    #
    NN = round.(Int, (Ns-1)/2)
    metric = 1/sqrt(det(hh))
    #
    s_lmn = s_grid[:,ip]
    #
    f = 0.0 + im*0.0
    # loop structure should be the same as the one used in init_s_grid
    for kz = -NN[3]:NN[3]
        for ky = -NN[2]:NN[2]
            for kx = -NN[1]:NN[1]
                ks = dot( [kx,ky,kz], (s - s_lmn) )
                f = f + cos(2π*ks)
            end
        end
    end
    return metric/sqrt(prod(Ns))*f
end

include("../../PW/common/gen_lattice.jl")

function test_main()
    # Sampling points
    Ns = [21,21,21]

    LL = gen_lattice_hexagonal(10)
    #LL = 10.0*eye(3,3)  # cubic
    hh = LL'

    s_grid = init_s_grid(Ns)

    ip = 2

    #r = [5.0, 5.0, 5.0]
    #s = inv(hh)*r
    s = s_grid[:,1]
    println( eval_μ_lmn(Ns, hh, s_grid, ip, s) )

    s = s_grid[:,2]
    println( eval_μ_lmn(Ns, hh, s_grid, ip, s) )
end

test_main()


export Window,
       include_asset

immutable Window
    alive::Input
    dimension::Input
    route::Input
    dir::String
    assets::Input
end

Window(;
    alive=true,
    dimension=(0px, 0px),
    route="",
    dir="ltr") =
    Window(Input{Bool}(alive), Input{Any}(dimension), Input{Any}(route), "ltr", Input{Any}("basics"))

resolve_asset(slug::String, prefix="/assets", joinfn=(x, y) -> x * "/" * y) = begin
    path = Pkg.dir("Escher", "assets", slug * ".html")
    if isfile(path)
        return joinfn(prefix, "$slug.html")
    else
        error("Asset file $path doesn't exist")
    end
end

resolve_asset(tup :: (@compat Tuple{String, String}), prefix ="/pkg", joinfn=(x, y) -> x * "/" * y) = begin
    pkg = tup[1]
    slug = tup[2]
    path = Pkg.dir(pkg, "assets", slug * ".html")
    if isfile(path)
        return joinfn(prefix, joinfn( pkg, "$slug.html") )
    else
        error("Asset file $path doesn't exist")
    end
end

Add access to work directory

export Window,
       include_asset

immutable Window
    alive::Input
    dimension::Input
    route::Input
    dir::String
    assets::Input
end

Window(;
    alive=true,
    dimension=(0px, 0px),
    route="",
    dir="ltr") =
    Window(Input{Bool}(alive), Input{Any}(dimension), Input{Any}(route), "ltr", Input{Any}("basics"))

resolve_asset(slug::String, prefix="/escher/assets", joinfn=(x, y) -> x * "/" * y) = begin
    path = Pkg.dir("Escher", "assets", slug * ".html")
    if isfile(path)
        return joinfn(prefix, "$slug.html")
    else
        error("Asset file $path doesn't exist")
    end
end

resolve_asset(tup :: (@compat Tuple{String, String}), prefix ="/pkg", joinfn=(x, y) -> x * "/" * y) = begin
    pkg = tup[1]
    slug = tup[2]
    path = Pkg.dir(pkg, "assets", slug * ".html")
    if isfile(path)
        return joinfn(prefix, joinfn( pkg, "$slug.html") )
    else
        error("Asset file $path doesn't exist")
    end
end


using Kalman
using Base.Test

s = UnscentedState([1.0, 0.0],4*eye(2),0.1,2.0,0.0)

@test s.x == [1.0,0.0]
@test s.p == [4.0 0; 0 4.0]
@test_approx_eq s.σ[5] [1.0,-sqrt(0.08)]

@test_approx_eq dot(s.wm,s.σ) s.x
@test_approx_eq dot(s.wc,map(x->(x-s.x)*(x-s.x)',s.σ)) s.p

const dt = 0.01

function f(x)
    x1 = zeros(x)
    x1[1] = x[1] + dt*x[2]
    x1[2] = x[2] - dt*x[1]
    x1
end

fm = AdditiveUnscentedModel(f,1e-10*eye(2))

h(x) = [x[1]]

zm = AdditiveUnscentedObservationModel(h,[0.1]')

kf = AdditiveUnscentedKalmanFilter(s,fm,zm)

Fix typos which stopped tests

using Kalman
using Base.Test

s = UnscentedState([1.0, 0.0],4*eye(2),0.1,2.0,0.0)

@test s.x == [1.0,0.0]
@test s.p == [4.0 0; 0 4.0]
@test_approx_eq s.σ[5] [1.0,-sqrt(0.08)]

@test_approx_eq dot(s.wm,s.σ) s.x
@test_approx_eq dot(s.wc,map(x->(x-s.x)*(x-s.x)',s.σ)) s.p

dt = 0.01

function fu(x)
    x1 = zeros(x)
    x1[1] = x[1] + dt*x[2]
    x1[2] = x[2] - dt*x[1]
    x1
end

fm = AdditiveUnscentedModel(fu,1e-10*eye(2))

hu(x) = [x[1]]

zm = AdditiveUnscentedObservationModel(hu,[0.1]')

kf = AdditiveUnscentedKalmanFilter(s,fm,zm)


using Interact
using LightGraph
using VisJS

# Little slow to update!
@manipulate for i=1:100
    VisJS.drawGraph(WheelGraph(i))
end

Fix typo in wheelgraph example

using Interact
using LightGraphs
using VisJS

# Little slow to update!
@manipulate for i=1:100
    VisJS.drawGraph(WheelGraph(i))
end


@testset "Export All Files Macro Tests" begin

  @test isdefined(Julz, Symbol("@export_all_files")) == true

end

Add test for “export_all_files” macro

initial_dir = pwd()

cd("dummy")

Julz.generate("function", "roo")

module Woof
  using Julz
  Julz.include_all_files("$(pwd())/src/functions")
  Julz.@export_all_files "$(pwd())/src/functions"
end

@testset "Export All Files Macro Tests" begin

  @test isdefined(Julz, Symbol("@export_all_files")) == true

  @test isdefined(Woof, :roo) == true

  Julz.destroy("function", "roo")

  cd(initial_dir)

end


using DataFrames

module Clustering
    using DataFrames

    import Base.print, Base.show, Base.repl_show

    export k_means, dp_means

    include(joinpath(julia_pkgdir(), "Clustering", "src", "types.jl"))
    include(joinpath(julia_pkgdir(), "Clustering", "src", "k_means.jl"))
    include(joinpath(julia_pkgdir(), "Clustering", "src", "dp_means.jl"))
end

Update to new Julia file ops

using DataFrames

module Clustering
    using DataFrames

    import Base.print, Base.show, Base.repl_show

    export k_means, dp_means

    include("types.jl")
    include("k_means.jl")
    include("dp_means.jl")
end


__precompile__()

module MPI

using Compat

if @windows? true : false
	include("win_mpiconstants.jl")
else
	const depfile = joinpath(dirname(@__FILE__), "..", "deps", "src", "compile-time.jl")
	isfile(depfile) || error("MPI not properly installed. Please run Pkg.build(\"MPI\")")
	include(depfile)
end

include("mpi-base.jl")
include("cman.jl")

function __init__()
    if @windows? true : false
    else
        # need to open libmpi with RTLD_GLOBAL flag for Linux, before any ccall
        # cannot use RTLD_DEEPBIND; this leads to segfaults at least on Ubuntu 15.10
        @eval const libmpi_handle =
            Libdl.dlopen(libmpi, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL)

        # look up all symbols ahead of time
        for (jname, fname) in _mpi_functions
            eval(:(const $jname = Libdl.dlsym(libmpi_handle, $fname)))
        end
    end
end

end

Use different language construct for platform specific code

__precompile__()

module MPI

using Compat

@windows_only begin
	const depfile = "win_mpiconstants.jl"
end

@unix_only begin
	const depfile = joinpath(dirname(@__FILE__), "..", "deps", "src", "compile-time.jl")
	isfile(depfile) || error("MPI not properly installed. Please run Pkg.build(\"MPI\")")
end

include(depfile)

include("mpi-base.jl")
include("cman.jl")

function __init__()
    @unix_only begin
        # need to open libmpi with RTLD_GLOBAL flag for Linux, before any ccall
        # cannot use RTLD_DEEPBIND; this leads to segfaults at least on Ubuntu 15.10
        @eval const libmpi_handle =
            Libdl.dlopen(libmpi, Libdl.RTLD_LAZY | Libdl.RTLD_GLOBAL)

        # look up all symbols ahead of time
        for (jname, fname) in _mpi_functions
            eval(:(const $jname = Libdl.dlsym(libmpi_handle, $fname)))
        end
    end
end

end


include("abstract_neural_networks.jl")

function zero!(nn::NeuralNetworkStorage)
    # Zeroes out all of the arrays in the neural network type
    names = names(nn)
    types = nn.types
    for t,n in zip(types, names)
        if isa(t, Weights)
        fill!(nn.(n), 0)
        end
    end
end

Fix sln_mll test so that zero! works

include("abstract_neural_networks.jl")

function zero!(nn::NeuralNetworkStorage)
    # Zeroes out all of the arrays in the neural network type
    fields = names(nn)
    types = typeof(nn).types
    for (t,f) in zip(types, fields)
        if t <: Weights
            fill!(nn.(f), 0)
        end
    end
end


using Compat

function main()
    info("Enabling widgetsnbextension")
    try
        run(`$(IJulia.jupyter) nbextension enable --py widgetsnbextension`)
    catch err
        warn("Could not enable widgetsnbextension")
    end

    if is_linux() || is_apple()
        python = strip(readline(readstring(`which $(IJulia.jupyter)`)|>strip), ['\n',' ', '#','!'])
    elseif is_windows()
        warn("cannot determine jupyter's python path in Windows, bailing.")
        return
    end

    try
        ipywver = readstring(`$python -c 'import ipywidgets; print(ipywidgets.__version__)'`) |> strip |> VersionNumber

        info("ipywidgets version found: $ipywver")
        if ipywver < v"5.0.0"
            warn("""This version of Interact requires ipywidgets > 5.0 to work correctly.
                    If you have ipywidgets version 4.x, run Pkg.checkout("Interact", "ipywidgets-4").""")
        else
            info("A compatible version of ipywidgets was found. All good.")
        end
    catch err
        warn("Could not determine ipywidgets version.")
    end
end

if isa(Pkg.installed("IJulia"), VersionNumber)
    using IJulia
    main()
else
    warn("""IJulia is not installed. run Pkg.build("Interact")
            once you install IJulia to use Interact inside IJulia""")
end

Check for the right version of IJulia

using Compat

function main()
    info("Enabling widgetsnbextension")
    try
        run(`$(IJulia.jupyter) nbextension enable --py widgetsnbextension`)
    catch err
        warn("Could not enable widgetsnbextension")
    end

    if is_linux() || is_apple()
        python = strip(readline(readstring(`which $(IJulia.jupyter)`)|>strip), ['\n',' ', '#','!'])
    elseif is_windows()
        warn("cannot determine jupyter's python path in Windows, bailing.")
        return
    end

    try
        ipywver = readstring(`$python -c 'import ipywidgets; print(ipywidgets.__version__)'`) |> strip |> VersionNumber

        info("ipywidgets version found: $ipywver")
        if ipywver < v"5.0.0"
            warn("""This version of Interact requires ipywidgets > 5.0 to work correctly.
                    If you have ipywidgets version 4.x, run Pkg.checkout("Interact", "ipywidgets-4").""")
        else
            info("A compatible version of ipywidgets was found. All good.")
        end
    catch err
        warn("Could not determine ipywidgets version.")
    end
end

if isa(Pkg.installed("IJulia"), VersionNumber)
    if Pkg.installed("IJulia") < v"1.3.3"
        info("This version of Interact requires IJulia version >= v1.3.3.")
        info("Attempting to update IJulia now.")
        try
            Pkg.update("IJulia")
        catch err
            # ask for help on 0.4
            warn("Failed to update IJulia. Run Pkg.update(\"IJulia\") manually.")
        end
    end
    using IJulia
    main()
else
    warn("""IJulia is not installed. run Pkg.build("Interact")
            once you install IJulia to use Interact inside IJulia""")
end


"""
    Ricker(; <keyword arguments>)

Create a Ricker wavelet.

# Arguments

**Keyword arguments**

* `dt::Real=0.002`: sampling interval in secs.
* `f0::Real=20.0`: central frequency in Hz.

# Example
```julia
julia> w = Ricker(); plot(w);
```

**Reference**

* Sheriff, Robert, 2002, Encyclopedic Dictionary of Applied Geophysics, fourth
ed.: Society of Exploration Geophysicists. Geophysical Reference Series No. 13.
"""

function Ricker(; dt::Real=0.002, f0::Real=20.0)

    nw = 2.0/(f0*dt)
    nc = floor(Int, nw/2)
    t = dt*collect(-nc:1:nc)
    b = (pi*f0*t).^2
    w = (1.-2.*b).*exp(-b)

end

Add an example given keywords values

"""
    Ricker(; <keyword arguments>)

Create a Ricker wavelet.

# Keyword arguments
* `dt::Real=0.002`: sampling interval in secs.
* `f0::Real=20.0`: central frequency in Hz.

# Examples
```julia
julia> w = Ricker(); plot(w)
julia> w = Ricker(dt=0.004, f0=20); plot(w)
```

# Reference
Sheriff, Robert, 2002, Encyclopedic Dictionary of Applied Geophysics, fourth
ed.: Society of Exploration Geophysicists. Geophysical Reference Series No. 13.
"""

function Ricker(; dt::Real=0.002, f0::Real=20.0)

    nw = 2.0/(f0*dt)
    nc = floor(Int, nw/2)
    t = dt*collect(-nc:1:nc)
    b = (pi*f0*t).^2
    w = (1.-2.*b).*exp(-b)

end


# Inspired from https://github.com/JuliaDatabases/MySQL.jl/blob/36eaf2bfbbdd9a27c408d0b2a734fff0d81b63ad/deps/build.jl
module Anon1 end
module Anon2 end

@static if VERSION < v"1.3.0"

using BinaryProvider # requires BinaryProvider 0.3.0 or later

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))

products = [
    LibraryProduct(prefix, ["libcsdp"], :libcsdp)
]

Anon1.include("build_OpenBLAS32.v0.3.9.jl")
Anon2.include("build_CSDP.v6.2.0.jl")

# Finally, write out a deps.jl file
write_deps_file(joinpath(@__DIR__, "deps.jl"), products)

end # VERSION

Add verbose=true to debug Mac OS

# Inspired from https://github.com/JuliaDatabases/MySQL.jl/blob/36eaf2bfbbdd9a27c408d0b2a734fff0d81b63ad/deps/build.jl
module Anon1 end
module Anon2 end

@static if VERSION < v"1.3.0"

using BinaryProvider # requires BinaryProvider 0.3.0 or later

# Parse some basic command-line arguments
const verbose = "--verbose" in ARGS
const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr")))

products = [
    LibraryProduct(prefix, ["libcsdp"], :libcsdp)
]

Anon1.include("build_OpenBLAS32.v0.3.9.jl")
Anon2.include("build_CSDP.v6.2.0.jl")

# Finally, write out a deps.jl file
write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=true)

end # VERSION


function imread(filename::String)
	hnd =  Mat(ccall( (:imread, "../libcv2"), Ptr{Void},(Ptr{Uint8},), bytestring(filename)))
	return hnd
end

function imshow(winName::String, mat::Mat)
	ccall( (:imshow, "../libcv2"), Void, (Ptr{Uint8}, Ptr{Void}), bytestring(winName), mat.handle)
end

function waitKey(delay::Int32)
	ccall( (:waitKey, "../libcv2"), Void, (Int32,), delay)
end

Move the test platform from 32bit to 64bit, set the parameter data type manually for now

function imread(filename::String)
	hnd =  Mat(ccall( (:imread, "../libcv2"), Ptr{Void},(Ptr{Uint8},), bytestring(filename)))
	return hnd
end

function imshow(winName::String, mat::Mat)
	ccall( (:imshow, "../libcv2"), Void, (Ptr{Uint8}, Ptr{Void}), bytestring(winName), mat.handle)
end

function waitKey(delay::Int)
	ccall( (:waitKey, "../libcv2"), Void, (Int32,), delay)
end


VERSION >= v"0.4.0" && __precompile__(true)

module SLAM

export
    # Types
    Scene,
    SlamState,
    EKFSlamState,
    PFSlamState,
    Vehicle,

    # Functions
    initial_pose,
    mpi_to_pi,
    frame_transform,
    step_vehicle!,
    steer!,
    predict,
    update,
    add_features,
    associate,
    compute_association,
    predict_observation

include("common.jl")
include("vehicle.jl")
include("ekf.jl")
include("data-association.jl")

end # SLAM

Generalize messages containing 2D points

__precompile__(true)

module SLAM

export
    # Types
    Scene,
    SlamState,
    EKFSlamState,
    PFSlamState,
    Vehicle,

    # Functions
    get_waypoints,
    initial_pose,
    mpi_to_pi,
    frame_transform,
    step_vehicle!,
    steer!,
    predict,
    update,
    add_features,
    associate,
    compute_association,
    predict_observation

include("common.jl")
include("vehicle.jl")
include("ekf.jl")
include("data-association.jl")

end # SLAM


module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop(loop=nothing)
    this                       = new()
    this.ioloop                = loop # or ioloop.IOLoop()
    this.ioloop.make_current()
    this.periodic_callback     = nothing

    this.instance                  = function() instance(this) end
    this.start                     = function() start(this) end
    this.stop                      = function() stop(this) end
    this.attach_periodic_callback  = function() attach_periodic_callback(this) end
    this.dettach_periodic_callback = function() dettach_periodic_callback(this) end

    this
  end

  function instance(self::Loop)
    # return Loop(ioloop.IOLoop.current())
  end

  function start(self::Loop)
  end

  function stop(self::Loop)
  end

  function attach_periodic_callback(self::Loop, callback::Callback, callback_time::Int)
  end

  function dettach_periodic_callback(self::Loop)
  end

end

end # module loop

Implement Loop.start, Loop.stop and some features

module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop(loop=nothing)
    this                        = new()
    this.ioloop                 = loop # or ioloop.IOLoop()
    this.ioloop.make_current()
    this.periodic_callback      = nothing
    this.periodic_callback_time = 1

    this.instance                  = function() instance(this) end
    this.start                     = function() start(this) end
    this.stop                      = function() stop(this) end
    this.attach_periodic_callback  = function() attach_periodic_callback(this, this.periodic_callback, this.periodic_callback_time) end
    this.dettach_periodic_callback = function() dettach_periodic_callback(this) end

    this
  end

  function instance(self::Loop)
    # return Loop(ioloop.IOLoop.current())
  end

  function start(self::Loop)
    self.ioloop.start()
  end

  function stop(self::Loop)
    self.ioloop.stop()
  end

  function attach_periodic_callback(self::Loop, callback::Callback, callback_time::Int)
  end

  function dettach_periodic_callback(self::Loop)
  end

end

end # module loop


#!/usr/bin/env julia

import JSON

"""
    gen( x, name )

Generate fixture data and write to file.

# Arguments

* `x`: x-values
* `y`: y-values
* `name::AbstractString`: output filename

# Examples

``` julia
julia> x = rand( 2003 ) * 1000.0;
julia> y = rand( 2003 ) * 1000.0;
julia> gen( x, y, \"data.json\" );
```
"""
function gen( x, y, name )
	h = hypot( x, y );

	# Store data to be written to file as a collection:
	data = Dict([
		("x", x),
		("y", y),
		("expected", h)
	]);

	# Based on the script directory, create an output filepath:
	filepath = joinpath( dir, name );

	# Write the data to the output filepath as JSON:
	outfile = open( filepath, "w" );
	write( outfile, JSON.json(data) );
	close( outfile );
end

# Get the filename:
file = @__FILE__;

# Extract the directory in which this file resides:
dir = dirname( file );

# Generate fixture data:
x = rand( 2003 ) * 2000.0 - 1000.0;
y = rand( 2003 ) * 2000.0 - 1000.0;
gen( x, y, "data.json" );

Fix fcn signature in docs

#!/usr/bin/env julia

import JSON

"""
    gen( x, y, name )

Generate fixture data and write to file.

# Arguments

* `x`: x-values
* `y`: y-values
* `name::AbstractString`: output filename

# Examples

``` julia
julia> x = rand( 2003 ) * 1000.0;
julia> y = rand( 2003 ) * 1000.0;
julia> gen( x, y, \"data.json\" );
```
"""
function gen( x, y, name )
	h = hypot( x, y );

	# Store data to be written to file as a collection:
	data = Dict([
		("x", x),
		("y", y),
		("expected", h)
	]);

	# Based on the script directory, create an output filepath:
	filepath = joinpath( dir, name );

	# Write the data to the output filepath as JSON:
	outfile = open( filepath, "w" );
	write( outfile, JSON.json(data) );
	close( outfile );
end

# Get the filename:
file = @__FILE__;

# Extract the directory in which this file resides:
dir = dirname( file );

# Generate fixture data:
x = rand( 2003 ) * 2000.0 - 1000.0;
y = rand( 2003 ) * 2000.0 - 1000.0;
gen( x, y, "data.json" );


@testset "AWSConfig" begin
    @testset "default profile assumes role" begin
        access_key_id = "assumed_access_key_id"
        config_dir = joinpath(@__DIR__, "configs", "default-role")

        # Avoid calling out to STS with invalid credentials
        patch = Patches._assume_role_patch("AssumeRole"; access_key=access_key_id)

        config = withenv(
            "AWS_CONFIG_FILE" => joinpath(config_dir, "config"),
            "AWS_SHARED_CREDENTIALS_FILE" => joinpath(config_dir, "credentials"),
            "AWS_ACCESS_KEY_ID" => nothing,
            "AWS_SECRET_ACCESS_KEY" => nothing,
        ) do
            apply(patch) do
                AWSConfig(; profile="default")
            end
        end

        @test config.credentials.access_key_id == access_key_id
    end

    @testset "default profile section names" begin
        allowed_default_sections = ["default", "profile default"]
        mktemp() do config_path, _
            for default_section_str in allowed_default_sections
                write(config_path, """
                      [$default_section_str]
                      region = xx-yy-1
                      """)
                @test aws_get_region(profile="default", config=config_path) == "xx-yy-1"
            end
        end
    end
end

Add temporary to avoid terrible auto-formatting

@testset "AWSConfig" begin
    @testset "default profile assumes role" begin
        access_key_id = "assumed_access_key_id"
        config_dir = joinpath(@__DIR__, "configs", "default-role")

        # Avoid calling out to STS with invalid credentials
        patch = Patches._assume_role_patch("AssumeRole"; access_key=access_key_id)

        config = withenv(
            "AWS_CONFIG_FILE" => joinpath(config_dir, "config"),
            "AWS_SHARED_CREDENTIALS_FILE" => joinpath(config_dir, "credentials"),
            "AWS_ACCESS_KEY_ID" => nothing,
            "AWS_SECRET_ACCESS_KEY" => nothing,
        ) do
            apply(patch) do
                AWSConfig(; profile="default")
            end
        end

        @test config.credentials.access_key_id == access_key_id
    end

    @testset "default profile section names" begin
        allowed_default_sections = ["default", "profile default"]
        mktemp() do config_path, _
            for default_section_str in allowed_default_sections
                config = """
                [$default_section_str]
                region = xx-yy-1
                """
                write(config_path, config)
                @test aws_get_region(; profile="default", config=config_path) == "xx-yy-1"
            end
        end
    end
end


println("IntelPSE: build.jl begin.")
println("IntelPSE: Building j2c-array shared library")
run(`icpc -fPIC -shared -o libj2carray.so.1.0 j2c-array.cpp`)
println("IntelPSE: build.jl done.")

Update to new package name.

println("ParallelAccelerator: build.jl begin.")
println("ParallelAccelerator: Building j2c-array shared library")
run(`icpc -fPIC -shared -o libj2carray.so.1.0 j2c-array.cpp`)
println("ParallelAccelerator: build.jl done.")


require("src/svmlight.jl")
require("src/liblinear.jl")

import StatsBase: fit, predict
import MLBase: roc, recall, precision, f1score
import liblinear: ClassificationParams, ClassificationModel, RegressionModel

function read(file)
  open(ARGS[1], "r") do f
    x, y = read_svmlight(f)
    return x, convert(Array{Int}, y)
  end
end

file_prefix = ARGS[1]
train_file = "$file_prefix.train"
test_file = "$file_prefix.test"
t0 = time()
x_train, y_train = read(train_file)
x_test, y_test = read(test_file)
t1 = time()

params = ClassificationParams((-1, 1); eps=0.01)
model = fit(ClassificationModel{Int}, x_train, y_train, params)
t_train = time()

y1 = predict(model, x_test)
t_test = time()

rc = roc(y_test, y1)
@printf "julia: precision=%.5f recall=%.5f f1=%.5f\n" precision(rc) recall(rc) f1score(rc)
@printf "julia: read=%.3f train=%.3f test=%.3f" t1-t0 t_train-t1 t_test-t_train

Add warm up step in julia benchmark.

require("src/svmlight.jl")
require("src/liblinear.jl")

import StatsBase: fit, predict
import MLBase: roc, recall, precision, f1score
import liblinear: ClassificationParams, ClassificationModel, RegressionModel

function read(file)
  open(ARGS[1], "r") do f
    x, y = read_svmlight(f)
    return x, convert(Array{Int}, y)
  end
end

function run(file_prefix, silent=false)
  train_file = "$file_prefix.train"
  test_file = "$file_prefix.test"

  t0 = time()
  x_train, y_train = read(train_file)
  x_test, y_test = read(test_file)
  t1 = time()

  params = ClassificationParams((-1, 1); eps=0.01)
  model = fit(ClassificationModel{Int}, x_train, y_train, params)
  t_train = time()

  y1 = predict(model, x_test)
  t_test = time()

  if !silent
    rc = roc(y_test, y1)
    @printf "julia: precision=%.5f recall=%.5f f1=%.5f\n" precision(rc) recall(rc) f1score(rc)
    @printf "julia: read=%.5f train=%.5f test=%.5f\n" t1-t0 t_train-t1 t_test-t_train
  end
end

file_prefix = ARGS[1]

# warm up
run(file_prefix, true)

# measure
run(file_prefix, false)


module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop()
    this = new()
    this
  end

  function instance()
  end

  function start()
  end

  function stop()
  end

  function attach_periodic_callback()
  end

  function dettach_periodic_callback()
  end

end

end # module loop

Add skeleton code for Loop

module loop

export Loop

type Loop

  instance::Function
  start::Function
  stop::Function
  attach_periodic_callback::Function
  dettach_periodic_callback::Function

  function Loop(loop=nothing)
    this                       = new()
    this.ioloop                = loop # or ioloop.IOLoop()
    this.ioloop.make_current()
    this.periodic_callback     = nothing

    this.instance                  = function() instance(this) end
    this.start                     = function() start(this) end
    this.stop                      = function() stop(this) end
    this.attach_periodic_callback  = function() attach_periodic_callback(this) end
    this.dettach_periodic_callback = function() dettach_periodic_callback(this) end

    this
  end

  function instance(self::Loop)
    # return Loop(ioloop.IOLoop.current())
  end

  function start(self::Loop)
  end

  function stop(self::Loop)
  end

  function attach_periodic_callback(self::Loop, callback::Callback, callback_time::Int)
  end

  function dettach_periodic_callback(self::Loop)
  end

end

end # module loop


include("occa.fl")

entries = 5

device = occa.device("OpenMP", 0, 0);

# Dynamic range?
a  = [convert(Float32, 1 - i) for i in 1:5]
b  = [convert(Float32, i    ) for i in 1:5]
ab = [convert(Float32, 0    ) for i in 1:5]

o_a  = occa.malloc(device, a);
o_b  = occa.malloc(device, b);
o_ab = occa.malloc(device, ab);

k = occa.buildKernelFromSource(device,
                               "addVectors.occa",
                               "addVectors")

dims = 1;
itemsPerGroup = 2;
groups = (entries + itemsPerGroup - 1)/itemsPerGroup;

occa.setWorkingDims(k,
                    dims, itemsPerGroup, groups);

occa.runKernel(k,
               (entries, Int32),
               o_a, o_b, o_ab)

occa.memcpy(ab, o_ab)

println(ab)

Change k->addVectors in Julia example

include("occa.jl")

entries = 5

device = occa.device("OpenMP", 0, 0);

# Dynamic range?
a  = [convert(Float32, 1 - i) for i in 1:5]
b  = [convert(Float32, i    ) for i in 1:5]
ab = [convert(Float32, 0    ) for i in 1:5]

o_a  = occa.malloc(device, a);
o_b  = occa.malloc(device, b);
o_ab = occa.malloc(device, ab);

addVectors = occa.buildKernelFromSource(device,
                               "addVectors.occa",
                               "addVectors")

dims = 1;
itemsPerGroup = 2;
groups = (entries + itemsPerGroup - 1)/itemsPerGroup;

occa.setWorkingDims(addVectors,
                    dims, itemsPerGroup, groups);

occa.runKernel(addVectors,
               (entries, Int32),
               o_a, o_b, o_ab)

occa.memcpy(ab, o_ab)

println(ab)


#CppSimData: A Julia wrapper for CppSimData tools
#-------------------------------------------------------------------------------
module CppSimData

const rootpath = realpath(joinpath(dirname(realpath(@__FILE__)),"../."))
const libroot = joinpath(rootpath, "core/lib")

#TODO: is Sys.ARCH a supported feature??
const objfile = joinpath(libroot,
@windows? ("win32/cppsimdata_lib.dll"
):@osx? ("macosx/cppsimdata_lib.so"
): joinpath(:x86_64 == Sys.ARCH?"glnxa64":"glnx86", "cppsimdata_lib.so")
)
#else: error("OS not supported: ", Sys.OS_NAME))??

@show objfile

include("base.jl")
include("show.jl")

initialize() #Initialize CppSimData module

export loadsig, lssig, evalsig

end #CppSimData
#Last line

Use joinpath() more rigorously & remove @show.

#CppSimData: A Julia wrapper for CppSimData tools
#-------------------------------------------------------------------------------
module CppSimData

const rootpath = realpath(joinpath(dirname(realpath(@__FILE__)),"../."))
const libroot = joinpath(rootpath, "core/lib")

#TODO: is Sys.ARCH a supported feature??
const objfile = joinpath(libroot,
@windows? (joinpath("win32", "cppsimdata_lib.dll")
):@osx? (joinpath("macosx", "cppsimdata_lib.so")
): joinpath(:x86_64 == Sys.ARCH?"glnxa64":"glnx86", "cppsimdata_lib.so")
)
#else: error("OS not supported: ", Sys.OS_NAME))??

include("base.jl")
include("show.jl")

initialize() #Initialize CppSimData module

export loadsig, lssig, evalsig

end #CppSimData
#Last line


using ParallelAccelerator

#using CompilerTools
#CompilerTools.ReadWriteSet.set_debug_level(3)
#ParallelAccelerator.CGen.set_debug_level(3)

@acc function normalizeW(W::DenseMatrix{Float64}, k::Int)
# normalize each column
#=
    for j = 1:k
        w = view(W,:,j)
        scale!(w, 1.0 / sqrt(sumabs2(w)))
	#s = sqrt(sumabs2(W[:,j]))
	#W[:,j] /= s
    end
=#
    s = [sqrt(sumabs2(W[:,j])) for j in 1:k]
    scale!(W,s)
end

function main(m::Int, k::Int, n::Int)
    W  = Array(Float64, m, k)
    fill!(W, 3)
    normalizeW(W, k)
    println("done")

end

main(100, 100, 200)
println("Done testing test_norm_w.")

Use W = scale(W,s) rather than scale\!(W,s)

using ParallelAccelerator

#using CompilerTools
#CompilerTools.ReadWriteSet.set_debug_level(3)
#ParallelAccelerator.CGen.set_debug_level(3)

@acc function normalizeW(W::DenseMatrix{Float64}, k::Int)
# normalize each column
#=
    for j = 1:k
        w = view(W,:,j)
        scale!(w, 1.0 / sqrt(sumabs2(w)))
	#s = sqrt(sumabs2(W[:,j]))
	#W[:,j] /= s
    end
=#
    s = [sqrt(sumabs2(W[:,j])) for j in 1:k]
    W = scale(W,s)
end

function main(m::Int, k::Int, n::Int)
    W  = Array(Float64, m, k)
    fill!(W, 3)
    normalizeW(W, k)
    println("done")

end

main(100, 100, 200)
println("Done testing test_norm_w.")


### TODO: remove. Until Docile is tagged we need master here. ###
Pkg.checkout("Docile")

module LexiconTests

using Docile
@document

using Docile.Interface, Lexicon, FactCheck

import Lexicon: Query

include("testcases.jl")

include("facts/query-parsing.jl")
include("facts/querying-results.jl")
include("facts/rendering.jl")

end

Remove cloning of Docile master.


require("Options")
require("Distributions")
require("Calculus")

module Optim
    using OptionsMod
    using Distributions
    using Calculus

    function loadoptim(filename)
        include(file_path(julia_pkgdir(), "Optim", "src", filename))
    end

    function centroid(p::Matrix)
         reshape(mean(p, 2), size(p, 1))
    end

    import Base.assign,
           Base.dot,
           Base.length,
           Base.push,
           Base.ref,
           Base.repl_show,
           Base.show

    export curve_fit,
           estimate_errors,
           optimize

    # Types
    loadoptim("types.jl")

    # RNG Sources
    loadoptim("rng.jl")

    # Grid Search
    loadoptim("grid_search.jl")

    # Line Search Methods
    loadoptim("backtracking_line_search.jl")

    # Gradient Descent Methods
    loadoptim("naive_gradient_descent.jl")
    loadoptim("gradient_descent.jl")

    # Conjugate gradient
    loadoptim("cgdescent.jl")

    # Newton and Quasi-Newton Methods
    loadoptim("newton.jl")
    loadoptim("bfgs.jl")
    loadoptim("l_bfgs.jl")

    # Constrained optimization
    loadoptim("fminbox.jl")

    # trust region methods
    loadoptim("levenberg_marquardt.jl")

    # Heuristic Optimization Methods
    loadoptim("nelder_mead.jl")
    loadoptim("simulated_annealing.jl")

    # End-User Facing Wrapper Functions
    loadoptim("optimize.jl")
    loadoptim("curve_fit.jl")
end

Update to latest Julia file operations

require("Options")
require("Distributions")
require("Calculus")

module Optim
    using OptionsMod
    using Distributions
    using Calculus

    function loadoptim(filename)
        include(joinpath(julia_pkgdir(), "Optim", "src", filename))
    end

    function centroid(p::Matrix)
         reshape(mean(p, 2), size(p, 1))
    end

    import Base.assign,
           Base.dot,
           Base.length,
           Base.push,
           Base.ref,
           Base.repl_show,
           Base.show

    export curve_fit,
           estimate_errors,
           optimize

    # Types
    loadoptim("types.jl")

    # RNG Sources
    loadoptim("rng.jl")

    # Grid Search
    loadoptim("grid_search.jl")

    # Line Search Methods
    loadoptim("backtracking_line_search.jl")

    # Gradient Descent Methods
    loadoptim("naive_gradient_descent.jl")
    loadoptim("gradient_descent.jl")

    # Conjugate gradient
    loadoptim("cgdescent.jl")

    # Newton and Quasi-Newton Methods
    loadoptim("newton.jl")
    loadoptim("bfgs.jl")
    loadoptim("l_bfgs.jl")

    # Constrained optimization
    loadoptim("fminbox.jl")

    # trust region methods
    loadoptim("levenberg_marquardt.jl")

    # Heuristic Optimization Methods
    loadoptim("nelder_mead.jl")
    loadoptim("simulated_annealing.jl")

    # End-User Facing Wrapper Functions
    loadoptim("optimize.jl")
    loadoptim("curve_fit.jl")
end


using Documenter, Hecke

makedocs(
    modules = Hecke,
    clean   = true,
    doctest = false,
)

#deploydocs(
#    deps = Deps.pip("pygments", "mkdocs", "mkdocs-material", "python-markdown-math"),
#    repo = "github.com/thofma/Hecke.jl.git",
#    julia = "0.4",
#)

Enable docs deployment via travis

using Documenter, Hecke

makedocs(
    modules = Hecke,
    clean   = true,
    doctest = false,
)

deploydocs(
    deps = Deps.pip("pygments", "mkdocs", "mkdocs-material", "python-markdown-math"),
    repo = "github.com/thofma/Hecke.jl.git",
    julia = "0.4",
)


# auto reload edited files
@schedule begin
    sleep(0.1)
    @eval using Revise
end

# fix GR.jl: "Launching GKSTerm failed."
@schedule begin
    sleep(0.1)
    @eval gkstermpath = joinpath(Pkg.dir("GR"), "deps/gr/Applications/GKSTerm.app")
    @eval run(`open $gkstermpath`)
end

Remove GR gks workaround, works OOTB now

# auto reload edited files
#= @schedule begin =#
#=     sleep(0.1) =#
#=     @eval using Revise =#
#= end =#


export fitness, hamming_max, hamming_raw

# Evaluates the fitness of a particular chromosome relative to a
# particular goal. The sum of the Hamming distances for each output
# relative to the goal for that output is passed through the `h2f`
# function to convert it into a useful fitness value.
function fitness(c::Chromosome, g::Goal, h2f::Function)
    outputs = execute_chromosome(c)
    dist = 0
    for i = 1:g.num_outputs
        dist += count_ones(outputs[i] $ g.truth_table[i])
    end
    return h2f(dist)
end

fitness(c::Chromosome, g::Goal) = fitness(c, g, hamming_max)

hamming_max(dist) = 1.0 / (1.0 + dist)
hamming_raw(dist) = dist

Use type parameter for goal.

export fitness, hamming_max, hamming_raw

# Evaluates the fitness of a particular chromosome relative to a
# particular goal. The sum of the Hamming distances for each output
# relative to the goal for that output is passed through the `h2f`
# function to convert it into a useful fitness value.
function fitness{N}(c::Chromosome, g::Goal{N}, h2f::Function)
    outputs = execute_chromosome(c)
    dist = 0
    for i = 1:N
        dist += count_ones(outputs[i] $ g.truth_table[i])
    end
    return h2f(dist)
end

fitness(c::Chromosome, g::Goal) = fitness(c, g, hamming_max)

hamming_max(dist) = 1.0 / (1.0 + dist)
hamming_raw(dist) = dist


function startswith(str::AbstractString, pats...)
    for pat in pats
        if start(search(str, pat)) != 1
            return false
        end
    end
    true
end

function constantly(value)
    function(_...)
        value
    end
end

Fix startswith function, which was horribly borken.

function startswith(str::AbstractString, pats...)
    for pat in pats
        if start(search(str, pat)) == 1
            return true
        end
    end
    false
end

function constantly(value)
    function(_...)
        value
    end
end


const JSON_MAX_INT = 2^53 -1
const JSON_MIN_INT = -JSON_MAX_INT

const MAX_INT64 = 2^63-1
const MIN_INT64 = -(2^63)

const MAP_AS_ARR = "^ "
const ESC = "~"
const SUB = "^"
const RES = "`"
const TAG = "~#"
const QUOTE = "'"

const ESC_ESC = string(ESC, ESC)
const ESC_SUB = string(ESC, SUB)
const ESC_RES = string(ESC, RES)

Make constant name a little clearer.

const JSON_MAX_INT = 2^53 -1
const JSON_MIN_INT = -JSON_MAX_INT

const MAX_INT64 = 2^63-1
const MIN_INT64 = -(2^63)

const MAP_AS_ARRAY = "^ "
const ESC = "~"
const SUB = "^"
const RES = "`"
const TAG = "~#"
const QUOTE = "'"

const ESC_ESC = string(ESC, ESC)
const ESC_SUB = string(ESC, SUB)
const ESC_RES = string(ESC, RES)


Implement HMC sampler using Radford Neal's R code.

# Adapted directly from Radford Neal's R code

# Alternative interface using Density type
hmc_sampler(x::Array{Float64}, dd::DifferentiableDensity, epsilon::Float64, L::Int64) = hmc_sampler(x, dd.f, dd.gradient, epsilon, L)
# Some default values for epsilon and L
hmc_sampler(x::Array{Float64}, dd::DifferentiableDensity, gx::Float64) = hmc_sampler(x,dd,.01,20)

function hmc_sampler(x::Array{Float64}, dd::DifferentiableDensity, params::Array)
  L = convert(Int64, params[2])
  hmc_sampler(x,dd,params[1],L)  # TODO Use a different data structure for params
end

function hmc_sampler(current_q::Array{Float64}, U::Function, grad_U::Function, epsilon::Float64, L::Int64)

  q = current_q
  p = randn(length(q))'  # independent standard normal variates (row vector)
  current_p = p

  # Make a half step for momentum at the beginning
  p = p - epsilon * grad_U(q) / 2

  # Alternate full steps for position and momentum
  for i in 1:L
    # Make a full step for the position
    q = q + epsilon * p
    # Make a full step for the momentum, except at end of trajectory
    if i!=L
        p = p - epsilon * grad_U(q)
    end
  end

  # Make a half step for momentum at the end.
  p = p - epsilon * grad_U(q) / 2

  # Negate momentum at end of trajectory to make the proposal symmetric
  p = -p

  # Evaluate potential and kinetic energies at start and end of trajectory
  current_U = U(current_q)
  current_K = sum(current_p.^2) / 2
  proposed_U = U(q)
  proposed_K = sum(p.^2) / 2

  # Accept or reject the state at end of trajectory, returning either
  # the position at the end of the trajectory or the initial position
  if rand() < exp(current_U-proposed_U+current_K-proposed_K)
    return q, proposed_U  # accept
  else
    return current_q, current_U  # reject
  end
end


type Agent
	alive::Bool

	function Agent()
		return new(Bool(true))
	end
end

function isAlive{T <: Agent}(a::T)
	return a.alive;
end

function setAlive{T <: Agent}(a::T, bv::Bool)
	a.alive = bv;
	nothing;
end

Define abstract Action types and the Percept type. Added TableDrivenAgentProgram implementation of the abstract AgentProgram DataType.

type Percept
	attr::Dict{Any, Any}

	function Percept()
		return new(Dict{Any, Any}());
	end
end

abstract Action;		#declare Action as a supertype

type AAction <: Action
	isNoOp::Bool
	name::String

	function AAction(n::String)
		return new(Bool(false), n);
	end
end

type NoOpAction <: Action
	isNoOp::Bool
	name::String

	function NoOpAction()
		return new(Bool(true), "NoOp");
	end
end

abstract AgentProgram;

#=

	Define a global execute() function to be implemented for each respective
	AgentProgram DataType implementation.

=#

execute{T <: AgentProgram}(ap::T, p::Percept) = function() end		#implement functionality later

type TableDrivenAgentProgram <: AgentProgram
	isTracing::Bool
	percepts::Array{Percept, 1}
	table::Dict{Any, Any}

	function TableDrivenAgentProgram(;t=C_NULL, trace=false)
		if (t == C_NULL)			#no table given, create empty dictionary
			return new(Bool(trace), Array{Percept, 1}(), Dict{Any, Any}());
		else
			return new(Bool(trace), Array{Percept, 1}(), t);
		end
	end
end

function execute(ap::TableDrivenAgentProgram, p::Percept)
	ap.percepts.push(p);
	action = ap.table[Tuple((ap.percepts...))]	#convert percept sequence to tuple
	if (ap.isTracing)
		@printf("%s perceives %s and does %s", string(typeof(ap)), string(p), action.name);
	end
	return action;
end

#=

	Agents can interact with the environment through percepts and actions.

=#

type Agent
	alive::Bool
	program::AgentProgram

	function Agent()
		return new(Bool(true))
	end
end

function isAlive{T <: Agent}(a::T)
	return a.alive;
end

function setAlive{T <: Agent}(a::T, bv::Bool)
	a.alive = bv;
	nothing;
end


abstract XMLError

immutable XMLParseError <: XMLError
    msg::String
end

immutable XMLNoRootError <: XMLError
end

immutable XMLAttributeNotFound <: XMLError
end

immutable XMLWriteError <: XMLError
    msg::String
end

immutable XMLTreeError <: XMLError
    msg::String
end

const dom_exception_causes = [
    "Index size error",        #  1
    "DOM string size error",   #  2
    "Hierarchy request error", #  3
    "Wrong document",          #  4
    "Invalid character",       #  5
    "No data allowed",         #  6
    "No modification allowed", #  7
    "Not found",               #  8
    "Not supported",           #  9
    "Inused attribute"         # 10
]

immutable DOMException <: XMLError
    code::Int
    cause::String

    DOMException(code::Int) = new(code, dom_exception_causes[code])
end

Make XMLError a subtype of Exception

abstract XMLError <: Exception

immutable XMLParseError <: XMLError
    msg::String
end

immutable XMLNoRootError <: XMLError
end

immutable XMLAttributeNotFound <: XMLError
end

immutable XMLWriteError <: XMLError
    msg::String
end

immutable XMLTreeError <: XMLError
    msg::String
end

const dom_exception_causes = [
    "Index size error",        #  1
    "DOM string size error",   #  2
    "Hierarchy request error", #  3
    "Wrong document",          #  4
    "Invalid character",       #  5
    "No data allowed",         #  6
    "No modification allowed", #  7
    "Not found",               #  8
    "Not supported",           #  9
    "Inused attribute"         # 10
]

immutable DOMException <: XMLError
    code::Int
    cause::String

    DOMException(code::Int) = new(code, dom_exception_causes[code])
end


using Documenter, Optim

# use include("Rosenbrock.jl") etc

# assuming linux.
#run('mv ../LICENSE.md ./LICENSE.md')
#run('mv ../CONTRIBUTING.md ./dev/CONTRIBUTING.md')
makedocs(
    doctest = false
)

deploydocs(
    repo = "github.com/JuliaOpt/Optim.jl.git"
)

Fix Documenter by changing from nightly to v0.5.

using Documenter, Optim

# use include("Rosenbrock.jl") etc

# assuming linux.
#run('mv ../LICENSE.md ./LICENSE.md')
#run('mv ../CONTRIBUTING.md ./dev/CONTRIBUTING.md')
makedocs(
    doctest = false
)

deploydocs(
    repo = "github.com/JuliaOpt/Optim.jl.git",
    julia = "0.5"
)


function read_data(x::String, mode::String)

    num_features = num_labels = 0

    if x == "scene"
        num_features = 294
        num_labels = 6
    end

    if x == "yeast"
        num_features = 103
        num_labels = 14
    end

    if x == "emotions"
        num_features = 72
        num_labels = 6

    end

    if mode == "train"
        suffix = "-train.csv"
    else
        suffix = "-test.csv"
    end

    path = string("data/", x, "/", x, suffix)
    file = readdlm(path, ',')

    n = size(file, 1)
    features = file[1:n, 1:num_features]
    labels = fil[1:n, (num_features + 1):(num_features+num_labels))

    return (features, labels)

end

Read data from a file

function read_data(x::String, mode::String)
    num_features = num_labels = 0

    if x == "scene"
        num_features = 294
        num_labels = 6
    elseif x == "yeast"
        num_features = 103
        num_labels = 14
    elseif x == "emotions"
        num_features = 72
        num_labels = 6
    else
        error("Unknown dataset")
    end

    if mode == "train"
        suffix = "train"
    else
        suffix = "test"
    end

    path = joinpath("data", x, string(x, "-", suffix, ".csv"))
    file = readdlm(path, ',')

    n = size(file, 1)
    features = file[1:n, 1:num_features]
    labels = file[1:n, (num_features + 1):(num_features + num_labels)]

    return (features, labels)
end


using ForwardDiff

abstract ExtendedKalmanFilter <: KalmanFilter

type NonlinearModel <: Model
    f::Function
    j::Function
    g::Function
    q::Matrix
    function NonlinearModel(f::Function,g::Function,q::Matrix)
        j = forwarddiff_jacobian(f,Float64,fadtype=:typed)
        new(f,j,g,q)
    end
end

type NonlinearObservationModel <: ObservationModel
    h::Function
    j::Function
    r::Matrix
    function NonlinearObservationModel(h::Function,r::Matrix)
        j = forwarddiff_jacobian(h,Float64,fadtype=:typed)
        new(h,j,r)
    end
end

type BasicExtendedKalmanFilter <: ExtendedKalmanFilter
    x::State
    f::NonlinearModel
    z::NonlinearObservationModel
end

function ap(f::NonlinearModel,x::State)
    x1 = f.f(x.x)
    F = f.j(x.x)
    G = f.g(x.x)
    p1 = F*x.p*F' + G*f.q*G'
    State(x1,p1)
end

function covs(kf::BasicExtendedKalmanFilter,y::Observation)
    res = y.y - kf.z.h(kf.x.x)
    H = kf.z.j(kf.x.x)'
    ph = kf.x.p * H'
    s = H * kf.x.p * H' + kf.z.r
    (res,ph,s)
end

Move ap up to make it consistent with types.jl

using ForwardDiff

abstract ExtendedKalmanFilter <: KalmanFilter

type NonlinearModel <: Model
    f::Function
    j::Function
    g::Function
    q::Matrix
    function NonlinearModel(f::Function,g::Function,q::Matrix)
        j = forwarddiff_jacobian(f,Float64,fadtype=:typed)
        new(f,j,g,q)
    end
end

function ap(f::NonlinearModel,x::State)
    x1 = f.f(x.x)
    F = f.j(x.x)
    G = f.g(x.x)
    p1 = F*x.p*F' + G*f.q*G'
    State(x1,p1)
end

type NonlinearObservationModel <: ObservationModel
    h::Function
    j::Function
    r::Matrix
    function NonlinearObservationModel(h::Function,r::Matrix)
        j = forwarddiff_jacobian(h,Float64,fadtype=:typed)
        new(h,j,r)
    end
end

type BasicExtendedKalmanFilter <: ExtendedKalmanFilter
    x::State
    f::NonlinearModel
    z::NonlinearObservationModel
end

function covs(kf::BasicExtendedKalmanFilter,y::Observation)
    res = y.y - kf.z.h(kf.x.x)
    H = kf.z.j(kf.x.x)'
    ph = kf.x.p * H'
    s = H * kf.x.p * H' + kf.z.r
    (res,ph,s)
end


# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/blob/master/LICENSE.md

function assemble!(problem::Problem, time, ::Type{Val{:mass_matrix}})
    assemble_mass_matrix!(problem, time)
end

Add module Abaqus back to code

# This file is a part of JuliaFEM.
# License is MIT: see https://github.com/JuliaFEM/JuliaFEM.jl/blob/master/LICENSE.md

function assemble!(problem::Problem, time, ::Type{Val{:mass_matrix}})
    assemble_mass_matrix!(problem, time)
end

module Abaqus
using JuliaFEM.Preprocess: create_surface_elements
end


#Test basic rospy interactions
init_node("jltest", anonymous=true)

#Parameters
@test length(RobotOS.get_param_names()) > 0
@test has_param("rosdistro")
@test chomp(get_param("rosdistro")) in ["hydro", "indigo", "jade", "kinetic"]
@test ! has_param("some_param")
@test_throws KeyError get_param("some_param")
@test_throws KeyError delete_param("some_param")
@test get_param("some_param", 1.1) == 1.1
@test get_param("some_param", "some_val") == "some_val"
set_param("some_param", "val")
@test get_param("some_param", 1.1) == "val"
delete_param("some_param")
@test ! has_param("some_param")

#Really just running this stuff for coverage

#Logging
logdebug("testing: %s", "debug")
loginfo("testing: %s", "info")
logwarn("testing: %s", "warn")
logerr("testing: %s", "err")
logfatal("testing: %s", "fatal")
@test ! is_shutdown()

#Generic stuff
@test startswith(RobotOS.get_name()[2:end], "jltest")
@test RobotOS.get_namespace() == "/"
RobotOS.get_node_uri()
RobotOS.get_caller_id()
RobotOS.get_published_topics()
RobotOS.get_ros_root()

Add "lunar" to list of possible rosdistros

#Test basic rospy interactions
init_node("jltest", anonymous=true)

#Parameters
@test length(RobotOS.get_param_names()) > 0
@test has_param("rosdistro")
@test chomp(get_param("rosdistro")) in ["hydro", "indigo", "jade", "kinetic", "lunar"]
@test ! has_param("some_param")
@test_throws KeyError get_param("some_param")
@test_throws KeyError delete_param("some_param")
@test get_param("some_param", 1.1) == 1.1
@test get_param("some_param", "some_val") == "some_val"
set_param("some_param", "val")
@test get_param("some_param", 1.1) == "val"
delete_param("some_param")
@test ! has_param("some_param")

#Really just running this stuff for coverage

#Logging
logdebug("testing: %s", "debug")
loginfo("testing: %s", "info")
logwarn("testing: %s", "warn")
logerr("testing: %s", "err")
logfatal("testing: %s", "fatal")
@test ! is_shutdown()

#Generic stuff
@test startswith(RobotOS.get_name()[2:end], "jltest")
@test RobotOS.get_namespace() == "/"
RobotOS.get_node_uri()
RobotOS.get_caller_id()
RobotOS.get_published_topics()
RobotOS.get_ros_root()


module nj

function topExpr(mod::Module,paths::Array{ASCIIString,1})
   res = Expr(:toplevel,:(eval(x) = Core.eval(mod,x)),:(eval(m,x) = Core.eval(m,x)))
   for path in paths
      push!(res.args,:(include($path)))
   end
   return res
end

include(mod::Module,path,args::Vector) = include(mod,path,UTF8String[args...])

function scriptify(mod::Module,filename::ASCIIString)
    ast = parse("function _(args...)\n" * readall(filename) * "end");
    args2 = Array(Any,0);
    paths = Array(ASCIIString,0);

    for astNode in ast.args[2].args
       if(typeof(astNode) == Expr && astNode.head == :call && astNode.args[1] == :include)
          push!(paths,astNode.args[2]);
       else
          push!(args2,astNode);
       end
    end
    res = topExpr(mod,paths);
    push!(res.args,Expr(ast.head,ast.args[1],Expr(ast.args[2].head,args2...)));
    res
end

newRegex(pattern::AbstractString) = Regex(pattern)
getPattern(re::Regex) = re.pattern

end

Remove reference to AbstractString for compatibility with 0.3

module nj

function topExpr(mod::Module,paths::Array{ASCIIString,1})
   res = Expr(:toplevel,:(eval(x) = Core.eval(mod,x)),:(eval(m,x) = Core.eval(m,x)))
   for path in paths
      push!(res.args,:(include($path)))
   end
   return res
end

include(mod::Module,path,args::Vector) = include(mod,path,UTF8String[args...])

function scriptify(mod::Module,filename::ASCIIString)
    ast = parse("function _(args...)\n" * readall(filename) * "end");
    args2 = Array(Any,0);
    paths = Array(ASCIIString,0);

    for astNode in ast.args[2].args
       if(typeof(astNode) == Expr && astNode.head == :call && astNode.args[1] == :include)
          push!(paths,astNode.args[2]);
       else
          push!(args2,astNode);
       end
    end
    res = topExpr(mod,paths);
    push!(res.args,Expr(ast.head,ast.args[1],Expr(ast.args[2].head,args2...)));
    res
end

newRegex(pattern) = Regex(pattern)
getPattern(re::Regex) = re.pattern

end