text:
# autogenerated by deps/error_codes.jl using https://www.postgresql.org/docs/current/errcodes-appendix.html

@cenum(Class,
    C00,
    C01,
    C02,
    C03,
    C08,
    C09,
    C0A,
    C0B,
    C0F,
    C0L,
    C0P,
    C0Z,
    C20,
    C21,
    C22,
    C23,
    C24,
    C25,
    C26,
    C27,
    C28,
    C2B,
    C2D,
    C2F,
    C34,
    C38,
    C39,
    C3B,
    C3D,
    C3F,
    C40,
    C42,
    C44,
    C53,
    C54,
    C55,
    C57,
    C58,
    C72,
    CF0,
    CHV,
    CP0,
    CXX,
    CUN,
)

@cenum(ErrorCode,
    E00000,
    E01000,
    E0100C,
    E01008,
    E01003,
    E01007,
    E01006,
    E01004,
    E01P01,
    E02000,
    E02001,
    E03000,
    E08000,
    E08003,
    E08006,
    E08001,
    E08004,
    E08007,
    E08P01,
    E09000,
    E0A000,
    E0B000,
    E0F000,
    E0F001,
    E0L000,
    E0LP01,
    E0P000,
    E0Z000,
    E0Z002,
    E20000,
    E21000,
    E22000,
    E2202E,
    E22021,
    E22008,
    E22012,
    E22005,
    E2200B,
    E22022,
    E22015,
    E2201E,
    E22014,
    E22016,
    E2201F,
    E2201G,
    E22018,
    E22007,
    E22019,
    E2200D,
    E22025,
    E22P06,
    E22010,
    E22023,
    E22013,
    E2201B,
    E2201W,
    E2201X,
    E2202H,
    E2202G,
    E22009,
    E2200C,
    E2200G,
    E22004,
    E22002,
    E22003,
    E2200H,
    E22026,
    E22001,
    E22011,
    E22027,
    E22024,
    E2200F,
    E22P01,
    E22P02,
    E22P03,
    E22P04,
    E22P05,
    E2200L,
    E2200M,
    E2200N,
    E2200S,
    E2200T,
    E22030,
    E22031,
    E22032,
    E22033,
    E22034,
    E22035,
    E22036,
    E22037,
    E22038,
    E22039,
    E2203A,
    E2203B,
    E2203C,
    E2203D,
    E2203E,
    E2203F,
    E23000,
    E23001,
    E23502,
    E23503,
    E23505,
    E23514,
    E23P01,
    E24000,
    E25000,
    E25001,
    E25002,
    E25008,
    E25003,
    E25004,
    E25005,
    E25006,
    E25007,
    E25P01,
    E25P02,
    E25P03,
    E26000,
    E27000,
    E28000,
    E28P01,
    E2B000,
    E2BP01,
    E2D000,
    E2F000,
    E2F005,
    E2F002,
    E2F003,
    E2F004,
    E34000,
    E38000,
    E38001,
    E38002,
    E38003,
    E38004,
    E39000,
    E39001,
    E39004,
    E39P01,
    E39P02,
    E39P03,
    E3B000,
    E3B001,
    E3D000,
    E3F000,
    E40000,
    E40002,
    E40001,
    E40003,
    E40P01,
    E42000,
    E42601,
    E42501,
    E42846,
    E42803,
    E42P20,
    E42P19,
    E42830,
    E42602,
    E42622,
    E42939,
    E42804,
    E42P18,
    E42P21,
    E42P22,
    E42809,
    E428C9,
    E42703,
    E42883,
    E42P01,
    E42P02,
    E42704,
    E42701,
    E42P03,
    E42P04,
    E42723,
    E42P05,
    E42P06,
    E42P07,
    E42712,
    E42710,
    E42702,
    E42725,
    E42P08,
    E42P09,
    E42P10,
    E42611,
    E42P11,
    E42P12,
    E42P13,
    E42P14,
    E42P15,
    E42P16,
    E42P17,
    E44000,
    E53000,
    E53100,
    E53200,
    E53300,
    E53400,
    E54000,
    E54001,
    E54011,
    E54023,
    E55000,
    E55006,
    E55P02,
    E55P03,
    E55P04,
    E57000,
    E57014,
    E57P01,
    E57P02,
    E57P03,
    E57P04,
    E58000,
    E58030,
    E58P01,
    E58P02,
    E72000,
    EF0000,
    EF0001,
    EHV000,
    EHV005,
    EHV002,
    EHV010,
    EHV021,
    EHV024,
    EHV007,
    EHV008,
    EHV004,
    EHV006,
    EHV091,
    EHV00B,
    EHV00C,
    EHV00D,
    EHV090,
    EHV00A,
    EHV009,
    EHV014,
    EHV001,
    EHV00P,
    EHV00J,
    EHV00K,
    EHV00Q,
    EHV00R,
    EHV00L,
    EHV00M,
    EHV00N,
    EP0000,
    EP0001,
    EP0002,
    EP0003,
    EP0004,
    EXX000,
    EXX001,
    EXX002,
    EUNOWN,
)

const SuccessfulCompletionClass = PQResultError{C00}

const SuccessfulCompletion = PQResultError{C00, E00000}

const WarningClass = PQResultError{C01}

const WarningWarning = PQResultError{C01, E01000}
const DynamicResultSetsReturnedWarning = PQResultError{C01, E0100C}
const ImplicitZeroBitPaddingWarning = PQResultError{C01, E01008}
const NullValueEliminatedInSetFunctionWarning = PQResultError{C01, E01003}
const PrivilegeNotGrantedWarning = PQResultError{C01, E01007}
const PrivilegeNotRevokedWarning = PQResultError{C01, E01006}
const StringDataRightTruncationWarning = PQResultError{C01, E01004}
const DeprecatedFeatureWarning = PQResultError{C01, E01P01}

const NoDataClass = PQResultError{C02}

const NoDataWarning = PQResultError{C02, E02000}
const NoAdditionalDynamicResultSetsReturnedWarning = PQResultError{C02, E02001}

const SqlStatementNotYetCompleteErrorClass = PQResultError{C03}

const SqlStatementNotYetComplete = PQResultError{C03, E03000}

const ConnectionExceptionErrorClass = PQResultError{C08}

const ConnectionException = PQResultError{C08, E08000}
const ConnectionDoesNotExist = PQResultError{C08, E08003}
const ConnectionFailure = PQResultError{C08, E08006}
const SqlclientUnableToEstablishSqlconnection = PQResultError{C08, E08001}
const SqlserverRejectedEstablishmentOfSqlconnection = PQResultError{C08, E08004}
const TransactionResolutionUnknown = PQResultError{C08, E08007}
const ProtocolViolation = PQResultError{C08, E08P01}

const TriggeredActionExceptionErrorClass = PQResultError{C09}

const TriggeredActionException = PQResultError{C09, E09000}

const FeatureNotSupportedErrorClass = PQResultError{C0A}

const FeatureNotSupported = PQResultError{C0A, E0A000}

const InvalidTransactionInitiationErrorClass = PQResultError{C0B}

const InvalidTransactionInitiation = PQResultError{C0B, E0B000}

const LocatorExceptionErrorClass = PQResultError{C0F}

const LocatorException = PQResultError{C0F, E0F000}
const InvalidLocatorSpecification = PQResultError{C0F, E0F001}

const InvalidGrantorErrorClass = PQResultError{C0L}

const InvalidGrantor = PQResultError{C0L, E0L000}
const InvalidGrantOperation = PQResultError{C0L, E0LP01}

const InvalidRoleSpecificationErrorClass = PQResultError{C0P}

const InvalidRoleSpecification = PQResultError{C0P, E0P000}

const DiagnosticsExceptionErrorClass = PQResultError{C0Z}

const DiagnosticsException = PQResultError{C0Z, E0Z000}
const StackedDiagnosticsAccessedWithoutActiveHandler = PQResultError{C0Z, E0Z002}

const CaseNotFoundErrorClass = PQResultError{C20}

const CaseNotFound = PQResultError{C20, E20000}

const CardinalityViolationErrorClass = PQResultError{C21}

const CardinalityViolation = PQResultError{C21, E21000}

const DataExceptionErrorClass = PQResultError{C22}

const DataException = PQResultError{C22, E22000}
const ArraySubscriptError = PQResultError{C22, E2202E}
const CharacterNotInRepertoire = PQResultError{C22, E22021}
const DatetimeFieldOverflow = PQResultError{C22, E22008}
const DivisionByZero = PQResultError{C22, E22012}
const ErrorInAssignment = PQResultError{C22, E22005}
const EscapeCharacterConflict = PQResultError{C22, E2200B}
const IndicatorOverflow = PQResultError{C22, E22022}
const IntervalFieldOverflow = PQResultError{C22, E22015}
const InvalidArgumentForLogarithm = PQResultError{C22, E2201E}
const InvalidArgumentForNtileFunction = PQResultError{C22, E22014}
const InvalidArgumentForNthValueFunction = PQResultError{C22, E22016}
const InvalidArgumentForPowerFunction = PQResultError{C22, E2201F}
const InvalidArgumentForWidthBucketFunction = PQResultError{C22, E2201G}
const InvalidCharacterValueForCast = PQResultError{C22, E22018}
const InvalidDatetimeFormat = PQResultError{C22, E22007}
const InvalidEscapeCharacter = PQResultError{C22, E22019}
const InvalidEscapeOctet = PQResultError{C22, E2200D}
const InvalidEscapeSequence = PQResultError{C22, E22025}
const NonstandardUseOfEscapeCharacter = PQResultError{C22, E22P06}
const InvalidIndicatorParameterValue = PQResultError{C22, E22010}
const InvalidParameterValue = PQResultError{C22, E22023}
const InvalidPrecedingOrFollowingSize = PQResultError{C22, E22013}
const InvalidRegularExpression = PQResultError{C22, E2201B}
const InvalidRowCountInLimitClause = PQResultError{C22, E2201W}
const InvalidRowCountInResultOffsetClause = PQResultError{C22, E2201X}
const InvalidTablesampleArgument = PQResultError{C22, E2202H}
const InvalidTablesampleRepeat = PQResultError{C22, E2202G}
const InvalidTimeZoneDisplacementValue = PQResultError{C22, E22009}
const InvalidUseOfEscapeCharacter = PQResultError{C22, E2200C}
const MostSpecificTypeMismatch = PQResultError{C22, E2200G}
const NullValueNotAllowed = PQResultError{C22, E22004}
const NullValueNoIndicatorParameter = PQResultError{C22, E22002}
const NumericValueOutOfRange = PQResultError{C22, E22003}
const SequenceGeneratorLimitExceeded = PQResultError{C22, E2200H}
const StringDataLengthMismatch = PQResultError{C22, E22026}
const StringDataRightTruncation = PQResultError{C22, E22001}
const SubstringError = PQResultError{C22, E22011}
const TrimError = PQResultError{C22, E22027}
const UnterminatedCString = PQResultError{C22, E22024}
const ZeroLengthCharacterString = PQResultError{C22, E2200F}
const FloatingPointException = PQResultError{C22, E22P01}
const InvalidTextRepresentation = PQResultError{C22, E22P02}
const InvalidBinaryRepresentation = PQResultError{C22, E22P03}
const BadCopyFileFormat = PQResultError{C22, E22P04}
const UntranslatableCharacter = PQResultError{C22, E22P05}
const NotAnXmlDocument = PQResultError{C22, E2200L}
const InvalidXmlDocument = PQResultError{C22, E2200M}
const InvalidXmlContent = PQResultError{C22, E2200N}
const InvalidXmlComment = PQResultError{C22, E2200S}
const InvalidXmlProcessingInstruction = PQResultError{C22, E2200T}
const DuplicateJsonObjectKeyValue = PQResultError{C22, E22030}
const InvalidArgumentForSqlJsonDatetimeFunction = PQResultError{C22, E22031}
const InvalidJsonText = PQResultError{C22, E22032}
const InvalidSqlJsonSubscript = PQResultError{C22, E22033}
const MoreThanOneSqlJsonItem = PQResultError{C22, E22034}
const NoSqlJsonItem = PQResultError{C22, E22035}
const NonNumericSqlJsonItem = PQResultError{C22, E22036}
const NonUniqueKeysInAJsonObject = PQResultError{C22, E22037}
const SingletonSqlJsonItemRequired = PQResultError{C22, E22038}
const SqlJsonArrayNotFound = PQResultError{C22, E22039}
const SqlJsonMemberNotFound = PQResultError{C22, E2203A}
const SqlJsonNumberNotFound = PQResultError{C22, E2203B}
const SqlJsonObjectNotFound = PQResultError{C22, E2203C}
const TooManyJsonArrayElements = PQResultError{C22, E2203D}
const TooManyJsonObjectMembers = PQResultError{C22, E2203E}
const SqlJsonScalarRequired = PQResultError{C22, E2203F}

const IntegrityConstraintViolationErrorClass = PQResultError{C23}

const IntegrityConstraintViolation = PQResultError{C23, E23000}
const RestrictViolation = PQResultError{C23, E23001}
const NotNullViolation = PQResultError{C23, E23502}
const ForeignKeyViolation = PQResultError{C23, E23503}
const UniqueViolation = PQResultError{C23, E23505}
const CheckViolation = PQResultError{C23, E23514}
const ExclusionViolation = PQResultError{C23, E23P01}

const InvalidCursorStateErrorClass = PQResultError{C24}

const InvalidCursorState = PQResultError{C24, E24000}

const InvalidTransactionStateErrorClass = PQResultError{C25}

const InvalidTransactionState = PQResultError{C25, E25000}
const ActiveSqlTransaction = PQResultError{C25, E25001}
const BranchTransactionAlreadyActive = PQResultError{C25, E25002}
const HeldCursorRequiresSameIsolationLevel = PQResultError{C25, E25008}
const InappropriateAccessModeForBranchTransaction = PQResultError{C25, E25003}
const InappropriateIsolationLevelForBranchTransaction = PQResultError{C25, E25004}
const NoActiveSqlTransactionForBranchTransaction = PQResultError{C25, E25005}
const ReadOnlySqlTransaction = PQResultError{C25, E25006}
const SchemaAndDataStatementMixingNotSupported = PQResultError{C25, E25007}
const NoActiveSqlTransaction = PQResultError{C25, E25P01}
const InFailedSqlTransaction = PQResultError{C25, E25P02}
const IdleInTransactionSessionTimeout = PQResultError{C25, E25P03}

const InvalidSqlStatementNameErrorClass = PQResultError{C26}

const InvalidSqlStatementName = PQResultError{C26, E26000}

const TriggeredDataChangeViolationErrorClass = PQResultError{C27}

const TriggeredDataChangeViolation = PQResultError{C27, E27000}

const InvalidAuthorizationSpecificationErrorClass = PQResultError{C28}

const InvalidAuthorizationSpecification = PQResultError{C28, E28000}
const InvalidPassword = PQResultError{C28, E28P01}

const DependentPrivilegeDescriptorsStillExistErrorClass = PQResultError{C2B}

const DependentPrivilegeDescriptorsStillExist = PQResultError{C2B, E2B000}
const DependentObjectsStillExist = PQResultError{C2B, E2BP01}

const InvalidTransactionTerminationErrorClass = PQResultError{C2D}

const InvalidTransactionTermination = PQResultError{C2D, E2D000}

const SqlRoutineExceptionErrorClass = PQResultError{C2F}

const SqlRoutineException = PQResultError{C2F, E2F000}
const FunctionExecutedNoReturnStatement = PQResultError{C2F, E2F005}
const ModifyingSqlDataNotPermitted = PQResultError{C2F, E2F002}
const ProhibitedSqlStatementAttempted = PQResultError{C2F, E2F003}
const ReadingSqlDataNotPermitted = PQResultError{C2F, E2F004}

const InvalidCursorNameErrorClass = PQResultError{C34}

const InvalidCursorName = PQResultError{C34, E34000}

const ExternalRoutineExceptionErrorClass = PQResultError{C38}

const ExternalRoutineException = PQResultError{C38, E38000}
const ContainingSqlNotPermitted = PQResultError{C38, E38001}
const ModifyingSqlDataNotPermittedExt = PQResultError{C38, E38002}
const ProhibitedSqlStatementAttemptedExt = PQResultError{C38, E38003}
const ReadingSqlDataNotPermittedExt = PQResultError{C38, E38004}

const ExternalRoutineInvocationExceptionErrorClass = PQResultError{C39}

const ExternalRoutineInvocationException = PQResultError{C39, E39000}
const InvalidSqlstateReturned = PQResultError{C39, E39001}
const NullValueNotAllowedExt = PQResultError{C39, E39004}
const TriggerProtocolViolated = PQResultError{C39, E39P01}
const SrfProtocolViolated = PQResultError{C39, E39P02}
const EventTriggerProtocolViolated = PQResultError{C39, E39P03}

const SavepointExceptionErrorClass = PQResultError{C3B}

const SavepointException = PQResultError{C3B, E3B000}
const InvalidSavepointSpecification = PQResultError{C3B, E3B001}

const InvalidCatalogNameErrorClass = PQResultError{C3D}

const InvalidCatalogName = PQResultError{C3D, E3D000}

const InvalidSchemaNameErrorClass = PQResultError{C3F}

const InvalidSchemaName = PQResultError{C3F, E3F000}

const TransactionRollbackErrorClass = PQResultError{C40}

const TransactionRollback = PQResultError{C40, E40000}
const TransactionIntegrityConstraintViolation = PQResultError{C40, E40002}
const SerializationFailure = PQResultError{C40, E40001}
const StatementCompletionUnknown = PQResultError{C40, E40003}
const DeadlockDetected = PQResultError{C40, E40P01}

const SyntaxErrorOrAccessRuleViolationErrorClass = PQResultError{C42}

const SyntaxErrorOrAccessRuleViolation = PQResultError{C42, E42000}
const SyntaxError = PQResultError{C42, E42601}
const InsufficientPrivilege = PQResultError{C42, E42501}
const CannotCoerce = PQResultError{C42, E42846}
const GroupingError = PQResultError{C42, E42803}
const WindowingError = PQResultError{C42, E42P20}
const InvalidRecursion = PQResultError{C42, E42P19}
const InvalidForeignKey = PQResultError{C42, E42830}
const InvalidName = PQResultError{C42, E42602}
const NameTooLong = PQResultError{C42, E42622}
const ReservedName = PQResultError{C42, E42939}
const DatatypeMismatch = PQResultError{C42, E42804}
const IndeterminateDatatype = PQResultError{C42, E42P18}
const CollationMismatch = PQResultError{C42, E42P21}
const IndeterminateCollation = PQResultError{C42, E42P22}
const WrongObjectType = PQResultError{C42, E42809}
const GeneratedAlways = PQResultError{C42, E428C9}
const UndefinedColumn = PQResultError{C42, E42703}
const UndefinedFunction = PQResultError{C42, E42883}
const UndefinedTable = PQResultError{C42, E42P01}
const UndefinedParameter = PQResultError{C42, E42P02}
const UndefinedObject = PQResultError{C42, E42704}
const DuplicateColumn = PQResultError{C42, E42701}
const DuplicateCursor = PQResultError{C42, E42P03}
const DuplicateDatabase = PQResultError{C42, E42P04}
const DuplicateFunction = PQResultError{C42, E42723}
const DuplicatePreparedStatement = PQResultError{C42, E42P05}
const DuplicateSchema = PQResultError{C42, E42P06}
const DuplicateTable = PQResultError{C42, E42P07}
const DuplicateAlias = PQResultError{C42, E42712}
const DuplicateObject = PQResultError{C42, E42710}
const AmbiguousColumn = PQResultError{C42, E42702}
const AmbiguousFunction = PQResultError{C42, E42725}
const AmbiguousParameter = PQResultError{C42, E42P08}
const AmbiguousAlias = PQResultError{C42, E42P09}
const InvalidColumnReference = PQResultError{C42, E42P10}
const InvalidColumnDefinition = PQResultError{C42, E42611}
const InvalidCursorDefinition = PQResultError{C42, E42P11}
const InvalidDatabaseDefinition = PQResultError{C42, E42P12}
const InvalidFunctionDefinition = PQResultError{C42, E42P13}
const InvalidPreparedStatementDefinition = PQResultError{C42, E42P14}
const InvalidSchemaDefinition = PQResultError{C42, E42P15}
const InvalidTableDefinition = PQResultError{C42, E42P16}
const InvalidObjectDefinition = PQResultError{C42, E42P17}

const WithCheckOptionViolationErrorClass = PQResultError{C44}

const WithCheckOptionViolation = PQResultError{C44, E44000}

const InsufficientResourcesErrorClass = PQResultError{C53}

const InsufficientResources = PQResultError{C53, E53000}
const DiskFull = PQResultError{C53, E53100}
const OutOfMemory = PQResultError{C53, E53200}
const TooManyConnections = PQResultError{C53, E53300}
const ConfigurationLimitExceeded = PQResultError{C53, E53400}

const ProgramLimitExceededErrorClass = PQResultError{C54}

const ProgramLimitExceeded = PQResultError{C54, E54000}
const StatementTooComplex = PQResultError{C54, E54001}
const TooManyColumns = PQResultError{C54, E54011}
const TooManyArguments = PQResultError{C54, E54023}

const ObjectNotInPrerequisiteStateErrorClass = PQResultError{C55}

const ObjectNotInPrerequisiteState = PQResultError{C55, E55000}
const ObjectInUse = PQResultError{C55, E55006}
const CantChangeRuntimeParam = PQResultError{C55, E55P02}
const LockNotAvailable = PQResultError{C55, E55P03}
const UnsafeNewEnumValueUsage = PQResultError{C55, E55P04}

const OperatorInterventionErrorClass = PQResultError{C57}

const OperatorIntervention = PQResultError{C57, E57000}
const QueryCanceled = PQResultError{C57, E57014}
const AdminShutdown = PQResultError{C57, E57P01}
const CrashShutdown = PQResultError{C57, E57P02}
const CannotConnectNow = PQResultError{C57, E57P03}
const DatabaseDropped = PQResultError{C57, E57P04}

const SystemErrorErrorClass = PQResultError{C58}

const SystemError = PQResultError{C58, E58000}
const IoError = PQResultError{C58, E58030}
const UndefinedFile = PQResultError{C58, E58P01}
const DuplicateFile = PQResultError{C58, E58P02}

const SnapshotTooOldErrorClass = PQResultError{C72}

const SnapshotTooOld = PQResultError{C72, E72000}

const ConfigFileErrorErrorClass = PQResultError{CF0}

const ConfigFileError = PQResultError{CF0, EF0000}
const LockFileExists = PQResultError{CF0, EF0001}

const FdwErrorErrorClass = PQResultError{CHV}

const FdwError = PQResultError{CHV, EHV000}
const FdwColumnNameNotFound = PQResultError{CHV, EHV005}
const FdwDynamicParameterValueNeeded = PQResultError{CHV, EHV002}
const FdwFunctionSequenceError = PQResultError{CHV, EHV010}
const FdwInconsistentDescriptorInformation = PQResultError{CHV, EHV021}
const FdwInvalidAttributeValue = PQResultError{CHV, EHV024}
const FdwInvalidColumnName = PQResultError{CHV, EHV007}
const FdwInvalidColumnNumber = PQResultError{CHV, EHV008}
const FdwInvalidDataType = PQResultError{CHV, EHV004}
const FdwInvalidDataTypeDescriptors = PQResultError{CHV, EHV006}
const FdwInvalidDescriptorFieldIdentifier = PQResultError{CHV, EHV091}
const FdwInvalidHandle = PQResultError{CHV, EHV00B}
const FdwInvalidOptionIndex = PQResultError{CHV, EHV00C}
const FdwInvalidOptionName = PQResultError{CHV, EHV00D}
const FdwInvalidStringLengthOrBufferLength = PQResultError{CHV, EHV090}
const FdwInvalidStringFormat = PQResultError{CHV, EHV00A}
const FdwInvalidUseOfNullPointer = PQResultError{CHV, EHV009}
const FdwTooManyHandles = PQResultError{CHV, EHV014}
const FdwOutOfMemory = PQResultError{CHV, EHV001}
const FdwNoSchemas = PQResultError{CHV, EHV00P}
const FdwOptionNameNotFound = PQResultError{CHV, EHV00J}
const FdwReplyHandle = PQResultError{CHV, EHV00K}
const FdwSchemaNotFound = PQResultError{CHV, EHV00Q}
const FdwTableNotFound = PQResultError{CHV, EHV00R}
const FdwUnableToCreateExecution = PQResultError{CHV, EHV00L}
const FdwUnableToCreateReply = PQResultError{CHV, EHV00M}
const FdwUnableToEstablishConnection = PQResultError{CHV, EHV00N}

const PlpgsqlErrorErrorClass = PQResultError{CP0}

const PlpgsqlError = PQResultError{CP0, EP0000}
const RaiseException = PQResultError{CP0, EP0001}
const NoDataFound = PQResultError{CP0, EP0002}
const TooManyRows = PQResultError{CP0, EP0003}
const AssertFailure = PQResultError{CP0, EP0004}

const InternalErrorErrorClass = PQResultError{CXX}

const InternalError = PQResultError{CXX, EXX000}
const DataCorrupted = PQResultError{CXX, EXX001}
const IndexCorrupted = PQResultError{CXX, EXX002}

const UnknownErrorClass = PQResultError{CUN}

const UnknownError = PQResultError{CUN, EUNOWN}

const ERROR_NAMES = Dict(
    SuccessfulCompletion => "SuccessfulCompletion",
    WarningWarning => "WarningWarning",
    DynamicResultSetsReturnedWarning => "DynamicResultSetsReturnedWarning",
    ImplicitZeroBitPaddingWarning => "ImplicitZeroBitPaddingWarning",
    NullValueEliminatedInSetFunctionWarning => "NullValueEliminatedInSetFunctionWarning",
    PrivilegeNotGrantedWarning => "PrivilegeNotGrantedWarning",
    PrivilegeNotRevokedWarning => "PrivilegeNotRevokedWarning",
    StringDataRightTruncationWarning => "StringDataRightTruncationWarning",
    DeprecatedFeatureWarning => "DeprecatedFeatureWarning",
    NoDataWarning => "NoDataWarning",
    NoAdditionalDynamicResultSetsReturnedWarning => "NoAdditionalDynamicResultSetsReturnedWarning",
    SqlStatementNotYetComplete => "SqlStatementNotYetComplete",
    ConnectionException => "ConnectionException",
    ConnectionDoesNotExist => "ConnectionDoesNotExist",
    ConnectionFailure => "ConnectionFailure",
    SqlclientUnableToEstablishSqlconnection => "SqlclientUnableToEstablishSqlconnection",
    SqlserverRejectedEstablishmentOfSqlconnection => "SqlserverRejectedEstablishmentOfSqlconnection",
    TransactionResolutionUnknown => "TransactionResolutionUnknown",
    ProtocolViolation => "ProtocolViolation",
    TriggeredActionException => "TriggeredActionException",
    FeatureNotSupported => "FeatureNotSupported",
    InvalidTransactionInitiation => "InvalidTransactionInitiation",
    LocatorException => "LocatorException",
    InvalidLocatorSpecification => "InvalidLocatorSpecification",
    InvalidGrantor => "InvalidGrantor",
    InvalidGrantOperation => "InvalidGrantOperation",
    InvalidRoleSpecification => "InvalidRoleSpecification",
    DiagnosticsException => "DiagnosticsException",
    StackedDiagnosticsAccessedWithoutActiveHandler => "StackedDiagnosticsAccessedWithoutActiveHandler",
    CaseNotFound => "CaseNotFound",
    CardinalityViolation => "CardinalityViolation",
    DataException => "DataException",
    ArraySubscriptError => "ArraySubscriptError",
    CharacterNotInRepertoire => "CharacterNotInRepertoire",
    DatetimeFieldOverflow => "DatetimeFieldOverflow",
    DivisionByZero => "DivisionByZero",
    ErrorInAssignment => "ErrorInAssignment",
    EscapeCharacterConflict => "EscapeCharacterConflict",
    IndicatorOverflow => "IndicatorOverflow",
    IntervalFieldOverflow => "IntervalFieldOverflow",
    InvalidArgumentForLogarithm => "InvalidArgumentForLogarithm",
    InvalidArgumentForNtileFunction => "InvalidArgumentForNtileFunction",
    InvalidArgumentForNthValueFunction => "InvalidArgumentForNthValueFunction",
    InvalidArgumentForPowerFunction => "InvalidArgumentForPowerFunction",
    InvalidArgumentForWidthBucketFunction => "InvalidArgumentForWidthBucketFunction",
    InvalidCharacterValueForCast => "InvalidCharacterValueForCast",
    InvalidDatetimeFormat => "InvalidDatetimeFormat",
    InvalidEscapeCharacter => "InvalidEscapeCharacter",
    InvalidEscapeOctet => "InvalidEscapeOctet",
    InvalidEscapeSequence => "InvalidEscapeSequence",
    NonstandardUseOfEscapeCharacter => "NonstandardUseOfEscapeCharacter",
    InvalidIndicatorParameterValue => "InvalidIndicatorParameterValue",
    InvalidParameterValue => "InvalidParameterValue",
    InvalidPrecedingOrFollowingSize => "InvalidPrecedingOrFollowingSize",
    InvalidRegularExpression => "InvalidRegularExpression",
    InvalidRowCountInLimitClause => "InvalidRowCountInLimitClause",
    InvalidRowCountInResultOffsetClause => "InvalidRowCountInResultOffsetClause",
    InvalidTablesampleArgument => "InvalidTablesampleArgument",
    InvalidTablesampleRepeat => "InvalidTablesampleRepeat",
    InvalidTimeZoneDisplacementValue => "InvalidTimeZoneDisplacementValue",
    InvalidUseOfEscapeCharacter => "InvalidUseOfEscapeCharacter",
    MostSpecificTypeMismatch => "MostSpecificTypeMismatch",
    NullValueNotAllowed => "NullValueNotAllowed",
    NullValueNoIndicatorParameter => "NullValueNoIndicatorParameter",
    NumericValueOutOfRange => "NumericValueOutOfRange",
    SequenceGeneratorLimitExceeded => "SequenceGeneratorLimitExceeded",
    StringDataLengthMismatch => "StringDataLengthMismatch",
    StringDataRightTruncation => "StringDataRightTruncation",
    SubstringError => "SubstringError",
    TrimError => "TrimError",
    UnterminatedCString => "UnterminatedCString",
    ZeroLengthCharacterString => "ZeroLengthCharacterString",
    FloatingPointException => "FloatingPointException",
    InvalidTextRepresentation => "InvalidTextRepresentation",
    InvalidBinaryRepresentation => "InvalidBinaryRepresentation",
    BadCopyFileFormat => "BadCopyFileFormat",
    UntranslatableCharacter => "UntranslatableCharacter",
    NotAnXmlDocument => "NotAnXmlDocument",
    InvalidXmlDocument => "InvalidXmlDocument",
    InvalidXmlContent => "InvalidXmlContent",
    InvalidXmlComment => "InvalidXmlComment",
    InvalidXmlProcessingInstruction => "InvalidXmlProcessingInstruction",
    DuplicateJsonObjectKeyValue => "DuplicateJsonObjectKeyValue",
    InvalidArgumentForSqlJsonDatetimeFunction => "InvalidArgumentForSqlJsonDatetimeFunction",
    InvalidJsonText => "InvalidJsonText",
    InvalidSqlJsonSubscript => "InvalidSqlJsonSubscript",
    MoreThanOneSqlJsonItem => "MoreThanOneSqlJsonItem",
    NoSqlJsonItem => "NoSqlJsonItem",
    NonNumericSqlJsonItem => "NonNumericSqlJsonItem",
    NonUniqueKeysInAJsonObject => "NonUniqueKeysInAJsonObject",
    SingletonSqlJsonItemRequired => "SingletonSqlJsonItemRequired",
    SqlJsonArrayNotFound => "SqlJsonArrayNotFound",
    SqlJsonMemberNotFound => "SqlJsonMemberNotFound",
    SqlJsonNumberNotFound => "SqlJsonNumberNotFound",
    SqlJsonObjectNotFound => "SqlJsonObjectNotFound",
    TooManyJsonArrayElements => "TooManyJsonArrayElements",
    TooManyJsonObjectMembers => "TooManyJsonObjectMembers",
    SqlJsonScalarRequired => "SqlJsonScalarRequired",
    IntegrityConstraintViolation => "IntegrityConstraintViolation",
    RestrictViolation => "RestrictViolation",
    NotNullViolation => "NotNullViolation",
    ForeignKeyViolation => "ForeignKeyViolation",
    UniqueViolation => "UniqueViolation",
    CheckViolation => "CheckViolation",
    ExclusionViolation => "ExclusionViolation",
    InvalidCursorState => "InvalidCursorState",
    InvalidTransactionState => "InvalidTransactionState",
    ActiveSqlTransaction => "ActiveSqlTransaction",
    BranchTransactionAlreadyActive => "BranchTransactionAlreadyActive",
    HeldCursorRequiresSameIsolationLevel => "HeldCursorRequiresSameIsolationLevel",
    InappropriateAccessModeForBranchTransaction => "InappropriateAccessModeForBranchTransaction",
    InappropriateIsolationLevelForBranchTransaction => "InappropriateIsolationLevelForBranchTransaction",
    NoActiveSqlTransactionForBranchTransaction => "NoActiveSqlTransactionForBranchTransaction",
    ReadOnlySqlTransaction => "ReadOnlySqlTransaction",
    SchemaAndDataStatementMixingNotSupported => "SchemaAndDataStatementMixingNotSupported",
    NoActiveSqlTransaction => "NoActiveSqlTransaction",
    InFailedSqlTransaction => "InFailedSqlTransaction",
    IdleInTransactionSessionTimeout => "IdleInTransactionSessionTimeout",
    InvalidSqlStatementName => "InvalidSqlStatementName",
    TriggeredDataChangeViolation => "TriggeredDataChangeViolation",
    InvalidAuthorizationSpecification => "InvalidAuthorizationSpecification",
    InvalidPassword => "InvalidPassword",
    DependentPrivilegeDescriptorsStillExist => "DependentPrivilegeDescriptorsStillExist",
    DependentObjectsStillExist => "DependentObjectsStillExist",
    InvalidTransactionTermination => "InvalidTransactionTermination",
    SqlRoutineException => "SqlRoutineException",
    FunctionExecutedNoReturnStatement => "FunctionExecutedNoReturnStatement",
    ModifyingSqlDataNotPermitted => "ModifyingSqlDataNotPermitted",
    ProhibitedSqlStatementAttempted => "ProhibitedSqlStatementAttempted",
    ReadingSqlDataNotPermitted => "ReadingSqlDataNotPermitted",
    InvalidCursorName => "InvalidCursorName",
    ExternalRoutineException => "ExternalRoutineException",
    ContainingSqlNotPermitted => "ContainingSqlNotPermitted",
    ModifyingSqlDataNotPermittedExt => "ModifyingSqlDataNotPermittedExt",
    ProhibitedSqlStatementAttemptedExt => "ProhibitedSqlStatementAttemptedExt",
    ReadingSqlDataNotPermittedExt => "ReadingSqlDataNotPermittedExt",
    ExternalRoutineInvocationException => "ExternalRoutineInvocationException",
    InvalidSqlstateReturned => "InvalidSqlstateReturned",
    NullValueNotAllowedExt => "NullValueNotAllowedExt",
    TriggerProtocolViolated => "TriggerProtocolViolated",
    SrfProtocolViolated => "SrfProtocolViolated",
    EventTriggerProtocolViolated => "EventTriggerProtocolViolated",
    SavepointException => "SavepointException",
    InvalidSavepointSpecification => "InvalidSavepointSpecification",
    InvalidCatalogName => "InvalidCatalogName",
    InvalidSchemaName => "InvalidSchemaName",
    TransactionRollback => "TransactionRollback",
    TransactionIntegrityConstraintViolation => "TransactionIntegrityConstraintViolation",
    SerializationFailure => "SerializationFailure",
    StatementCompletionUnknown => "StatementCompletionUnknown",
    DeadlockDetected => "DeadlockDetected",
    SyntaxErrorOrAccessRuleViolation => "SyntaxErrorOrAccessRuleViolation",
    SyntaxError => "SyntaxError",
    InsufficientPrivilege => "InsufficientPrivilege",
    CannotCoerce => "CannotCoerce",
    GroupingError => "GroupingError",
    WindowingError => "WindowingError",
    InvalidRecursion => "InvalidRecursion",
    InvalidForeignKey => "InvalidForeignKey",
    InvalidName => "InvalidName",
    NameTooLong => "NameTooLong",
    ReservedName => "ReservedName",
    DatatypeMismatch => "DatatypeMismatch",
    IndeterminateDatatype => "IndeterminateDatatype",
    CollationMismatch => "CollationMismatch",
    IndeterminateCollation => "IndeterminateCollation",
    WrongObjectType => "WrongObjectType",
    GeneratedAlways => "GeneratedAlways",
    UndefinedColumn => "UndefinedColumn",
    UndefinedFunction => "UndefinedFunction",
    UndefinedTable => "UndefinedTable",
    UndefinedParameter => "UndefinedParameter",
    UndefinedObject => "UndefinedObject",
    DuplicateColumn => "DuplicateColumn",
    DuplicateCursor => "DuplicateCursor",
    DuplicateDatabase => "DuplicateDatabase",
    DuplicateFunction => "DuplicateFunction",
    DuplicatePreparedStatement => "DuplicatePreparedStatement",
    DuplicateSchema => "DuplicateSchema",
    DuplicateTable => "DuplicateTable",
    DuplicateAlias => "DuplicateAlias",
    DuplicateObject => "DuplicateObject",
    AmbiguousColumn => "AmbiguousColumn",
    AmbiguousFunction => "AmbiguousFunction",
    AmbiguousParameter => "AmbiguousParameter",
    AmbiguousAlias => "AmbiguousAlias",
    InvalidColumnReference => "InvalidColumnReference",
    InvalidColumnDefinition => "InvalidColumnDefinition",
    InvalidCursorDefinition => "InvalidCursorDefinition",
    InvalidDatabaseDefinition => "InvalidDatabaseDefinition",
    InvalidFunctionDefinition => "InvalidFunctionDefinition",
    InvalidPreparedStatementDefinition => "InvalidPreparedStatementDefinition",
    InvalidSchemaDefinition => "InvalidSchemaDefinition",
    InvalidTableDefinition => "InvalidTableDefinition",
    InvalidObjectDefinition => "InvalidObjectDefinition",
    WithCheckOptionViolation => "WithCheckOptionViolation",
    InsufficientResources => "InsufficientResources",
    DiskFull => "DiskFull",
    OutOfMemory => "OutOfMemory",
    TooManyConnections => "TooManyConnections",
    ConfigurationLimitExceeded => "ConfigurationLimitExceeded",
    ProgramLimitExceeded => "ProgramLimitExceeded",
    StatementTooComplex => "StatementTooComplex",
    TooManyColumns => "TooManyColumns",
    TooManyArguments => "TooManyArguments",
    ObjectNotInPrerequisiteState => "ObjectNotInPrerequisiteState",
    ObjectInUse => "ObjectInUse",
    CantChangeRuntimeParam => "CantChangeRuntimeParam",
    LockNotAvailable => "LockNotAvailable",
    UnsafeNewEnumValueUsage => "UnsafeNewEnumValueUsage",
    OperatorIntervention => "OperatorIntervention",
    QueryCanceled => "QueryCanceled",
    AdminShutdown => "AdminShutdown",
    CrashShutdown => "CrashShutdown",
    CannotConnectNow => "CannotConnectNow",
    DatabaseDropped => "DatabaseDropped",
    SystemError => "SystemError",
    IoError => "IoError",
    UndefinedFile => "UndefinedFile",
    DuplicateFile => "DuplicateFile",
    SnapshotTooOld => "SnapshotTooOld",
    ConfigFileError => "ConfigFileError",
    LockFileExists => "LockFileExists",
    FdwError => "FdwError",
    FdwColumnNameNotFound => "FdwColumnNameNotFound",
    FdwDynamicParameterValueNeeded => "FdwDynamicParameterValueNeeded",
    FdwFunctionSequenceError => "FdwFunctionSequenceError",
    FdwInconsistentDescriptorInformation => "FdwInconsistentDescriptorInformation",
    FdwInvalidAttributeValue => "FdwInvalidAttributeValue",
    FdwInvalidColumnName => "FdwInvalidColumnName",
    FdwInvalidColumnNumber => "FdwInvalidColumnNumber",
    FdwInvalidDataType => "FdwInvalidDataType",
    FdwInvalidDataTypeDescriptors => "FdwInvalidDataTypeDescriptors",
    FdwInvalidDescriptorFieldIdentifier => "FdwInvalidDescriptorFieldIdentifier",
    FdwInvalidHandle => "FdwInvalidHandle",
    FdwInvalidOptionIndex => "FdwInvalidOptionIndex",
    FdwInvalidOptionName => "FdwInvalidOptionName",
    FdwInvalidStringLengthOrBufferLength => "FdwInvalidStringLengthOrBufferLength",
    FdwInvalidStringFormat => "FdwInvalidStringFormat",
    FdwInvalidUseOfNullPointer => "FdwInvalidUseOfNullPointer",
    FdwTooManyHandles => "FdwTooManyHandles",
    FdwOutOfMemory => "FdwOutOfMemory",
    FdwNoSchemas => "FdwNoSchemas",
    FdwOptionNameNotFound => "FdwOptionNameNotFound",
    FdwReplyHandle => "FdwReplyHandle",
    FdwSchemaNotFound => "FdwSchemaNotFound",
    FdwTableNotFound => "FdwTableNotFound",
    FdwUnableToCreateExecution => "FdwUnableToCreateExecution",
    FdwUnableToCreateReply => "FdwUnableToCreateReply",
    FdwUnableToEstablishConnection => "FdwUnableToEstablishConnection",
    PlpgsqlError => "PlpgsqlError",
    RaiseException => "RaiseException",
    NoDataFound => "NoDataFound",
    TooManyRows => "TooManyRows",
    AssertFailure => "AssertFailure",
    InternalError => "InternalError",
    DataCorrupted => "DataCorrupted",
    IndexCorrupted => "IndexCorrupted",
    UnknownError => "UnknownError",
)


text:
try
    using Revise
catch e
    if e isa ArgumentError
        import Pkg
        Pkg.add("Revise")
        using Revise
    else
        rethrow()
    end
end

ext: jl

max_stars_repo_name: wangl-cc/my-vim-config

max_issues_repo_name: wangl-cc/my-vim-config

max_forks_repo_name: wangl-cc/my-vim-config


text:
using StaticArrays
using LinearAlgebra
import DifferentialEquations;	const DE = DifferentialEquations

function pauli_matrices(; type=Float64)
	σ1 = SMatrix{2, 2, Complex{type}}([0 1; 1 0])
	σ2 = SMatrix{2, 2, Complex{type}}([0 -1im; 1im 0])
	σ3 = SMatrix{2, 2, Complex{type}}([1 0; 0 -1])
	σ4 = SMatrix{2, 2, Complex{type}}([1 0; 0 1])
	σ = (σ1, σ2, σ3, σ4)
	return σ
end
"""
Cosine envelope function.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `n::Integer`: harmonic order.
"""
function fc(t, tf, n)
	tau = t/tf
	ft = (1 - cos(2*pi*n*tau))/tf
	return ft
end
"""
Sine envelope function.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `n::Integer`: harmonic order.
"""
function fs(t, tf, n)
	tau = t/tf
	ft = sin(2*pi*n*tau)/tf
	return ft
end
"""
Definite integral of fc.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `n::Integer`: harmonic order.
"""
function intfc(t, tf, n)
	tau = t/tf
	c = 2*pi*n
	return tau - sin(c*tau)/c
end
"""
Driving fields in the x and y direction in a given subspace n of the bosonic system.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `α::Real`: angle of the rotation axis.
"""
function f(t, tf, α)
	#ft = zeros(2)
	theta = pi/2
	T = tf/2
	if t < T
		# ft[1] = theta*fc(t, T, 1)
		fx, fy = theta*fc(t, T, 1), 0.0
	else
		fct = theta*fc(t - T, T, 1)
		# ft[1], ft[2] = fct*cos(α), fct*sin(α)
		fx, fy = fct*cos(α), fct*sin(α)
	end
	#return ft
	return fx, fy
end
"""
Driving fields in the x and y direction in the whole truncated bosonic Hilbert space.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `α::Array{Real}`: angle of the rotation axes.
- `N::Integer`: size of the truncated bosonic Hilbert space.
"""
function f(t, tf, levels, α, N)
	ft = zeros(2, N)
	theta = pi/2
	index = levels .+ 1
	T = tf/2
	if t < T
		ft[1, index] .= theta*fc(t, T, 1)
	else
		fct = theta*fc(t - T, T, 1)
		ft[1, index] .= fct.*cos.(α)
		ft[2, index] .= fct.*sin.(α)
	end
	return ft
end
"""
Integral of the driving fields in the x and y direction in in a given subspace n of the
bosonic system.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `α::Array{Real}`: angle of the rotation axes.
"""
function intf(t, tf, α)
	theta = pi/2

	intfct = theta*intfc(t, tf, 1)
	intfx = intfct*cos(α)
	intfy = -intfct*sin(α)

	return intfx, intfy
end
"""
Integral of the driving fields in the x and y direction in the whole truncated bosonic
Hilbert space.
# Arguments
- `t::Real`: time.
- `tf::Real`: duration of the snap gate.
- `levels::Array{Integer}`: bosonic levels that are resonantly driven.
- `α::Array{Real}`: angle of the rotation axes.
- `N::Integer`: size of the truncated bosonic Hilbert space.
"""
function intf(t, tf, levels, α, N)
	intft = zeros(2, N)
	theta = pi/2
	index = levels .+ 1

	intfct = theta*intfc(t, tf, 1)
	intft[1, index] .= intfct.*cos.(α)
	intft[2, index] .= -intfct.*sin.(α)

	return intft
end

function F(t, tf, χ, levels, α, N; ideal_interaction::Bool=false)
	χef = (χ[1], χ[2]/2, χ[3]/6)
	Ft = zeros(4, N)
	for i = 1: length(levels)
		Fj!(Ft, t, tf, χef, levels[i], α[i], N, ideal_interaction)
	end
	return Ft
end

function Fj!(Ft, t, tf, χef, j, α, N, ideal_interaction)
	fx, fy = f(t, tf, α)
	if ideal_interaction == true
		Ft[1, j + 1] = fx
		Ft[2, j + 1] = -fy
	else
		for n = 0: N - 1
			dφn = χef[1]*n + χef[2]*n*(n - 1) + χef[3]*n*(n - 1)*(n - 2)
			dφj = χef[1]*j + χef[2]*j*(j - 1) + χef[3]*j*(j - 1)*(j - 2)
			φ = (dφn - dφj)*t
			cosφ = cos(φ)
			sinφ = sin(φ)
			Ft[1, n + 1] +=  + fx*cosφ - fy*sinφ
			Ft[2, n + 1] +=  - fx*sinφ - fy*cosφ
		end
	end
	return nothing
end

function V(t, tf, χ, levels, α, N)
	χef = (χ[1], χ[2]/2, χ[3]/6)
	Vt = zeros(4, N)
	for i = 1: length(levels)
		Vj!(Vt, t, tf, χef, levels[i], α[i], N)
	end
	return Vt
end

function Vj!(Vt, t, tf, χef, j, α, N)
	fx, fy = f(t, tf, α)
	for n = 0: N - 1
		if n != j
			dφn = χef[1]*n + χef[2]*n*(n - 1) + χef[3]*n*(n - 1)*(n - 2)
			dφj = χef[1]*j + χef[2]*j*(j - 1) + χef[3]*j*(j - 1)*(j - 2)
			φ = (dφn - dφj)*t
			cosφ = cos(φ)
			sinφ = sin(φ)
			Vt[1, n + 1] +=  + fx*cosφ - fy*sinφ
			Vt[2, n + 1] +=  - fx*sinφ - fy*cosφ
		end
	end
	return nothing
end

function VI(t, tf, χ, levels, α, N)
	T = tf/2
	Vt = V(t, tf, χ, levels, α, N)
	v = zeros(4, N)
	if t < T + 10.0*eps()
		v[1: 2, :] .= intf(t, T, levels, α.*0, N)
		unitary_tranformation!(Vt, v, N)
	else
		v[1: 2, :] .= intf(t - T, T, levels, α, N)
		unitary_tranformation!(Vt, v, N)
		v[1: 2, :] .= intf(T, T, levels, α.*0, N)
		unitary_tranformation!(Vt, v, N)
	end
	return Vt
end

function VI2(t, tf, χ, levels, α, N)
	Vt = V(t, tf, χ, levels, α, N)
	Vt = vector2matrix(Vt, σ)
	U0 = U(t, tf, χ, levels, α, N)
	VIt = adjoint(U0)*Vt*U0
	VI2t = zeros(4, N)
	for i = 1: N
		VI2t[:, i] = pauli_decomp(VIt[2*(i - 1) + 1: 2*i, 2*(i - 1) + 1: 2*i])
	end
	return VI2t
end

function H(t, F, args)
    σ = args[1]
	N = args[2]
    Ft = F(t)
	Ht = zeros(Complex{Float64}, 2, 2, N)
	for j = 1: N
		vj = view(Ft,:,j)
		Htj = view(Ht, :, :, j)
		vector2matrix!(Htj, vj, σ)
	end
	return Ht
end

function U(t, tf, χ, levels, α, N, σ)
	index = levels .+ 1
	aux = zeros(Complex{Float64}, N, 4)
	T = tf/2
	if t < T
		aux[1:2,:] .= -intf(t, T, levels, α.*0, N)
		aux .= exp_matrix(aux, N)
		U0 = vector2matrix(aux, σ)
	else
		aux[1: 2, :] .= -intf(T, T, levels, α.*0, N)
		aux .= exp_matrix(aux, N)
		U0 = vector2matrix(aux, σ)

		aux[1: 2, :] .= -intf(t-T, T, levels, α, N)
		aux[3: 4, :] .= zero(Complex{Float64})#zeros(Complex{Float64}, 2, N)
		aux .= exp_matrix(aux, N)
		M = vector2matrix(aux, σ)
		U0 = M*U0
	end
	return U0
end

function U2(t, tf, χ, levels, α, N, σ)
	index = levels .+ 1
	aux = zeros(4, N)
	M = zeros(Complex{Float64}, 2*N, 2*N)
	T = tf/2
	if t<T
		aux[1: 2, :] .= intf(t, T, levels, α.*0, N)
		vector2matrix!(M, aux, σ)
		U0 = exp(-1im*M)
	else
		aux[1: 2, :] .= intf(T, T, levels, α.*0, N)
		vector2matrix!(M, aux, σ)
		U0 = exp(-1im*M)

		aux[1: 2, :] .= intf(t-T, T, levels, α, N)
		vector2matrix!(M, aux, σ)
		U0 = exp(-1im*M)*U0
	end
	return U0
end

function dU!(dU, U, args, t)
	H = args[1]
	N = args[2]::Int
	Ht = args[3]
	M = args[4]
	Ht .= H(t)
	for j = 1: N
		mul!(M, view(Ht,:,:,j), view(U,:,:,j))
		dU[:,:,j] .= (-1im).*M
	end
end

function solveU(H, χ, F, tf, N, σ)
    args = (σ, N)
	fH = @closure t-> H(t, F, args)

	U0 = zeros(Complex{Float64}, 2, 2, N)
	for j = 1: N
		U0[:, :, j] .= Matrix{Complex{Float64}}(I, 2, 2)
	end
	tspan = (zero(tf), tf)
	args2 = (fH, N, zeros(Complex{Float64}, 2, 2, N), zeros(Complex{Float64}, 2, 2))
	prob = DE.ODEProblem(dU!, U0, tspan, args2)
	sol = DE.solve(prob, DE.Vern9(), saveat=[tf], reltol=1e-10, abstol=1e-14, maxiters=1e6)
	return sol(tf)
end

function U(system_params, σ; ideal_dynamics::Bool = false, matrix::Bool = false,
		   frame::String = "qubit")
	tf = system_params["tf"]
	χ = system_params["chi"]
	levels = system_params["levels"]
	α = system_params["alpha"]
	N = system_params["N"]

	if frame == "qubit"
		Faux = @closure t-> F(t, tf, χ, levels, α, N, ideal_interaction=ideal_dynamics)
	elseif frame == "interaction"
		if ideal_dynamics == true
			Faux = @closure t-> zeros(4, N)
		else
			Faux = @closure t-> VI(t, tf, χ, levels, α, N)
		end
	elseif frame == "lab"
		Faux = @closure t-> Flab(t, tf, χ, levels, α, N; ideal_interaction=ideal_dynamics)
	end

	sol = solveU(H, χ, Faux, tf, N, σ)
	if matrix == false
		return sol
	else
		return tensor2matrix(sol)
	end
end

function solveOmega_snap(H, tf, order, N)
	numdims = 4*N
	fH = @closure t-> -reshape(H(t), (numdims))

	Omegaf = solveOmega(tf, order, fH, comm!, numdims)

	reshaped_Omegaf = zeros(order, 4, N)
	for i = 1: order
		reshaped_Omegaf[i, :, :] .= reshape(Omegaf[:, i], (4, N))
	end
	return reshaped_Omegaf

end

max_stars_repo_name: thalesfr/MagnusCorrection

max_issues_repo_name: thalesfr/MagnusCorrection

max_forks_repo_name: thalesfr/MagnusCorrection


text:
# test
println("Hello")


text:
### A Hamiltonian is composed of blocks (kpoints), which have a list of RealFourierOperator
# corresponding to each term
# This is the "high-level" interface, provided for convenience

abstract type HamiltonianBlock end

# Generic HamiltonianBlock
struct GenericHamiltonianBlock <: HamiltonianBlock
    basis::PlaneWaveBasis
    kpoint::Kpoint

    # The operators are vectors of RealFourierOperator,
    # not typed because of type invariance issues.
    operators::Vector  # the original list of RealFourierOperator
                       # (as many as there are terms), kept for easier exploration
    optimized_operators::Vector  # Optimized list of RealFourierOperator, for application
end

# More optimized HamiltonianBlock for the important case of a DFT Hamiltonian
struct DftHamiltonianBlock <: HamiltonianBlock
    basis::PlaneWaveBasis
    kpoint::Kpoint
    operators::Vector

    # Individual operators for easy access
    fourier_op::FourierMultiplication
    local_op::RealSpaceMultiplication
    nonlocal_op::Union{Nothing,NonlocalOperator}
    divAgrad_op::Union{Nothing,DivAgradOperator}

    scratch  # Pre-allocated scratch arrays for fast application
end

function HamiltonianBlock(basis, kpoint, operators, scratch=ham_allocate_scratch_(basis))
    optimized_operators = optimize_operators_(operators)
    fourier_ops  = filter(o -> o isa FourierMultiplication,   optimized_operators)
    real_ops     = filter(o -> o isa RealSpaceMultiplication, optimized_operators)
    nonlocal_ops = filter(o -> o isa NonlocalOperator,        optimized_operators)
    divAgrid_ops = filter(o -> o isa DivAgradOperator,        optimized_operators)

    is_dft_ham = (   length(fourier_ops) == 1 && length(real_ops) == 1
                  && length(nonlocal_ops) < 2 && length(divAgrid_ops) < 2)
    if is_dft_ham
        nonlocal_op = isempty(nonlocal_ops) ? nothing : only(nonlocal_ops)
        divAgrid_op = isempty(divAgrid_ops) ? nothing : only(divAgrid_ops)
        DftHamiltonianBlock(basis, kpoint, operators,
                            only(fourier_ops), only(real_ops),
                            nonlocal_op, divAgrid_op, scratch)
    else
        GenericHamiltonianBlock(basis, kpoint, operators, optimized_operators)
    end
end
function ham_allocate_scratch_(basis::PlaneWaveBasis{T}) where {T}
    (ψ_reals=[zeros(complex(T), basis.fft_size...) for _ = 1:Threads.nthreads()], )
end

Base.:*(H::HamiltonianBlock, ψ) = mul!(similar(ψ), H, ψ)
Base.eltype(block::HamiltonianBlock) = complex(eltype(block.basis))
Base.size(block::HamiltonianBlock, i::Integer) = i < 3 ? size(block)[i] : 1
function Base.size(block::HamiltonianBlock)
    n_G = length(G_vectors(block.basis, block.kpoint))
    (n_G, n_G)
end

import Base: Matrix, Array
Array(block::HamiltonianBlock)  = Matrix(block)
Matrix(block::HamiltonianBlock) = sum(Matrix, block.operators)
Matrix(block::GenericHamiltonianBlock) = sum(Matrix, block.optimized_operators)

struct Hamiltonian
    basis::PlaneWaveBasis
    blocks::Vector{HamiltonianBlock}
end

function LinearAlgebra.mul!(Hψ, H::Hamiltonian, ψ)
    for ik = 1:length(H.basis.kpoints)
        mul!(Hψ[ik], H.blocks[ik], ψ[ik])
    end
    Hψ
end
# need `deepcopy` here to copy the elements of the array of arrays ψ (not just pointers)
Base.:*(H::Hamiltonian, ψ) = mul!(deepcopy(ψ), H, ψ)

# Loop through bands, IFFT to get ψ in real space, loop through terms, FFT and accumulate into Hψ
# For the common DftHamiltonianBlock there is an optimized version below
@views @timing "Hamiltonian multiplication" function LinearAlgebra.mul!(Hψ::AbstractArray,
                                                                        H::GenericHamiltonianBlock,
                                                                        ψ::AbstractArray)
    T = eltype(H.basis)
    n_bands = size(ψ, 2)
    Hψ_fourier = similar(Hψ[:, 1])
    ψ_real  = zeros(complex(T), H.basis.fft_size...)
    Hψ_real = zeros(complex(T), H.basis.fft_size...)

    # take ψi, IFFT it to ψ_real, apply each term to Hψ_fourier and Hψ_real, and add it to Hψ
    for iband = 1:n_bands
        Hψ_real .= 0
        Hψ_fourier .= 0
        G_to_r!(ψ_real, H.basis, H.kpoint, ψ[:, iband])
        for op in H.optimized_operators
            @timing "$(nameof(typeof(op)))" begin
                apply!((fourier=Hψ_fourier, real=Hψ_real),
                       op,
                       (fourier=ψ[:, iband], real=ψ_real))
            end
        end
        Hψ[:, iband] .= Hψ_fourier
        r_to_G!(Hψ_fourier, H.basis, H.kpoint, Hψ_real)
        Hψ[:, iband] .+= Hψ_fourier
    end

    Hψ
end

# Fast version, specialized on DFT models. Minimizes the number of FFTs and allocations
@views @timing "DftHamiltonian multiplication" function LinearAlgebra.mul!(Hψ::AbstractArray,
                                                                           H::DftHamiltonianBlock,
                                                                           ψ::AbstractArray)
    n_bands = size(ψ, 2)
    have_divAgrad = !isnothing(H.divAgrad_op)

    # Notice that we use unnormalized plans for extra speed
    potential = H.local_op.potential / prod(H.basis.fft_size)

    # parallelize the loop by breaking it into nthreads() chunks. The ψ_reals are chunk-local
    chunk_length = cld(n_bands, Threads.nthreads())
    @sync for (ichunk, chunk) in enumerate(Iterators.partition(1:n_bands, chunk_length))
        Threads.@spawn for iband in chunk # spawn a task per chunk
            to = TimerOutput()  # Thread-local timer output
            ψ_real = H.scratch.ψ_reals[ichunk]

            @timeit to "local+kinetic" begin
                G_to_r!(ψ_real, H.basis, H.kpoint, ψ[:, iband]; normalize=false)
                ψ_real .*= potential
                r_to_G!(Hψ[:, iband], H.basis, H.kpoint, ψ_real; normalize=false)  # overwrites ψ_real
                Hψ[:, iband] .+= H.fourier_op.multiplier .* ψ[:, iband]
            end

            if have_divAgrad
                @timeit to "divAgrad" begin
                    apply!((fourier=Hψ[:, iband], real=nothing),
                           H.divAgrad_op,
                           (fourier=ψ[:, iband], real=nothing),
                           ψ_real)  # ψ_real used as scratch
                end
            end

            if Threads.threadid() == 1
                merge!(DFTK.timer, to; tree_point=[t.name for t in DFTK.timer.timer_stack])
            end
       end
    end

    # Apply the nonlocal operator
    if !isnothing(H.nonlocal_op)
        @timing "nonlocal" begin
            apply!((fourier=Hψ, real=nothing), H.nonlocal_op, (fourier=ψ, real=nothing))
        end
    end

    Hψ
end

# Get energies and Hamiltonian
# kwargs is additional info that might be useful for the energy terms to precompute
# (eg the density ρ)
@timing function energy_hamiltonian(basis::PlaneWaveBasis, ψ, occupation; kwargs...)
    # it: index into terms, ik: index into kpoints
    @timing "ene_ops" ene_ops_arr = [ene_ops(term, basis, ψ, occupation; kwargs...)
                                     for term in basis.terms]
    energies  = [eh.E for eh in ene_ops_arr]
    operators = [eh.ops for eh in ene_ops_arr]         # operators[it][ik]

    # flatten the inner arrays in case a term returns more than one operator
    function flatten(arr)
        ret = []
        for a in arr
            if a isa RealFourierOperator
                push!(ret, a)
            else
                push!(ret, a...)
            end
        end
        ret
    end
    hks_per_k   = [flatten([blocks[ik] for blocks in operators])
                   for ik = 1:length(basis.kpoints)]      # hks_per_k[ik][it]

    H = Hamiltonian(basis, [HamiltonianBlock(basis, kpt, hks)
                            for (hks, kpt) in zip(hks_per_k, basis.kpoints)])
    E = Energies(basis.model.term_types, energies)
    (E=E, H=H)
end
function Hamiltonian(basis::PlaneWaveBasis; ψ=nothing, occupation=nothing, kwargs...)
    _, H = energy_hamiltonian(basis, ψ, occupation; kwargs...)
    H
end

"""
Get the total local potential of the given Hamiltonian, in real space
in the spin components.
"""
function total_local_potential(ham::Hamiltonian)
    n_spin = ham.basis.model.n_spin_components
    pots = map(1:n_spin) do σ
        # Get the potential from the first Hamiltonian block of this spin component
        # (works since all local potentials are the same)
        i_σ = first(krange_spin(ham.basis, σ))
        total_local_potential(ham.blocks[i_σ])
    end
    cat(pots..., dims=4)
end
total_local_potential(Hk::DftHamiltonianBlock) = Hk.local_op.potential
function total_local_potential(Hk::GenericHamiltonianBlock)
    only(o for o in Hk.optimized_operators if o isa RealSpaceMultiplication).potential
end

"""
Returns a new Hamiltonian with local potential replaced by the given one
"""
function hamiltonian_with_total_potential(ham::Hamiltonian, V)
    @assert size(V, 4) == ham.basis.model.n_spin_components
    newblocks = [hamiltonian_with_total_potential(Hk, V[:, :, :, Hk.kpoint.spin])
                 for Hk in ham.blocks]
    Hamiltonian(ham.basis, newblocks)
end
function hamiltonian_with_total_potential(Hk::HamiltonianBlock, V)
    operators = [op for op in Hk.operators if !(op isa RealSpaceMultiplication)]
    push!(operators, RealSpaceMultiplication(Hk.basis, Hk.kpoint, V))
    HamiltonianBlock(Hk.basis, Hk.kpoint, operators, Hk.scratch)
end


text:
@testset "Bitcoin address functions" begin
        @testset "address" begin
                secret = 888^3
                mainnet_address = "148dY81A9BmdpMhvYEVznrM45kWN32vSCN"
                testnet_address = "mieaqB68xDCtbUBYFoUNcmZNwk74xcBfTP"
                point = secret * ECC.G
                @test address(point, true, false) == mainnet_address
                @test address(point, true, true) == testnet_address
                secret = 321
                mainnet_address = "1S6g2xBJSED7Qr9CYZib5f4PYVhHZiVfj"
                testnet_address = "mfx3y63A7TfTtXKkv7Y6QzsPFY6QCBCXiP"
                point = secret * ECC.G
                @test address(point, false, false) == mainnet_address
                @test address(point, false, true) == testnet_address
                secret = 4242424242
                mainnet_address = "1226JSptcStqn4Yq9aAmNXdwdc2ixuH9nb"
                testnet_address = "mgY3bVusRUL6ZB2Ss999CSrGVbdRwVpM8s"
                point = secret * ECC.G
                @test address(point, false, false) == mainnet_address
                @test address(point, false, true) == testnet_address
        end
        @testset "WIF" begin
                pk = PrivateKey(big(2)^256-big(2)^199)
                expected = "L5oLkpV3aqBJ4BgssVAsax1iRa77G5CVYnv9adQ6Z87te7TyUdSC"
                @test wif(pk, true, false) == expected
                pk = PrivateKey(big(2)^256-big(2)^201)
                expected = "93XfLeifX7Jx7n7ELGMAf1SUR6f9kgQs8Xke8WStMwUtrDucMzn"
                @test wif(pk, false, true) == expected
                pk = PrivateKey(parse(BigInt, "0dba685b4511dbd3d368e5c4358a1277de9486447af7b3604a69b8d9d8b7889d", base=16))
                expected = "5HvLFPDVgFZRK9cd4C5jcWki5Skz6fmKqi1GQJf5ZoMofid2Dty"
                @test wif(pk, false, false) == expected
                pk = PrivateKey(parse(BigInt, "1cca23de92fd1862fb5b76e5f4f50eb082165e5191e116c18ed1a6b24be6a53f", base=16))
                expected = "cNYfWuhDpbNM1JWc3c6JTrtrFVxU4AGhUKgw5f93NP2QaBqmxKkg"
                @test wif(pk, true, true) == expected
        end
end


text:
using CUDA: has_cuda
using OrderedCollections: OrderedDict

using Oceananigans: AbstractModel, AbstractOutputWriter, AbstractDiagnostic

using Oceananigans.Architectures: AbstractArchitecture, GPU
using Oceananigans.Advection: AbstractAdvectionScheme, CenteredSecondOrder, VectorInvariantSchemes, VectorInvariant, WENOVectorInvariant
using Oceananigans.BuoyancyModels: validate_buoyancy, regularize_buoyancy, SeawaterBuoyancy, g_Earth
using Oceananigans.BoundaryConditions: regularize_field_boundary_conditions
using Oceananigans.Fields: Field, CenterField, tracernames, VelocityFields, TracerFields
using Oceananigans.Forcings: model_forcing
using Oceananigans.Grids: halo_size, inflate_halo_size, with_halo, AbstractRectilinearGrid
using Oceananigans.Grids: AbstractCurvilinearGrid, AbstractHorizontallyCurvilinearGrid, architecture
using Oceananigans.Models.NonhydrostaticModels: extract_boundary_conditions
using Oceananigans.TimeSteppers: Clock, TimeStepper, update_state!
using Oceananigans.TurbulenceClosures: validate_closure, with_tracers, DiffusivityFields, add_closure_specific_boundary_conditions
using Oceananigans.TurbulenceClosures: time_discretization, implicit_diffusion_solver
using Oceananigans.LagrangianParticleTracking: LagrangianParticles
using Oceananigans.Utils: tupleit

""" Returns a default_tracer_advection, tracer_advection `tuple`. """
validate_tracer_advection(invalid_tracer_advection, grid) = error("$invalid_tracer_advection is invalid tracer_advection!")
validate_tracer_advection(tracer_advection_tuple::NamedTuple, grid) = CenteredSecondOrder(), tracer_advection_tuple
validate_tracer_advection(tracer_advection::AbstractAdvectionScheme, grid) = tracer_advection, NamedTuple()

PressureField(grid) = (; pHY′ = CenterField(grid))

mutable struct HydrostaticFreeSurfaceModel{TS, E, A<:AbstractArchitecture, S,
                                           G, T, V, B, R, F, P, U, C, Φ, K, AF} <: AbstractModel{TS}

          architecture :: A        # Computer `Architecture` on which `Model` is run
                  grid :: G        # Grid of physical points on which `Model` is solved
                 clock :: Clock{T} # Tracks iteration number and simulation time of `Model`
             advection :: V        # Advection scheme for tracers
              buoyancy :: B        # Set of parameters for buoyancy model
              coriolis :: R        # Set of parameters for the background rotation rate of `Model`
          free_surface :: S        # Free surface parameters and fields
               forcing :: F        # Container for forcing functions defined by the user
               closure :: E        # Diffusive 'turbulence closure' for all model fields
             particles :: P        # Particle set for Lagrangian tracking
            velocities :: U        # Container for velocity fields `u`, `v`, and `w`
               tracers :: C        # Container for tracer fields
              pressure :: Φ        # Container for hydrostatic pressure
    diffusivity_fields :: K        # Container for turbulent diffusivities
           timestepper :: TS       # Object containing timestepper fields and parameters
      auxiliary_fields :: AF       # User-specified auxiliary fields for forcing functions and boundary conditions
end

"""
    HydrostaticFreeSurfaceModel(; grid,
                                             clock = Clock{eltype(grid)}(0, 0, 1),
                                momentum_advection = CenteredSecondOrder(),
                                  tracer_advection = CenteredSecondOrder(),
                                          buoyancy = SeawaterBuoyancy(eltype(grid)),
                                          coriolis = nothing,
                                      free_surface = ExplicitFreeSurface(gravitational_acceleration=g_Earth),
                               forcing::NamedTuple = NamedTuple(),
                                           closure = nothing,
                   boundary_conditions::NamedTuple = NamedTuple(),
                                           tracers = (:T, :S),
    particles::Union{Nothing, LagrangianParticles} = nothing,
                                        velocities = nothing,
                                          pressure = nothing,
                                diffusivity_fields = nothing,
                                  auxiliary_fields = NamedTuple(),
    )

Construct a hydrostatic model with a free surface on `grid`.

Keyword arguments
=================

  - `grid`: (required) The resolution and discrete geometry on which `model` is solved. The
    architecture (CPU/GPU) that the model is solve is inferred from the architecture of the grid.
  - `momentum_advection`: The scheme that advects velocities. See `Oceananigans.Advection`.
  - `tracer_advection`: The scheme that advects tracers. See `Oceananigans.Advection`.
  - `buoyancy`: The buoyancy model. See `Oceananigans.BuoyancyModels`.
  - `coriolis`: Parameters for the background rotation rate of the model.
  - `forcing`: `NamedTuple` of user-defined forcing functions that contribute to solution tendencies.
  - `free_surface`: The free surface model.
  - `closure`: The turbulence closure for `model`. See `Oceananigans.TurbulenceClosures`.
  - `boundary_conditions`: `NamedTuple` containing field boundary conditions.
  - `tracers`: A tuple of symbols defining the names of the modeled tracers, or a `NamedTuple` of
               preallocated `CenterField`s.
  - `particles`: Lagrangian particles to be advected with the flow. Default: `nothing`.
  - `velocities`: The model velocities. Default: `nothing`.
  - `pressure`: Hydrostatic pressure field. Default: `nothing`.
  - `diffusivity_fields`: Diffusivity fields. Default: `nothing`.
  - `auxiliary_fields`: `NamedTuple` of auxiliary fields. Default: `nothing`.

"""
function HydrostaticFreeSurfaceModel(; grid,
                                             clock = Clock{eltype(grid)}(0, 0, 1),
                                momentum_advection = CenteredSecondOrder(),
                                  tracer_advection = CenteredSecondOrder(),
                                          buoyancy = SeawaterBuoyancy(eltype(grid)),
                                          coriolis = nothing,
                                      free_surface = ExplicitFreeSurface(gravitational_acceleration=g_Earth),
                               forcing::NamedTuple = NamedTuple(),
                                           closure = nothing,
                   boundary_conditions::NamedTuple = NamedTuple(),
                                           tracers = (:T, :S),
    particles::Union{Nothing, LagrangianParticles} = nothing,
                                        velocities = nothing,
                                          pressure = nothing,
                                diffusivity_fields = nothing,
                                  auxiliary_fields = NamedTuple(),
    )

    # Check halos and throw an error if the grid's halo is too small
    user_halo = halo_size(grid)
    required_halo = inflate_halo_size(user_halo..., topology(grid),
                                      momentum_advection,
                                      tracer_advection,
                                      closure)

    any(user_halo .< required_halo) &&
        throw(ArgumentError("The grid halo $user_halo must be larger than $required_halo."))

    arch = architecture(grid)

    if arch == CUDAGPU() && !has_cuda()
        throw(ArgumentError("Cannot create a GPU model. No CUDA-enabled GPU was detected!"))
    end
    if arch == ROCMGPU() && !AMDGPU.has_rocm_gpu()
        throw(ArgumentError("Cannot create a GPU model. No ROCM-enabled GPU was detected!"))
    end

    momentum_advection = validate_momentum_advection(momentum_advection, grid)

    tracers = tupleit(tracers) # supports tracers=:c keyword argument (for example)

    validate_buoyancy(buoyancy, tracernames(tracers))
    buoyancy = regularize_buoyancy(buoyancy)

    # Collect boundary conditions for all model prognostic fields and, if specified, some model
    # auxiliary fields. Boundary conditions are "regularized" based on the _name_ of the field:
    # boundary conditions on u, v are regularized assuming they represent momentum at appropriate
    # staggered locations. All other fields are regularized assuming they are tracers.
    # Note that we do not regularize boundary conditions contained in *tupled* diffusivity fields right now.
    #
    # First, we extract boundary conditions that are embedded within any _user-specified_ field tuples:
    embedded_boundary_conditions = merge(extract_boundary_conditions(velocities),
                                         extract_boundary_conditions(tracers),
                                         extract_boundary_conditions(pressure),
                                         extract_boundary_conditions(diffusivity_fields))

    # Next, we form a list of default boundary conditions:
    prognostic_field_names = (:u, :v, :η, tracernames(tracers)...)
    default_boundary_conditions = NamedTuple{prognostic_field_names}(Tuple(FieldBoundaryConditions() for name in prognostic_field_names))

    # Then we merge specified, embedded, and default boundary conditions. Specified boundary conditions
    # have precedence, followed by embedded, followed by default.
    boundary_conditions = merge(default_boundary_conditions, embedded_boundary_conditions, boundary_conditions)
    boundary_conditions = regularize_field_boundary_conditions(boundary_conditions, grid, prognostic_field_names)

    # Finally, we ensure that closure-specific boundary conditions, such as
    # those required by TKEBasedVerticalDiffusivity, are enforced:
    boundary_conditions = add_closure_specific_boundary_conditions(closure, boundary_conditions, grid, tracernames(tracers), buoyancy)

    # Ensure `closure` describes all tracers
    closure = with_tracers(tracernames(tracers), closure)

    # Put CATKE first in the list of closures
    closure = validate_closure(closure)

    # Either check grid-correctness, or construct tuples of fields
    velocities         = HydrostaticFreeSurfaceVelocityFields(velocities, grid, clock, boundary_conditions)
    tracers            = TracerFields(tracers, grid, boundary_conditions)
    pressure           = PressureField(grid)
    diffusivity_fields = DiffusivityFields(diffusivity_fields, grid, tracernames(tracers), boundary_conditions, closure)

    validate_velocity_boundary_conditions(velocities)

    free_surface = FreeSurface(free_surface, velocities, grid)

    # Instantiate timestepper if not already instantiated
    implicit_solver = implicit_diffusion_solver(time_discretization(closure), grid)
    timestepper = TimeStepper(:QuasiAdamsBashforth2, grid, tracernames(tracers);
                              implicit_solver = implicit_solver,
                              Gⁿ = HydrostaticFreeSurfaceTendencyFields(velocities, free_surface, grid, tracernames(tracers)),
                              G⁻ = HydrostaticFreeSurfaceTendencyFields(velocities, free_surface, grid, tracernames(tracers)))

    # Regularize forcing for model tracer and velocity fields.
    model_fields = hydrostatic_prognostic_fields(velocities, free_surface, tracers)
    forcing = model_forcing(model_fields; forcing...)

    default_tracer_advection, tracer_advection = validate_tracer_advection(tracer_advection, grid)

    # Advection schemes
    tracer_advection_tuple = with_tracers(tracernames(tracers),
                                          tracer_advection,
                                          (name, tracer_advection) -> default_tracer_advection,
                                          with_velocities=false)

    advection = merge((momentum=momentum_advection,), tracer_advection_tuple)

    model = HydrostaticFreeSurfaceModel(arch, grid, clock, advection, buoyancy, coriolis,
                                        free_surface, forcing, closure, particles, velocities, tracers,
                                        pressure, diffusivity_fields, timestepper, auxiliary_fields)

    update_state!(model)

    return model
end

validate_velocity_boundary_conditions(velocities) = validate_vertical_velocity_boundary_conditions(velocities.w)

function validate_vertical_velocity_boundary_conditions(w)
    w.boundary_conditions.top === nothing || error("Top boundary condition for HydrostaticFreeSurfaceModel velocities.w
                                                    must be `nothing`!")
    return nothing
end

momentum_advection_squawk(momentum_advection, grid) = error("$(typeof(momentum_advection)) is not supported with $(typeof(grid))")

validate_momentum_advection(momentum_advection, grid) = momentum_advection
validate_momentum_advection(momentum_advection, grid::AbstractHorizontallyCurvilinearGrid) = momentum_advection_squawk(momentum_advection, grid)
validate_momentum_advection(momentum_advection::Union{VectorInvariantSchemes, Nothing}, grid::AbstractHorizontallyCurvilinearGrid) = momentum_advection


text:
using MyProject
using Test

@testset "MyProject.jl" begin
    @test hello("codekomali") == "Hello, codekomali"
    @test addnums(1,2) == 3
    @test mulnums(2,3) == 6
end


text:
#!/usr/bin/env julia

using Celeste: Model, DeterministicVI

import Celeste: Infer, DeterministicVI, ParallelRun
import Celeste: PSF, SDSSIO, SensitiveFloats, Transform
import SensitiveFloats.clear!
import SDSSIO: RunCamcolField

include("Synthetic.jl")
include("SampleData.jl")
include("DerivativeTestUtils.jl")

import Synthetic
using SampleData

using Base.Test
using Distributions

anyerrors = false

# Ensure that test images are available.
const datadir = joinpath(Pkg.dir("Celeste"), "test", "data")
wd = pwd()
cd(datadir)
run(`make`)
run(`make RUN=4263 CAMCOL=5 FIELD=119`)
cd(wd)

# Check whether to run time-consuming derivatives tests.
test_derivatives_flag = "--test_derivatives"
test_detailed_derivatives = test_derivatives_flag in ARGS
test_files = setdiff(ARGS, [ test_derivatives_flag ])

if length(test_files) > 0
    testfiles = ["test_$(arg).jl" for arg in test_files]
else
    testfiles = ["test_elbo_values.jl",
                 "test_score.jl",
                 "test_derivatives.jl",
                 "test_psf.jl",
                 "test_images.jl",
                 "test_misc.jl",
                 "test_optimization.jl",
                 "test_sdssio.jl",
                 "test_transforms.jl",
                 "test_wcs.jl",
                 "test_infer.jl"]
end

if test_detailed_derivatives
    warn("Testing ELBO derivatives, which may be slow.")
    push!(testfiles, "test_slow_derivatives.jl")
else
    warn("Skipping slow derivative tests.  ",
         "To test slow derivatives, run tests with the flag ", test_derivatives_flag)
end

for testfile in testfiles
    try
        println("Running ", testfile)
        include(testfile)
        println("\t\033[1m\033[32mPASSED\033[0m: $(testfile)")
    catch e
        anyerrors = true
        println("\t\033[1m\033[31mFAILED\033[0m: $(testfile)")
        rethrow()  # Fail fast.
    end
end


text:
# Analog IO API

#------------------------------------ Control

#------------------------------------ Configuration

function analogIOChannelNodeSet(hdwf::Hdwf,idxChannel::Int32,idxNode::Int32,value::Float64)
  succ = ccall((:FDwfAnalogIOChannelNodeSet,libdwf),Cint,(Hdwf,Cint,Cint,Cdouble),
    hdwf,idxChannel,idxNode,value)
  succ == 0 && error("Error calling FDwfAnalogIOChannelNodeSet.")
  return nothing
end

function analogIOEnableSet(hdwf::Hdwf,fMasterEnable::Bool)
  succ = ccall((:FDwfAnalogIOEnableSet,libdwf),Cint,(Hdwf,Cint),
    hdwf,Int32(fMasterEnable))
  succ == 0 && error("Error calling FDwfAnalogIOEnableSet.")
  return nothing
end

#### TODO ####
# // Control:
# DWFAPI BOOL FDwfAnalogIOReset(HDWF hdwf);
# DWFAPI BOOL FDwfAnalogIOConfigure(HDWF hdwf);
# DWFAPI BOOL FDwfAnalogIOStatus(HDWF hdwf);
#
# // Configure:
# DWFAPI BOOL FDwfAnalogIOEnableInfo(HDWF hdwf, BOOL *pfSet, BOOL *pfStatus);
# DWFAPI BOOL FDwfAnalogIOEnableGet(HDWF hdwf, BOOL *pfMasterEnable);
# DWFAPI BOOL FDwfAnalogIOEnableStatus(HDWF hdwf, BOOL *pfMasterEnable);
# DWFAPI BOOL FDwfAnalogIOChannelCount(HDWF hdwf, int *pnChannel);
# DWFAPI BOOL FDwfAnalogIOChannelName(HDWF hdwf, int idxChannel, char szName[32], char szLabel[16]);
# DWFAPI BOOL FDwfAnalogIOChannelInfo(HDWF hdwf, int idxChannel, int *pnNodes);
# DWFAPI BOOL FDwfAnalogIOChannelNodeName(HDWF hdwf, int idxChannel, int idxNode, char szNodeName[32], char szNodeUnits[16]);
# DWFAPI BOOL FDwfAnalogIOChannelNodeInfo(HDWF hdwf, int idxChannel, int idxNode, ANALOGIO *panalogio);
# DWFAPI BOOL FDwfAnalogIOChannelNodeSetInfo(HDWF hdwf, int idxChannel, int idxNode, double *pmin, double *pmax, int *pnSteps);
# DWFAPI BOOL FDwfAnalogIOChannelNodeGet(HDWF hdwf, int idxChannel, int idxNode, double *pvalue);
# DWFAPI BOOL FDwfAnalogIOChannelNodeStatusInfo(HDWF hdwf, int idxChannel, int idxNode, double *pmin, double *pmax, int *pnSteps);
# DWFAPI BOOL FDwfAnalogIOChannelNodeStatus(HDWF hdwf, int idxChannel, int idxNode, double *pvalue);


text:
"""
$(SIGNATURES)

Get code of type <: `AbstractGNSSSystem` at phase `phase` of PRN `prn`.
```julia-repl
julia> get_code(GPSL1, 1200.3, 1)
```
"""
Base.@propagate_inbounds function get_code(
    ::Type{T},
    phase,
    prn::Int
) where T <: AbstractGNSSSystem
    floored_phase = floor(Int, phase)
    get_code_unsafe(
        T,
        mod(floored_phase, get_code_length(T) * get_secondary_code_length(T)),
        prn
    )
end

"""
$(SIGNATURES)

Get code of type <: `AbstractGNSSSystem` at phase `phase` of PRN `prn`.
The phase will not be wrapped by the code length. The phase has to smaller
than the code length incl. secondary code.
```julia-repl
julia> get_code_unsafe(GPSL1, 10.3, 1)
```
"""
Base.@propagate_inbounds function get_code_unsafe(
    ::Type{T},
    phase,
    prn::Int
) where T <: AbstractGNSSSystem
    get_code_unsafe(T, floor(Int, phase), prn)
end

"""
$(SIGNATURES)

Get code to center frequency ratio
```julia-repl
julia> get_code_unsafe(GPSL1, 10.3, 1)
```
"""
@inline function get_code_center_frequency_ratio(::Type{T}) where T <: AbstractGNSSSystem
    get_code_frequency(T) / get_center_frequency(T)
end


text:
# wrappers for functionality provided by the CUDA toolkit

const overrides = quote end

macro device_override(ex)
    code = quote
        $GPUCompiler.@override($method_table, $ex)
    end
    if isdefined(Base.Experimental, Symbol("@overlay"))
        return esc(code)
    else
        push!(overrides.args, code)
        return
    end
end

macro device_function(ex)
    ex = macroexpand(__module__, ex)
    def = splitdef(ex)

    # generate a function that errors
    def[:body] = quote
        error("This function is not intended for use on the CPU")
    end

    esc(quote
        $(combinedef(def))
        @device_override $ex
    end)
end

# extensions to the C language
include("intrinsics/memory_shared.jl")
include("intrinsics/indexing.jl")
include("intrinsics/synchronization.jl")
include("intrinsics/warp_vote.jl")
include("intrinsics/warp_shuffle.jl")
include("intrinsics/output.jl")
include("intrinsics/assertion.jl")
include("intrinsics/memory_dynamic.jl")
include("intrinsics/atomics.jl")
include("intrinsics/misc.jl")
include("intrinsics/wmma.jl")
include("intrinsics/random.jl")

# functionality from libdevice
#
# > The libdevice library is a collection of NVVM bitcode functions that implement common
# > functions for NVIDIA GPU devices, including math primitives and bit-manipulation
# > functions. These functions are optimized for particular GPU architectures, and are
# > intended to be linked with an NVVM IR module during compilation to PTX.
include("intrinsics/math.jl")
# TODO: native mathematical functions, CUDA C programming guide" > "C language extensions"
#       https://docs.nvidia.com/cuda/cuda-math-api/group__CUDA__MATH__INTRINSIC__DOUBLE.html
#       see /path/to/cuda/include/sm_20_intrinsics.h

# functionality from libcudadevrt
#
# The libcudadevrt library is a collection of PTX bitcode functions that implement parts of
# the CUDA API for execution on the device, such as device synchronization primitives,
# dynamic kernel APIs, etc.
using CEnum
include("intrinsics/libcudadevrt_common.jl")
include("intrinsics/libcudadevrt.jl")
include("intrinsics/cooperative_groups.jl")
include("intrinsics/dynamic_parallelism.jl")


text:
using Documenter, Islander

makedocs(;
    modules=[Islander],
    format=Documenter.HTML(assets=String[]),
    pages=[
        "Home" => "index.md",
        "Conventions" => "conventions.md"
    ],
    repo="https://github.com/xzackli/Islander.jl/blob/{commit}{path}#L{line}",
    sitename="Islander.jl",
    authors="xzackli"
)

deploydocs(
    repo = "github.com/xzackli/Islander.jl.git",
)


text:
"""
    print_for_maple(ode, package)

Prints the ODE in the format accepted by maple packages
- SIAN (https://github.com/pogudingleb/SIAN) if package=:SIAN
- DifferentialAlgebra if package=:DifferentialAlgebra
- DifferentialThomas if package=:DifferentialThomas
"""
function print_for_maple(ode::ODE, package=:SIAN)
    varstr = Dict(x => var_to_str(x) * "(t)" for x in vcat(ode.x_vars, ode.u_vars, ode.y_vars))
    merge!(varstr, Dict(p => var_to_str(p) for p in ode.parameters))
    R_print, vars_print = Nemo.PolynomialRing(base_ring(ode.poly_ring), [varstr[v] for v in gens(ode.poly_ring)])
    x_names = join(map(var_to_str, ode.x_vars), ", ")
    y_names = join(map(var_to_str, ode.y_vars), ", ")
    u_names = join(map(var_to_str, ode.u_vars), ", ")
    u_string = length(u_names) > 0 ? ", [$u_names]" : ""
    ranking = "[$x_names], [$y_names] $u_string"

    result = ""

    # Forming the header
    if package == :SIAN
        result *= "read \"../IdentifiabilityODE.mpl\";\n\nsys := [\n"
    elseif package == :DifferentialAlgebra
        result *= "with(DifferentialAlgebra):\n"
        u_string = length(u_names) > 0 ? "[$u_names]" : ""
        result *= "ring_diff := DifferentialRing(blocks = [$ranking], derivations = [t]):\n"
        result *= "sys := [\n"
    elseif package == :DifferentialThomas
        result *= "with(DifferentialThomas):\nwith(Tools):\n"
        result *= "Ranking([t], [$ranking]):\n"
        result *= "sys := [\n"
    else
        throw(Base.ArgumentError("Unknown package: $package"))
    end

    # Form the equations
    function _rhs_to_str(rhs)
        num, den = unpack_fraction(rhs)
        res = string(evaluate(num, vars_print))
        if den != 1
             res = "($res) / ($(evaluate(den, vars_print)))"
        end
        return res
    end

    eqs = []
    for (x, f) in ode.x_equations
        push!(eqs, ("diff(" * var_to_str(x) * "(t), t)", _rhs_to_str(f)))
    end
    for (y, g) in ode.y_equations
        push!(eqs, (var_to_str(y) * "(t)", _rhs_to_str(g)))
    end
    if package == :SIAN
        result *= join(map(a -> a[1] * " = " * a[2], eqs), ",\n") * "\n];\n"
    else
        result *= join(map(a -> "$(a[1]) - ($(a[2]))", eqs), ",\n") * "\n];\n"
    end

    # Forming the footer
    if package == :SIAN
        result *= "CodeTools[CPUTime](IdentifiabilityODE(sys, GetParameters(sys)));"
    elseif package == :DifferentialAlgebra
        result *= "res := CodeTools[CPUTime](RosenfeldGroebner(sys, ring_diff, singsol=none));"
    else
        result *= "res := CodeTools[CPUTime](ThomasDecomposition(sys));"
    end

    # Eliminating Julia integer divisions and variable name I
    result = replace(result, "//" => "/")
    result = replace(result, "I(t)" => "II(t)")
    return result
end

#------------------------------------------------------------------------------

function _rhs_to_str(lhs)
    num, den = unpack_fraction(lhs)
    rslt = string(num)
    if den != 1
         rslt = "($rslt) / ($den)"
    end
    return rslt
end

"""
    print_for_DAISY(ode)

Prints the ODE in the format accepted by DAISY (https://daisy.dei.unipd.it/)
"""
function print_for_DAISY(ode::ODE)
    result = ""

    # listing functions (ordering u, y, x matters!)
    result = result * "B_:={" * join(map(var_to_str, vcat(ode.u_vars, ode.y_vars, ode.x_vars)), ", ") * "}\$\n"

    result = result * "FOR EACH EL_ IN B_ DO DEPEND EL_,T\$\n\n"

    # listing parameters
    result = result * "B1_:={" * join(map(var_to_str, ode.parameters), ", ") * "}\$\n"

    result = result * " %NUMBER OF STATES\nNX_:=$(length(ode.x_vars))\$\n"
    result = result * " %NUMBER OF INPUTS\nNU_:=$(length(ode.u_vars))\$\n"
    result = result * " %NUMBER OF OUTPUTS\nNY_:=$(length(ode.y_vars))\$\n\n"

    eqs = []

    for (x, f) in ode.x_equations
        push!(eqs, "df($(var_to_str(x)), t) = " * _rhs_to_str(f))
    end
    for (y, g) in ode.y_equations
        push!(eqs, "$(var_to_str(y)) = " * _rhs_to_str(g))
    end

    result = result * "C_:={" * join(eqs, ",\n") * "}\$\n"

    result = result * "FLAG_:=1\$\nSHOWTIME\$\nDAISY()\$\nSHOWTIME\$\nEND\$\n"

    result = replace(result, "//" => "/")
    return result
end

#-------------------------------------------------------------------------------

"""
    print_for_GenSSI(ode)

Prints the ODE in the format accepted by GenSSI 2.0 (https://github.com/genssi-developer/GenSSI)
"""
function print_for_GenSSI(ode::ODE)
    result = "function model = SMTH()\n"

    result *= "syms " * join(var_to_str.(ode.x_vars)," ") * "\n"
    result *= "syms " * join(var_to_str.(ode.parameters), " ") * "\n"
    result *= "syms " * join(map(v -> var_to_str(v) * "0", ode.x_vars), " ") * "\n"
    if length(ode.u_vars) > 0
        result *= "syms " * join(var_to_str.(ode.u_vars), " ") * "\n"
    end

    result *= "model.sym.p = [" * join(var_to_str.(ode.parameters), "; ") * "; "
    result *= join(map(v -> var_to_str(v) * "0", ode.x_vars), "; ") * "];\n"

    result *= "model.sym.x = [" * join(var_to_str.(ode.x_vars), "; ") * "];\n"
    result *= "model.sym.g = [" * join(var_to_str.(ode.u_vars), "; ") * "];\n"

    result *= "model.sym.x0 = [" * join(map(v -> var_to_str(v) * "0", ode.x_vars), "; ") * "];\n"

    result *= "model.sym.xdot = ["

    eqs = []
    for x in ode.x_vars
        f = ode.x_equations[x]
        push!(eqs, _rhs_to_str(f))
    end
    result *= join(eqs, "\n") * "];\n"

    result *= "model.sym.y = ["
    eqs = []
    for y in ode.y_vars
        g = ode.y_equations[y]
        push!(eqs, _rhs_to_str(g))
    end
    result *= join(eqs, "\n") * "];\n"

    result *= "end"

    result = replace(result, "//" => "/")
    return result
end

#------------------------------------------------------------------------------

"""
    print_for_COMBOS(ode)

Prints the ODE in the format accepted by COMBOS (http://biocyb1.cs.ucla.edu/combos/)
"""
function print_for_COMBOS(ode::ODE)
    varstr = Dict(x => "x" * string(ind) for (ind, x) in enumerate(ode.x_vars))
    merge!(varstr, Dict(u => "u" * string(ind) for (ind, u) in enumerate(ode.u_vars)))
    merge!(varstr, Dict(y => "y" * string(ind) for (ind, y) in enumerate(ode.y_vars)))
    merge!(varstr, Dict(p => var_to_str(p) for p in ode.parameters))
    R_print, vars_print = Nemo.PolynomialRing(base_ring(ode.poly_ring), [varstr[v] for v in gens(ode.poly_ring)])

    result = ""

    eqs = []

    function _lhs_to_str(lhs)
        num, den = unpack_fraction(lhs)
        res = string(evaluate(num, vars_print))
        if den != 1
             res = "($res) / ($(evaluate(den, vars_print)))"
        end
        return res
    end

    for (x, f) in ode.x_equations
        push!(eqs, "d$(varstr[x])/dt = " * _lhs_to_str(f))
    end
    for (y, g) in ode.y_equations
        push!(eqs, "$(varstr[y]) = " * _lhs_to_str(g))
    end

    result = result * join(eqs, "; ")

    result = replace(result, "//" => "/")
    result = replace(result, "_" => ",")
    return result
end


text:
using AstronomicalDetectors
using Test

@testset "AstronomicalDetectors.jl" begin
    # Write your tests here.
end


text:
const cuDeviceTotalMem = cuDeviceTotalMem_v2
const cuCtxCreate = cuCtxCreate_v2
const cuModuleGetGlobal = cuModuleGetGlobal_v2
const cuMemGetInfo = cuMemGetInfo_v2
const cuMemAlloc = cuMemAlloc_v2
const cuMemAllocPitch = cuMemAllocPitch_v2
const cuMemFree = cuMemFree_v2
const cuMemGetAddressRange = cuMemGetAddressRange_v2
const cuMemAllocHost = cuMemAllocHost_v2
const cuMemHostGetDevicePointer = cuMemHostGetDevicePointer_v2
const cuMemcpyHtoD = cuMemcpyHtoD_v2
const cuMemcpyDtoH = cuMemcpyDtoH_v2
const cuMemcpyDtoD = cuMemcpyDtoD_v2
const cuMemcpyDtoA = cuMemcpyDtoA_v2
const cuMemcpyAtoD = cuMemcpyAtoD_v2
const cuMemcpyHtoA = cuMemcpyHtoA_v2
const cuMemcpyAtoH = cuMemcpyAtoH_v2
const cuMemcpyAtoA = cuMemcpyAtoA_v2
const cuMemcpyHtoAAsync = cuMemcpyHtoAAsync_v2
const cuMemcpyAtoHAsync = cuMemcpyAtoHAsync_v2
const cuMemcpy2D = cuMemcpy2D_v2
const cuMemcpy2DUnaligned = cuMemcpy2DUnaligned_v2
const cuMemcpy3D = cuMemcpy3D_v2
const cuMemcpyHtoDAsync = cuMemcpyHtoDAsync_v2
const cuMemcpyDtoHAsync = cuMemcpyDtoHAsync_v2
const cuMemcpyDtoDAsync = cuMemcpyDtoDAsync_v2
const cuMemcpy2DAsync = cuMemcpy2DAsync_v2
const cuMemcpy3DAsync = cuMemcpy3DAsync_v2
const cuMemsetD8 = cuMemsetD8_v2
const cuMemsetD16 = cuMemsetD16_v2
const cuMemsetD32 = cuMemsetD32_v2
const cuMemsetD2D8 = cuMemsetD2D8_v2
const cuMemsetD2D16 = cuMemsetD2D16_v2
const cuMemsetD2D32 = cuMemsetD2D32_v2
const cuArrayCreate = cuArrayCreate_v2
const cuArrayGetDescriptor = cuArrayGetDescriptor_v2
const cuArray3DCreate = cuArray3DCreate_v2
const cuArray3DGetDescriptor = cuArray3DGetDescriptor_v2
const cuTexRefSetAddress = cuTexRefSetAddress_v2
const cuTexRefGetAddress = cuTexRefGetAddress_v2
const cuGraphicsResourceGetMappedPointer = cuGraphicsResourceGetMappedPointer_v2
const cuCtxDestroy = cuCtxDestroy_v2
const cuCtxPopCurrent = cuCtxPopCurrent_v2
const cuCtxPushCurrent = cuCtxPushCurrent_v2
const cuStreamDestroy = cuStreamDestroy_v2
const cuEventDestroy = cuEventDestroy_v2
const cuTexRefSetAddress2D = cuTexRefSetAddress2D_v3
const cuLinkCreate = cuLinkCreate_v2
const cuLinkAddData = cuLinkAddData_v2
const cuLinkAddFile = cuLinkAddFile_v2
const cuMemHostRegister = cuMemHostRegister_v2
const cuGraphicsResourceSetMapFlags = cuGraphicsResourceSetMapFlags_v2


text:
using Images, BenchmarkTools

function calc(a,b)
    z = c = complex(a, b)
    for i in 1:3000
        z = z*z + c
        if abs(z) > 3
            return true
        end
    end
    return false
end

function buddha(points::Array{ComplexF64}, h::Int, w::Int)
    img = zeros(RGB,w,h)
    for c::ComplexF64 in points
        i::Int = 0
        z::ComplexF64 = c
        while abs(z) < 3 && i < 1000
            x::Int = trunc(Int,(real(z) + 2)*w/3); y::Int = trunc(Int,(imag(z) + 1.5)*h/3)
            0<x<w && 0<y<h && i > 20 ? img[x,y] += RGB(0,0,0.004) : nothing #log10(i)/3
            z = z*z + c
            i += 1
        end
    end
    return img
end

function main()
    h::Int = 8000
    w::Int = 8000
    points::Array{ComplexF64} = []
    for b in -1.5:3/h:1.5
        for a in -2.:3/w:1.
            calc(a,b) && append!(points, complex(a,b))
        end
    end
    println("Init done")
    return map(clamp01nan, buddha(points,2000,2000))
end

#@benchmark main()
@time save("./out/buddha.png", main())

max_stars_repo_name: BoardTM/fractals

max_issues_repo_name: BoardTM/fractals

max_forks_repo_name: BoardTM/fractals


text:
"""
GenX: An Configurable Capacity Expansion Model
Copyright (C) 2021,  Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
A complete copy of the GNU General Public License v2 (GPLv2) is available
in LICENSE.txt.  Users uncompressing this from an archive may not have
received this license file.  If not, see <http://www.gnu.org/licenses/>.
"""

@doc raw"""
	write_costs(path::AbstractString, inputs::Dict, setup::Dict, EP::Model)

Function for writing the costs pertaining to the objective function (fixed, variable O&M etc.).
"""
function write_costs(path::AbstractString, inputs::Dict, setup::Dict, EP::Model)
	## Cost results
	dfGen = inputs["dfGen"]
	SEG = inputs["SEG"]  # Number of lines
	Z = inputs["Z"]     # Number of zones
	T = inputs["T"]     # Number of time steps (hours)

	dfCost = DataFrame(Costs = ["cTotal", "cFix", "cVar", "cNSE", "cStart", "cUnmetRsv", "cNetworkExp"])
	if setup["ParameterScale"] == 1
		cVar = (value(EP[:eTotalCVarOut])+ (!isempty(inputs["STOR_ALL"]) ? value(EP[:eTotalCVarIn]) : 0) + (!isempty(inputs["FLEX"]) ? value(EP[:eTotalCVarFlexIn]) : 0)) * (ModelScalingFactor^2)
		cFix = (value(EP[:eTotalCFix]) + (!isempty(inputs["STOR_ALL"]) ? value(EP[:eTotalCFixEnergy]) : 0) + (!isempty(inputs["STOR_ASYMMETRIC"]) ? value(EP[:eTotalCFixCharge]) : 0)) * (ModelScalingFactor^2)
		dfCost[!,Symbol("Total")] = [objective_value(EP) * (ModelScalingFactor^2), cFix, cVar, value(EP[:eTotalCNSE]) * (ModelScalingFactor^2), 0, 0, 0]
	else
		cVar = (value(EP[:eTotalCVarOut])+ (!isempty(inputs["STOR_ALL"]) ? value(EP[:eTotalCVarIn]) : 0) + (!isempty(inputs["FLEX"]) ? value(EP[:eTotalCVarFlexIn]) : 0))
		#cVar = value(EP[:eTotalCVarOut])+(!isempty(inputs["STOR_ALL"]) ? value(EP[:eTotalCVarIn]) : 0) + (!isempty(inputs["FLEX"]) ? value(EP[:eTotalCVarFlexIn]) : 0)
		cFix = value(EP[:eTotalCFix]) + (!isempty(inputs["STOR_ALL"]) ? value(EP[:eTotalCFixEnergy]) : 0) + (!isempty(inputs["STOR_ASYMMETRIC"]) ? value(EP[:eTotalCFixCharge]) : 0)
		dfCost[!,Symbol("Total")] = [objective_value(EP), cFix, cVar, value(EP[:eTotalCNSE]), 0, 0, 0]
	end

	if setup["UCommit"]>=1
		if setup["ParameterScale"] == 1
			dfCost[!,2][5] = value(EP[:eTotalCStart]) * (ModelScalingFactor^2)
		else
			dfCost[!,2][5] = value(EP[:eTotalCStart])
		end
	end
	if setup["Reserves"]==1
		if setup["ParameterScale"] == 1
			dfCost[!,2][6] = value(EP[:eTotalCRsvPen]) * (ModelScalingFactor^2)
		else
			dfCost[!,2][6] = value(EP[:eTotalCRsvPen])
		end
	end
	if setup["NetworkExpansion"] == 1 && Z > 1
		if setup["ParameterScale"] == 1
			dfCost[!,2][7] = value(EP[:eTotalCNetworkExp]) * (ModelScalingFactor^2)
		else
			dfCost[!,2][7] = value(EP[:eTotalCNetworkExp])
		end
	end

	for z in 1:Z
		tempCTotal = 0
		tempCFix = 0
		tempCVar = 0
		tempCStart = 0
		for y in dfGen[dfGen[!,:Zone].==z,:][!,:R_ID]
			tempCFix = tempCFix +
				(y in inputs["STOR_ALL"] ? value.(EP[:eCFixEnergy])[y] : 0) +
				(y in inputs["STOR_ASYMMETRIC"] ? value.(EP[:eCFixCharge])[y] : 0) +
				value.(EP[:eCFix])[y]
			tempCVar = tempCVar +
				(y in inputs["STOR_ALL"] ? sum(value.(EP[:eCVar_in])[y,:]) : 0) +
				(y in inputs["FLEX"] ? sum(value.(EP[:eCVarFlex_in])[y,:]) : 0) +
				sum(value.(EP[:eCVar_out])[y,:])
			if setup["UCommit"]>=1
				tempCTotal = tempCTotal +
					value.(EP[:eCFix])[y] +
					(y in inputs["STOR_ALL"] ? sum(value.(EP[:eCVar_in])[y,:]) : 0) +
					(y in inputs["FLEX"] ? sum(value.(EP[:eCVarFlex_in])[y,:]) : 0) +
					sum(value.(EP[:eCVar_out])[y,:])
					(y in inputs["COMMIT"] ? sum(value.(EP[:eCStart])[y,:]) : 0)
				tempCStart = tempCStart +
					(y in inputs["COMMIT"] ? sum(value.(EP[:eCStart])[y,:]) : 0)
			else
				tempCTotal = tempCTotal +
					value.(EP[:eCFix])[y] +
					(y in inputs["STOR_ALL"] ? sum(value.(EP[:eCVar_in])[y,:]) : 0) +
					(y in inputs["FLEX"] ? sum(value.(EP[:eCVarFlex_in])[y,:]) : 0) +
					sum(value.(EP[:eCVar_out])[y,:])
			end
		end

		if setup["ParameterScale"] == 1
			tempCFix = tempCFix * (ModelScalingFactor^2)
			tempCVar = tempCVar * (ModelScalingFactor^2)
			tempCTotal = tempCTotal * (ModelScalingFactor^2)
			tempCStart = tempCStart * (ModelScalingFactor^2)
		end
		if setup["ParameterScale"] == 1
			tempCNSE = sum(value.(EP[:eCNSE])[:,:,z]) * (ModelScalingFactor^2)
		else
			tempCNSE = sum(value.(EP[:eCNSE])[:,:,z])
		end
		dfCost[!,Symbol("Zone$z")] = [tempCTotal, tempCFix, tempCVar, tempCNSE, tempCStart, "-", "-"]
	end
	CSV.write(joinpath(path, "costs.csv"), dfCost)
end

max_stars_repo_name: Betristor/LTESOM

max_issues_repo_name: Betristor/LTESOM

max_forks_repo_name: Betristor/LTESOM


text:
# -*- coding: utf-8 -*-
# # Poisson Equation
#
# $$
# \frac{\partial^2 u}{\partial x^2} = b  \qquad x \in [0,1]
# $$
#
# $$
# u(0) = u(1) = 0, \qquad b = \sin(2\pi x)
# $$

using Plots, BenchmarkTools

function plot_solution(x, u)
    plot([0;x;1],[0;u;0], label="computed")
    scatter!([0;x;1],-sin.(2π*[0;x;1])/(4π^2),label="exact")
end

Δx = 0.05
x = Δx:Δx:1-Δx ## Solve only interior points: the endpoints are set to zero.
N = length(x)

A = zeros(N,N)
for i in 1:N, j in 1:N
    abs(i-j) <= 1 && (A[i,j] +=1)
    i==j          && (A[i,j] -=3)
end

B = sin.(2π*x) * Δx^2
u = A \ B

plot_solution(x, u)

# # SparseArrays

using SparseArrays

Δx = 0.05
x = Δx:Δx:1-Δx ## Solve only interior points: the endpoints are set to zero.
N = length(x)
B = sin.(2π*x) * Δx^2

P = spdiagm( -1 =>    ones(Float64,N-1),
              0 => -2*ones(Float64,N),
              1 =>    ones(Float64,N-1))

u = P \ B

plot_solution(x, u)

# # LinearAlgebra

using LinearAlgebra

Δx = 0.05
x = Δx:Δx:1-Δx ## Solve only interior points: the endpoints are set to zero.
N = length(x)
B = sin.(2π*x) * Δx^2

DU =  ones(Float64, N-1)
D = -2ones(Float64, N)
DL =  ones(Float64, N-1)

T = Tridiagonal(DL, D, DU)

u = T \ B

plot_solution(x, u)
#----------------------------------------------------------------------------

# # LAPACK

using LinearAlgebra

Δx = 0.05
x = Δx:Δx:1-Δx ## Solve only interior points: the endpoints are set to zero.
N = length(x)
B = sin.(2π*x) * Δx^2

DU =   ones(Float64, N-1)
D  = -2ones(Float64, N)
DL =   ones(Float64, N-1)

LAPACK.gtsv!(DL, D, DU, B)

plot_solution(x, B)
#----------------------------------------------------------------------------

# # DIffEqOperators.jl
#
# [docs](http://docs.juliadiffeq.org/latest/features/diffeq_operator.html)

using DiffEqOperators
#----------------------------------------------------------------------------

Δx = 0.05
x = Δx:Δx:1-Δx ## Solve only interior points: the endpoints are set to zero.
N = length(x)
B = sin.(2π*x)

## Second order approximation to the second derivative
order = 2
deriv = 2

A = DerivativeOperator{Float64}(order, deriv, Δx, N, :Dirichlet0,:Dirichlet0)

u = A \ B

plot_solution(x, u)

max_stars_repo_name: pnavaro/math-julia

max_issues_repo_name: pnavaro/math-julia

max_forks_repo_name: pnavaro/math-julia


text:
module YaoBlocks

include("utils.jl")
# include("traits.jl")

include("abstract_block.jl")
include("block_map.jl")

# concrete blocks
include("routines.jl")
include("primitive/primitive.jl")
include("composite/composite.jl")

include("algebra.jl")
include("blocktools.jl")
include("layout.jl")

include("deprecations.jl")

end # YaoBlocks


text:
using DTU_BrayamValqui_SP2021
using Test
using Gurobi
using GLPK
using CPLEX

println("*****************Benders Solution*****************")
#OPF------------------------------------------------------#
#@time (syscost_det,p_G_value,p_D_value,Dual_constraint6,f_value)=solver_OPF(Gurobi.Optimizer,"results/OPF_Solution.txt")

@time (Set_stage1_cost,Set_invements_wind,Set_invements_thermal,Set_upperbound,Τ)=Solver_Benders(Gurobi.Optimizer,"results/Benders_Solution.txt")
#cd("C:\\Users\\braya\\.julia\\dev\\DTU_BrayamValqui_SP2021\\test")


text:
function myunzip(file,directory)
    @assert splitext(file)[2]==".zip"
    if Sys.isunix() && Sys.KERNEL != :FreeBSD
        return (`unzip -x $file -d $directory`)
    end

    if Sys.KERNEL == :FreeBSD
        tar_args = ["--no-same-owner", "--no-same-permissions"]
        return pipeline(
            `/bin/mkdir -p $dir`,
            `/usr/bin/tar -xf $file -C $dir $tar_args`)
    end

    if Sys.iswindows()
        #exe7z = joinpath(Sys.BINDIR, "7z.exe")
        #return (`$exe7z x $file -y -o$directory`)
        cmd = `powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('$(file)', '$(directory)'); }"`
        return cmd
    end
end #end function

#=
    fi="H:\\Code\\Julia\\DecisionTrees.jl\\data\\freMTPL2\\freMTPL2.zip"
    cmd=myunzip(fi,splitdir(fi)[1])
    run(cmd)
=#