text:
#
# exports.jl --
#
# Exported symbols for the Julia wrapper of X11 library.
#
#------------------------------------------------------------------------------
#
# Copyright (C) 2017, Éric Thiébaut.
#
# This file is part of Xlib.jl which is licensed under the MIT "Expat" License.
#

export
    Above,
    AbstractXEvent,
    AllPlanes,
    AllTemporary,
    AllocAll,
    AllocNone,
    AllowExposures,
    AlreadyGrabbed,
    Always,
    AnyButton,
    AnyKey,
    AnyModifier,
    AnyPropertyType,
    ArcChord,
    ArcPieSlice,
    AsyncBoth,
    AsyncKeyboard,
    AsyncPointer,
    Atom,
    AutoRepeatModeDefault,
    AutoRepeatModeOff,
    AutoRepeatModeOn,
    BadAccess,
    BadAlloc,
    BadAtom,
    BadColor,
    BadCursor,
    BadDrawable,
    BadFont,
    BadGC,
    BadIDChoice,
    BadImplementation,
    BadLength,
    BadMatch,
    BadName,
    BadPixmap,
    BadRequest,
    BadValue,
    BadWindow,
    Below,
    BitmapBitOrder,
    BitmapPad,
    BitmapUnit,
    BlackPixel,
    BlackPixelOfScreen,
    BottomIf,
    Button1,
    Button1Mask,
    Button1MotionMask,
    Button2,
    Button2Mask,
    Button2MotionMask,
    Button3,
    Button3Mask,
    Button3MotionMask,
    Button4,
    Button4Mask,
    Button4MotionMask,
    Button5,
    Button5Mask,
    Button5MotionMask,
    ButtonMotionMask,
    ButtonPress,
    ButtonPressMask,
    ButtonRelease,
    ButtonReleaseMask,
    CWBackPixel,
    CWBackPixmap,
    CWBackingPixel,
    CWBackingPlanes,
    CWBackingStore,
    CWBitGravity,
    CWBorderPixel,
    CWBorderPixmap,
    CWBorderWidth,
    CWColormap,
    CWCursor,
    CWDontPropagate,
    CWEventMask,
    CWHeight,
    CWOverrideRedirect,
    CWSaveUnder,
    CWSibling,
    CWStackMode,
    CWWidth,
    CWWinGravity,
    CWX,
    CWY,
    CapButt,
    CapNotLast,
    CapProjecting,
    CapRound,
    Cbuf10short,
    Cbuf20char,
    Cbuf32char,
    Cbuf5long,
    CellsOfScreen,
    CenterGravity,
    Cfunc,
    CirculateNotify,
    CirculateRequest,
    ClientMessage,
    ClipByChildren,
    Colormap,
    ColormapChangeMask,
    ColormapInstalled,
    ColormapNotify,
    ColormapUninstalled,
    ConfigureNotify,
    ConfigureRequest,
    ConnectionNumber,
    ControlMapIndex,
    ControlMask,
    Convex,
    CoordModeOrigin,
    CoordModePrevious,
    CopyFromParent,
    CreateNotify,
    CurrentTime,
    Cursor,
    CursorShape,
    DefaultBlanking,
    DefaultColormap,
    DefaultColormapOfScreen,
    DefaultDepth,
    DefaultDepthOfScreen,
    DefaultExposures,
    DefaultGC,
    DefaultGCOfScreen,
    DefaultRootWindow,
    DefaultScreen,
    DefaultScreenOfDisplay,
    DefaultVisual,
    DefaultVisualOfScreen,
    Depth,
    DestroyAll,
    DestroyNotify,
    DirectColor,
    DisableAccess,
    DisableScreenInterval,
    DisableScreenSaver,
    DisplayCells,
    DisplayHeight,
    DisplayHeightMM,
    DisplayOfScreen,
    DisplayPlanes,
    DisplayString,
    DisplayWidth,
    DisplayWidthMM,
    DoBlue,
    DoGreen,
    DoRed,
    DoesBackingStore,
    DoesSaveUnders,
    DontAllowExposures,
    DontPreferBlanking,
    Drawable,
    EastGravity,
    EnableAccess,
    EnterNotify,
    EnterWindowMask,
    EvenOddRule,
    EventMaskOfScreen,
    EventType,
    Expose,
    ExposureMask,
    False,
    FamilyChaos,
    FamilyDECnet,
    FamilyInternet,
    FamilyInternet6,
    FamilyServerInterpreted,
    FillOpaqueStippled,
    FillSolid,
    FillStippled,
    FillTiled,
    FirstExtensionError,
    FocusChangeMask,
    FocusIn,
    FocusOut,
    Font,
    FontChange,
    FontLeftToRight,
    FontRightToLeft,
    ForgetGravity,
    GC,
    GCArcMode,
    GCBackground,
    GCCapStyle,
    GCClipMask,
    GCClipXOrigin,
    GCClipYOrigin,
    GCDashList,
    GCDashOffset,
    GCFillRule,
    GCFillStyle,
    GCFont,
    GCForeground,
    GCFunction,
    GCGraphicsExposures,
    GCJoinStyle,
    GCLastBit,
    GCLineStyle,
    GCLineWidth,
    GCPlaneMask,
    GCStipple,
    GCSubwindowMode,
    GCTile,
    GCTileStipXOrigin,
    GCTileStipYOrigin,
    GContext,
    GXand,
    GXandInverted,
    GXandReverse,
    GXclear,
    GXcopy,
    GXcopyInverted,
    GXequiv,
    GXinvert,
    GXnand,
    GXnoop,
    GXnor,
    GXor,
    GXorInverted,
    GXorReverse,
    GXset,
    GXxor,
    GenericEvent,
    GrabFrozen,
    GrabInvalidTime,
    GrabModeAsync,
    GrabModeSync,
    GrabNotViewable,
    GrabSuccess,
    GraphicsExpose,
    GravityNotify,
    GrayScale,
    HeightMMOfScreen,
    HeightOfScreen,
    HostDelete,
    HostInsert,
    ImageByteOrder,
    IncludeInferiors,
    InputFocus,
    InputOnly,
    InputOutput,
    IsUnmapped,
    IsUnviewable,
    IsViewable,
    JoinBevel,
    JoinMiter,
    JoinRound,
    KBAutoRepeatMode,
    KBBellDuration,
    KBBellPercent,
    KBBellPitch,
    KBKey,
    KBKeyClickPercent,
    KBLed,
    KBLedMode,
    KeyCode,
    KeyPress,
    KeyPressMask,
    KeyRelease,
    KeyReleaseMask,
    KeySym,
    KeymapNotify,
    KeymapStateMask,
    LASTEvent,
    LSBFirst,
    LastExtensionError,
    LastKnownRequestProcessed,
    LeaveNotify,
    LeaveWindowMask,
    LedModeOff,
    LedModeOn,
    LineDoubleDash,
    LineOnOffDash,
    LineSolid,
    LockMapIndex,
    LockMask,
    LowerHighest,
    MSBFirst,
    MapNotify,
    MapRequest,
    MappingBusy,
    MappingFailed,
    MappingKeyboard,
    MappingModifier,
    MappingNotify,
    MappingPointer,
    MappingSuccess,
    Mask,
    MaxCmapsOfScreen,
    MinCmapsOfScreen,
    Mod1MapIndex,
    Mod1Mask,
    Mod2MapIndex,
    Mod2Mask,
    Mod3MapIndex,
    Mod3Mask,
    Mod4MapIndex,
    Mod4Mask,
    Mod5MapIndex,
    Mod5Mask,
    MotionNotify,
    NeedWidePrototypes,
    NextRequest,
    NoEventMask,
    NoExpose,
    NoSymbol,
    Nonconvex,
    None,
    NorthEastGravity,
    NorthGravity,
    NorthWestGravity,
    NotUseful,
    NotifyAncestor,
    NotifyDetailNone,
    NotifyGrab,
    NotifyHint,
    NotifyInferior,
    NotifyNonlinear,
    NotifyNonlinearVirtual,
    NotifyNormal,
    NotifyPointer,
    NotifyPointerRoot,
    NotifyUngrab,
    NotifyVirtual,
    NotifyWhileGrabbed,
    Opaque,
    Opposite,
    OwnerGrabButtonMask,
    ParentRelative,
    Pixmap,
    PlaceOnBottom,
    PlaceOnTop,
    PlanesOfScreen,
    PointerMotionHintMask,
    PointerMotionMask,
    PointerRoot,
    PointerWindow,
    PreferBlanking,
    PropModeAppend,
    PropModePrepend,
    PropModeReplace,
    PropertyChangeMask,
    PropertyDelete,
    PropertyNewValue,
    PropertyNotify,
    ProtocolRevision,
    ProtocolVersion,
    PseudoColor,
    QLength,
    QueuedAfterFlush,
    QueuedAfterReading,
    QueuedAlready,
    RaiseLowest,
    ReparentNotify,
    ReplayKeyboard,
    ReplayPointer,
    ResizeRedirectMask,
    ResizeRequest,
    RetainPermanent,
    RetainTemporary,
    RevertToNone,
    RevertToParent,
    RevertToPointerRoot,
    RootWindow,
    RootWindowOfScreen,
    Screen,
    ScreenCount,
    ScreenFormat,
    ScreenOfDisplay,
    ScreenSaverActive,
    ScreenSaverReset,
    SelectionClear,
    SelectionNotify,
    SelectionRequest,
    ServerVendor,
    SetModeDelete,
    SetModeInsert,
    ShiftMapIndex,
    ShiftMask,
    SouthEastGravity,
    SouthGravity,
    SouthWestGravity,
    StaticColor,
    StaticGravity,
    StaticGray,
    Status,
    StippleShape,
    StructureNotifyMask,
    SubstructureNotifyMask,
    SubstructureRedirectMask,
    Success,
    SyncBoth,
    SyncKeyboard,
    SyncPointer,
    TileShape,
    Time,
    TopIf,
    True,
    TrueColor,
    UnmapGravity,
    UnmapNotify,
    Unsorted,
    VendorRelease,
    VisibilityChangeMask,
    VisibilityFullyObscured,
    VisibilityNotify,
    VisibilityPartiallyObscured,
    VisibilityUnobscured,
    Visual,
    VisualID,
    WestGravity,
    WhenMapped,
    WhitePixel,
    WhitePixelOfScreen,
    WidthMMOfScreen,
    WidthOfScreen,
    WindingRule,
    Window,
    XActivateScreenSaver,
    XAddConnectionWatch,
    XAddExtension,
    XAddHost,
    XAddHosts,
    XAddToExtensionList,
    XAddToSaveSet,
    XAllPlanes,
    XAllocColor,
    XAllocColorCells,
    XAllocColorPlanes,
    XAllocID,
    XAllocNamedColor,
    XAllowEvents,
    XAnyEvent,
    XArc,
    XAutoRepeatOff,
    XAutoRepeatOn,
    XBaseFontNameListOfFontSet,
    XBell,
    XBitmapBitOrder,
    XBitmapPad,
    XBitmapUnit,
    XBlackPixel,
    XBlackPixelOfScreen,
    XBufferOverflow,
    XButtonEvent,
    XButtonPressedEvent,
    XButtonReleasedEvent,
    XCellsOfScreen,
    XChangeActivePointerGrab,
    XChangeGC,
    XChangeKeyboardControl,
    XChangeKeyboardMapping,
    XChangePointerControl,
    XChangeProperty,
    XChangeSaveSet,
    XChangeWindowAttributes,
    XChar2b,
    XCharStruct,
    XCheckIfEvent,
    XCheckMaskEvent,
    XCheckTypedEvent,
    XCheckTypedWindowEvent,
    XCheckWindowEvent,
    XCirculateEvent,
    XCirculateRequestEvent,
    XCirculateSubwindows,
    XCirculateSubwindowsDown,
    XCirculateSubwindowsUp,
    XClearArea,
    XClearWindow,
    XClientMessageEvent,
    XCloseDisplay,
    XCloseIM,
    XCloseOM,
    XColor,
    XColormapEvent,
    XConfigureEvent,
    XConfigureRequestEvent,
    XConfigureWindow,
    XConnectionNumber,
    XConnectionWatchProc,
    XContextDependentDrawing,
    XContextualDrawing,
    XConvertSelection,
    XCopyArea,
    XCopyColormapAndFree,
    XCopyGC,
    XCopyPlane,
    XCreateBitmapFromData,
    XCreateColormap,
    XCreateFontCursor,
    XCreateFontSet,
    XCreateGC,
    XCreateGlyphCursor,
    XCreateImage,
    XCreatePixmap,
    XCreatePixmapCursor,
    XCreatePixmapFromBitmapData,
    XCreateSimpleWindow,
    XCreateWindow,
    XCreateWindowEvent,
    XCrossingEvent,
    XDefaultColormap,
    XDefaultColormapOfScreen,
    XDefaultDepth,
    XDefaultDepthOfScreen,
    XDefaultGC,
    XDefaultGCOfScreen,
    XDefaultRootWindow,
    XDefaultScreen,
    XDefaultScreenOfDisplay,
    XDefaultVisual,
    XDefaultVisualOfScreen,
    XDefineCursor,
    XDeleteModifiermapEntry,
    XDeleteProperty,
    XDestroyIC,
    XDestroyOC,
    XDestroySubwindows,
    XDestroyWindow,
    XDestroyWindowEvent,
    XDirectionalDependentDrawing,
    XDisableAccessControl,
    XDisplay,
    XDisplayCells,
    XDisplayHeight,
    XDisplayHeightMM,
    XDisplayKeycodes,
    XDisplayMotionBufferSize,
    XDisplayName,
    XDisplayOfIM,
    XDisplayOfOM,
    XDisplayOfScreen,
    XDisplayPlanes,
    XDisplayString,
    XDisplayWidth,
    XDisplayWidthMM,
    XDoesBackingStore,
    XDoesSaveUnders,
    XDrawArc,
    XDrawArcs,
    XDrawImageString,
    XDrawImageString16,
    XDrawLine,
    XDrawLines,
    XDrawPoint,
    XDrawPoints,
    XDrawRectangle,
    XDrawRectangles,
    XDrawSegments,
    XDrawString,
    XDrawString16,
    XDrawText,
    XDrawText16,
    XEDataObject,
    XEHeadOfExtensionList,
    XEnableAccessControl,
    XEnterWindowEvent,
    XErrorEvent,
    XErrorHandler,
    XEvent,
    XEventMaskOfScreen,
    XEventsQueued,
    XExposeEvent,
    XExtCodes,
    XExtData,
    XExtendedMaxRequestSize,
    XExtentsOfFontSet,
    XFetchBuffer,
    XFetchBytes,
    XFetchName,
    XFillArc,
    XFillArcs,
    XFillPolygon,
    XFillRectangle,
    XFillRectangles,
    XFilterEvent,
    XFindOnExtensionList,
    XFlush,
    XFlushGC,
    XFocusChangeEvent,
    XFocusInEvent,
    XFocusOutEvent,
    XFontProp,
    XFontSet,
    XFontSetExtents,
    XFontStruct,
    XFontsOfFontSet,
    XForceScreenSaver,
    XFree,
    XFreeColormap,
    XFreeColors,
    XFreeCursor,
    XFreeEventData,
    XFreeExtensionList,
    XFreeFont,
    XFreeFontInfo,
    XFreeFontNames,
    XFreeFontPath,
    XFreeFontSet,
    XFreeGC,
    XFreeModifiermap,
    XFreePixmap,
    XFreeStringList,
    XGCValues,
    XGContextFromGC,
    XGenericEvent,
    XGenericEventCookie,
    XGeometry,
    XGetAtomName,
    XGetAtomNames,
    XGetCommand,
    XGetDefault,
    XGetErrorDatabaseText,
    XGetErrorText,
    XGetEventData,
    XGetFontPath,
    XGetFontProperty,
    XGetGCValues,
    XGetGeometry,
    XGetIconName,
    XGetImage,
    XGetInputFocus,
    XGetKeyboardControl,
    XGetKeyboardMapping,
    XGetModifierMapping,
    XGetMotionEvents,
    XGetPointerControl,
    XGetPointerMapping,
    XGetScreenSaver,
    XGetSelectionOwner,
    XGetSubImage,
    XGetTransientForHint,
    XGetWMColormapWindows,
    XGetWMProtocols,
    XGetWindowAttributes,
    XGetWindowProperty,
    XGrabButton,
    XGrabKey,
    XGrabKeyboard,
    XGrabPointer,
    XGrabServer,
    XGraphicsExposeEvent,
    XGravityEvent,
    XHeightMMOfScreen,
    XHeightOfScreen,
    XHostAddress,
    XIC,
    XICCallback,
    XICProc,
    XID,
    XIDProc,
    XIM,
    XIMAbsolutePosition,
    XIMBackwardChar,
    XIMBackwardWord,
    XIMBitmapType,
    XIMCallback,
    XIMCaretDirection,
    XIMCaretDown,
    XIMCaretStyle,
    XIMCaretUp,
    XIMDontChange,
    XIMFeedback,
    XIMForwardChar,
    XIMForwardWord,
    XIMHighlight,
    XIMHotKeyState,
    XIMHotKeyStateOFF,
    XIMHotKeyStateON,
    XIMHotKeyTrigger,
    XIMHotKeyTriggers,
    XIMInitialState,
    XIMIsInvisible,
    XIMIsPrimary,
    XIMIsSecondary,
    XIMLineEnd,
    XIMLineStart,
    XIMNextLine,
    XIMOfIC,
    XIMPreeditArea,
    XIMPreeditCallbacks,
    XIMPreeditCaretCallbackStruct,
    XIMPreeditDisable,
    XIMPreeditDrawCallbackStruct,
    XIMPreeditEnable,
    XIMPreeditNone,
    XIMPreeditNothing,
    XIMPreeditPosition,
    XIMPreeditState,
    XIMPreeditStateNotifyCallbackStruct,
    XIMPreeditUnKnown,
    XIMPreserveState,
    XIMPreviousLine,
    XIMPrimary,
    XIMProc,
    XIMResetState,
    XIMReverse,
    XIMSecondary,
    XIMStatusArea,
    XIMStatusCallbacks,
    XIMStatusDataType,
    XIMStatusDrawCallbackStruct,
    XIMStatusNone,
    XIMStatusNothing,
    XIMStringConversionBottomEdge,
    XIMStringConversionBuffer,
    XIMStringConversionCallbackStruct,
    XIMStringConversionChar,
    XIMStringConversionConcealed,
    XIMStringConversionFeedback,
    XIMStringConversionLeftEdge,
    XIMStringConversionLine,
    XIMStringConversionOperation,
    XIMStringConversionPosition,
    XIMStringConversionRetrieval,
    XIMStringConversionRightEdge,
    XIMStringConversionSubstitution,
    XIMStringConversionText,
    XIMStringConversionTopEdge,
    XIMStringConversionType,
    XIMStringConversionWord,
    XIMStringConversionWrapped,
    XIMStyle,
    XIMStyles,
    XIMTertiary,
    XIMText,
    XIMTextType,
    XIMUnderline,
    XIMValuesList,
    XIMVisibleToBackword,
    XIMVisibleToCenter,
    XIMVisibleToForward,
    XIOErrorHandler,
    XIconifyWindow,
    XIfEvent,
    XImage,
    XImageByteOrder,
    XInitExtension,
    XInitImage,
    XInitThreads,
    XInsertModifiermapEntry,
    XInstallColormap,
    XInternAtom,
    XInternAtoms,
    XInternalConnectionNumbers,
    XKeyEvent,
    XKeyPressedEvent,
    XKeyReleasedEvent,
    XKeyboardControl,
    XKeyboardState,
    XKeycodeToKeysym,
    XKeymapEvent,
    XKeysymToKeycode,
    XKeysymToString,
    XKillClient,
    XLastKnownRequestProcessed,
    XLeaveWindowEvent,
    XListDepths,
    XListExtensions,
    XListFonts,
    XListFontsWithInfo,
    XListHosts,
    XListInstalledColormaps,
    XListPixmapFormats,
    XListProperties,
    XLoadFont,
    XLoadQueryFont,
    XLocaleOfFontSet,
    XLocaleOfIM,
    XLocaleOfOM,
    XLockDisplay,
    XLookupBoth,
    XLookupChars,
    XLookupColor,
    XLookupKeySym,
    XLookupKeysym,
    XLookupNone,
    XLowerWindow,
    XMapEvent,
    XMapRaised,
    XMapRequestEvent,
    XMapSubwindows,
    XMapWindow,
    XMappingEvent,
    XMaskEvent,
    XMaxCmapsOfScreen,
    XMaxRequestSize,
    XMinCmapsOfScreen,
    XModifierKeymap,
    XMotionEvent,
    XMoveResizeWindow,
    XMoveWindow,
    XNArea,
    XNAreaNeeded,
    XNBackground,
    XNBackgroundPixmap,
    XNBaseFontName,
    XNClientWindow,
    XNColormap,
    XNContextualDrawing,
    XNCursor,
    XNDefaultString,
    XNDestroyCallback,
    XNDirectionalDependentDrawing,
    XNFilterEvents,
    XNFocusWindow,
    XNFontInfo,
    XNFontSet,
    XNForeground,
    XNGeometryCallback,
    XNHotKey,
    XNHotKeyState,
    XNInputStyle,
    XNLineSpace,
    XNMissingCharSet,
    XNOMAutomatic,
    XNOrientation,
    XNPreeditAttributes,
    XNPreeditCaretCallback,
    XNPreeditDoneCallback,
    XNPreeditDrawCallback,
    XNPreeditStartCallback,
    XNPreeditState,
    XNPreeditStateNotifyCallback,
    XNQueryICValuesList,
    XNQueryIMValuesList,
    XNQueryInputStyle,
    XNQueryOrientation,
    XNR6PreeditCallback,
    XNRequiredCharSet,
    XNResetState,
    XNResourceClass,
    XNResourceName,
    XNSeparatorofNestedList,
    XNSpotLocation,
    XNStatusAttributes,
    XNStatusDoneCallback,
    XNStatusDrawCallback,
    XNStatusStartCallback,
    XNStdColormap,
    XNStringConversion,
    XNStringConversionCallback,
    XNVaNestedList,
    XNVisiblePosition,
    XNewModifiermap,
    XNextEvent,
    XNextRequest,
    XNoExposeEvent,
    XNoOp,
    XOC,
    XOM,
    XOMCharSetList,
    XOMFontInfo,
    XOMOfOC,
    XOMOrientation,
    XOMOrientation_Context,
    XOMOrientation_LTR_TTB,
    XOMOrientation_RTL_TTB,
    XOMOrientation_TTB_LTR,
    XOMOrientation_TTB_RTL,
    XOpenDisplay,
    XOpenIM,
    XOpenOM,
    XOrientation,
    XParseColor,
    XParseGeometry,
    XPeekEvent,
    XPeekIfEvent,
    XPending,
    XPixmapFormatValues,
    XPlanesOfScreen,
    XPoint,
    XPointer,
    XPointerMovedEvent,
    XPrivate,
    XProcessInternalConnection,
    XPropertyEvent,
    XProtocolRevision,
    XProtocolVersion,
    XPutBackEvent,
    XPutImage,
    XQLength,
    XQueryBestCursor,
    XQueryBestSize,
    XQueryBestStipple,
    XQueryBestTile,
    XQueryColor,
    XQueryColors,
    XQueryExtension,
    XQueryFont,
    XQueryKeymap,
    XQueryPointer,
    XQueryTextExtents,
    XQueryTextExtents16,
    XQueryTree,
    XRaiseWindow,
    XReadBitmapFile,
    XReadBitmapFileData,
    XRebindKeysym,
    XRecolorCursor,
    XReconfigureWMWindow,
    XRectangle,
    XRefreshKeyboardMapping,
    XRegisterIMInstantiateCallback,
    XRemoveConnectionWatch,
    XRemoveFromSaveSet,
    XRemoveHost,
    XRemoveHosts,
    XReparentEvent,
    XReparentWindow,
    XResetScreenSaver,
    XResizeRequestEvent,
    XResizeWindow,
    XResourceManagerString,
    XRestackWindows,
    XRootWindow,
    XRootWindowOfScreen,
    XRotateBuffers,
    XRotateWindowProperties,
    XScreenCount,
    XScreenNumberOfScreen,
    XScreenOfDisplay,
    XScreenResourceString,
    XSegment,
    XSelectInput,
    XSelectionClearEvent,
    XSelectionEvent,
    XSelectionRequestEvent,
    XSendEvent,
    XServerInterpretedAddress,
    XServerVendor,
    XSetAccessControl,
    XSetArcMode,
    XSetAuthorization,
    XSetBackground,
    XSetClipMask,
    XSetClipOrigin,
    XSetClipRectangles,
    XSetCloseDownMode,
    XSetCommand,
    XSetDashes,
    XSetErrorHandler,
    XSetFillRule,
    XSetFillStyle,
    XSetFont,
    XSetFontPath,
    XSetForeground,
    XSetFunction,
    XSetGraphicsExposures,
    XSetICFocus,
    XSetIOErrorHandler,
    XSetIconName,
    XSetInputFocus,
    XSetLineAttributes,
    XSetLocaleModifiers,
    XSetModifierMapping,
    XSetPlaneMask,
    XSetPointerMapping,
    XSetScreenSaver,
    XSetSelectionOwner,
    XSetState,
    XSetStipple,
    XSetSubwindowMode,
    XSetTSOrigin,
    XSetTile,
    XSetTransientForHint,
    XSetWMColormapWindows,
    XSetWMProtocols,
    XSetWindowAttributes,
    XSetWindowBackground,
    XSetWindowBackgroundPixmap,
    XSetWindowBorder,
    XSetWindowBorderPixmap,
    XSetWindowBorderWidth,
    XSetWindowColormap,
    XStoreBuffer,
    XStoreBytes,
    XStoreColor,
    XStoreColors,
    XStoreName,
    XStoreNamedColor,
    XStringToKeysym,
    XSupportsLocale,
    XSync,
    XTextExtents,
    XTextExtents16,
    XTextItem,
    XTextItem16,
    XTextWidth,
    XTextWidth16,
    XTimeCoord,
    XTranslateCoordinates,
    XUndefineCursor,
    XUngrabButton,
    XUngrabKey,
    XUngrabKeyboard,
    XUngrabPointer,
    XUngrabServer,
    XUninstallColormap,
    XUnloadFont,
    XUnlockDisplay,
    XUnmapEvent,
    XUnmapSubwindows,
    XUnmapWindow,
    XUnregisterIMInstantiateCallback,
    XUnsetICFocus,
    XVaNestedList,
    XVendorRelease,
    XVisibilityEvent,
    XVisualIDFromVisual,
    XWarpPointer,
    XWhitePixel,
    XWhitePixelOfScreen,
    XWidthMMOfScreen,
    XWidthOfScreen,
    XWindowAttributes,
    XWindowChanges,
    XWindowEvent,
    XWithdrawWindow,
    XWriteBitmapFile,
    XYBitmap,
    XYPixmap,
    X_HAVE_UTF8_STRING,
    X_PROTOCOL,
    X_PROTOCOL_REVISION,
    Xlib,
    XlibSpecificationRelease,
    XmbDrawImageString,
    XmbDrawString,
    XmbDrawText,
    XmbLookupString,
    XmbResetIC,
    XmbTextEscapement,
    XmbTextExtents,
    XmbTextItem,
    XmbTextPerCharExtents,
    XrmHashBucketRec,
    XrmInitialize,
    Xutf8DrawImageString,
    Xutf8DrawString,
    Xutf8DrawText,
    Xutf8LookupString,
    Xutf8ResetIC,
    Xutf8TextEscapement,
    Xutf8TextExtents,
    Xutf8TextPerCharExtents,
    XwcDrawImageString,
    XwcDrawString,
    XwcDrawText,
    XwcLookupString,
    XwcResetIC,
    XwcTextEscapement,
    XwcTextExtents,
    XwcTextItem,
    XwcTextPerCharExtents,
    YSorted,
    YXBanded,
    YXSorted,
    ZPixmap,
    _Bool,
    _Complex,
    _KeyCode,
    _Xmbtowc,
    _Xwctomb


text:
using Test, LinearFractionalTransformations, LinearAlgebra

@testset "Basics" begin
    f = LFT(1, 0, 0, 1)  # identity
    @test f(1 + im) == 1 + im

    f = LFT(2, 0, 0, 1)  # f(x) = 2x
    @test f(-im) == -2im

    g = inv(f)
    @test g(im) == 0.5im

    g = f * f
    @test g(2 - im) == 4 * (2 - im)

    f = LFT(1, 2 + im, 3, 0, 1 - im, 5)
    @test f(1) == 2 + im
    @test f(3) == 0
    @test f(1 - im) == 5

    g = inv(f)
    @test g(0) == 3

    @test LFT() == g * f

    f = LFT(0, 1, 1, 0)
    @test f(Inf) == 0
    @test isinf(f(0))

    f = LFT(3 - im, 2 + im, 6)
    @test f(3 - im) == 0
    @test f(2 + im) == 1
    @test isinf(f(6))

end

# check out LFTQ
@testset "LFTQ" begin
    for k = 1:5
        Q = [1 0; 0 -1]
        while det(Q) < 0.5
            Q, R = qr(randn(3, 3))
        end
        F = LFTQ(Q)
        v = randn() + randn() * im

        w1 = stereo(Q * stereo(v))
        w2 = F(v)
        @test abs(w1 - w2) <= 1e-8

        z = stereo(Q * stereo(0))
        @test abs(z - F(0)) <= 1e-8

        z = stereo(Q * stereo(1))
        @test abs(z - F(1)) <= 1e-8

        z = stereo(Q * stereo(Inf))
        @test abs(z - F(Inf)) <= 1e-8

    end
end

ext: jl


text:
#jl #! format: off
# # 5-bus Market simulation with [PowerSimulations.jl](https://github.com/NREL-SIIP/PowerSimulations.jl)

# **Originally Contributed by**: Clayton Barrows

# ## Introduction

# PowerSimulations.jl supports simulations that consist of sequential optimization problems
# where results from previous problems inform subsequent problems in a variety of ways. This
# example demonstrates some of these capabilities to represent electricity market clearing.

# ## Dependencies and Data
# First, let's create `System`s to represent the Day-Ahead and Real-Time market clearing
# process with hourly, and 5-minute time series data, respectively.

# ### Modeling Packages
using PowerSystems
using PowerSimulations
using PowerSystemCaseBuilder

# ### Data management packages
using Dates
using DataFrames

# ### Optimization packages
using HiGHS # mip solver
solver = optimizer_with_attributes(HiGHS.Optimizer, "mip_rel_gap" => 0.5)

# ### 5-bus Data
# The five bus system data here includes hourly day-ahead data, 5-minute real-time market
# data, and 6-second actual data. We'll only use the hourly and 5-minute data for the
# example simulations below, but the 6-second data is included for future development.
sys_DA = build_system(SIIPExampleSystems, "5_bus_matpower_DA")
sys_RT = build_system(SIIPExampleSystems, "5_bus_matpower_RT")

# ## `ProblemTemplate`s

template_uc = template_unit_commitment(use_slacks = true)
template_ed = template_economic_dispatch(
    network = NetworkModel(CopperPlatePowerModel, duals = [CopperPlateBalanceConstraint]),
)

# ### Define the Simulation Sequence

models = SimulationModels(
    decision_models = [
        DecisionModel(template_uc, sys_DA, name = "UC", optimizer = solver),
        DecisionModel(template_ed, sys_RT, name = "ED", optimizer = solver),
    ],
)

feedforward = Dict(
    "ED" => [
        SemiContinuousFeedforward(
            component_type = ThermalStandard,
            source = OnVariable,
            affected_values = [ActivePowerVariable],
        ),
    ],
)

DA_RT_sequence = SimulationSequence(
    models = models,
    ini_cond_chronology = InterProblemChronology(),
    feedforwards = feedforward,
)

# ## `Simulation`
file_path = mktempdir(".", cleanup = true)
sim = Simulation(
    name = "5bus-test",
    steps = 1,
    models = models,
    sequence = DA_RT_sequence,
    simulation_folder = file_path,
)

# ### Build simulation

build!(sim)

# ### Execute simulation

execute!(sim, enable_progress_bar = false)

## Results
# First we can load the result metadata
results = SimulationResults(sim);
uc_results = get_decision_problem_results(results, "UC")
ed_results = get_decision_problem_results(results, "ED");

# Then we can read and examine the results of interest. For example, if we want to read
# marginal prices of the balance constraint, we can see what dual values are available:
list_dual_names(ed_results)

# Then, we can read the results of the dual
prices = read_dual(ed_results, "CopperPlateBalanceConstraint__System")

# or if we want to look at the realized values
read_realized_dual(ed_results, "CopperPlateBalanceConstraint__System")

# *note that in this simulation the prices are all equal to the balance slack
# penalty value of $100000/MWh because there is unserved energy in the result*

max_stars_repo_name: NREL-SIIP/Examples

max_issues_repo_name: NREL-SIIP/Examples

max_forks_repo_name: NREL-SIIP/Examples


text:
using Test
using LowRankModels

## Tests for NNDSVD initialization

# apply init_nnmf! to random dataset
m,n,k = 10,5,3
A = rand(m,k)*rand(k,n)
losses = fill(QuadLoss(),n)
r = NonNegConstraint()
glrm = GLRM(A,losses,r,r,k)
init_nndsvd!(glrm)

# Test dims and nonnegativity of X,Y
@test(all(glrm.X .>= 0.0))
@test(all(glrm.Y .>= 0.0))
@test(size(glrm.X,1) == k)
@test(size(glrm.X,2) == m)
@test(size(glrm.Y,1) == k)
@test(size(glrm.Y,2) == n)

# validate against NMF.jl
A = [ 0.245774   0.481246   0.293614   0.528272   0.608255
      0.906146   0.0847498  0.963121   0.113728   0.552843
      0.269553   0.830981   0.067466   0.854045   0.170701
      0.781552   0.0302068  0.709045   0.578069   0.542792
      0.824889   0.538719   0.881363   0.229199   0.356273
      0.0530284  0.618962   0.96237    0.0877032  0.921746
      0.295122   0.626784   0.348475   0.299937   0.35043
      0.0499904  0.728344   0.573141   0.850758   0.425369
      0.872088   0.322181   0.903238   0.695946   0.706841
      0.542786   0.581426   0.0477561  0.601374   0.176598 ]

# Wt and H produced by NMF.jl
Wt = [0.25814 0.34329 0.24898 0.33489 0.35953 0.33798 0.23164 0.31705 0.43949 0.22484
      0.24305 0.0 0.71244 0.0 0.0 0.0 0.19987 0.49127 0.0 0.38994
      0.13531 0.0 0.0 0.0 0.0 0.94666 0.13278 0.26056 0.0 0.0]

H = [1.60738 1.42165 1.97295 1.47396 1.57709
     0.0 0.67822 0.0 0.6408 0.0
     0.0 0.23296 0.27065 0.0 0.35102]

# initialize glrm and check output
glrm.A = A
init_nndsvd!(glrm; scale=false)

@test(all(round(glrm.X,5) .== Wt))
@test(all(round(glrm.Y,5) .== H))

# Test with missing entries for A
obs = [(1,1),(1,3),(1,5),
       (2,1),(2,2),(2,4),
       (3,2),(3,3),(3,5),
       (4,1),(4,2),(4,5),
       (5,2),(5,3),(5,5),
       (6,1),(6,2),(6,5),
       (7,1),(7,3),(7,4),
       (8,2),(8,3),(8,4),
       (9,1),(9,3),(9,5),
       (10,3),(10,4),(10,5)]
glrm = GLRM(A,losses,r,r,k,obs=obs)
init_nndsvd!(glrm; max_iters=5)


text:
"""
    abstract type ReferenceFE{D}

Abstract type representing a Reference finite element. `D` is the underlying coordinate space dimension.
We follow the Ciarlet definition. A reference finite element
is defined by a polytope (cell topology), a basis of an interpolation space
of top of this polytope (denoted here as the prebasis), and a basis of the dual of this space
(i.e. the degrees of freedom). From this information one can compute the shape functions
(i.e, the canonical basis of w.r.t. the degrees of freedom) with a simple change of basis.
In addition, we also encode in this type information about how the interpolation space
in a reference finite element is "glued" with neighbors in order to build conforming
cell-wise spaces.

The `ReferenceFE` interface is defined by overloading these methods:

- [`num_dofs(reffe::ReferenceFE)`](@ref)
- [`get_polytope(reffe::ReferenceFE)`](@ref)
- [`get_prebasis(reffe::ReferenceFE)`](@ref)
- [`get_dofs(reffe::ReferenceFE)`](@ref)
- [`get_face_own_dofids(reffe::ReferenceFE)`](@ref)

and optionally these ones:

- [`ReferenceFE{N}(reffe::ReferenceFE,nfaceid::Integer) where N`](@ref)
- [`get_own_dofs_permutations(reffe::ReferenceFE)`](@ref)

"""
abstract type ReferenceFE{D} end

"""
    num_dofs(reffe::ReferenceFE) -> Int

Returns the number of DOFs.
"""
function num_dofs(reffe::ReferenceFE)
  @abstractmethod
end

"""
    get_polytope(reffe::ReferenceFE) -> Polytope

Returns the underlying polytope object.
"""
function get_polytope(reffe::ReferenceFE)
  @abstractmethod
end

"""
    get_prebasis(reffe::ReferenceFE) -> Field

Returns the underlying prebasis encoded as a `Field` object.
"""
function get_prebasis(reffe::ReferenceFE)
  @abstractmethod
end

"""
    get_dofs(reffe::ReferenceFE) -> Dof

Returns the underlying dof basis encoded in a `Dof` object.
"""
function get_dofs(reffe::ReferenceFE)
  @abstractmethod
end

"""
    get_face_own_dofids(reffe::ReferenceFE) -> Vector{Vector{Int}}
"""
function get_face_own_dofids(reffe::ReferenceFE)
  @abstractmethod
end

# optional

"""
    ReferenceFE{N}(reffe::ReferenceFE,nfaceid::Integer) where N

Returns a reference FE obtained by the restriction of the given one
to the face with `nfaceid` within dimension `N`.
"""
function ReferenceFE{N}(reffe::ReferenceFE,nfaceid::Integer) where N
  @abstractmethod
end

"""
    get_own_dofs_permutations(reffe::ReferenceFE) -> Vector{Vector{Int}}

Returns a vector of vectors indicating how the dofs owned by the reference
fe have to be relabeled when the vertices of the underlying polytope are relabeled
according the permutations in

    polytope = get_polytope(reffe)
    vertex_perms = get_vertex_permutations(polytope)

That is, if the vertices are relabeled with the permutation number `iperm`

    oldvertex_to_newvertex = vertex_perms[iperm]

The dofs are relabeled as

    olddof_to_newdof = get_own_dofs_permutations(reffe)[iperm]

Note that in some cases, a valid relabeling of the dofs
for a corresponding relabeling of the vertices does not exist (i.e., lagrangian FEs with
anisotropic order). For these permutations the corresponding vector in
`get_own_dofs_permutations(reffe)` has to be filled with the constant value [`INVALID_PERM`](@ref).

# Examples

Relabeling of the dofs owned by the 4-th order segment

```jldoctest
using InplaceArrays.ReferenceFEs

order = 4
seg5 = LagrangianRefFE(Float64,SEGMENT,order)

vertexperms = get_vertex_permutations(SEGMENT)
dofperms = get_own_dofs_permutations(seg5)

println(vertexperms)
println(dofperms)

# output
Array{Int64,1}[[1, 2], [2, 1]]
Array{Int64,1}[[1, 2, 3], [3, 2, 1]]

```

Note that when the segment is flipped (the second permutation) the first owned dof becomes the third
owned dof, the second owned dof becomes the second one and the third becomes the first one as one would
expect.

Relabeling of the dofs owned by an anisotropic quadrilateral

```jldoctest
using InplaceArrays.ReferenceFEs

orders = (2,3)
quad12 = LagrangianRefFE(Float64,QUAD,orders)

vertexperms = get_vertex_permutations(QUAD)
dofperms = get_own_dofs_permutations(quad12)

println(vertexperms)
println(dofperms)
println(INVALID_PERM)

# output
Array{Int64,1}[[1, 2, 3, 4], [1, 3, 2, 4], [2, 1, 4, 3], [2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 1, 2], [4, 2, 3, 1], [4, 3, 2, 1]]
Array{Int64,1}[[1, 2], [0, 0], [1, 2], [0, 0], [0, 0], [2, 1], [0, 0], [2, 1]]
0
```

Note that not all permutations are valid in this case.

"""
function get_own_dofs_permutations(reffe::ReferenceFE)
  @abstractmethod
end

"""
Constant of type `Int`  used to signal that a permutation is not valid.
"""
const INVALID_PERM = 0

# API

"""
    get_shapefuns(reffe::ReferenceFE) -> Field

Returns the basis of shape functions (i.e. the canonical basis)
associated with the reference FE. The result is encoded as a `Field` object.
"""
function get_shapefuns(reffe::ReferenceFE)
  dofs = get_dofs(reffe)
  prebasis = get_prebasis(reffe)
  compute_shapefuns(dofs,prebasis)
end

"""
    compute_shapefuns(dofs,prebasis)

Helper function used to compute the shape function basis
associated with the dof basis `dofs` and the basis `prebasis`.

It is equivalent to

    change = inv(evaluate(dofs,prebasis))
    change_basis(prebasis,change)
"""
function compute_shapefuns(dofs,prebasis)
  change = inv(evaluate(dofs,prebasis))
  change_basis(prebasis,change)
end

num_dims(::Type{<:ReferenceFE{D}}) where D = D

"""
    num_dims(::Type{<:ReferenceFE{D}}) where D
    num_dims(reffe::ReferenceFE{D}) where D

Returns `D`.
"""
num_dims(reffe::ReferenceFE) = num_dims(typeof(reffe))

# Test

"""
    test_reference_fe(reffe::ReferenceFE{D};optional::Bool=false) where D

Test if the methods in the `ReferenceFE` interface are defined for the object `reffe`.
If `optional=false` (the default) only the mandatory methods are checked. Otherwise, the optional
methods are also tested.
"""
function test_reference_fe(reffe::ReferenceFE{D};optional::Bool=false) where D
  @test D == num_dims(reffe)
  p = get_polytope(reffe)
  @test isa(p,Polytope{D})
  basis = get_prebasis(reffe)
  @test isa(basis,Field)
  dofs = get_dofs(reffe)
  @test isa(dofs,Dof)
  facedofs = get_face_own_dofids(reffe)
  @test isa(facedofs,Vector{Vector{Int}})
  @test length(facedofs) == num_faces(p)
  shapefuns = get_shapefuns(reffe)
  @test isa(shapefuns,Field)
  ndofs = num_dofs(reffe)
  m = evaluate(dofs,basis)
  @test ndofs == size(m,1)
  @test ndofs == size(m,2)
  if optional
    dofperms = get_own_dofs_permutations(reffe)
    @test isa(dofperms,Vector{Vector{Int}})
    vertexperms = get_vertex_permutations(p)
    @test length(vertexperms) == length(dofperms)
    @test all( length.(dofperms) .== length(facedofs[end]) )
    for d in 0:D
      for iface in 1:num_faces(p,d)
        refface = ReferenceFE{d}(reffe,iface)
        @test isa(refface,ReferenceFE{d})
      end
    end
  end
end

# Concrete implementation

"""
    struct GenericRefFE{D} <: ReferenceFE{D}
      polytope::Polytope{D}
      prebasis::Field
      dofs::Dof
      face_own_dofids::Vector{Vector{Int}}
      shapefuns::Field
      ndofs::Int
      own_dofs_permutations::Vector{Vector{Int}}
      reffaces
    end

This type is a *materialization* of the `ReferenceFE` interface. That is, it is a
`struct` that stores the values of all abstract methods in the `ReferenceFE` interface.
This type is useful to build reference FEs from the underlying ingredients without
the need to create a new type.

Note that some fields in this `struct` are type unstable deliberately in order to simplify the
type signature. Don't access them in computationally expensive functions,
instead extract the required fields before and pass them to the computationally expensive function.
"""
struct GenericRefFE{D} <: ReferenceFE{D}
    ndofs::Int
    polytope::Polytope{D}
    prebasis::Field
    dofs::Dof
    face_own_dofids::Vector{Vector{Int}}
    own_dofs_permutations::Vector{Vector{Int}}
    shapefuns::Field
    reffaces
  @doc """
      GenericRefFE(
        polytope::Polytope{D},
        prebasis::Field,
        dofs::Dof,
        face_own_dofids::Vector{Vector{Int}};
        shapefuns::Field,
        ndofs::Int,
        own_dofs_permutations::Vector{Vector{Int}},
        reffaces) where D

  Constructs a `GenericRefFE` object with the provided data. Positional arguments are mandatory.
  All Key-word ones are optional.
  """
  function GenericRefFE(
    polytope::Polytope{D},
    prebasis::Field,
    dofs::Dof,
    face_own_dofids::Vector{Vector{Int}};
    shapefuns::Field = compute_shapefuns(dofs,prebasis),
    ndofs::Int = size(evaluate(dofs,prebasis),1),
    own_dofs_permutations::Vector{Vector{Int}} = [ fill(INVALID_PERM,length(fi)) for fi in face_own_dofids],
    reffaces = nothing) where D

    new{D}(ndofs,polytope,prebasis,dofs,face_own_dofids,own_dofs_permutations,shapefuns,reffaces)
  end
end

num_dofs(reffe::GenericRefFE) = reffe.ndofs

get_polytope(reffe::GenericRefFE) = reffe.polytope

get_prebasis(reffe::GenericRefFE) = reffe.prebasis

get_dofs(reffe::GenericRefFE) = reffe.dofs

get_face_own_dofids(reffe::GenericRefFE) = reffe.face_own_dofids

get_own_dofs_permutations(reffe::GenericRefFE) = reffe.own_dofs_permutations

get_shapefuns(reffe::GenericRefFE) = reffe.shapefuns

function ReferenceFE{N}(reffe::GenericRefFE,iface::Integer) where N
  @assert reffe.reffaces != nothing "ReferenceFE cannot be provided. Make sure that you are using the keyword argument reffaces in the GenericRefFE constructor."
  reffe.reffaces[N+1][iface]
end

function ReferenceFE{D}(reffe::GenericRefFE{D},iface::Integer) where D
  @assert iface == 1 "Only one D-face"
  reffe
end


text:
module JuliaSyntax

using Mmap

# Internal utilities which aren't related to JuliaSyntax per se.
include("utils.jl")

# Lexing
#
# We're using a git subtree for a modified version of Tokenize.jl, as we need
# several significant changes.
# TODO: Perhaps integrate these back into Tokenize? Or maybe JuliaSyntax would
# be a sensible home for the Tokenize lexer in the future?
include("../Tokenize/src/Tokenize.jl")
using .Tokenize.Tokens: Token
const TzTokens = Tokenize.Tokens
include("tokens.jl")

# Source and diagnostics
include("source_files.jl")
include("diagnostics.jl")

# Parsing
include("parse_stream.jl")
include("parser.jl")
include("parser_api.jl")
include("value_parsing.jl")

# Tree data structures
include("green_tree.jl")
include("syntax_tree.jl")

# Hooks to integrate the parser with Base
include("hooks.jl")

end


text:
module FFMPEG

const libpath = joinpath(@__DIR__, "..", "deps", "usr", "lib")

if Sys.iswindows()
    const execenv = ("PATH" => string(libpath, ";", Sys.BINDIR))
elseif Sys.isapple()
    const execenv = ("DYLD_LIBRARY_PATH" => libpath)
else
    const execenv = ("LD_LIBRARY_PATH" => libpath)
end

# Load in `deps.jl`, complaining if it does not exist
const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl")
if !isfile(depsjl_path)
    println("Deps path: $depsjl_path")
    error("FFMPEG not installed properly, run `] build FFMPEG`, restart Julia and try again")
end

include(depsjl_path)

av_version(v) = VersionNumber(v >> 16, (v >> 8) & 0xff, v & 0xff)

have_avcodec()    = Libdl.dlopen_e(libavcodec)    != C_NULL
have_avformat()   = Libdl.dlopen_e(libavformat)   != C_NULL
have_avutil()     = Libdl.dlopen_e(libavutil)     != C_NULL
have_swscale()    = Libdl.dlopen_e(libswscale)    != C_NULL
have_avdevice()   = Libdl.dlopen_e(libavdevice)   != C_NULL
have_avfilter()   = Libdl.dlopen_e(libavfilter)   != C_NULL
#have_avresample() = @isdefined(libavresample) && Libdl.dlopen_e(libavresample) != C_NULL
#have_swresample() = @isdefined(libswresample) && Libdl.dlopen_e(libswresample) != C_NULL

_avcodec_version()    = have_avcodec()    ? av_version(ccall((:avcodec_version,    libavcodec),    UInt32, ())) : v"0"
_avformat_version()   = have_avformat()   ? av_version(ccall((:avformat_version,   libavformat),   UInt32, ())) : v"0"
_avutil_version()     = have_avutil()     ? av_version(ccall((:avutil_version,     libavutil),     UInt32, ())) : v"0"
_swscale_version()    = have_swscale()    ? av_version(ccall((:swscale_version,    libswscale),    UInt32, ())) : v"0"
_avdevice_version()   = have_avdevice()   ? av_version(ccall((:avdevice_version,   libavdevice),   UInt32, ())) : v"0"
_avfilter_version()   = have_avfilter()   ? av_version(ccall((:avfilter_version,   libavfilter),   UInt32, ())) : v"0"
#_avresample_version() = have_avresample() ? av_version(ccall((:avresample_version, libavresample), UInt32, ())) : v"0"
#_swresample_version() = have_swresample() ? av_version(ccall((:swresample_version, libswresample), UInt32, ())) : v"0"

function versioninfo()
    println("Using ffmpeg")
    println("AVCodecs version $(_avcodec_version())")
    println("AVFormat version $(_avformat_version())")
    println("AVUtil version $(_avutil_version())")
    println("SWScale version $(_swscale_version())")
    println("AVDevice version $(_avdevice_version())")
    println("AVFilters version $(_avfilter_version())")
    #println("AVResample version $(_avresample_version())")
    #println("SWResample version $(_swresample_version())")
end

"""
    @ffmpeg_env arg

Runs `arg` within the build environment of FFMPEG.

## Examples

```jldoctest
julia> @ffmpeg_env run(`\$ffmpeg -version`)
ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
built with clang version 6.0.1 (tags/RELEASE_601/final)
[...]
```
"""
macro ffmpeg_env(arg)
    return esc(quote
        withenv(FFMPEG.execenv) do
            $(arg)
        end
    end)
end

"""
    exe(args...)

Execute the given commands as arguments to the given executable.

## Examples

```jldoctest
julia> FFMPEG.exe("-version")
ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
built with clang version 6.0.1 (tags/RELEASE_601/final)
[...]
```
"""
exe(args::AbstractString...; command = FFMPEG.ffmpeg, collect = false) = exe(Cmd([args...]), command=command, collect=collect)

"""
    collectexecoutput(exec::Cmd) -> Array of output lines

Takes the dominant output std from ffmpeg.
"""
function collectexecoutput(exec::Cmd)
    out = Pipe(); err = Pipe()
    p = Base.open(pipeline(ignorestatus(exec), stdout=out, stderr=err))
    close(out.in); close(err.in)
    err_s = readlines(err); out_s = readlines(out)
    return (length(out_s) > length(err_s)) ? out_s : err_s
end

"""
    exe(arg)

Execute the given command literal as an argument to the given executable.

## Examples

```jldoctest
julia> FFMPEG.exe(`-version`)
ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers
built with clang version 6.0.1 (tags/RELEASE_601/final)
[...]
```
"""
function exe(arg::Cmd; command = ffmpeg, collect = false)
    if collect
        withenv(execenv) do
            collectexecoutput(`$command $arg`)
        end
    else
        withenv(execenv) do
            Base.run(`$command $arg`)
        end
    end
end

"""
    ffmpeg_exe(arg::Cmd)
    ffmpeg_exe(args::String...)

Execute the given arguments as arguments to the `ffmpeg` executable.
"""
ffmpeg_exe(args...) = exe(args...; command = ffmpeg)

"""
    ffprobe_exe(arg::Cmd)
    ffprobe_exe(args::String...)

Execute the given arguments as arguments to the `ffprobe` executable.
"""
ffprobe_exe(args...) = exe(args...; command = ffprobe)

"""
    ffmpeg\`<ARGS>\`

Execute the given arguments as arguments to the `ffmpeg` executable.
"""
macro ffmpeg_cmd(arg)
    esc(:(ffmpeg_exe($arg)))
end

"""
    ffprobe\`<ARGS>\`

Execute the given arguments as arguments to the `ffprobe` executable.
"""
macro ffprobe_cmd(arg)
    esc(:(ffprobe_exe($arg)))
end

export ffmpeg_exe, @ffmpeg_env, ffprobe_exe, ffmpeg, ffprobe, @ffmpeg_cmd, @ffprobe_cmd, libavcodec, libavformat, libavutil, libswscale, libavfilter, libavdevice

end # module


text:
###
  Name     : c7_20_JuMP01.jl
  Book     : Hands-on Data Science with Anaconda )
  Publisher: Packt Publishing Ltd.
  Author   : Yuxing Yan and James Yan
  Date     : 3/15/2018
  email    : yany@canisius.edu
             paulyxy@hotmail.com
###

using JuMP
using ECOS
m= Model(solver =ECOSSolver())
@variable(m, 0 <= x <= 2 )
@variable(m, 0 <= y <= 30 )
@setObjective(m, Max, 5x + 3*y )
@addConstraint(m, 1x + 5y <= 3.0 )
print(m)
status = solve(m)
println("Objective value: ", getObjectiveValue(m))
println("x = ", getValue(x))
println("y = ", getValue(y))

#https://jump.readthedocs.io/en/release-0.2/jump.html


text:
function mats(p)
    p.A, p.B, p.K
end
function model_from_params(p, h, ny)
    A, B, K = mats(p)
    x0      = copy(p.x0)
    sys     = StateSpaceNoise(A, B, K, h)
    sysf    = SysFilter(sys, x0, similar(x0, ny))
end

function pem_costfun(p, y, u, h, metric::F) where {F} # To ensure specialization on metric
    nu, ny = obslength(u), obslength(y)
    model = model_from_params(p, h, ny)
    return mean(metric(e) for e in prediction_errors(model, y, u))
end
function sem_costfun(p, y, u, h, metric::F) where {F} # To ensure specialization on metric
    nu, ny = obslength(u), obslength(y)
    model = model_from_params(p, h, ny)
    return mean(metric(e) for e in simulation_errors(model, y, u))
end

"""
    sys, x0, opt = pem(data; nx, kwargs...)

System identification using the prediction-error method.

# Arguments:
- `data`: iddata object containing `y` and `u`.
    - `y`: Measurements, either a matrix with time along dim 2, or a vector of vectors
    - `u`: Control signals, same structure as `y`
- `nx`: Number of poles in the estimated system. Thus number should be chosen as number of system poles plus number of poles in noise models for measurement noise and load disturbances.
- `focus`: Either `:prediction` or `:simulation`. If `:simulation` is chosen, a two stage problem is solved with prediction focus first, followed by a refinement for simulation focus.
- `metric`: A Function determining how the size of the residuals is measured, default `sse` (e'e), but any Function such as `norm`, `e->sum(abs,e)` or `e -> e'Q*e` could be used.
- `regularizer(p)=0`: function for regularization. The structure of `p` is detailed below
- `solver` Defaults to `Optim.BFGS()`
- `stabilize_predictor=true`: Modifies the estimated Kalman gain `K` in case `A-KC` is not stable by moving all unstable eigenvalues to the unit circle.
- `difficult=false`: If the identification problem appears to be difficult and ends up in a local minimum, set this flag to true to solve an initial global optimization problem to supply a good initial guess. This is expected to take some time.
- `kwargs`: additional keyword arguments are sent to `Optim.Options`.

# Return values
- `sys::StateSpaceNoise`: identified system. Can be converted to `StateSpace` by `convert(StateSpace, sys)`, but this will discard the Kalman gain matrix.
- `x0`: Estimated initial state
- `opt`: Optimization problem structure. Contains info of the result of the optimization problem

## Structure of parameter vector `p`
The parameter vector is of type [`ComponentVector`](https://github.com/jonniedie/ComponentArrays.jl) and the fields `A,B,K,x0` can be accessed as `p.A` etc. The internal storage is according to
```julia
A = size(nx,nx)
B = size(nx,nu)
K = size(nx,ny)
x0 = size(nx)
p = [A[:]; B[:]; K[:]; x0]
```
"""
function pem(
    d;
    nx,
    solver              = BFGS(),
    focus               = :prediction,
    metric              = sse,
    regularizer         = p -> 0,
    iterations          = 1000,
    stabilize_predictor = true,
    difficult           = false,
    A                   = 0.0001randn(nx, nx),
    B                   = 0.001randn(nx, obslength(input(d))),
    # C                   = 0.001randn(obslength(output(d)), nx),
    K                   = 0.001randn(nx, obslength(output(d))),
    x0                  = 0.001randn(nx),
    kwargs...,
)

    y, u = output(d), input(d)
    nu, ny = obslength(u), obslength(y)
    if size(A,1) != size(A,2) # Old API
        A = [A zeros(nx, nx-ny)]
    end
    p = ComponentVector((; A, B, K, x0))
    options = Options(; iterations = iterations, kwargs...)
    cost_pred = p -> pem_costfun(p, y, u, d.Ts, metric) + regularizer(p)
    if difficult
        stabilizer = p -> 10000 * !stabfun(d.Ts, ny)(p)
        options0 = Options(; iterations = iterations, kwargs...)
        opt = optimize(
            p -> cost_pred(p) + stabilizer(p),
            1000p,
            # ParticleSwarm(n_particles = 100length(p)),
            NelderMead(),
            options0,
        )
        p = minimizer(opt)
    end
    opt = optimize(cost_pred, p, solver, options; autodiff = :forward)
    println(opt)
    if focus == :simulation
        @info "Focusing on simulation"
        cost_sim = p -> sem_costfun(p, y, u, d.Ts, metric) + regularizer(p)
        opt = optimize(
            cost_sim,
            minimizer(opt),
            NewtonTrustRegion(),
            Options(; iterations = iterations ÷ 2, kwargs...);
            autodiff = :forward,
        )
        println(opt)
    end
    model = model_from_params(minimizer(opt), d.Ts, ny)
    if !isstable(model.sys)
        @warn("Estimated system does not have a stable prediction filter (A-KC)")
        if stabilize_predictor
            @info("Stabilizing predictor")
            # model = stabilize(model)
            model = stabilize(model, solver, options, cost_pred)
        end
    end
    isstable(ss(model.sys)) || @warn("Estimated system is not stable")

    model.sys, copy(model.state), opt
end

function stabilize(model)
    s            = model.sys
    @unpack A, K = s
    C            = s.C
    poles        = eigvals(A - K * C)
    newpoles     = map(poles) do p
        ap = abs(p)
        ap <= 1 && (return p)
        p / (ap + sqrt(eps()))
    end
    K2           = ControlSystems.acker(A', C', newpoles)' .|> real
    all(abs(p) <= 1 for p in eigvals(A - K * C)) || @warn("Failed to stabilize predictor")
    s.K .= K2
    model
end

function stabilize(model, solver, options, cfi)
    s = model.sys
    cost = function (p)
        maximum(abs.(eigvals(s.A - p * s.K * s.C))) - 0.9999999
    end
    p = fzero(cost, 1e-9, 1 - 1e-9)
    s.K .*= p
    model
end

function stabfun(h, ny)
    function (p)
        model = model_from_params(p, h, ny)
        isstable(model.sys)
    end
end


text:
# This file is a part of Julia. License is MIT: https://julialang.org/license

using Documenter, DocumenterLaTeX
using Pkg

include("generate.jl")

const formats = Any[
    Documenter.HTML(
        prettyurls = get(ENV, "CI", nothing) == "true",
        canonical = "https://julialang.github.io/Pkg.jl/v1/",
        assets = ["assets/custom.css"],
    ),
]
if "pdf" in ARGS
    push!(formats, LaTeX(platform = "docker"))
end

# setup for doctesting
DocMeta.setdocmeta!(Pkg.BinaryPlatforms, :DocTestSetup, :(using Pkg.BinaryPlatforms); recursive=true)

makedocs(
    format = formats,
    modules = [Pkg],
    sitename = "Pkg.jl",
    pages = Any[
        "index.md",
        "getting-started.md",
        "managing-packages.md",
        "environments.md",
        "creating-packages.md",
        "compatibility.md",
        "registries.md",
        "artifacts.md",
        # "faq.md",
        "glossary.md",
        "toml-files.md",
        "repl.md",
        "api.md",
    ],
)

mktempdir() do tmp
    # Hide the PDF from html-deploydocs
    build = joinpath(@__DIR__, "build")
    files = readdir(build)
    idx = findfirst(f -> startswith(f, "Pkg.jl") && endswith(f, ".pdf"), files)
    pdf = idx === nothing ? nothing : joinpath(build, files[idx])
    if pdf !== nothing
        pdf = mv(pdf, joinpath(tmp, basename(pdf)))
    end
    # Deploy HTML pages
    @info "Deploying HTML pages"
    deploydocs(
        repo = "github.com/JuliaLang/Pkg.jl",
        versions = ["v#.#", "dev" => "dev"],
    )
    # Put back PDF into docs/build/pdf
    mkpath(joinpath(build, "pdf"))
    if pdf !== nothing
        pdf = mv(pdf, joinpath(build, "pdf", basename(pdf)))
    end
    # Deploy PDF
    @info "Deploying PDF"
    deploydocs(
        repo = "github.com/JuliaLang/Pkg.jl",
        target = "build/pdf",
        branch = "gh-pages-pdf",
        forcepush = true,
    )
end


text:
using Polyhedra
using Base.Test

A = [1 1; -1 0; 0 -1]
b = [1, 0, 0]
linset = IntSet([1])

@test_throws ErrorException SimpleHRepresentation(A, [0, 0], linset)
@test_throws ErrorException SimpleHRepresentation(A, [0, 0], IntSet([4]))
ine = SimpleHRepresentation(A, b, linset)
@test fulldim(ine) == 2
@test eltype(ine) == Int

V = [0 1; 1 0]
@test_throws ErrorException SimpleVRepresentation(V, [1 0 0], IntSet([]), IntSet([]))
@test_throws ErrorException SimpleVRepresentation(V, [1 1], IntSet([]), IntSet([2]))
@test_throws ErrorException SimpleVRepresentation(V, [1 1], IntSet([4]), IntSet([]))
@test_throws ErrorException SimpleVRepresentation(V, IntSet([4]))
ext = SimpleVRepresentation(V)
@test fulldim(ext) == 2
@test eltype(ext) == Int


text:
using Test, LinearMaps, LinearAlgebra

@testset "kronecker products" begin
    @testset "Kronecker product" begin
        A = rand(ComplexF64, 3, 3)
        B = rand(ComplexF64, 2, 2)
        K = kron(A, B)
        LA = LinearMap(A)
        LB = LinearMap(B)
        LK = @inferred kron(LA, LB)
        @test @inferred size(LK) == size(K)
        @test LinearMaps.MulStyle(LK) === LinearMaps.ThreeArg()
        for i in (1, 2)
            @test @inferred size(LK, i) == size(K, i)
        end
        @test LK isa LinearMaps.KroneckerMap{ComplexF64}
        for transform in (identity, transpose, adjoint)
            @test Matrix(transform(LK)) ≈ transform(Matrix(LK)) ≈ transform(kron(A, B))
            @test Matrix(kron(transform(LA), transform(LB))) ≈ transform(kron(A, B))
            @test Matrix(transform(LinearMap(LK))) ≈ transform(Matrix(LK)) ≈ transform(kron(A, B))
        end
        @test kron(LA, kron(LA, B)) == kron(LA, LA, LB)
        @test kron(kron(LA, LB), kron(LA, LB)) == kron(LA, LB, LA, LB)
        @test kron(A, A, A) ≈ Matrix(@inferred kron(LA, LA, LA)) ≈ Matrix(@inferred LA^⊗(3)) ≈ Matrix(@inferred A^⊗(3))
        K = @inferred kron(A, A, A, LA)
        @test K isa LinearMaps.KroneckerMap
        @test Matrix(K) ≈ kron(A, A, A, A)
        @test Matrix(@inferred K*K) ≈ kron(A, A, A, A)*kron(A, A, A, A)
        K4 = @inferred kron(A, B, B, LB)
        # check that matrices don't get Kronecker-multiplied, but that all is lazy
        @test K4.maps[1].lmap === A
        @test @inferred kron(LA, LB)' == @inferred kron(LA', LB')
        @test (@inferred kron(LA, B)) == (@inferred kron(LA, LB)) == (@inferred kron(A, LB))
        @test @inferred ishermitian(kron(LA'LA, LB'LB))
        A = rand(2, 5); B = rand(4, 2)
        K = @inferred kron(A, LinearMap(B))
        @test Matrix(K) ≈ kron(A, B)
        K = @inferred kron(LinearMap(B), A)
        @test Matrix(K) ≈ kron(B, A)
        A = rand(3, 3); B = rand(2, 2); LA = LinearMap(A); LB = LinearMap(B)
        @test @inferred issymmetric(kron(LA'LA, LB'LB))
        @test @inferred ishermitian(kron(LA'LA, LB'LB))
        # use mixed-product rule
        K = kron(LA, LB) * kron(LA, LB) * kron(LA, LB)
        @test Matrix(K) ≈ kron(A, B)^3
        # example that doesn't use mixed-product rule
        A = rand(3, 2); B = rand(2, 3)
        K = @inferred kron(A, LinearMap(B))
        @test Matrix(@inferred K*K) ≈ kron(A, B)*kron(A, B)
        A = rand(3, 2); B = rand(4, 3)
        @test Matrix(kron(LinearMap(A), B, [A A])*kron(LinearMap(A), B, A')) ≈ kron(A, B, [A A])*kron(A, B, A')
    end
    @testset "Kronecker sum" begin
        for elty in (Float64, ComplexF64)
            A = rand(elty, 3, 3)
            B = rand(elty, 2, 2)
            LA = LinearMap(A)
            LB = LinearMap(B)
            KS = @inferred kronsum(LA, B)
            KSmat = kron(A, Matrix(I, 2, 2)) + kron(Matrix(I, 3, 3), B)
            @test Matrix(KS) ≈ Matrix(kron(A, LinearMap(I, 2)) + kron(LinearMap(I, 3), B))
            @test size(KS) == size(kron(A, Matrix(I, 2, 2)))
            for transform in (identity, transpose, adjoint)
                @test Matrix(transform(KS)) ≈ transform(Matrix(KS)) ≈ transform(KSmat)
                @test Matrix(kronsum(transform(LA), transform(LB))) ≈ transform(KSmat)
                @test Matrix(transform(LinearMap(kronsum(LA, LB)))) ≈ Matrix(transform(KS)) ≈ transform(KSmat)
            end
            @test @inferred(kronsum(A, A, LB)) == @inferred(⊕(A, A, B))
            @test Matrix(@inferred LA^⊕(3)) == Matrix(@inferred A^⊕(3)) ≈ Matrix(kronsum(LA, A, A))
            @test @inferred(kronsum(LA, LA, LB)) == @inferred(kronsum(LA, kronsum(LA, LB))) == @inferred(kronsum(A, A, B))
            @test Matrix(@inferred kronsum(A, B, A, B, A, B)) ≈ Matrix(@inferred kronsum(LA, LB, LA, LB, LA, LB))
        end
    end
end


text:
# ------------------------------------------------------------------
# Licensed under the ISC License. See LICENSE in the project root.
# ------------------------------------------------------------------

"""
    AbstractErrorEstimator

A method for estimating error of geostatistical solvers.
"""
abstract type AbstractErrorEstimator end

"""
    error(solver, problem, eestimator)

Estimate error of `solver` in a given `problem` with
`eestimator` error estimation method.
"""
Base.error(::AbstractSolver, ::AbstractProblem,
           ::AbstractErrorEstimator) = @error "not implemented"

#------------------
# IMPLEMENTATIONS
#------------------
include("errors/leave_ball_out.jl")
include("errors/cross_validation.jl")
include("errors/block_cross_validation.jl")
include("errors/ball_sample_validation.jl")
include("errors/weighted_hold_out.jl")
include("errors/weighted_cross_validation.jl")
include("errors/weighted_bootstrap.jl")
include("errors/density_ratio_validation.jl")


text:
"""
    mixture_gauss_moments(prim::AbstractMatrix{T}, inK) where {T<:Real}

Calculate moments of Gaussian distribution in multi-component gas
"""
function mixture_gauss_moments(prim::AbstractMatrix{T}, inK) where {T<:Real}
    if eltype(prim) <: Integer
        Mu = OffsetArray(similar(prim, Float64, 7, axes(prim, 2)), 0:6, axes(prim, 2))
    else
        Mu = OffsetArray(similar(prim, 7, axes(prim, 2)), 0:6, axes(prim, 2))
    end

    MuL = similar(Mu)
    MuR = similar(Mu)

    if size(prim, 1) == 3

        Mxi = similar(Mu, 0:2, axes(prim, 2))
        for j in axes(prim, 2)
            _tu, _txi, _tuL, _tuR = gauss_moments(prim[:, j], inK)

            Mu[:, j] .= _tu
            Mxi[:, j] .= _txi
            MuL[:, j] .= _tuL
            MuR[:, j] .= _tuR
        end

        return Mu, Mxi, MuL, MuR

    elseif size(prim, 1) == 4

        Mv = similar(Mu)
        Mxi = similar(Mu, 0:2, axes(prim, 2))
        for j in axes(prim, 2)
            _tu, _tv, _txi, _tuL, _tuR = gauss_moments(prim[:, j], inK)

            Mu[:, j] .= _tu
            Mv[:, j] .= _tv
            Mxi[:, j] .= _txi
            MuL[:, j] .= _tuL
            MuR[:, j] .= _tuR
        end

        return Mu, Mv, Mxi, MuL, MuR

    elseif size(prim, 1) == 5

        Mv = similar(Mu)
        Mw = similar(Mu)

        for j in axes(prim, 2)
            _tu, _tv, _tw, _tuL, _tuR = gauss_moments(prim[:, j], inK)

            Mu[:, j] .= _tu
            Mv[:, j] .= _tv
            Mw[:, j] .= _tw
            MuL[:, j] .= _tuL
            MuR[:, j] .= _tuR
        end

        return Mu, Mv, Mw, MuL, MuR

    end
end

"""
    mixture_moments_conserve(
        Mu::T,
        Mxi::T,
        alpha::I,
        delta::I,
    ) where {T<:OffsetArray{<:Real,2},I<:Int}

    function mixture_moments_conserve(
        Mu::T,
        Mv::T,
        Mw::T,
        alpha::I,
        beta::I,
        delta::I,
    ) where {T<:OffsetArray{<:Real,2},I<:Int}

Calculate conservative moments of particle distribution in multi-component gas
"""
function mixture_moments_conserve(
    Mu::T,
    Mxi::T,
    alpha::I,
    delta::I,
) where {T<:OffsetArray{<:Real,2},I<:Integer}

    Muv = similar(Mu, 3, size(Mu, 2))
    for j in axes(Muv, 2)
        Muv[:, j] .= moments_conserve(Mu[:, j], Mxi[:, j], alpha, delta)
    end

    return Muv

end

function mixture_moments_conserve(
    Mu::T,
    Mv::T,
    Mw::T,
    alpha::I,
    beta::I,
    delta::I,
) where {T<:OffsetArray{<:Real,2},I<:Integer}

    Muv = ifelse(size(Mw, 1) == 3, similar(Mu, 4, size(Mu, 2)), similar(Mu, 5, size(Mu, 2)))
    for j in axes(Muv, 2)
        Muv[:, j] .= moments_conserve(Mu[:, j], Mv[:, j], Mw[:, j], alpha, beta, delta)
    end

    return Muv

end

# ------------------------------------------------------------
# Discrete moments of conservative variables
# ------------------------------------------------------------
#--- 1F1V ---#
function mixture_moments_conserve(
    f::X,
    u::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,2},T<:AbstractArray{<:AbstractFloat,2}}

    w = similar(f, 3, size(f, 2))
    for j in axes(w, 2)
        w[:, j] .= moments_conserve(f[:, j], u, ω)
    end

    return w

end

#--- 2F1V ---#
function mixture_moments_conserve(
    h::X,
    b::X,
    u::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,2},T<:AbstractArray{<:AbstractFloat,2}}

    w = similar(h, 3, size(h, 2))
    for j in axes(w, 2)
        w[:, j] .= moments_conserve(h[:, j], b[:, j], u, ω)
    end

    return w

end

#--- 4F1V ---#
function mixture_moments_conserve(
    h0::X,
    h1::X,
    h2::X,
    h3::X,
    u::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,2},T<:AbstractArray{<:AbstractFloat,2}}

    moments = similar(h0, 5, size(h0, 2))
    for j in axes(moments, 2)
        moments[:, j] .=
            moments_conserve(h0[:, j], h1[:, j], h2[:, j], h3[:, j], u[:, j], ω[:, j])
    end

    return moments

end

#--- 1F2V ---#
function mixture_moments_conserve(
    f::X,
    u::T,
    v::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,3},T<:AbstractArray{<:AbstractFloat,3}}

    w = similar(f, 4, size(f, 3))
    for j in axes(w, 2)
        w[:, j] .= moments_conserve(f[:, :, j], u[:, :, j], v[:, :, j], ω[:, :, j])
    end

    return w

end

#--- 2F2V ---#
function mixture_moments_conserve(
    h::X,
    b::X,
    u::T,
    v::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,3},T<:AbstractArray{<:AbstractFloat,3}}

    w = similar(h, 4, size(f, 3))
    for j in axes(w, 2)
        w[:, j] .=
            moments_conserve(h[:, :, j], b[:, :, j], u[:, :, j], v[:, :, j], ω[:, :, j])
    end

    return w

end

#--- 3F2V ---#
function mixture_moments_conserve(
    h0::X,
    h1::X,
    h2::X,
    u::T,
    v::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,3},T<:AbstractArray{<:AbstractFloat,3}}

    w = similar(h0, 5, size(h0, 3))
    for j in axes(w, 2)
        w[:, j] .= moments_conserve(
            h0[:, :, j],
            h1[:, :, j],
            h2[:, :, j],
            u[:, :, j],
            v[:, :, j],
            ω[:, :, j],
        )
    end

    return w

end

#--- 1F3V ---#
function mixture_moments_conserve(
    f::X,
    u::T,
    v::T,
    w::T,
    ω::T,
) where {X<:AbstractArray{<:AbstractFloat,4},T<:AbstractArray{<:AbstractFloat,4}}

    moments = similar(f, 5, size(f, 4))
    for j in axes(w, 2)
        moments[:, j] .= moments_conserve(
            f[:, :, :, j],
            u[:, :, :, j],
            v[:, :, :, j],
            w[:, :, :, j],
            ω[:, :, :, j],
        )
    end

    return moments

end

"""
mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mxi::Y,
    alpha::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mv::Y,
    Mxi::Y,
    alpha::I,
    beta::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mv::Y,
    Mw::Y,
    alpha::I,
    beta::I,
    delta::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

Calculate slope-related conservative moments under the assumption
`a = a1 + u * a2 + 0.5 * u^2 * a3`

"""
function mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mxi::Y,
    alpha::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

    au = similar(a, 3, axes(a, 2))
    for j in axes(au, 2)
        au[:, j] .= moments_conserve_slope(a[:, j], Mu[:, j], Mxi[:, j], alpha)
    end

    return au

end

function mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mv::Y,
    Mxi::Y,
    alpha::I,
    beta::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

    au = similar(a, 4, axes(a, 2))
    for j in axes(au, 2)
        au[:, j] .=
            moments_conserve_slope(a[:, j], Mu[:, j], Mv[:, j], Mxi[:, j], alpha, beta)
    end

    return au

end

function mixture_moments_conserve_slope(
    a::X,
    Mu::Y,
    Mv::Y,
    Mw::Y,
    alpha::I,
    beta::I,
    delta::I,
) where {X<:AbstractArray{<:Real,2},Y<:OffsetArray{<:Real,2},I<:Integer}

    au = similar(a, 5, axes(a, 2))
    for j in axes(au, 2)
        au[:, j] .= moments_conserve_slope(
            a[:, j],
            Mu[:, j],
            Mv[:, j],
            Mw[:, j],
            alpha,
            beta,
            delta,
        )
    end

    return au

end


text:
function write_and_readchomp(data, cmd::Cmd)
    r, w, p = readandwrite(cmd)
    print(w,data); close(w)
    v = readchomp(r)
    wait(p)
    return v
end

function mktree(d::Dict)
    lstree = ""
    for (name, data) in d
        if isa(data, String)
            sha1 = write_and_readchomp(data, `git hash-object -w --stdin`)
            lstree *= "100644 blob $sha1\t$name\n"
        elseif isa(data, Dict)
            sha1 = mktree(data)
            lstree *= "040000 tree $sha1\t$name\n"
        elseif is(data, nothing)
            # ignore it
        else
            error("mktree: don't know what to do with $name => $data")
        end
    end
    write_and_readchomp(lstree, `git mktree`)
end

function verify_tree(d::Dict, tree::String)
    # check that tree matches d
    seen = Set()
    for line in eachline(`git ls-tree $tree`)
        m = match(r"^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$", line)
        @test m != nothing
        perm, kind, sha1, name = m.captures
        @test haskey(d,name)
        data = d[name]
        if isa(data, String)
            @test kind == "blob"
            @test data == readall(`git cat-file blob $sha1`)
        elseif isa(data, Dict)
            @test kind == "tree"
            verify_tree(data, sha1)
        else
            error("verify_tree: don't know what to do with $name => $data")
        end
        push!(seen, name)
    end
    # check that nothing was missing from tree
    for (name, data) in d
        @test is(data,nothing) || in(name,seen)
    end
end

function verify_work(d::Dict)
    # check what's in d
    for (name, data) in d
        if is(data, nothing)
            @test !ispath(name)
            continue
        end
        @test ispath(name)
        if isa(data, String)
            @test isfile(name)
            @test readall(name) == data
        elseif isa(data, Dict)
            cd(name) do
                verify_work(data)
            end
        else
            error("verify_work: don't know what to do with $name => $data")
        end
    end
    # check for anything that's not in d
    for line in eachline(`ls -A`)
        name = chomp(line)
        @test name == ".git" || haskey(d,name)
    end
end

function git_verify(h::Dict, i::Dict, w::Dict)
    verify_tree(h, "HEAD")
    verify_tree(i, readchomp(`git write-tree`))
    verify_work(w)
end

function git_setup(h::Dict, i::Dict, w::Dict, parents::String...)
    # create tree objects
    headt = mktree(h)
    index = mktree(i)
    work  = mktree(w)

    # clear the repo
    for line in eachline(`ls -A`)
        name = chomp(line)
        name == ".git" || rm(name, recursive=true)
    end

    # create the head commit
    commit_tree = `git commit-tree $headt`
    for parent in parents
        commit_tree = `$commit_tree -p $parent`
    end
    head = write_and_readchomp(headt, commit_tree)
    run(`git reset -q --soft $head`)

    run(`git read-tree $work`)      # read work into the index
    run(`git checkout-index -fa`)   # check the index out
    run(`git read-tree $index`)     # setup the index

    # verify that everything is as expected
    git_verify(h, i, w)
end
git_setup(h::Dict, i::Dict, w::Dict) = git_setup(h, i, w, readchomp(`git rev-parse HEAD`))

max_stars_repo_name: jakebolewski/julia

max_issues_repo_name: jakebolewski/julia

max_forks_repo_name: jakebolewski/julia


text:
module LearnBenchmark

export bayeserror

#########################################################
#########################################################
################### Hash Map Scheme #####################
#########################################################
#########################################################

"""
    hashblock(x, b, ϵ)::Integer

Converts a scalar `x` to an integer through `floor((x+b)/ϵ)`
"""
function hashblock(x, b, ϵ)::Integer
    return floor((x + b)/ϵ)
end

"""
    FiniteHashBlock

Functor defining the randomized hashmap.
Defined function returns H(floor((x+b)/ϵ)),
where H is a random map from integers to a
set of the given `cardinality`.

### Constructor

    FiniteHashBlock(cardinality,b,ϵ,maxvalue)

 - `cardinality` - Cardinality of output hash
 - `b`           - Shift of input
 - `ϵ`           - Input Scaling
 - `maxvalue`    - maximum value of function input for each dimension

### Defined Function Definition

    (h::FiniteHashBlock)(x)

### Example Usage

    cardinality = 2
    b = 0
    ϵ = 1
    maxvalue = 10
    h = FiniteHashBlock(cardinality, b, ϵ, maxvalue)

    hashed = h(rand())
    @test hashed == 1 || hashed == 2
"""
struct FiniteHashBlock
    cardinality::Integer
    b::Real
    ϵ::Real
    indexmap::Array{Integer}

    function FiniteHashBlock(cardinality,b,ϵ,maxvalue)
        maxargs = map((x) -> hashblock(x,b,ϵ), maxvalue)
        indexmap = rand(1:cardinality,maxargs...)

        return new(cardinality, b, ϵ, indexmap)
    end
end

function (h::FiniteHashBlock)(x)
    return h.indexmap[hashblock(x,h.b,h.ϵ)...]
end

"""
    countpoints_hash(X, h::FiniteHashBlock)

Count the number of points that occur in each hash bin
for each given class of data.

### Arguments
 - `X` - Array of Arrays of datapoints
 - `h` - Hash function

### Returns
A matrix of dimensionality `size(X)[1]` × `h.cardinality`, where each column
corresponds to the count of datapoints for each class in a given bin.
"""
function countpoints_hash(X, h::FiniteHashBlock)
    out = zeros(size(X)[1],h.cardinality)

    for class in 1:size(X)[1]
        dataset = X[1]
        for i in 1:size(dataset)[2]
            out[class, h(X[:,i])] += 1
        end
    end

    return out
end

#########################################################
#########################################################
################# Ensemble Learner ######################
#########################################################
#########################################################

"""
    ensemblelearner(X, L, bound_ratio, scale=10, offset=1)

### Arguments
 - `X`              -   Data as an array of λ matrices of shape M × Nᵢ
 - `L`              -   Number of ϵ-balls
 - `bound_ratio`    -   Ratio of density bounds CL/CU
 - `scale`          -   Scaling for radii
 - `offset`         -   Offset for radii

### Returns
An estimate of the Bayes error based on ϵ-balls with a chosen number of radii.
"""
function ensemblelearner(X, L, bound_ratio, scale=10, offset=1)
    N = [size(data)[2] for data in X]
    d = size(X[1])[1]
    λ = length(N)

    prior = N./sum(N)
    ϵ² = chebyshev_roots(L).^2 ./ (N[1] .^(1/d))
    ϵ² = ϵ² / maximum(ϵ²)*scale .+ offset
    weights = chebyshev_weights(L, d)

    ratios = zeros(λ,L)

    estimate = 0

    # For Each Class
    for l in 2:λ

        # For each datapoint in the class
        for i in 1:N[l]
            # Set center of ϵ-ball
            center = @view X[l][:,i]

            # For each radius
            for k in 1:L
                # Compute estimates of density ratios
                density_ratio_estimator!(   view(ratios,1:l,k),
                                            center,
                                            ϵ²[k],
                                            view(X,1:l))
            end
            # Weight Ratios
            weighted_ratios = ratios * weights

            # update estimate
            estimate += tₖ_bar( prior[1:l],
                                weighted_ratios[1:l],
                                bound_ratio) / N[l]
        end
    end

    return 1 - prior[1] - estimate
end

"""
    bayeserror(X, L, bound_ratio)

### Arguments
 - `X`              -   Data as an array of λ matrices of shape M × Nᵢ
 - `L`              -   Number of ϵ-balls
 - `bound_ratio`    -   Ratio of density bounds CL/CU
 - `scale`          -   Scaling for radii
 - `offset`         -   Offset for radii

### Returns
An estimate of the Bayes error based on ϵ-balls
"""
bayeserror(X, L, bound_ratio, scale=10, offset=1) = ensemblelearner(X, L, bound_ratio, scale, offset)

#########################################################
#########################################################
##################### Weak Learner ######################
#########################################################
#########################################################

"""
    baselearner(X, ϵ², bound_ratio)

### Arguments
 - `X`              -   Data as an array of λ matrices of shape M × Nᵢ
 - `ϵ²`             -   Sets radius of ϵ-ball
 - `bound_ratio`    -   Ratio of density bounds CL/CU

### Returns
An estimate of the Bayes error based on ϵ-balls with a given radius.
"""
function baselearner(X, ϵ², bound_ratio)
    N = [size(data)[2] for data in X]
    d = size(X[1])[1]
    λ = length(N)

    prior = N./sum(N)

    ratios = zeros(λ)

    estimate = 0

    # For Each Class
    for l in 2:λ

        # For each datapoint in the class
        for i in 1:N[l]
            # Set center of ϵ-ball
            center = @view X[l][:,i]

            density_ratio_estimator!(   view(ratios,1:l),
                                        center,
                                        ϵ²,
                                        view(X,1:l))

            # update estimate
            estimate += tₖ_bar( prior[1:l],
                                ratios[1:l],
                                bound_ratio) / N[l]
        end
    end

    return 1 - prior[1] - estimate
end
export baselearner

"""
    countpoints(center, ϵ², dataset)

Counts the number of points in the intersection of a dataset
and an ϵ-ball specified by its center and radius.

### Arguments
 - `center` - Center of ϵ-ball
 - `ϵ²`     - Squared radius of ϵ-ball
 - `dataset`- Dataset to count, N × M matrix with N different points

### Returns
The number of points from `dataset` within the specified ϵ-ball
"""
function countpoints(center, ϵ², dataset)
    M, N = size(dataset)
    count = 0

    for i in 1:N
        if sum((x) -> x^2, dataset[:,i] - center) < ϵ²
            count += 1
        end
    end

    return count
end

"""
    density_ratio_estimator!(ratios,center, ϵ², dataset)

Construct the set of density ratio estimators for a given ϵ-ball.
This corresponds to the weak learner in this algorithm

### Arguments
 - `ratios` - Stores density ratio estimates
 - `center` - Center of the ϵ-ball
 - `ϵ²`     - Defines radius of ϵ-ball
 - `dataset`- Dataset for learner
"""
function density_ratio_estimator!(ratios,center, ϵ², dataset)
    l = size(dataset)[1]

    # For each previous class, count points
    for j in 1:l
        ratios[j] = countpoints(center,ϵ²,dataset[j])
    end

    # Normalize to construct ratios
    ratios[1:l-1] ./= ratios[l]
end

#########################################################
#########################################################
################ Divergence Functions ###################
#########################################################
#########################################################

"""
    tₖ(prior,data)

Divergence function used in the paper

### Arguments
 - `prior`  - prior distribution based on number of points
 - `data`   - function inputs based on local density
"""
function tₖ(prior,data)
    return max(0, prior[end] - maximum(prior[1:end-1] .* data[1:end-1]))
end

"""
    tₖ_bar(prior, data, bound_ratio)

Divergence function used in the paper

### Arguments
 - `prior`          - prior distribution based on number of points
 - `data`           - function inputs based on local density
 - `bound_ratio`    - Ratio of density bounds CL/CU
"""
function tₖ_bar(prior, data, bound_ratio = 1e-4)
    bound_ratio_array = [bound_ratio for i in 1:length(prior)]

    return min(     tₖ(prior,data),
                    tₖ(prior,bound_ratio_array))
end

#########################################################
#########################################################
################# Weight Computation ####################
#########################################################
#########################################################

"""
    chebyshev_weights(L, d)

Computes the optimal weights for the ensemble learner
"""
function chebyshev_weights(L, d, α=.5)
    @assert L ≥ d

    roots = chebyshev_roots(L, α)

    weights = zeros(L)
    weights .-= 1/L
    for i in 1:L
        for k in 0:d
            tmp  = chebyshev_poly_scaled(0,k, α)
            tmp *= chebyshev_poly_scaled(roots[i],k, α)
            tmp *= 2/L

            weights[i] += tmp
        end
    end

    return weights
end

"""
    chebyshev_roots(L)

Computes the roots of an L+1'th order Chebyshev polynomial
scaled horizontally by a factor of 2
"""
function chebyshev_roots(L, α=.5)
    roots = zeros(L)
    for i in 1:L
        roots[i] = cos((i - 0.5) * π/L)*α/2 + α/2
    end
    return roots
end

"""
    chebyshev_poly_scaled(x, k)

Evaluates the k'th Chebyshev polynomial at x after horizontal scaling by 2 and shifting by 1
"""
function chebyshev_poly_scaled(x, k, α=.5)
    return chebyshev_poly(x*2/α - 1, k)
end

"""
chebyshev_poly(x, k)

Evaluates the k'th Chebyshev polynomial at x
"""
function chebyshev_poly(x, k)
    if  k == 0
        return 1
    end
    d = 1
    out = x
    out_old = 1
    for i = d+1:k
        tmp = out
        out = 2*x*out - out_old
        out_old = tmp
    end
    return out
end

end


text:
mutable struct DuelingDouble_DeepQPolicy <: QPolicy
    primaryBaseNetwork   # Neural Netowrk for running before V and A networks
    primaryVNetwork      # Neural Network for Value function
    primaryANetwork      # Neural Network for Advantage function
    targetBaseNetwork    # Holds target values - call update_target to copy into this
    targetVNetwork       # Holds target values - call update_target to copy into this
    targetANetwork       # Holds target values - call update_target to copy into this
end
DuelingDouble_DeepQPolicy(primaryBase, primaryV, primaryA) = DuelingDouble_DeepQPolicy(primaryBase, primaryV, primaryA,
                                                                                deepcopy(primaryBase), deepcopy(primaryV), deepcopy(primaryA))

function get_QValues(policy::DuelingDouble_DeepQPolicy, inputs; primary=true)
    if primary
        baseresults = policy.primaryBaseNetwork(inputs)
        Aresults = policy.primaryANetwork(baseresults)
        return policy.primaryVNetwork(baseresults) .+ Aresults .- mean(Aresults, dims=1)
    else
        baseresults = policy.targetBaseNetwork(inputs)
        Aresults = policy.targetANetwork(baseresults)
        return policy.targetVNetwork(baseresults) .+ Aresults .- mean(Aresults, dims=1)
    end
end

function get_target(policy::DuelingDouble_DeepQPolicy, γ, r, done, s′)
    a_batch = argmax(get_QValues(policy, s′), dims=1)
    target = dropdims(r .+ γ.*(1.0 .- done).*get_QValues(policy, s′, primary=false)[a_batch], dims=1)
end

get_params(policy::DuelingDouble_DeepQPolicy) = Flux.params(policy.primaryBaseNetwork, policy.primaryVNetwork, policy.primaryANetwork)

function update_target(policy::DuelingDouble_DeepQPolicy)
    Flux.loadparams!(policy.targetBaseNetwork, Flux.params(policy.primaryBaseNetwork))
    Flux.loadparams!(policy.targetVNetwork,    Flux.params(policy.primaryVNetwork))
    Flux.loadparams!(policy.targetANetwork,    Flux.params(policy.primaryANetwork))
end

# Only need to run the advantage network since everything else is the same regardless of action
function action(policy::MooreDDQN.DuelingDouble_DeepQPolicy, r, s::S, A) where {S}
    baseresults = policy.primaryBaseNetwork(s())
    advantage = policy.primaryANetwork(baseresults)
    argmax(advantage)[1]
end


text:
using Omega
using Test

function testargmax()
  ## Model
  x = 1 ~ Uniform(0.0, 1.0)
  y = normal(0.0, 10.0)
  xisy = x ==ₛ y
  # loss = ω -> Omega.logerr(xisy(ω))   # Extract logerror
  loss = logerr(xisy)
  ω = argmax(loss)
  @test isapprox(x(ω), y(ω); atol = 0.01)
end

testargmax()

max_stars_repo_name: zenna/expect

max_issues_repo_name: zenna/expect

max_forks_repo_name: zenna/expect


text:
function devsetup()
    Base.depwarn("WebIO.devsetup() is no longer required. You can simply run WebIO.bundlejs().", :webio_devesetup)
end

function bundlejs(;watch=false)
    if watch
        ENV["WEBIO_WEBPACK_ARGS"] = "--watch"
    end
    build_dir = joinpath(dirname(@__FILE__), "..", "deps")
    # how do I pass an argument into this?
    include(joinpath(build_dir, "_bundlejs.jl"))
end


text:
#!/usr/bin/env julia

# There are a lot of Julia examples that use the REPL and not
# scripting. For something as simples as @printf, you need to
# use the 'using Printf' which is Julia's equivalent to import
# or include. That's because printf was moved out of core Julia
# in the Julia 1.0 release.

using Printf

# Simple function to calculate the volume of a sphere.
#
VolumeSphere(r) = (4/3 * pi * r^3)

# And a simple way to test it all.
#
volume = VolumeSphere(3)
@printf "volume = %0.3f\n" volume

max_stars_repo_name: wbeebe/julia

max_issues_repo_name: wbeebe/julia

max_forks_repo_name: wbeebe/julia


text:
module MyJuliaGEMM

export mygemm!

using SIMD, StaticArrays
using GPUifyLoops: @unroll

Base.elsize(::Type{<:MVector{S,T}}) where {S,T} = sizeof(T)

struct BlockSizes{MC, NC, KC, MR, NR} end

function mygemm!(C, A, B; MR = 8, NR = 6, MC = 96, NC = 2016, KC = 256)
  m, n = size(C)

  @assert m % MR == 0
  @assert MC % MR == 0
  @assert n % NR == 0
  @assert NC % NR == 0

  packedA = MVector{MC * KC, Float64}(undef)
  packedB = MVector{KC * NC, Float64}(undef)

  loop_five!(C, A, B, packedA, packedB, BlockSizes{MC, NC, KC, MR, NR}())
end

function loop_five!(C, A, B, packedA, packedB,
                    sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  n = size(C, 2)
  @inbounds for j = 1:NC:n
    jb = min(j + NC - 1, n)
    Ctile = view(C, :, j:jb)
    Btile = view(B, :, j:jb)
    loop_four!(Ctile, A, Btile, packedA, packedB, sizes)
  end
end

@inline function packB!(packedB, B, rangeB,
                        sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  k, n = size(B)
  ix = 1
  @inbounds for jt = 1:NR:n
    @unroll 4 for p in 1:k
      @simd ivdep for j = 0:NR-1
        packedB[ix] = B[p, jt + j]
        ix += 1
      end
    end
  end
end

@inline function loop_four!(C, A, B, packedA, packedB,
                            sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  k = size(A, 2)
  @inbounds for p = 1:KC:k
    pb = min(p + KC - 1, k)
    Atile = view(A, :, p:pb)
    Btile = view(B, p:pb, :)
    packB!(packedB, Btile, p:pb, sizes)
    realKC = (pb - p + 1)
    lineA = realKC * MR
    lineB = realKC * NR
    loop_three!(C, Atile, lineA, packedB, lineB, packedA, sizes)
  end
end

@inline function packA!(packedA, A, rangeA,
                        sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  m, k = size(A)
  ix = 1
  @inbounds for it = 1:MR:m
    @unroll 4 for p = 1:k
      @simd ivdep for i = 0:MR-1
        packedA[ix] = A[it + i, p]
        ix += 1
      end
    end
  end
end

@inline function loop_three!(C, A, lineA, B, lineB, packedA,
                             sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  m = size(C, 1)
  @inbounds for i = 1:MC:m
    ib = min(i + MC - 1, m)
    Ctile = view(C, i:ib, :)
    Atile = view(A, i:ib, :)
    packA!(packedA, Atile, i:ib, sizes)
    loop_two!(Ctile, packedA, lineA, B, lineB, sizes)
  end
end

@inline function loop_two!(C, A, lineA, B, lineB,
                           sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  n = size(C, 2)
  @inbounds for j = 1:NR:n
    Ctile  = view(C, :, j:j+NR-1)
    tix = div(j, NR)
    Btile = view(B, 1+tix*lineB:(tix+1)*lineB)
    loop_one!(Ctile, A, lineA, Btile, sizes)
  end
end

@inline function loop_one!(C, A, lineA, B,
                           sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  m = size(C, 1)
  @inbounds for i = 1:MR:m
    Ctile = view(C, i:i+MR-1, :)
    tix = div(i, MR)
    Atile = view(A, 1+tix*lineA:(tix+1)*lineA)
    micro_kernel!(Ctile, Atile, B, sizes)
  end
end

@inline function micro_kernel!(C, A, B,
                               sizes::BlockSizes{MC, NC, KC, MR, NR}) where {MC, NC, KC, MR, NR}
  vecT = Vec{4, Float64}
  MRdiv4 = div(MR, 4)
  # full C size
  m = size(parent(C), 1)

  cT = MArray{Tuple{MRdiv4, NR}, vecT}(undef)

  @unroll for q = 1:NR
    @unroll for r = 1:MRdiv4
      offset = 8 * (4(r - 1) + (q - 1) * m)
      @inbounds cT[r, q] = vload(vecT, pointer(C) + offset, nothing, Val(true))
    end
  end

  a = MVector{MRdiv4, vecT}(undef)

  lBdiv4 = div(length(B), NR)

  @inbounds @unroll 4 for p = 1:lBdiv4
    @unroll for r = 1:MRdiv4
      offset = 8 * (4(r - 1) + MR * (p - 1))
      a[r] = vload(vecT, pointer(A) + offset, nothing, Val(true))
    end

    @unroll for q = 1:NR
      b = vecT(B[q + NR * (p - 1)])
      @unroll for r = 1:MRdiv4
        cT[r, q] = muladd(a[r], b, cT[r, q])
      end
    end
  end

  @unroll for q = 1:NR
    @unroll for r = 1:MRdiv4
      offset = 8 * (4(r - 1) + (q - 1) * m)
      @inbounds vstore(cT[r, q], pointer(C) + offset, nothing, Val(true),
                       Val(true))
    end
  end
end

end # module

max_stars_repo_name: lcw/MyJuliaGEMM

max_issues_repo_name: lcw/MyJuliaGEMM

max_forks_repo_name: lcw/MyJuliaGEMM


text:
using CVRPLIB, TSPLIB

# Write your package code here.
include("../deps/deps.jl") # const LIBHGSCVRP
include("c_api.jl")
include("cvrp.jl")
include("tsp.jl")

function reporting(visited_customers)
    routes = deepcopy(visited_customers)
    for r in routes
        r .-= 1
    end
    return routes
end


text:
##
using Plots
using Statistics
using SparseArrays
include("../src/Graph_Louvain.jl")

using MAT
num = 9
mat = matread("../data/Amazon_$num.mat")
H = mat["H"]
m,n = size(H)
NodeLabels = mat["labels"]
order = round.(Int64,vec(sum(H,dims=2)))

## Three different ways of converting a graph to hypergraph
d = vec(sum(H,dims=1))
A = [spzeros(n,n) sparse(H'); H spzeros(m,m)]
w = [d; zeros(m)]
A3 = SimpleCliqueExp(H)
M = sum(d)
A2 = WeightedCliqueExp(H,order)
A2 = M/sum(A2)*A2
A3 = M/sum(A3)*A3

w2 = vec(sum(A2,dims=2))
w3 = vec(sum(A3,dims=2))

matwrite("Matrices/Amazon_($num).mat", Dict("A"=>A, "A2"=>A2, "A3"=>A3))
##
numtimes = 5
numpoints = 10
lin_ari = zeros(numpoints)
wce_ari = zeros(numpoints)
sce_ari = zeros(numpoints)

lin_nc = zeros(numpoints)
wce_nc = zeros(numpoints)
sce_nc = zeros(numpoints)

lin_t = zeros(numpoints)
wce_t = zeros(numpoints)
sce_t= zeros(numpoints)

LinC = zeros(n,numpoints)
WC = zeros(n,numpoints)
SC = zeros(n,numpoints)

Mstart = 4
Mend = 4
Lams = range(1/(Mstart*M),Mend/M,length=numpoints)
numits = 1000
for i = 1:length(Lams)

    lam = round(Lams[i],digits = 5)

    # Run the method with a linear cut
    s = time()
    c, BestObj = Many_Louvain(A,w,lam,numtimes,numits)
    lin_t[i] = time()-s
    cLin = c[1:n]
    LinC[:,i] = cLin
    lin_ari[i] = ari(cLin,NodeLabels)
    lin_nc[i] = length(unique(cLin))

    s = time()
    cW, BestObj = Many_Louvain(A2,w2,lam,numtimes,numits)
    wce_t[i] = time()-s
    WC[:,i] = cW
    wce_ari[i] = ari(cW,NodeLabels)
    wce_nc[i] = length(unique(cW))

    s = time()
    cS, BestObj = Many_Louvain(A2,w3,lam,numtimes,numits)
    sce_t[i] = time()-s
    SC[:,i] = cS
    sce_ari[i] = ari(cS,NodeLabels)
    sce_nc[i] = length(unique(cS))

    println("$(lin_ari[i]) \t $(wce_ari[i]) \t $(sce_ari[i]) ")

end

##
matwrite("Output/Amazon_$(num)_($numtimes)_$(Mstart)_$(Mend).mat", Dict(
"lin_ari"=>lin_ari, "lin_t"=>lin_t, "lin_nc"=>lin_nc, "LinC"=>LinC,
"wce_ari"=>wce_ari, "wce_t"=>wce_t, "wce_nc"=>wce_nc, "WC"=>WC,
"sce_ari"=>sce_ari, "sce_t"=>sce_t, "sce_nc"=>sce_nc,   "SC"=>SC))

max_stars_repo_name: nveldt/ParamCC

max_issues_repo_name: nveldt/ParamCC

max_forks_repo_name: nveldt/ParamCC


text:
using Countries
import Countries: name, code, capital, continent, isdeveloping, region, subregion, currencies, US, PH, HK, SG

using Test

countries = [US,PH,HK,SG]
names = ["United States of America","Philippines","China, Hong Kong Special Administrative Region","Singapore"]
codes = [840,608,344,702]
capitals = ["Washington","Manila","Hong Kong","Singapore"]
continents = ["NA","AS","AS","AS"]
isdevelopings = [false,true,true,true]
regions = ["Americas","Asia","Asia","Asia"]
subregions = ["Northern America","South-eastern Asia","Eastern Asia","South-eastern Asia"]

for (c,nm,cd,cp,ct,dv,rg,sr) in zip(countries,names,codes,capitals,continents,isdevelopings,regions,subregions)
    @test name(c) == nm
    @test code(c) == cd
    @test capital(c) == cp
    @test continent(c) == ct
    @test isdeveloping(c) == dv
    @test region(c) == rg
    @test subregion(c) == sr
end


text:
function Laurent_cases{S<:Integer,T<:Number}(num::S;tol::T= 5.0e-12,Range::Vector{S}=collect(1:2:55),enum::Tuple{S,Any}=(0,NaN))
srand(13); #123 235
  if 2*Range[1]+1 < enum[1]+1
    Range = collect(enum[1]+1:(Range[2]-Range[1]):Range[end])
end
if         num == 1 # Fernandez PhysicsLettersA 160(1991) 511—514
    ap = [0.0, 1]
    an = [0.0, 0, 0, 0, 0, 9/64]
  #  enum = (0,4.0)
#    enum = (2,NaN)
#    Range=collect(1:1:100)
elseif     num == 2 # Fernandez PhysicsLettersA 160(1991) 511—514
    par1 = 9.0/10
    par2 = 3.0
    par3 = 1.0
    ap = [0, par3^2]
    an = [0, par1*(par1+1)-2*par2*par3, 0, par2*(2*par1-1), 0, par2^2]
    enum = (0, par3*(2*par1+3))
elseif     num == 3 #Varshni
    alpha = 2.0
    gamma2 = 3.0
    beta =-2*sqrt(gamma2)+sqrt(gamma2)*sqrt( 1 + 8*sqrt(alpha*gamma2))
    ap = [0, alpha]
    an = [0, 0, 0, beta, 0, gamma2]
    enum = (0, sqrt(alpha)*(4+beta/sqrt(gamma2)))
elseif     num == 4
    ap = vcat(rand(Uniform(-1, 1),99),[1.0])
    an = vcat(rand(Uniform(-1, 1),99),[1.0])
    #    enum = (0,NaN)
elseif     num == 5
    ap = vcat(rand(Uniform(-5, 5),7),[5.0])
    an = vcat(rand(Uniform(-5, 5),2),[10.0])
#    enum = (0,NaN)
end
# Optimal parameters
gaopt = [(length(an)-2.0)/2 , (length(ap)+2.0)/2]
Bopt = [2*sqrt(an[end])/(length(an)-2) , 2*sqrt(ap[end])/(length(ap)+2)]
dopt = pi/(2*maximum(gaopt))
  #=
q(t) = V(t,ap,an)
β=Bopt
γ=gaopt
tol = 5e-10
=#
(RESULTS, All_Abs_Error_Approx , hoptimal , n, MatrixSizes, All_Eigenvectors, MN) = SincEigen_Ireg(t->V(t,ap,an),Bopt,gaopt,dopt,Range=Range,tol=tol,enum=enum)
RESULTS
  PyPlot.clf()
figure(1)
subplot(1,3,1)
title(latexstring("Convergence of DESCM for \$E_{$(enum[1])}\$"))
xlabel(latexstring("Matrix Size: \$M+N+1\$"))
if isnan(enum[2]) == true
ylabel(latexstring("Absolute Error Approximation: \$\\epsilon_{$(enum[1])} \$"))
else
ylabel("Absolute Error")
end
ylim([1e-15,1])
Error = real(All_Abs_Error_Approx[enum[1]+1,:]')
Inthehouse = findnext(Error.<tol, true, 1)+3
xlim([MatrixSizes[2],MatrixSizes[Inthehouse]])
semilogy(MatrixSizes[2:Inthehouse],Error[1:Inthehouse-1],linestyle="--",color="b")

subplot(1,3,3)
Index = findfirst(MatrixSizes,RESULTS[enum[1]+1,2])
k = collect(-MN[Index,1]:1:MN[Index,2])
v_coeff = All_Eigenvectors[1:length(k),Index]
h = hoptimal[Index]
extreme=[1.0]
temp1 = wavefunction(extreme,h,k,v_coeff)
while  abs(temp1[1])>0.0005
   extreme[1]+=1.0
   temp1 =  wavefunction(extreme,h,k,v_coeff)
end
x=linspace(0.00000001,2,300)
#x = linspace(0.00000001,6,300)
W = wavefunction(x,h,k,v_coeff)
title(latexstring("Wavefunction: \$\\psi_{$(enum[1])}(x)\$"))
xlabel(latexstring("\$x\$"))
#ylabel(latexstring("\$\\psi_{$(enum[1])}(x)\$"))
plot(x,W,color="r")

subplot(1,3,2)
Potential = V(convert(Array{Float64,1},x),ap,an)
title(L"Potential Function: $V(x)$")
xlabel(L"x")
#ylabel(L"V(x)")
ylim([minimum(Potential)-20,200]) #29397.608029716015
A=plot(x,Potential,color="k",label=L"V(x)")
B=plot(x,vec(repmat([RESULTS[enum[1]+1,3]],1,length(x))),label=latexstring("\$E_{$(enum[1])}\$"),linestyle="--")
legend()
return (RESULTS, All_Abs_Error_Approx , hoptimal , n, MatrixSizes, All_Eigenvectors, MN,ap,an)
end
##################################################################################################
function V{T<:Number}(t::T,ap::Vector{T},an::Vector{T})
  p,n = length(ap),length(an)
  dot(an,1./t.^collect(1:n))+dot(ap,t.^collect(1:p))
end
function V{T<:Number}(t::Vector{T},ap::Vector{T},an::Vector{T})
  p,n = length(ap),length(an)
  (1./t.^(collect(1:n)'))*an .+ (t.^(collect(1:p)'))*ap
end

function SincEigen_Ireg{T<:Number,S<:Integer}(q::Function,β::Vector{T},γ::Vector{T},dopt::T; enum::Tuple{S,Any}=(0,NaN), tol::T=5e-12, Range::Vector{S}=collect(1:1:40))
  qtilde(t) = exp(2t).*q(exp(t)).+0.25
  rhotilde(t) = exp(2t)
  # Determining step sizes and left and right collocation points based on asymptotic information.
  if γ[1]>γ[2]
    n = M = Range
    gam = γ[1]
    beta = β[1]
    hoptimal = lambertW(pi*dopt*gam*n/beta)./(gam*n)
    N = max( ceil( (γ[1]/γ[2]).*n .+ log(β[1]/β[2])./ (γ[2].*hoptimal) ) , 0 )
  elseif γ[2]>γ[1]
    n = N = Range
    gam = γ[2]
    beta = β[2]
    hoptimal = lambertW(pi*dopt*gam*n/beta)./(gam*n)
    M = max( floor( (γ[2]/γ[1]).*n .+ log(β[2]/β[1])./ (γ[1].*hoptimal) ) , 0 )
  elseif γ[1] == γ[2] && β[1] > β[2]
    n = M = Range
    gam = γ[1]
    beta = β[1]
    hoptimal = lambertW(pi*dopt*gam*n/beta)./(gam*n)
    N = ceil( n .+ log(β[1]/β[2])./ (γ[2].*hoptimal) )
  elseif γ[1] == γ[2] && β[1] < β[2]
    n = N = Range
    gam = γ[2]
    beta = β[2]
    hoptimal = lambertW(pi*dopt*gam*n/beta)./(gam*n)
    M = floor(n .+ log(β[2]/β[1])./ (γ[1].*hoptimal) )
  elseif γ[1] == γ[2] && β[1] == β[2]
    n = N = Range
    M = 1.0*N
    gam = γ[2]
    beta = β[2]
    hoptimal = lambertW(pi*dopt*gam*n/beta)./(gam*n)
  end # if loop

  #  INITIAL CONDITIONS
  Length = length(Range)                                            # Length of the vectors in the following algorithm given the previous conditions
  MatrixSizes = N.+M.+1                                       # Array of all square matrix sizes for every iteration.
  All_Eigenvalues = zeros(round(Int,MatrixSizes[end]),Length) # Matrix used for storing all obtained eigenvalues as columns at every iteration.
  All_Eigenvectors = zeros(round(Int,MatrixSizes[end]),Length) # Matrix used for storing all obtained eigenvalues as columns at every iteration.
@inbounds for i = 1:Length
    h = hoptimal[i]                                        # Mesh size used at every iteration.
    k = collect(-M[i]:N[i])                                # Vector of Mesh points.
    A = Symmetric(diagm(qtilde(k*h))-sinc(2,k'.-k)/h^2)    # Construct symmetric A matrix.
    D2 = Symmetric(diagm(rhotilde(k*h)))                   # Construct Diagonal pos. def. matrix D^2
    eig_and_vec = eigfact!(A,D2)                                # Solving Generalized eigenvalue problem.
    E = eig_and_vec[:values]
    vec = eig_and_vec[:vectors][:,enum[1]+1]

    All_Eigenvalues[1:length(E),i] = E                     # Storing all eigenvalues in columns in matrix All_Eigenvalues
    All_Eigenvectors[1:length(vec),i] = vec                     # Storing all eigenvalues in columns in matrix All_Eigenvalues.
  end
  isnan(enum[2])
  # Calculating an Approximation to the Absolute Error for all Energy values
  if isnan(enum[2]) == true
    All_Abs_Error_Approx  = abs(All_Eigenvalues[:,2:end].-All_Eigenvalues[:,1:end-1])
  else
    All_Abs_Error_Approx = zeros(All_Eigenvalues[:,2:end])
    Index = [collect(1:enum[1]);collect((enum[1]+2):Length)]
    All_Abs_Error_Approx[Index,:] =  abs(All_Eigenvalues[Index,2:end].-All_Eigenvalues[Index,1:(end-1)])
    All_Abs_Error_Approx[enum[1]+1,:] =  abs(All_Eigenvalues[enum[1]+1,2:end] .- enum[2])
  end # if loop
  ## Ouputing the convergence analysis of the algorithm given the number of iterations and the tolerance level tol.
  RESULTS = Convergence_Analysis(All_Eigenvalues,tol,MatrixSizes,All_Abs_Error_Approx)
  (RESULTS, All_Abs_Error_Approx, hoptimal, n, MatrixSizes,All_Eigenvectors,hcat(M,N))
end

function  Convergence_Analysis{T<:Number}(All_Eigenvalues::Matrix{T},tol::T,MatrixSizes::Vector{T},All_Abs_Error_Approx::Matrix{T})
    #Finding which Eigenvalues satisfy the condition Absolute Error Approxmiation < tol
    m = size(All_Abs_Error_Approx,1)
    First_Non_Zero = [findfirst(All_Abs_Error_Approx[i,:]) for i in collect(1:m)]
    Less_than_tol_matrix =  All_Abs_Error_Approx .< tol
    Eig_less_than_tol_posi = [findnext(Less_than_tol_matrix[i,:], true, First_Non_Zero[i]+1) for i in collect(1:m)]
    # list of eigenvalues  that satisfy the condition Relative Error Approxmiation<tol
    Posi_index = findn(Eig_less_than_tol_posi)#[1]
    # number of eigenvalues that satisfy the condition Error<tol
    num_eig_less_than_tol = length(Posi_index)
    # Find the optimal value of N for the eignvalues from the list Posi_index
    idx = [Eig_less_than_tol_posi[Posi_index[j]]+1 for j in collect(1:num_eig_less_than_tol)]
    # Find the value of the eigenvalues and Relative Error Approximation for the eignvalues from the list Posi_index
    Error = [All_Abs_Error_Approx[Posi_index[i],idx[i]-1] for i in collect(1:num_eig_less_than_tol)]
    Eigenvalues = [All_Eigenvalues[Posi_index[i],idx[i]] for i in collect(1:num_eig_less_than_tol)]
    # Display wanted results
    Eig_number = Posi_index.-1
    MatrixSizeOpt = MatrixSizes[idx]
    [Eig_number MatrixSizeOpt Eigenvalues Error]
end

function wavefunction{T<:Number}(x::LinSpace{T},h::T,k::Vector{T},v=Vector{T})
xk=linspace(0.00000001,100,300000)
wavefunction_squared = (sqrt(xk).*(sinc(log(xk)/h.-k')*v)).^2
Normalizing_Constant = sum((xk[2:end]-xk[1:end-1]).*(wavefunction_squared[2:end]+wavefunction_squared[1:end-1]))./2
#
return sqrt(x).*(sinc(log(x)/h.-k')*v)/sqrt(Normalizing_Constant)
end
function wavefunction{T<:Number}(x::Vector{T},h::T,k::Vector{T},v=Vector{T})
xk=linspace(0.00000001,100,300000)
wavefunction_squared = (sqrt(xk).*(sinc(log(xk)/h.-k')*v)).^2
Normalizing_Constant = sum((xk[2:end]-xk[1:end-1]).*(wavefunction_squared[2:end]+wavefunction_squared[1:end-1]))./2
#
return sqrt(x).*(sinc(log(x)/h.-k')*v)/sqrt(Normalizing_Constant)
end


text:
# solver settings
# set_config(:nls_atol_break, 1E-3)
# set_config(:nls_rtol_break, 1E-3)
# set_config(:nls_stol_break, 1E-3)

# run configuration
const Δt    = 0.01
const ntime = 10000

# plot configuration
const nplot = 1
const splot = true
# const XLIM  = ( 0.90,  1.10)
# const YLIM  = (-0.10, +0.10)

# output configuration
const title     = "Lotka-Volterra 2D"
const prefix    = "lotka_volterra_2d_"
const fig_dir   = run_id
const html_file = run_id * ".html"
const coll_title = "Lotka-Volterra 2D"

# create list of figures to put in list
figures = (
    "_solution",
    "_energy_error"
)

figures_detail = (
    "",
    "_solution",
    "_energy_error",
    "_energy_drift",
    figures_custom...
)

# suffix of figure files
fig_suff = ".png"