file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
frontend/src/components/ui/sheet.tsx
TypeScript (TSX)
import { cn } from '@/lib/utils'; import * as SheetPrimitive from '@radix-ui/react-dialog'; import { type VariantProps, cva } from 'class-variance-authority'; import { X } from 'lucide-react'; import * as React from 'react'; const Sheet = SheetPrimitive.Root; const SheetTrigger = SheetPrimitive.Trigger; const SheetClose = SheetPrimitive.Close; const SheetPortal = SheetPrimitive.Portal; const SheetOverlay = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Overlay>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay> >(({ className, ...props }, ref) => ( <SheetPrimitive.Overlay className={cn( 'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0', className )} {...props} ref={ref} /> )); SheetOverlay.displayName = SheetPrimitive.Overlay.displayName; const sheetVariants = cva( 'fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out', { variants: { side: { top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top', bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom', left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm', right: 'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm' } }, defaultVariants: { side: 'right' } } ); interface SheetContentProps extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>, VariantProps<typeof sheetVariants> {} const SheetContent = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Content>, SheetContentProps >(({ side = 'right', className, children, ...props }, ref) => ( <SheetPortal> <SheetOverlay /> <SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props} > <SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary"> <X className="h-4 w-4" /> <span className="sr-only">Close</span> </SheetPrimitive.Close> {children} </SheetPrimitive.Content> </SheetPortal> )); SheetContent.displayName = SheetPrimitive.Content.displayName; const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( 'flex flex-col space-y-2 text-center sm:text-left', className )} {...props} /> ); SheetHeader.displayName = 'SheetHeader'; const SheetFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => ( <div className={cn( 'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2', className )} {...props} /> ); SheetFooter.displayName = 'SheetFooter'; const SheetTitle = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Title>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title> >(({ className, ...props }, ref) => ( <SheetPrimitive.Title ref={ref} className={cn('text-lg font-semibold text-foreground', className)} {...props} /> )); SheetTitle.displayName = SheetPrimitive.Title.displayName; const SheetDescription = React.forwardRef< React.ElementRef<typeof SheetPrimitive.Description>, React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description> >(({ className, ...props }, ref) => ( <SheetPrimitive.Description ref={ref} className={cn('text-sm text-muted-foreground', className)} {...props} /> )); SheetDescription.displayName = SheetPrimitive.Description.displayName; export { Sheet, SheetPortal, SheetOverlay, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/components/ui/sonner.tsx
TypeScript (TSX)
import { useTheme } from 'next-themes'; import { Toaster as Sonner } from 'sonner'; type ToasterProps = React.ComponentProps<typeof Sonner>; const Toaster = ({ ...props }: ToasterProps) => { const { theme = 'system' } = useTheme(); return ( <Sonner theme={theme as ToasterProps['theme']} className="toaster group" toastOptions={{ classNames: { toast: 'group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg', description: 'group-[.toast]:text-muted-foreground', actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground', cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground' } }} {...props} /> ); }; export { Toaster };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/components/ui/switch.tsx
TypeScript (TSX)
import { cn } from '@/lib/utils'; import * as SwitchPrimitives from '@radix-ui/react-switch'; import * as React from 'react'; const Switch = React.forwardRef< React.ElementRef<typeof SwitchPrimitives.Root>, React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root> >(({ className, ...props }, ref) => ( <SwitchPrimitives.Root className={cn( 'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input', className )} {...props} ref={ref} > <SwitchPrimitives.Thumb className={cn( 'pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0' )} /> </SwitchPrimitives.Root> )); Switch.displayName = SwitchPrimitives.Root.displayName; export { Switch };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/components/ui/table.tsx
TypeScript (TSX)
import { cn } from '@/lib/utils'; import * as React from 'react'; const Table = React.forwardRef< HTMLTableElement, React.HTMLAttributes<HTMLTableElement> >(({ className, ...props }, ref) => ( <div className="relative w-full overflow-auto"> <table ref={ref} className={cn('w-full caption-bottom text-sm', className)} {...props} /> </div> )); Table.displayName = 'Table'; const TableHeader = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} /> )); TableHeader.displayName = 'TableHeader'; const TableBody = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <tbody ref={ref} className={cn('[&_tr:last-child]:border-0', className)} {...props} /> )); TableBody.displayName = 'TableBody'; const TableFooter = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes<HTMLTableSectionElement> >(({ className, ...props }, ref) => ( <tfoot ref={ref} className={cn( 'border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className )} {...props} /> )); TableFooter.displayName = 'TableFooter'; const TableRow = React.forwardRef< HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement> >(({ className, ...props }, ref) => ( <tr ref={ref} className={cn( 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted', className )} {...props} /> )); TableRow.displayName = 'TableRow'; const TableHead = React.forwardRef< HTMLTableCellElement, React.ThHTMLAttributes<HTMLTableCellElement> >(({ className, ...props }, ref) => ( <th ref={ref} className={cn( 'h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]', className )} {...props} /> )); TableHead.displayName = 'TableHead'; const TableCell = React.forwardRef< HTMLTableCellElement, React.TdHTMLAttributes<HTMLTableCellElement> >(({ className, ...props }, ref) => ( <td ref={ref} className={cn( 'p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]', className )} {...props} /> )); TableCell.displayName = 'TableCell'; const TableCaption = React.forwardRef< HTMLTableCaptionElement, React.HTMLAttributes<HTMLTableCaptionElement> >(({ className, ...props }, ref) => ( <caption ref={ref} className={cn('mt-4 text-sm text-muted-foreground', className)} {...props} /> )); TableCaption.displayName = 'TableCaption'; export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/components/ui/textarea.tsx
TypeScript (TSX)
import { cn } from '@/lib/utils'; import * as React from 'react'; const Textarea = React.forwardRef< HTMLTextAreaElement, React.ComponentProps<'textarea'> >(({ className, ...props }, ref) => { return ( <textarea className={cn( 'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm', className )} ref={ref} {...props} /> ); }); Textarea.displayName = 'Textarea'; export { Textarea };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/components/ui/tooltip.tsx
TypeScript (TSX)
import { cn } from '@/lib/utils'; import * as TooltipPrimitive from '@radix-ui/react-tooltip'; import * as React from 'react'; const TooltipProvider = TooltipPrimitive.Provider; const Tooltip = TooltipPrimitive.Root; const TooltipTrigger = TooltipPrimitive.Trigger; const TooltipContent = React.forwardRef< React.ElementRef<typeof TooltipPrimitive.Content>, React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content> >(({ className, sideOffset = 4, ...props }, ref) => ( <TooltipPrimitive.Portal> <TooltipPrimitive.Content ref={ref} sideOffset={sideOffset} className={cn( 'z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2', className )} {...props} /> </TooltipPrimitive.Portal> )); TooltipContent.displayName = TooltipPrimitive.Content.displayName; export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useCurrentEditState.ts
TypeScript
import { editStateState } from '@/state'; import FunctionViewContext from '@/views/function/context'; import { useContext } from 'react'; import { useRecoilValue } from 'recoil'; export default function useCurrentEditState() { const { currentLineageId } = useContext(FunctionViewContext); const editState = useRecoilValue(editStateState); return editState[currentLineageId]; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useCurrentLineage.ts
TypeScript
import { stateHistoryByLineageState } from '@/state'; import FunctionViewContext from '@/views/function/context'; import { useContext } from 'react'; import { useRecoilValue } from 'recoil'; export default function useCurrentLineage() { const { currentLineageId } = useContext(FunctionViewContext); const stateHistoryByLineage = useRecoilValue(stateHistoryByLineageState); return stateHistoryByLineage[currentLineageId]; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useCurrentState.ts
TypeScript
import useCurrentEditState from './useCurrentEditState'; import useCurrentLineage from './useCurrentLineage'; import FunctionViewContext from '@/views/function/context'; import { useContext } from 'react'; export default function useCurrentState() { const editState = useCurrentEditState(); const { currentStateIndex } = useContext(FunctionViewContext); const currentLineage = useCurrentLineage(); if (editState) return editState; return currentLineage?.[currentStateIndex]; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useForkState.ts
TypeScript
import { type ILooplitState, forksByMessageIndexState, stateHistoryByLineageState } from '../state'; import useInteraction from './useInteraction'; import FunctionViewContext from '@/views/function/context'; import { useContext } from 'react'; import { useRecoilCallback } from 'recoil'; import { v4 as uuidv4 } from 'uuid'; export const useForkState = () => { const { callStatefulFunction } = useInteraction(); const { id, name, currentLineageId, setCurrentLineageId, setCurrentStateIndex } = useContext(FunctionViewContext); return useRecoilCallback( ({ set }) => async (state: ILooplitState, messageIndex: number) => { const newLineageId = uuidv4(); const newState: ILooplitState = { ...state, id: newLineageId }; // Update state history with new lineage set(stateHistoryByLineageState, (prevHistory) => ({ ...prevHistory, [newLineageId]: [newState] })); // Update forks tracking set(forksByMessageIndexState, (prevForks) => { // Create a deep copy of the previous forks const updatedForks = { ...prevForks }; // Initialize the function ID array if it doesn't exist if (!updatedForks[id]) { updatedForks[id] = []; } // Create a new array for the message index if it doesn't exist // or create a copy of the existing array const messageIndexForks = updatedForks[id][messageIndex] ? [...updatedForks[id][messageIndex]] : [currentLineageId]; // Create a new array with all indices up to messageIndex const newMessageIndexArray = [ ...updatedForks[id].slice(0, messageIndex) ]; // Add the updated forks array at messageIndex newMessageIndexArray[messageIndex] = [ ...messageIndexForks, newLineageId ]; // Update the function ID array with the new message index array updatedForks[id] = newMessageIndexArray; return updatedForks; }); // Switch to new lineage setCurrentLineageId?.(() => newLineageId); setCurrentStateIndex?.(() => 0); callStatefulFunction({ func_name: name, lineage_id: newLineageId, state: newState }); return newLineageId; }, [ callStatefulFunction, name, currentLineageId, setCurrentLineageId, setCurrentStateIndex ] ); };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useInteraction.ts
TypeScript
import { ILooplitState, errorState, sessionState } from '@/state'; import { useCallback } from 'react'; import { useRecoilValue, useSetRecoilState } from 'recoil'; export interface ICallStatefulFunctionPayload { func_name: string; lineage_id: string; state: ILooplitState; } export interface ICallCanvasAgentPayload { chat_id: string; context: string; message: string; state: string; } export default function useInteraction() { const session = useRecoilValue(sessionState); const setError = useSetRecoilState(errorState); const setInterrupt = useCallback( (interrupt: boolean) => { session?.socket.emit('set_interrupt', interrupt); }, [session?.socket] ); const callStatefulFunction = useCallback( (payload: ICallStatefulFunctionPayload) => { setError(undefined); session?.socket.emit('call_stateful_func', payload); }, [session?.socket, setError] ); const callCanvasAgent = useCallback( (payload: ICallCanvasAgentPayload) => { session?.socket.emit('call_canvas_agent', payload); }, [session?.socket] ); return { setInterrupt, callStatefulFunction, callCanvasAgent }; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/usePlatform.ts
TypeScript
import { useMemo } from 'react'; const MOBILE_REGEX = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i; type PlatformPayload = { isSSR: boolean; isMobile: boolean; isDesktop: boolean; isMac: boolean; }; export const usePlatform = (): PlatformPayload => { const platforms = useMemo(() => { if (navigator == null) { return { isSSR: true, isMobile: false, isDesktop: false, isMac: false }; } const isMobile = navigator.userAgent.match(MOBILE_REGEX) != null; const isMac = navigator.userAgent.toUpperCase().match(/MAC/) != null; return { isSSR: false, isMobile, isDesktop: !isMobile, isMac }; }, []); return platforms; };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/hooks/useSetEditState.ts
TypeScript
import { ILooplitState, editStateState } from '@/state'; import FunctionViewContext from '@/views/function/context'; import { useContext } from 'react'; import { useSetRecoilState } from 'recoil'; export default function useSetEditState() { const { currentLineageId } = useContext(FunctionViewContext); const setEditState = useSetRecoilState(editStateState); return (state?: ILooplitState) => { return setEditState((prev) => { const next = { ...prev }; if (state) { next[currentLineageId] = state; } else { delete next[currentLineageId]; } return next; }); }; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/index.css
CSS
@tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 96%; --foreground: 240 10% 3.9%; --card: 0 0% 98%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --muted: 0 0% 93%; --muted-foreground: 240 3.8% 46.1%; --accent: 0 0% 93%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 0 0% 88%; --input: 0 0% 88%; --primary: 0 0% 9%; --primary-foreground: 0 0% 98%; --secondary: 0 0% 96.1%; --secondary-foreground: 0 0% 9%; --ring: 0 0% 3.9%; --chart-1: 12 76% 61%; --chart-2: 173 58% 39%; --chart-3: 197 37% 24%; --chart-4: 43 74% 66%; --chart-5: 27 87% 67%; --radius: 0.5rem; } .dark { --background: 0 0% 4%; --foreground: 0 0% 95%; --card: 200 9% 6%; --card-foreground: 0 0% 95%; --popover: 0 0% 9%; --popover-foreground: 0 0% 95%; --primary: 0 0% 98%; --primary-foreground: 0 0% 9%; --secondary: 0 0% 14.9%; --secondary-foreground: 0 0% 98%; --muted: 0 0% 15%; --muted-foreground: 240 5% 64.9%; --accent: 12 6.5% 15.1%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 85.7% 97.3%; --border: 224 9% 15%; --input: 224 9% 15%; --ring: 0 0% 83.1%; --chart-1: 220 70% 50%; --chart-2: 160 60% 45%; --chart-3: 30 80% 55%; --chart-4: 280 65% 60%; --chart-5: 340 75% 55%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } .monaco-light-card { .monaco-editor { --vscode-editor-background: #FBFBFB; --vscode-editorGutter-background: #FBFBFB; } } .monaco-dark-card { .monaco-editor { --vscode-editor-background: #0E1011; --vscode-editorGutter-background: #0E1011; } }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/lib/utils.ts
TypeScript
import { type ClassValue, clsx } from 'clsx'; import { twMerge } from 'tailwind-merge'; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/main.tsx
TypeScript (TSX)
import App from './App.tsx'; import './index.css'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { RecoilRoot } from 'recoil'; createRoot(document.getElementById('root')!).render( <StrictMode> <RecoilRoot> <App /> </RecoilRoot> </StrictMode> );
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/state.ts
TypeScript
import type { IMessage } from './components/Message'; import { atom } from 'recoil'; import { Socket } from 'socket.io-client'; export interface ISession { socket: Socket; error?: boolean; } export const sessionState = atom<ISession | undefined>({ key: 'Session', dangerouslyAllowMutability: true, default: undefined }); export interface ILooplitState { id: string; metadata?: Record<string, any>; messages: IMessage[]; tools: Record<string, any>[]; } export const stateHistoryByLineageState = atom<Record<string, ILooplitState[]>>( { key: 'stateHistoryByLineage', default: {} } ); export const toolCallsToLineageIdsState = atom<Record<string, string>>({ key: 'toolCallsToLineageIds', default: {} }); export const forksByMessageIndexState = atom<Record<string, string[][]>>({ key: 'forksByMessageIndex', default: {} }); export const editStateState = atom<Record<string, ILooplitState>>({ key: 'editState', default: {} }); export const functionsState = atom<Record<string, ILooplitState> | undefined>({ key: 'Functions', default: undefined }); export const aiEditSuggestionState = atom<ILooplitState | undefined>({ key: 'AiEditSuggestion', default: { id: 'fef', messages: [], tools: [] } }); export interface IInterrupt { callback: () => void; func_name: string; } export const interruptState = atom<IInterrupt | undefined>({ key: 'Interrupt', default: undefined }); export const runningState = atom<boolean>({ key: 'Running', default: false }); export interface IError { lineage_id: string; error: string; } export const errorState = atom<IError | undefined>({ key: 'Error', default: undefined }); export interface ICanvasState { chatId: string; running: boolean; error?: string; acceptAll?: () => void; rejectAll?: () => void; messages: { role: string; content: string }[]; context: string; lineageId: string; openCoords: { x: number; y: number }; aiState: string; origState: string; } export const canvasState = atom<ICanvasState | undefined>({ key: 'Canvas', default: undefined }); export type EditorFormat = 'json' | 'yaml'; export const editorFormatState = atom<EditorFormat>({ key: 'editorFormatState', default: (() => { if (typeof window === 'undefined') return 'json'; try { const stored = localStorage.getItem('editor-format-preference'); if (stored === 'json' || stored === 'yaml') { return stored; } } catch (error) { console.error('Error reading from localStorage:', error); } return 'yaml'; })() });
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/connecting/index.tsx
TypeScript (TSX)
import { Loader } from '@/components/Loader'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { functionsState, sessionState } from '@/state'; import { AlertCircle } from 'lucide-react'; import { useRecoilValue } from 'recoil'; export default function ConnectingView() { const session = useRecoilValue(sessionState); const functions = useRecoilValue(functionsState); const alert = session?.error ? ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription> Failed to establish websocket connection. </AlertDescription> </Alert> ) : null; const connecting = !session || functions === undefined ? ( <div className="flex items-center gap-1"> <Loader /> Connecting... </div> ) : null; if (!alert && !connecting) return null; return ( <div className="h-screen w-screen flex items-center justify-center"> <div className="max-w-[48rem] flex flex-col gap-4"> {alert} {connecting} </div> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Body/AskAIButton.tsx
TypeScript (TSX)
import CanvasFloatingInput from '@/components/Canvas/CanvasFloatingInput'; import { Button } from '@/components/ui/button'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import useCurrentState from '@/hooks/useCurrentState'; import { runningState } from '@/state'; import { SparklesIcon } from 'lucide-react'; import { useState } from 'react'; import { useRecoilValue } from 'recoil'; interface Props { index: number; } export default function AskAIButton({ index }: Props) { const isRunning = useRecoilValue(runningState); const editState = useCurrentEditState(); const currentState = useCurrentState(); const [open, setOpen] = useState(false); if (!currentState) return null; return ( <Popover open={open} onOpenChange={setOpen}> <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <PopoverTrigger asChild> <Button disabled={isRunning || !!editState} className="text-muted-foreground" variant="ghost" size="icon" > <SparklesIcon /> </Button> </PopoverTrigger> </TooltipTrigger> <TooltipContent> <p>Ask AI</p> </TooltipContent> </Tooltip> </TooltipProvider> <PopoverContent align="start" className="p-0 shadow-none border-none bg-transparent" > <CanvasFloatingInput setOpen={setOpen} selectedText={JSON.stringify( currentState.messages[index], undefined, 2 )} /> </PopoverContent> </Popover> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Body/ForkButton.tsx
TypeScript (TSX)
import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import useCurrentLineage from '@/hooks/useCurrentLineage'; import useCurrentState from '@/hooks/useCurrentState'; import { useForkState } from '@/hooks/useForkState'; import useSetEditState from '@/hooks/useSetEditState'; import { runningState } from '@/state'; import { cloneDeep } from 'lodash'; import { RefreshCw } from 'lucide-react'; import { useRecoilValue } from 'recoil'; interface Props { index: number; } export default function ForkButton({ index }: Props) { const forkState = useForkState(); const isRunning = useRecoilValue(runningState); const setEditState = useSetEditState(); const editState = useCurrentEditState(); const currentLineage = useCurrentLineage(); const currentState = useCurrentState(); if (!currentLineage || !currentState) return null; const isAnyStateLastMessage = currentLineage.find( (s) => s.messages.length - 1 === index ); const isForkable = isAnyStateLastMessage; const isUserOrTool = ['user', 'tool'].includes( currentState.messages[index].role ); if (!isForkable || !isUserOrTool) return null; return ( <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <Button disabled={isRunning} onClick={() => { const state = cloneDeep(currentState); state.messages = state.messages.slice(0, index + 1); setEditState(undefined); forkState(state, index); }} className={editState ? 'text-green-500' : 'text-muted-foreground'} variant="ghost" size="icon" > <RefreshCw /> </Button> </TooltipTrigger> <TooltipContent> <p>Fork & Re-run</p> </TooltipContent> </Tooltip> </TooltipProvider> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Body/ForkNav.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import { Button } from '@/components/ui/button'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import { forksByMessageIndexState, stateHistoryByLineageState } from '@/state'; import { ChevronLeft, ChevronRight } from 'lucide-react'; import { useContext } from 'react'; import { useRecoilValue } from 'recoil'; interface Props { index: number; } export default function ForkNav({ index }: Props) { const editState = useCurrentEditState(); const { id, currentLineageId, setCurrentLineageId, setCurrentStateIndex } = useContext(FunctionViewContext); const stateHistoryByLineage = useRecoilValue(stateHistoryByLineageState); const forksByMessage = useRecoilValue(forksByMessageIndexState); const forks = forksByMessage[id]?.[index]; if (!forks?.length) return null; const currentForkIndex = forks.findIndex((f) => f === currentLineageId); if (currentForkIndex === undefined) return null; return ( <div className="flex items-center text-muted-foreground"> <Button onClick={() => { const goToLineageId = forks[currentForkIndex - 1]; setCurrentLineageId?.(() => goToLineageId); setCurrentStateIndex?.( () => stateHistoryByLineage[goToLineageId].length - 1 ); }} variant="ghost" size="icon" disabled={currentForkIndex === 0 || !!editState} > <ChevronLeft /> </Button> <span className="text-sm font-mono"> {currentForkIndex + 1}/{forks.length} </span> <Button onClick={() => { const goToLineageId = forks[currentForkIndex + 1]; setCurrentLineageId?.(() => goToLineageId); setCurrentStateIndex?.( () => stateHistoryByLineage[goToLineageId].length - 1 ); }} variant="ghost" size="icon" disabled={currentForkIndex === forks.length - 1 || !!editState} > <ChevronRight /> </Button> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Body/ToolCall.tsx
TypeScript (TSX)
import JsonEditor from '@/components/JsonEditor'; import { Loader } from '@/components/Loader'; import type { IMessage, IToolCall } from '@/components/Message'; import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import { runningState, toolCallsToLineageIdsState } from '@/state'; import NestedFunctionView from '@/views/nestedFunction'; import { PanelRightOpen, WrenchIcon } from 'lucide-react'; import { useRecoilValue } from 'recoil'; interface Props { call: IToolCall; messages: IMessage[]; } export default function ToolCall({ call, messages }: Props) { const running = useRecoilValue(runningState); const toolCallsToLineageIds = useRecoilValue(toolCallsToLineageIdsState); const response = messages.find( (m) => m.role === 'tool' && m.tool_call_id === call.id ); const loading = running && !response; const lineageId = toolCallsToLineageIds[call.id]; const callPrefix = 'call_'; const funcName = lineageId && call.function.name.startsWith(callPrefix) ? call.function.name.slice(callPrefix.length) : call.function.name; const tc = ( <Button variant="outline" size="sm" className={cn('w-fit', !lineageId ? 'cursor-auto' : '')} > {lineageId ? ( <PanelRightOpen className="w-3" /> ) : ( <WrenchIcon className="w-3" /> )}{' '} {call.function.name}{' '} <span className="italic font-normal text-muted-foreground">{call.id}</span>{' '} {loading ? <Loader /> : null} </Button> ); return ( <div className="flex flex-col gap-1"> {lineageId ? ( <NestedFunctionView toolCallId={call.id} funcName={funcName} lineageId={lineageId} > {tc} </NestedFunctionView> ) : ( tc )} <JsonEditor fitContent className="overflow-hidden rounded-md pt-2" value={ typeof call.function.arguments === 'string' ? JSON.parse(call.function.arguments) : call.function.arguments } /> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Body/index.tsx
TypeScript (TSX)
// ChatBody.tsx import FunctionViewContext from '../../context'; import AskAIButton from './AskAIButton'; import ForkButton from './ForkButton'; import ForkNav from './ForkNav'; import ToolCall from './ToolCall'; import CopyButton from '@/components/CopyButton'; import Message, { IMessage } from '@/components/Message'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import useCurrentState from '@/hooks/useCurrentState'; import useSetEditState from '@/hooks/useSetEditState'; import { errorState, runningState } from '@/state'; import { AlertCircle } from 'lucide-react'; import { useCallback, useContext, useEffect, useRef } from 'react'; import { useRecoilValue } from 'recoil'; export default function ChatBody() { const ref = useRef<HTMLDivElement>(null); const scrollPositionStore = useRef({ position: 0, set: (position: number) => { scrollPositionStore.current.position = position; }, get: () => scrollPositionStore.current.position }); const running = useRecoilValue(runningState); const { currentLineageId } = useContext(FunctionViewContext); const currentState = useCurrentState(); const setEditState = useSetEditState(); const error = useRecoilValue(errorState); // Handle scroll events to store position const handleScroll = useCallback((e: any) => { const target = e.target as HTMLDivElement; scrollPositionStore.current.set(target.scrollTop); }, []); // Auto scroll to bottom when running useEffect(() => { if (ref.current && currentState?.messages && running) { ref.current.scrollTop = ref.current.scrollHeight; } }, [currentState?.messages, running]); const onMessageChange = useCallback( (m: IMessage, index: number) => { const targetScroll = scrollPositionStore.current.get(); setEditState({ ...currentState, messages: [ ...currentState.messages.slice(0, index), m, ...currentState.messages.slice( index + 1, currentState.messages.length ) ] }); requestAnimationFrame(() => { if (ref.current) { ref.current.scrollTop = targetScroll; } }); }, [currentState, setEditState] ); if (!currentState) return null; return ( <div ref={ref} onScroll={handleScroll} className="flex flex-col gap-4 py-4 flex-grow overflow-y-auto" > {currentState.messages.map((m, i) => ( <div key={i} className="flex flex-col gap-1 border px-4 py-2 rounded-md bg-background" > <Message maxHeight={Number.MAX_SAFE_INTEGER} message={m} onChange={running ? undefined : (m) => onMessageChange(m, i)} > {m.tool_calls ? ( <div className="flex flex-col gap-1"> {m.tool_calls.map((tc) => ( <ToolCall key={tc.id} call={tc} messages={currentState.messages} /> ))} </div> ) : null} <div className="flex items-center -ml-2"> <CopyButton content={m} /> <ForkNav index={i} /> <ForkButton index={i} /> <AskAIButton index={i} /> </div> </Message> </div> ))} {error?.lineage_id === currentLineageId ? ( <Alert variant="destructive"> <AlertCircle className="h-4 w-4" /> <AlertTitle>Error</AlertTitle> <AlertDescription>{error.error}</AlertDescription> </Alert> ) : null} </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Header/EditMode.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import useSetEditState from '@/hooks/useSetEditState'; import { stateHistoryByLineageState } from '@/state'; import { cloneDeep } from 'lodash'; import { Check, RotateCcw } from 'lucide-react'; import { useContext } from 'react'; import { useSetRecoilState } from 'recoil'; export default function EditMode() { const { currentLineageId, setCurrentStateIndex } = useContext(FunctionViewContext); const setStateHistoryByLineage = useSetRecoilState( stateHistoryByLineageState ); const editState = useCurrentEditState(); const setEditState = useSetEditState(); if (editState) return ( <div className="flex items-center"> <Badge>Edit Mode</Badge> <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <Button onClick={() => setEditState(undefined)} size="icon" variant="ghost" > <RotateCcw className="text-red-500" /> </Button> </TooltipTrigger> <TooltipContent> <p>Remove changes</p> </TooltipContent> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button onClick={() => { const state = cloneDeep(editState); setEditState(undefined); setStateHistoryByLineage((prev) => ({ ...prev, [currentLineageId]: [...prev[currentLineageId], state] })); setCurrentStateIndex?.((prev) => prev.currentStateIndex + 1); }} size="icon" variant="ghost" > <Check className="text-green-500" /> </Button> </TooltipTrigger> <TooltipContent> <p>Apply changes & create new state</p> </TooltipContent> </Tooltip> </TooltipProvider> </div> ); return null; }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Header/FunctionSelect.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { functionsState, runningState } from '@/state'; import { useContext, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useRecoilValue } from 'recoil'; export default function FunctionSelect() { const navigate = useNavigate(); const { name, isRoot } = useContext(FunctionViewContext); const running = useRecoilValue(runningState); const functions = useRecoilValue(functionsState); const [goToFunc, setGoToFunc] = useState<string>(); return ( <> <AlertDialog open={!!goToFunc} onOpenChange={() => setGoToFunc(undefined)} > <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle> Do you want to work on{' '} <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold"> {goToFunc} </code> ? </AlertDialogTitle> <AlertDialogDescription> The current state will be lost. </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> <AlertDialogAction onClick={() => { navigate(`/fn/${goToFunc}`); }} > Continue </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> <Select disabled={running || !isRoot} onValueChange={setGoToFunc} value={name} > <SelectTrigger className="gap-1 w-fit shadow-none border-none"> <SelectValue placeholder="Role" /> </SelectTrigger> <SelectContent> {Object.keys(functions || {}).map((fn) => ( <SelectItem key={fn} value={fn}> {fn} </SelectItem> ))} </SelectContent> </Select> </> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Header/InterruptSwitch.tsx
TypeScript (TSX)
import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import useInteraction from '@/hooks/useInteraction'; export default function InterruptSwitch() { const { setInterrupt } = useInteraction(); return null; return ( <div className="flex items-center space-x-2"> <Label htmlFor="interrupt">Break</Label> <Switch onCheckedChange={(c) => setInterrupt(c)} id="interrupt" /> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Header/RunStateButton.tsx
TypeScript (TSX)
import { Loader } from '@/components/Loader'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { interruptState } from '@/state'; import { runningState } from '@/state'; import { PlayIcon } from 'lucide-react'; import { useRecoilState, useRecoilValue } from 'recoil'; export default function RunStateButton() { const running = useRecoilValue(runningState); const [interrupt, setInterrupt] = useRecoilState(interruptState); if (running) { return ( <Badge> <Loader className="text-primary-foreground w-3 mr-1.5" /> Running </Badge> ); } else if (interrupt) { return ( <div className="flex items-center gap-1"> <Button variant="ghost" size="icon" onClick={() => { interrupt.callback(); setInterrupt(undefined); }} > <PlayIcon className="text-green-500" /> </Button> <Badge>Paused</Badge> </div> ); } else { return null; } }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/Header/index.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import EditMode from './EditMode'; import FunctionSelect from './FunctionSelect'; import InterruptSwitch from './InterruptSwitch'; import RunStateButton from './RunStateButton'; import { Logo } from '@/components/Logo'; import { SheetClose } from '@/components/ui/sheet'; import { ArrowRight, SlashIcon } from 'lucide-react'; import { useContext } from 'react'; import { NavLink } from 'react-router-dom'; export default function ChatHeader() { const { isRoot } = useContext(FunctionViewContext); return ( <div className="border-b h-14 p-4 flex items-center justify-between"> <div className="flex items-center gap-1"> {isRoot ? ( <> <NavLink to="/"> <Logo className="w-6" /> </NavLink> <SlashIcon className="text-muted-foreground/30 h-4 -rotate-6" /> </> ) : ( <SheetClose> <ArrowRight className="w-4" /> </SheetClose> )} <FunctionSelect /> <RunStateButton /> </div> <div className="items-center flex"> <EditMode /> <InterruptSwitch /> </div> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/chat/index.tsx
TypeScript (TSX)
import ChatBody from './Body'; import ChatHeader from './Header'; import MessageComposer from '@/components/MessageComposer'; export default function ChatView() { return ( <div className="flex flex-col h-full bg-card relative"> <ChatHeader /> <div className="flex flex-col flex-grow px-4 overflow-y-auto"> <ChatBody /> </div> <MessageComposer /> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/context.ts
TypeScript
import { createContext } from 'react'; export interface IFunctionViewContext { isRoot: boolean; id: string; name: string; currentLineageId: string; currentStateIndex: number; setName?: (fn: (_ctx: IFunctionViewContext) => string) => void; setCurrentLineageId?: (fn: (_ctx: IFunctionViewContext) => string) => void; setCurrentStateIndex?: (fn: (_ctx: IFunctionViewContext) => number) => void; } const FunctionViewContext = createContext<IFunctionViewContext>({} as any); export default FunctionViewContext;
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/index.tsx
TypeScript (TSX)
import ChatView from './chat'; import FunctionViewContext from './context'; import StateView from './state'; import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable'; import useCurrentLineage from '@/hooks/useCurrentLineage'; import { useContext, useEffect } from 'react'; export default function FunctionView() { const { setCurrentStateIndex } = useContext(FunctionViewContext); const currentLineage = useCurrentLineage(); useEffect(() => { if (!currentLineage) return; setCurrentStateIndex?.(() => currentLineage.length - 1); }, [currentLineage, setCurrentStateIndex]); return ( <div className="h-screen w-full"> <ResizablePanelGroup direction="horizontal"> <ResizablePanel defaultSize={70}> <ChatView /> </ResizablePanel> <ResizableHandle /> <ResizablePanel defaultSize={30}> <StateView /> </ResizablePanel> </ResizablePanelGroup> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/Body/index.tsx
TypeScript (TSX)
import { useEditorFormat } from '@/components/EditorFormat'; import JsonEditor from '@/components/JsonEditor'; import YamlEditor from '@/components/YamlEditor'; import useCurrentState from '@/hooks/useCurrentState'; import useSetEditState from '@/hooks/useSetEditState'; import { omit } from 'lodash'; export default function StateBody() { const currentState = useCurrentState(); const setEditState = useSetEditState(); const [format] = useEditorFormat(); if (format === 'json') { return ( <JsonEditor onChange={(v) => setEditState({ ...(v as any), messages: currentState.messages }) } height="100%" className="h-full pt-2 px-1" value={omit(currentState, 'id', 'messages', 'metadata')} /> ); } else { return ( <YamlEditor onChange={(v) => setEditState({ ...(v as any), messages: currentState.messages }) } height="100%" className="h-full pt-2 px-1" value={omit(currentState, 'id', 'messages', 'metadata')} /> ); } }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/Header/LineageNav.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import useCurrentLineage from '@/hooks/useCurrentLineage'; import { ChevronLeft, ChevronRight } from 'lucide-react'; import { useContext, useEffect } from 'react'; export default function LineageNav() { const editState = useCurrentEditState(); const currentLineage = useCurrentLineage(); const { currentStateIndex, setCurrentStateIndex } = useContext(FunctionViewContext); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (editState) return; if ((event.metaKey || event.ctrlKey) && event.key === 'z') { if (event.shiftKey) { // Redo (Cmd+Shift+Z or Ctrl+Shift+Z) if (currentStateIndex < currentLineage.length - 1) { setCurrentStateIndex?.((prev) => prev.currentStateIndex + 1); } } else { // Undo (Cmd+Z or Ctrl+Z) if (currentStateIndex > 0) { setCurrentStateIndex?.((prev) => prev.currentStateIndex - 1); } } event.preventDefault(); } }; window.addEventListener('keydown', handleKeyDown); return () => { window.removeEventListener('keydown', handleKeyDown); }; }, [currentStateIndex, editState, currentLineage, setCurrentStateIndex]); if (!currentLineage) return null; return ( <div className="flex items-center text-muted-foreground"> <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <Button onClick={() => { setCurrentStateIndex?.((prev) => prev.currentStateIndex - 1); }} variant="ghost" size="icon" disabled={currentStateIndex === 0 || !!editState} > <ChevronLeft /> </Button> </TooltipTrigger> <TooltipContent> <p>Go to previous state</p> </TooltipContent> </Tooltip> <span className="text-sm font-mono"> {currentStateIndex + 1}/{currentLineage.length} </span> <Tooltip> <TooltipTrigger asChild> <Button onClick={() => { setCurrentStateIndex?.((prev) => prev.currentStateIndex + 1); }} variant="ghost" size="icon" disabled={ currentStateIndex === currentLineage.length - 1 || !!editState } > <ChevronRight /> </Button> </TooltipTrigger> <TooltipContent> <p>Go to next state</p> </TooltipContent> </Tooltip> </TooltipProvider> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/Header/SaveButton.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import useCurrentEditState from '@/hooks/useCurrentEditState'; import { forksByMessageIndexState, runningState, stateHistoryByLineageState, toolCallsToLineageIdsState } from '@/state'; import { SaveIcon } from 'lucide-react'; import { useCallback, useContext, useEffect } from 'react'; import { useRecoilValue } from 'recoil'; export default function SaveButton() { const { name } = useContext(FunctionViewContext); const running = useRecoilValue(runningState); const editMode = useCurrentEditState(); const stateHistoryByLineage = useRecoilValue(stateHistoryByLineageState); const toolCallsToLineageIds = useRecoilValue(toolCallsToLineageIdsState); const forksByMessageIndex = useRecoilValue(forksByMessageIndexState); const disabled = running || !!editMode; const handleSave = useCallback(() => { const json = JSON.stringify( { stateHistoryByLineage, toolCallsToLineageIds, forksByMessageIndex }, null, 2 ); // Convert state to JSON const blob = new Blob([json], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `${name}_state.json`; a.click(); URL.revokeObjectURL(url); }, [name, stateHistoryByLineage, toolCallsToLineageIds, forksByMessageIndex]); useEffect(() => { if (disabled) return; const handleKeyDown = (event: KeyboardEvent) => { if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); // Prevent the default save dialog in the browser handleSave(); } }; window.addEventListener('keydown', handleKeyDown); return () => { window.removeEventListener('keydown', handleKeyDown); }; }, [handleSave, disabled]); // Add stateHistory as a dependency if it changes frequently return ( <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <Button disabled={disabled} onClick={handleSave} variant="ghost" size="icon" > <SaveIcon /> </Button> </TooltipTrigger> <TooltipContent> <p>Save the state history</p> </TooltipContent> </Tooltip> </TooltipProvider> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/Header/UploadButton.tsx
TypeScript (TSX)
import { Button } from '@/components/ui/button'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { editStateState, errorState, forksByMessageIndexState, interruptState, runningState, stateHistoryByLineageState, toolCallsToLineageIdsState } from '@/state'; import { UploadIcon } from 'lucide-react'; import { ChangeEvent, useRef } from 'react'; import { useRecoilValue, useSetRecoilState } from 'recoil'; import { toast } from 'sonner'; export default function UploadButton() { const fileInputRef = useRef<HTMLInputElement>(null); // Handler to trigger file input click const handleButtonClick = () => { fileInputRef.current?.click(); }; const running = useRecoilValue(runningState); const setStateHistoryByLineage = useSetRecoilState( stateHistoryByLineageState ); const setToolCallsToLineageIds = useSetRecoilState( toolCallsToLineageIdsState ); const setForksByMessageIndex = useSetRecoilState(forksByMessageIndexState); const setInterrupt = useSetRecoilState(interruptState); const setEditState = useSetRecoilState(editStateState); const setError = useSetRecoilState(errorState); const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => { const file = event.target.files?.[0]; if (file && file.type === 'application/json') { const reader = new FileReader(); reader.onload = (e: ProgressEvent<FileReader>) => { try { const result = e.target?.result; if (typeof result === 'string') { const parsedData = JSON.parse(result); setStateHistoryByLineage(parsedData.stateHistoryByLineage); setToolCallsToLineageIds(parsedData.toolCallsToLineageIds); setForksByMessageIndex(parsedData.forksByMessageIndex); setInterrupt(undefined); setError(undefined); setEditState({}); } } catch (err) { toast.error('Invalid JSON file: ' + String(err)); } }; reader.readAsText(file); } else { toast.error('Please upload a valid JSON file'); } }; return ( <TooltipProvider delayDuration={100}> <Tooltip> <TooltipTrigger asChild> <Button onClick={handleButtonClick} disabled={running} variant="ghost" size="icon" > <UploadIcon /> <input ref={fileInputRef} className="hidden" disabled={running} type="file" accept=".json" onChange={handleFileChange} /> </Button> </TooltipTrigger> <TooltipContent> <p>Upload a saved state history</p> </TooltipContent> </Tooltip> </TooltipProvider> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/Header/index.tsx
TypeScript (TSX)
import FunctionViewContext from '../../context'; import LineageNav from './LineageNav'; import SaveButton from './SaveButton'; import UploadButton from './UploadButton'; import { EditorFormatSelect } from '@/components/EditorFormat'; import { useContext } from 'react'; export default function StateHeader() { const { isRoot } = useContext(FunctionViewContext); return ( <div className="border-b h-14 p-4 flex items-center justify-between"> <div className="flex items-center"> <span className="text-sm font-medium leading-none">State History</span> <LineageNav /> </div> {isRoot ? ( <div className="items-center flex gap-1"> <EditorFormatSelect /> <SaveButton /> <UploadButton /> </div> ) : null} </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/function/state/index.tsx
TypeScript (TSX)
import StateBody from './Body'; import StateHeader from './Header'; export default function StateView() { return ( <div className="flex flex-col h-full"> <StateHeader /> <div className="flex flex-col flex-grow"> <StateBody /> </div> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/home/Functions.tsx
TypeScript (TSX)
import InlineText from '@/components/InlineText'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { functionsState } from '@/state'; import { FunctionSquareIcon, InfoIcon } from 'lucide-react'; import { NavLink } from 'react-router-dom'; import { useRecoilValue } from 'recoil'; export default function Functions() { const functions = useRecoilValue(functionsState); if (!functions) return null; const functionNames = Object.keys(functions); let content; if (functionNames.length === 0) { content = ( <Alert variant="default"> <InfoIcon className="h-4 w-4" /> <AlertTitle>No Function Found</AlertTitle> <AlertDescription> Could not found a <InlineText>@stateful</InlineText> decorated function. </AlertDescription> </Alert> ); } else { content = ( <div className="flex flex-col gap-2"> {functionNames.map((fn) => { return ( <NavLink key={fn} to={`/fn/${fn}`}> <Button className="w-full" variant="outline"> <FunctionSquareIcon /> {fn} </Button> </NavLink> ); })} </div> ); } return ( <div className="flex flex-col gap-2"> <h1 className="scroll-m-20 text-3xl font-extrabold tracking-normal lg:text-4xl"> Looplit Agent Studio </h1> <p className="leading-7 text-muted-foreground [&:not(:first-child)]:mt-4"> Pick the agent you want to work on. </p> {content} </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/home/index.tsx
TypeScript (TSX)
import Functions from './Functions'; import { ThemeToggle } from '@/components/ThemeToggle'; export default function HomeView() { return ( <div className="h-screen w-screen flex items-center justify-center relative"> <div style={{ mask: 'url(/pattern.png) repeat center / contain', maskSize: '160px 160px, cover', background: 'radial-gradient(50% 43% at 93.5% 93.10000000000001%, hsl(var(--card-foreground)) 0%, rgba(0, 0, 0, 0) 100%)' }} className="fixed left-0 top-0 z-[-1] h-full w-full opacity-[0.36]" /> <ThemeToggle className="absolute top-4 right-4" /> <div className="max-w-[48rem] flex flex-col gap-4"> <Functions /> </div> </div> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/nestedFunction/index.tsx
TypeScript (TSX)
import FunctionView from '../function'; import FunctionViewContext, { IFunctionViewContext } from '../function/context'; import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'; import { stateHistoryByLineageState } from '@/state'; import { useMemo, useState } from 'react'; import { useRecoilValue } from 'recoil'; interface Props { children: React.ReactNode; funcName: string; toolCallId: string; lineageId: string; } export default function NestedFunctionView({ children, funcName, toolCallId, lineageId }: Props) { const stateHistory = useRecoilValue(stateHistoryByLineageState); const [ctx, setCtx] = useState<IFunctionViewContext>({ isRoot: false, id: toolCallId, name: funcName, currentLineageId: lineageId, currentStateIndex: stateHistory[lineageId]?.length || 0 }); const setFns: Pick< IFunctionViewContext, 'setCurrentLineageId' | 'setCurrentStateIndex' | 'setName' > = useMemo(() => { return { setName: (fn: (_ctx: IFunctionViewContext) => string) => { setCtx((_ctx) => ({ ..._ctx, name: fn(_ctx) })); }, setCurrentLineageId: (fn: (_ctx: IFunctionViewContext) => string) => { setCtx((_ctx) => ({ ..._ctx, currentLineageId: fn(_ctx) })); }, setCurrentStateIndex: (fn: (_ctx: IFunctionViewContext) => number) => { setCtx((_ctx) => ({ ..._ctx, currentStateIndex: fn(_ctx) })); } }; }, [setCtx]); return ( <FunctionViewContext.Provider value={{ ...ctx, ...setFns }} > <Sheet> <SheetTrigger asChild>{children}</SheetTrigger> <SheetContent className="!max-w-[90%] w-full p-0 [&>button]:hidden"> <FunctionView /> </SheetContent> </Sheet> </FunctionViewContext.Provider> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/views/rootFunction/index.tsx
TypeScript (TSX)
import FunctionView from '../function'; import FunctionViewContext, { IFunctionViewContext } from '../function/context'; import { functionsState, stateHistoryByLineageState } from '@/state'; import { useEffect, useMemo, useState } from 'react'; import { useParams } from 'react-router-dom'; import { useRecoilValue, useSetRecoilState } from 'recoil'; export default function RootFunctionView() { const { name: rootFunction } = useParams(); const functions = useRecoilValue(functionsState); const setstateHistoryByLineage = useSetRecoilState( stateHistoryByLineageState ); const [ctx, setCtx] = useState<IFunctionViewContext>({ isRoot: true, id: 'root', name: rootFunction!, currentLineageId: 'root', currentStateIndex: 0 }); useEffect(() => { const rootState = functions && rootFunction ? [functions[rootFunction]] : []; setstateHistoryByLineage({ root: rootState }); if (rootFunction) { document.title = rootFunction; } setCtx((prev) => ({ ...prev, name: rootFunction!, currentLineageId: 'root', currentStateIndex: 0 })); }, [rootFunction]); const setFns: Pick< IFunctionViewContext, 'setCurrentLineageId' | 'setCurrentStateIndex' | 'setName' > = useMemo(() => { return { setName: (fn: (_ctx: IFunctionViewContext) => string) => { setCtx((_ctx) => ({ ..._ctx, name: fn(_ctx) })); }, setCurrentLineageId: (fn: (_ctx: IFunctionViewContext) => string) => { setCtx((_ctx) => ({ ..._ctx, currentLineageId: fn(_ctx) })); }, setCurrentStateIndex: (fn: (_ctx: IFunctionViewContext) => number) => { setCtx((_ctx) => ({ ..._ctx, currentStateIndex: fn(_ctx) })); } }; }, [rootFunction, setCtx]); if (!rootFunction) return null; return ( <FunctionViewContext.Provider value={{ ...ctx, ...setFns }} > <FunctionView /> </FunctionViewContext.Provider> ); }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/src/vite-env.d.ts
TypeScript
/// <reference types="vite/client" />
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ export default { darkMode: ["class"], content: ["./index.html", "./src/**/*.{ts,tsx,js,jsx}"], theme: { extend: { borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' }, colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' } } } }, plugins: [require("tailwindcss-animate")], }
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
frontend/vite.config.ts
TypeScript
import path from "path" import react from "@vitejs/plugin-react" import { defineConfig } from "vite" export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src"), }, }, })
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
lint-staged.config.js
JavaScript
// eslint-disable-next-line no-undef module.exports = { '**/*.py': [ 'poetry run -C backend ruff check --fix', 'poetry run -C backend ruff format', () => 'pnpm run lint:python', ], '**/*.{ts,tsx}': [() => 'pnpm run lint:ui', () => 'pnpm run format:ui'], '.github/{workflows,actions}/**': ['actionlint'] };
willydouhard/looplit
13
TypeScript
willydouhard
Willy Douhard
Chainlit
aocd_example_parser/__init__.py
Python
from .plugins import *
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
aocd_example_parser/extraction.py
Python
import importlib.resources import json from functools import cache from aocd.examples import Example from aocd.examples import Page @cache def _locators() -> dict: # predetermined locations of code-blocks etc for example data resource = importlib.resources.files(__package__) / "examples.json" txt = resource.read_text() data = json.loads(txt) return data def extract_examples(page: Page, use_default_locators: bool = False) -> list[Example]: """ Takes the puzzle page's html and returns a list of `Example` instances. """ scope = {"page": page} part_b_locked = page.article_b is None parts = "a" if part_b_locked else "ab" for part in parts: for tag in "code", "pre", "em", "li": name = f"{part}_{tag}" scope[name] = getattr(page, name) result = [] locators = _locators() key = f"{page.year}/{page.day:02d}" default = locators["default_locators"] if use_default_locators: locs = [default] else: locs = locators.get(key, [default]) for loc in locs: vals = [] for k in "input_data", "answer_a", "answer_b": pos = loc.get(k, default[k]) if k == "answer_b" and (part_b_locked or page.day == 25): vals.append(None) continue try: val = eval(pos, scope) except Exception: val = None if isinstance(val, (tuple, list)): val = "\n".join(val) if val is not None: val = val.rstrip("\r\n") vals.append(val) if loc.get("extra"): vals.append(loc["extra"]) if vals[0] is not None: result.append(Example(*vals)) return result
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
aocd_example_parser/plugins.py
Python
from aocd.examples import Example from aocd.examples import Page from .extraction import extract_examples from .util import real_datas_unused __all__ = ["simple", "reference"] @real_datas_unused def simple(page: Page, datas: list[str]) -> list[Example]: """ Example parser implementation which always uses the aocd default locators. These are currently: "default_locators": { "input_data": "a_pre[0]", "answer_a": "a_code[-1].split()[-1]", "answer_b": "b_code[-1].split()[-1]", "extra": null }, The text of the first <pre> tag, if any, is the input data. The last <code> block of the first <article> contains the part a answer. The last <code> block of the second <article> contains the part b answer. The extra context is nothing. """ return extract_examples(page, use_default_locators=True) @real_datas_unused def reference(page: Page, datas: list[str]) -> list[Example]: """ Example parser implementation which always uses the pre-calculated locators. This implementation will always return correct results for puzzles which are published in the past. It can be used as a reference to compare the results of other example parser implementations against. For puzzles that hadn't been released yet, the results are the same as the "default locators" plugin defined above. """ return extract_examples(page)
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
aocd_example_parser/util.py
Python
from typing import Callable def real_datas_unused(parser: Callable) -> Callable: """ A decorator which indicates that the "datas" argument is not going to be used by the decorated parser. aocd will just send an empty list in this case, which speeds up invocation of the parser entrypoint somewhat. """ parser.uses_real_datas = False return parser
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
tests/integration.py
Python
#!/usr/bin/env python3 import argparse import ast import pathlib import sys from testfixtures import compare from aocd.models import Puzzle here = pathlib.Path(__file__).parent input_dir = here.parent.parent / "advent-of-code-wim" / "tests" def split_trailing_comments(lines): extra = [] while lines and (not lines[-1].strip() or lines[-1].startswith("#")): extra.append(lines.pop()) if len(lines) and "#" in lines[-1]: line, comment = lines[-1].split("#", 1) lines[-1] = line.strip() extra.append(comment.strip()) if len(lines) > 1 and "#" in lines[-2]: line, comment = lines[-2].split("#", 1) lines[-2] = line.strip() extra.append(comment.strip()) extra = [x.strip() for x in extra if x.strip()] return extra def parse_extra_context(extra): result = {} for line in extra: equals = line.count("=") commas = line.count(",") if equals and equals == commas + 1: for part in line.split(","): k, v = part.strip().split("=") k = k.strip() v = v.strip() try: v = ast.literal_eval(v) except ValueError: pass if k in result: raise NotImplementedError(f"Duplicate key {k!r}") result[k] = v return result def main(): parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="store_true") args = parser.parse_args() rc = 0 for puzzle in Puzzle.all(): date = f"{puzzle.year}/{puzzle.day:02d}" example_dir = input_dir / date egs = [x.name.split(".")[0] for x in example_dir.glob("*.txt")] n_examples_expected = max([1 + int(x) for x in egs if x.isdigit()], default=0) if len(puzzle.examples) != n_examples_expected: print(f"{date} {n_examples_expected=} but {len(puzzle.examples)=}") rc += 1 for i, example in enumerate(puzzle.examples): example_file = example_dir / f"{i}.txt" if not example_file.is_file(): try: [example_file] = example_dir.glob(f"{i}.*.txt") except ValueError: print(f"missing example {i} {date}") rc += 1 continue lines = example_file.read_text(encoding="utf-8").splitlines() extra = split_trailing_comments(lines) expected_extra = parse_extra_context(extra) *lines, expected_answer_a, expected_answer_b = lines expected_input_data = "\n".join(lines).rstrip() diff = compare( actual=example.input_data.rstrip(), expected=expected_input_data.rstrip(), raises=False ) if diff is not None: print(f"incorrect example data ({i}) for", puzzle.url, diff) rc += 1 for part in "ab": diff = compare( actual=getattr(example, f"answer_{part}") or "-", expected=locals()[f"expected_answer_{part}"], raises=False, ) if diff is not None: print(f"incorrect answer {part} ({i}) for", puzzle.url, diff) rc += 1 if example.extra or expected_extra: diff = compare( actual=example.extra, expected=expected_extra, raises=False, ) if diff is not None: print(f"incorrect extra ({i}) for", puzzle.url, diff) rc += 1 if args.verbose: print("processed", example_file) sys.exit(rc) if __name__ == "__main__": main()
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
tests/test_default_extraction.py
Python
from aocd.examples import Page from aocd_example_parser.extraction import extract_examples fake_prose = """ <title>Day 1 - Advent of Code 1234</title> <article> <pre><code>test input data</code></pre> <code>test answer_a</code> </article> <article> <code>test answer_b</code> </article> """ def test_default_extraction_both_parts(): page = Page.from_raw(html=fake_prose) examples = extract_examples(page) assert len(examples) == 1 [example] = examples assert example.input_data == "test input data" assert example.answer_a == "answer_a" assert example.answer_b == "answer_b" assert example.extra is None def test_default_extraction_part_a_only(): i = fake_prose.rindex("<article>") prose_locked = fake_prose[:i] page = Page.from_raw(html=prose_locked) assert page.article_b is None examples = extract_examples(page) assert len(examples) == 1 [example] = examples assert example.input_data == "test input data" assert example.answer_a == "answer_a" assert example.answer_b is None assert example.extra is None def test_sequence_line_join(mocker): page = Page.from_raw(html=fake_prose) lines = "line1", "line2" mocker.patch("aocd_example_parser.extraction.eval", return_value=lines) [example] = extract_examples(page, use_default_locators=True) assert example.input_data == "line1\nline2" def test_locator_crash(mocker): page = Page.from_raw(html=fake_prose) mock = mocker.patch("aocd_example_parser.extraction.eval", side_effect=Exception) examples = extract_examples(page, use_default_locators=True) assert examples == [] assert mock.call_count == 3 # input_data, answer_a, answer_b
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
tests/test_extra_context.py
Python
from aocd.examples import Page from aocd_example_parser.extraction import extract_examples fake_prose = """ <title>Day 10 - Advent of Code 2016</title> <article> <pre><code>test input data</code></pre> <code>test answer_a</code> </article> <article> <code>test answer_b</code> </article> """ def test_locator_extra_context(): page = Page.from_raw(html=fake_prose) examples = extract_examples(page) [example] = examples assert example.extra == {"chip1": 5, "chip2": 2}
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
tests/test_plugins.py
Python
from importlib.metadata import entry_points def test_plugin(mocker): [ep] = entry_points().select( group="adventofcode.examples", name="simple", ) plugin = ep.load() mock = mocker.patch("aocd_example_parser.plugins.extract_examples") plugin(page="fake page", datas=[]) mock.assert_called_once_with("fake page", use_default_locators=True) def test_reference(mocker): [ep] = entry_points().select( group="adventofcode.examples", name="reference", ) plugin = ep.load() mock = mocker.patch("aocd_example_parser.plugins.extract_examples") plugin(page="fake page", datas=[]) mock.assert_called_once_with("fake page")
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
tests/test_version_str.py
Python
from datetime import datetime from importlib.metadata import version from aocd_example_parser.extraction import _locators def test_version_str(): metadata_version = version("aocd-example-parser") date = datetime.strptime(metadata_version, "%Y.12.%d") assert date.year >= 2023 assert 1 <= date.day <= 25 latest = next(reversed(_locators())) year, day = map(int, latest.split("/")) assert date.year >= year assert date.day >= day
wimglenn/aocd-example-parser
7
Default implementation of an example parser plugin for advent-of-code-data
Python
wimglenn
Wim Jeantine-Glenn
conftest.py
Python
from sybil import Sybil from sybil.parsers.rest import DocTestParser, PythonCodeBlockParser, SkipParser sybil = Sybil( parsers=[ DocTestParser(), PythonCodeBlockParser(), SkipParser(), ], patterns=["*.rst"], ) pytest_collect_file = sybil.pytest()
wimglenn/monkey-magic
3
Monkeypatch built-in types
Python
wimglenn
Wim Jeantine-Glenn
monkey_magic.py
Python
import gc import types def _wrap_builtin_function(f): def f_py(*args, **kwargs): return f(*args, **kwargs) f_py.__name__ = f.__name__ return f_py def monkeypatch(type_, obj, name=None): if isinstance(type_, tuple): for t in type_: monkeypatch(t, obj, name) return if name is None: if isinstance(obj, property): name = obj.fget.__name__ else: name = obj.__name__ if isinstance(obj, types.BuiltinFunctionType): obj = _wrap_builtin_function(obj) gc.get_referents(type_.__dict__)[0][name] = obj
wimglenn/monkey-magic
3
Monkeypatch built-in types
Python
wimglenn
Wim Jeantine-Glenn
setuptools_reproducible.py
Python
import os import stat import tarfile from contextlib import contextmanager from types import SimpleNamespace from setuptools.build_meta import * from setuptools.build_meta import build_sdist as build_sdist_orig from setuptools.build_meta import build_wheel as build_wheel_orig class FixedMode: def __get__(self, instance, owner=None): if instance is None: return self if instance.isdir(): return stat.S_IFMT(instance._mode) | 0o755 elif instance.isreg(): return stat.S_IFMT(instance._mode) | 0o644 else: return instance._mode def __set__(self, instance, value): instance._mode = value class FixedAttr: def __init__(self, value): self.value = value def __get__(self, instance, owner=None): if instance is None: return self return self.value() if callable(self.value) else self.value def __set__(self, instance, value): pass class TarInfoNew(tarfile.TarInfo): mode = FixedMode() mtime = FixedAttr(lambda: float(os.environ["SOURCE_DATE_EPOCH"])) uid = FixedAttr(0) gid = FixedAttr(0) uname = FixedAttr("") gname = FixedAttr("") @contextmanager def monkey(): tarfile_time_orig = tarfile.time tarinfo_orig = tarfile.TarFile.tarinfo if (source_date_epoch_orig := os.environ.get("SOURCE_DATE_EPOCH")) is None: os.environ["SOURCE_DATE_EPOCH"] = "0" # 1970-01-01 00:00:00 UTC tarfile.TarFile.tarinfo = TarInfoNew tarfile.time = SimpleNamespace(time=lambda: float(os.environ["SOURCE_DATE_EPOCH"])) try: yield finally: tarfile.time = tarfile_time_orig tarfile.TarFile.tarinfo = tarinfo_orig if source_date_epoch_orig is None: os.environ.pop("SOURCE_DATE_EPOCH", None) def build_sdist(sdist_directory, config_settings=None): with monkey(): return build_sdist_orig(sdist_directory, config_settings) def build_wheel(wheel_directory, config_settings=None, metadata_directory=None): with monkey(): return build_wheel_orig(wheel_directory, config_settings, metadata_directory)
wimglenn/setuptools-reproducible
6
Extension of setuptools to support reproducible builds
Python
wimglenn
Wim Jeantine-Glenn
tests/test_reproducibility.py
Python
import hashlib import os import shutil from contextlib import contextmanager from pathlib import Path import pytest import setuptools_reproducible backend = Path(__file__).parent.parent / "setuptools_reproducible.py" example_readme = """\ this is the first line of the README.md file this is the second line of the README.md file — and it has non-ascii in it """ example_pyproject = """\ [build-system] requires = ["setuptools-reproducible"] build-backend = "setuptools_reproducible" backend-path = ["."] [project] name = "mypkg" version = "0.1" readme = "README.md" [tool.setuptools] packages = ["mypkg"] """ def sha256sum(path): return hashlib.sha256(path.read_bytes()).hexdigest() @pytest.fixture(autouse=True) def srctrees(tmp_path): for src in "src1", "src2": path = tmp_path / src path.mkdir() path.joinpath("README.md").write_text(example_readme, encoding="utf8") path.joinpath("pyproject.toml").write_text(example_pyproject, encoding="utf8") path.joinpath("mypkg").mkdir() path.joinpath("mypkg").joinpath("__init__.py").write_text("", encoding="utf8") mod1 = path / "mypkg" / "mod1.py" mod2 = path / "mypkg" / "mod2.py" mod1.write_text("") mod2.write_text("") shutil.copy(backend, path) # we now have identical source trees in src1, src2. # let's fudge one of their modes and times... mod1.chmod(0o644) mod2.chmod(0o666) st = mod2.stat() os.utime(mod2, (st.st_atime - 60, st.st_mtime - 70)) yield tmp_path.joinpath("src1"), tmp_path.joinpath("src2") @contextmanager def working_directory(path): """Change working directory and restore the previous on exit""" prev_dir = os.getcwd() os.chdir(str(path)) try: yield str(path) finally: os.chdir(prev_dir) def test_sdist_reproducibility(srctrees): path1, path2 = srctrees with working_directory(path1) as d: path1 /= setuptools_reproducible.build_sdist(d) with working_directory(path2) as d: path2 /= setuptools_reproducible.build_sdist(d) assert path1 != path2 assert path1.name == path2.name == "mypkg-0.1.tar.gz" assert sha256sum(path1) == sha256sum(path2) def test_wheel_reproducibility(srctrees): path1, path2 = srctrees with working_directory(path1) as d: path1 /= setuptools_reproducible.build_wheel(d) with working_directory(path2) as d: path2 /= setuptools_reproducible.build_wheel(d) assert path1 != path2 assert path1.name == path2.name == "mypkg-0.1-py3-none-any.whl" assert sha256sum(path1) == sha256sum(path2)
wimglenn/setuptools-reproducible
6
Extension of setuptools to support reproducible builds
Python
wimglenn
Wim Jeantine-Glenn
public/app.js
JavaScript
let currentProject = null; let currentConversation = null; let allProjects = []; let allConversations = []; let showWarmup = false; let showMeta = false; let currentMessages = []; // Initialize document.addEventListener('DOMContentLoaded', () => { loadProjects(); setupSearchHandlers(); setupFilterToggles(); }); // Load all projects async function loadProjects() { try { const response = await fetch('/api/projects'); allProjects = await response.json(); renderProjects(allProjects); } catch (error) { document.getElementById('projects-list').innerHTML = `<div class="empty-state"><h3>Error</h3><p>${error.message}</p></div>`; } } // Render projects list function renderProjects(projects) { const container = document.getElementById('projects-list'); if (projects.length === 0) { container.innerHTML = '<div class="empty-state"><h3>No projects found</h3></div>'; return; } container.innerHTML = projects.map(project => ` <div class="project-item" data-name="${project.name}" onclick="selectProject('${project.name}')"> <div class="project-name">${escapeHtml(project.projectName)}</div> <div class="project-path">${escapeHtml(project.parentPath)}</div> </div> `).join(''); } // Select a project async function selectProject(projectName) { currentProject = projectName; currentConversation = null; // Update active state document.querySelectorAll('.project-item').forEach(el => { el.classList.toggle('active', el.dataset.name === projectName); }); // Clear conversation selection document.getElementById('viewer').innerHTML = '<div class="empty-state"><h3>No conversation selected</h3><p>Select a conversation to view its messages</p></div>'; // Load conversations document.getElementById('conversations-list').innerHTML = '<div class="loading">Loading conversations...</div>'; try { const params = new URLSearchParams(); if (showWarmup) params.append('includeWarmup', 'true'); if (showMeta) params.append('includeMeta', 'true'); const url = `/api/projects/${projectName}/conversations${params.toString() ? '?' + params.toString() : ''}`; const response = await fetch(url); allConversations = await response.json(); renderConversations(allConversations); } catch (error) { document.getElementById('conversations-list').innerHTML = `<div class="empty-state"><h3>Error</h3><p>${error.message}</p></div>`; } } // Render conversations list function renderConversations(conversations) { const container = document.getElementById('conversations-list'); if (conversations.length === 0) { container.innerHTML = '<div class="empty-state"><h3>No conversations found</h3></div>'; return; } container.innerHTML = conversations.map(conv => { const date = new Date(conv.modified).toLocaleString(); const size = formatSize(conv.size); const specialClass = conv.isWarmup ? ' warmup-conversation' : (conv.isMeta ? ' meta-conversation' : ''); const badges = []; if (conv.isWarmup) badges.push('<span class="warmup-badge">WARMUP</span>'); if (conv.isMeta) badges.push('<span class="meta-badge">META</span>'); const badgesHtml = badges.join(''); return ` <div class="conversation-item${specialClass}" data-id="${conv.id}" onclick="selectConversation('${conv.id}')"> <div class="preview">${badgesHtml}${escapeHtml(conv.preview)}</div> <div class="meta">${date} • ${conv.messageCount} msgs • ${size}</div> </div> `; }).join(''); } // Select a conversation async function selectConversation(conversationId) { currentConversation = conversationId; // Update active state document.querySelectorAll('.conversation-item').forEach(el => { el.classList.toggle('active', el.dataset.id === conversationId); }); // Load conversation document.getElementById('viewer').innerHTML = '<div class="loading">Loading conversation...</div>'; try { const response = await fetch(`/api/projects/${currentProject}/conversations/${conversationId}`); const messages = await response.json(); renderConversation(messages); } catch (error) { document.getElementById('viewer').innerHTML = `<div class="empty-state"><h3>Error</h3><p>${error.message}</p></div>`; } } // Render a conversation function renderConversation(messages) { const viewer = document.getElementById('viewer'); if (messages.length === 0) { viewer.innerHTML = '<div class="empty-state"><h3>Empty conversation</h3></div>'; return; } currentMessages = messages; viewer.innerHTML = messages.map((msg, index) => { const timestamp = new Date(msg.timestamp).toLocaleString(); let role = msg.message?.role || msg.type; // Detect tool result messages (they have type="user" but contain tool_result content) if (role === 'user' && Array.isArray(msg.message?.content)) { const hasOnlyToolResults = msg.message.content.every(item => item.type === 'tool_result'); if (hasOnlyToolResults) { role = 'tool_result'; } } // Build metadata pills const pills = []; if (msg.isMeta) { pills.push('<span class="meta-pill">meta</span>'); } if (msg.isSidechain) { pills.push('<span class="meta-pill sidechain">sidechain</span>'); } const pillsHtml = pills.length > 0 ? `<div class="meta-pills">${pills.join('')}</div>` : ''; return ` <div class="message ${role}"> <div class="message-header"> <span class="message-role">${role}</span> <span class="message-timestamp">${timestamp}</span> <button class="json-button" onclick="showJsonModal(${index})" title="View raw JSON"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <path d="M16 3h5v5M4 20L21 3M21 16v5h-5M15 15l6 6M4 4l5 5"/> </svg> </button> </div> <div class="message-content"> ${renderMessageContent(msg.message)} </div> ${pillsHtml} </div> `; }).join(''); viewer.scrollTop = 0; } // Render message content function renderMessageContent(message) { if (!message || !message.content) return '<em>No content</em>'; const content = message.content; if (typeof content === 'string') { return escapeHtml(content); } if (Array.isArray(content)) { return content.map(item => { if (item.type === 'text') { return escapeHtml(item.text || ''); } else if (item.type === 'thinking') { return `<div class="thinking"><strong>Thinking:</strong><br>${escapeHtml(item.thinking || '')}</div>`; } else if (item.type === 'tool_use') { return ` <div class="tool-use"> <div class="tool-use-header">Tool: ${item.name}</div> <pre>${escapeHtml(JSON.stringify(item.input, null, 2))}</pre> </div> `; } else if (item.type === 'tool_result') { const resultContent = typeof item.content === 'string' ? item.content : JSON.stringify(item.content, null, 2); return ` <div class="tool-result"> <strong>Tool Result (${item.tool_use_id}):</strong> <pre>${escapeHtml(resultContent)}</pre> </div> `; } else { return `<pre>${escapeHtml(JSON.stringify(item, null, 2))}</pre>`; } }).join(''); } return escapeHtml(JSON.stringify(content, null, 2)); } // Setup filter toggles function setupFilterToggles() { const warmupToggle = document.getElementById('warmup-toggle'); const metaToggle = document.getElementById('meta-toggle'); warmupToggle.addEventListener('change', (e) => { showWarmup = e.target.checked; if (currentProject) { selectProject(currentProject); } }); metaToggle.addEventListener('change', (e) => { showMeta = e.target.checked; if (currentProject) { selectProject(currentProject); } }); } // Setup search handlers function setupSearchHandlers() { document.getElementById('project-search').addEventListener('input', (e) => { const query = e.target.value.toLowerCase(); const filtered = allProjects.filter(p => p.projectName.toLowerCase().includes(query) || p.parentPath.toLowerCase().includes(query) ); renderProjects(filtered); }); document.getElementById('conversation-search').addEventListener('input', (e) => { const query = e.target.value.toLowerCase(); const filtered = allConversations.filter(c => c.preview.toLowerCase().includes(query) ); renderConversations(filtered); }); } // JSON Modal functions function showJsonModal(messageIndex) { const msg = currentMessages[messageIndex]; const modal = document.getElementById('json-modal'); const content = document.getElementById('json-content'); content.textContent = JSON.stringify(msg, null, 2); modal.showModal(); } function closeJsonModal() { const modal = document.getElementById('json-modal'); modal.close(); } // Utility functions function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } function formatSize(bytes) { if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; }
wincent/clogue
0
Claude Code log explorer
JavaScript
wincent
Greg Hurrell
DataDog
public/index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Clogue - Claude Conversation Explorer</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif; background: #f5f5f5; color: #333; line-height: 1.6; } header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } header h1 { font-size: 2rem; font-weight: 600; } header p { opacity: 0.9; margin-top: 0.5rem; } .container { max-width: 1400px; margin: 0 auto; padding: 2rem; display: grid; grid-template-columns: 300px 350px 1fr; gap: 1.5rem; height: calc(100vh - 120px); } .panel { background: white; border-radius: 8px; padding: 1.5rem; box-shadow: 0 2px 8px rgba(0,0,0,0.08); overflow-y: auto; } .panel h2 { font-size: 1.2rem; margin-bottom: 1rem; color: #667eea; border-bottom: 2px solid #f0f0f0; padding-bottom: 0.5rem; } .project-item, .conversation-item { padding: 0.75rem; margin-bottom: 0.5rem; border-radius: 6px; cursor: pointer; transition: all 0.2s; border: 1px solid #e0e0e0; } .project-item:hover, .conversation-item:hover { background: #f8f9ff; border-color: #667eea; transform: translateX(2px); } .project-item.active, .conversation-item.active { background: #667eea; color: white; border-color: #667eea; } .project-item .project-name { font-weight: 600; word-break: break-word; } .project-item .project-path { font-size: 0.8rem; opacity: 0.6; margin-top: 0.25rem; word-break: break-word; } .project-item.active .project-path { opacity: 0.8; } .conversation-item .preview { font-size: 0.9rem; opacity: 0.8; margin-top: 0.25rem; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .conversation-item .meta { font-size: 0.8rem; opacity: 0.6; margin-top: 0.25rem; } .conversation-item.active .preview, .conversation-item.active .meta { opacity: 0.9; } #viewer { overflow-y: auto; } .message { margin-bottom: 1.5rem; padding: 1rem; border-radius: 8px; border-left: 4px solid #e0e0e0; } .message.user { background: #f8f9ff; border-left-color: #667eea; } .message.assistant { background: #f5f5f5; border-left-color: #764ba2; } .message.tool_result { background: #f0f8ff; border-left-color: #4a90e2; } .message-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; font-size: 0.9rem; } .message-role { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; } .message.user .message-role { color: #667eea; } .message.assistant .message-role { color: #764ba2; } .message.tool_result .message-role { color: #4a90e2; } .message-timestamp { color: #999; font-size: 0.8rem; } .message-content { white-space: pre-wrap; word-wrap: break-word; } .tool-use { background: #fff9e6; border: 1px solid #ffe08a; border-radius: 6px; padding: 0.75rem; margin: 0.5rem 0; font-family: 'Monaco', 'Courier New', monospace; font-size: 0.85rem; } .tool-use-header { font-weight: 600; color: #b8860b; margin-bottom: 0.5rem; } .tool-result { background: #f0f0f0; border: 1px solid #d0d0d0; border-radius: 6px; padding: 0.75rem; margin: 0.5rem 0; font-family: 'Monaco', 'Courier New', monospace; font-size: 0.85rem; max-height: 300px; overflow-y: auto; } .thinking { background: #fff0f5; border: 1px solid #ffb6c1; border-radius: 6px; padding: 0.75rem; margin: 0.5rem 0; font-style: italic; color: #8b4789; font-size: 0.9rem; } .empty-state { text-align: center; padding: 3rem; color: #999; } .empty-state h3 { margin-bottom: 0.5rem; color: #666; } .loading { text-align: center; padding: 2rem; color: #667eea; } .search-box { width: 100%; padding: 0.75rem; border: 2px solid #e0e0e0; border-radius: 6px; font-size: 0.9rem; margin-bottom: 1rem; transition: border-color 0.2s; } .search-box:focus { outline: none; border-color: #667eea; } .filter-toggle { display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; background: #f8f9ff; border-radius: 6px; margin-bottom: 1rem; font-size: 0.85rem; border: 1px solid #e0e0e0; } .filter-toggle .filter-label { color: #666; font-weight: 600; } .filter-toggle .filter-options { display: flex; gap: 0.75rem; } .filter-toggle .filter-option { display: flex; align-items: center; gap: 0.3rem; } .filter-toggle input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; } .filter-toggle label { cursor: pointer; user-select: none; color: #666; } .warmup-conversation, .meta-conversation { opacity: 0.7; border-style: dashed; } .warmup-badge, .meta-badge { display: inline-block; color: white; font-size: 0.65rem; font-weight: 700; padding: 0.2rem 0.4rem; border-radius: 3px; margin-right: 0.5rem; letter-spacing: 0.5px; } .warmup-badge { background: #ff9800; } .meta-badge { background: #9c27b0; } .json-button { background: transparent; border: 1px solid #ccc; border-radius: 4px; padding: 0.25rem 0.5rem; cursor: pointer; color: #666; transition: all 0.2s; display: flex; align-items: center; justify-content: center; } .json-button:hover { background: #667eea; border-color: #667eea; color: white; } #json-modal { border: none; border-radius: 12px; padding: 0; max-width: 800px; width: 90vw; max-height: 80vh; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; } #json-modal::backdrop { background: rgba(0, 0, 0, 0.5); backdrop-filter: blur(4px); } .modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem; border-bottom: 2px solid #f0f0f0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px 12px 0 0; } .modal-header h3 { margin: 0; color: white; font-size: 1.2rem; } .close-button { background: transparent; border: 1px solid rgba(255, 255, 255, 0.3); border-radius: 4px; padding: 0.25rem; cursor: pointer; color: white; transition: all 0.2s; display: flex; align-items: center; justify-content: center; } .close-button:hover { background: rgba(255, 255, 255, 0.2); border-color: white; } .json-content { padding: 1.5rem; margin: 0; overflow: auto; max-height: calc(80vh - 80px); font-family: 'Monaco', 'Courier New', monospace; font-size: 0.85rem; line-height: 1.5; background: #f8f9fa; color: #333; white-space: pre; word-wrap: break-word; } .meta-pills { display: flex; gap: 0.5rem; margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid rgba(0, 0, 0, 0.1); } .meta-pill { display: inline-block; background: #667eea; color: white; font-size: 0.7rem; font-weight: 600; padding: 0.25rem 0.6rem; border-radius: 12px; letter-spacing: 0.3px; text-transform: uppercase; } .meta-pill.sidechain { background: #e67e22; } </style> </head> <body> <header> <h1>Clogue</h1> <p>Claude Conversation Explorer</p> </header> <div class="container"> <div class="panel" id="projects-panel"> <h2>Projects</h2> <input type="text" class="search-box" id="project-search" placeholder="Search projects..."> <div id="projects-list"> <div class="loading">Loading projects...</div> </div> </div> <div class="panel" id="conversations-panel"> <h2>Conversations</h2> <div class="filter-toggle"> <span class="filter-label">Show:</span> <div class="filter-options"> <div class="filter-option"> <input type="checkbox" id="warmup-toggle"> <label for="warmup-toggle">Warmup</label> </div> <div class="filter-option"> <input type="checkbox" id="meta-toggle"> <label for="meta-toggle">Meta</label> </div> </div> </div> <input type="text" class="search-box" id="conversation-search" placeholder="Search conversations..."> <div id="conversations-list"> <div class="empty-state"> <h3>Select a project</h3> <p>Choose a project to view its conversations</p> </div> </div> </div> <div class="panel" id="viewer"> <div class="empty-state"> <h3>No conversation selected</h3> <p>Select a conversation to view its messages</p> </div> </div> </div> <dialog id="json-modal"> <div class="modal-header"> <h3>Raw JSON</h3> <button class="close-button" onclick="closeJsonModal()" title="Close"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <line x1="18" y1="6" x2="6" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line> </svg> </button> </div> <pre id="json-content" class="json-content"></pre> </dialog> <script src="app.js"></script> </body> </html>
wincent/clogue
0
Claude Code log explorer
JavaScript
wincent
Greg Hurrell
DataDog
server.js
JavaScript
#!/usr/bin/env node const express = require('express'); const fs = require('fs').promises; const path = require('path'); const os = require('os'); const app = express(); const PORT = 3000; const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects'); app.use(express.static('public')); // Reconstruct the actual filesystem path from the encoded directory name async function reconstructPath(dirName, homeDir) { // Remove leading dash and split into parts const parts = dirName.replace(/^-/, '').split('-'); // Start building path from root let currentPath = ''; let pathComponents = []; let i = 0; // Handle /Users/username pattern (username may contain dots) if (parts[0] === 'Users' && parts.length > 2) { // Try username with dot: Users/first.last const possibleUsername = parts[1] + '.' + parts[2]; if (homeDir === `/Users/${possibleUsername}`) { currentPath = homeDir; pathComponents.push('Users', possibleUsername); i = 3; } else { // Fall back to regular handling currentPath = '/Users'; pathComponents.push('Users'); i = 1; } } else { currentPath = '/' + parts[0]; pathComponents.push(parts[0]); i = 1; } // Walk through remaining parts, checking filesystem to determine actual structure while (i < parts.length) { let found = false; // Try dot-separated combination first (e.g., github + com = github.com) if (i + 1 < parts.length) { const dotCandidate = parts[i] + '.' + parts[i + 1]; const testPath = path.join(currentPath, dotCandidate); try { await fs.access(testPath); // Dot-separated path exists on disk currentPath = testPath; pathComponents.push(dotCandidate); i += 2; found = true; } catch (e) { // Dot-separated doesn't exist, continue with dash combinations } } // Try increasingly longer dash-separated combinations if (!found) { for (let j = i; j < parts.length; j++) { const candidate = parts.slice(i, j + 1).join('-'); const testPath = path.join(currentPath, candidate); try { await fs.access(testPath); // Path exists, use it currentPath = testPath; pathComponents.push(candidate); i = j + 1; found = true; break; } catch (e) { // Path doesn't exist, try longer combination } } } if (!found) { // Path doesn't exist on disk, fall back to treating each part as separate pathComponents.push(parts[i]); currentPath = path.join(currentPath, parts[i]); i++; } } return { fullPath: currentPath, components: pathComponents }; } // List all projects app.get('/api/projects', async (req, res) => { try { const entries = await fs.readdir(PROJECTS_DIR, { withFileTypes: true }); const homeDir = os.homedir(); const projects = await Promise.all( entries .filter(entry => entry.isDirectory()) .map(async (entry) => { const { fullPath, components } = await reconstructPath(entry.name, homeDir); // Get project name (last component) const projectName = components[components.length - 1]; // Get parent path components (domain patterns already handled in reconstructPath) const parentComponents = components.slice(0, -1); // Build the parent path const parentPath = '/' + parentComponents.join('/'); const displayParentPath = parentPath.startsWith(homeDir) ? '~' + parentPath.substring(homeDir.length) : parentPath; return { name: entry.name, projectName: projectName, parentPath: displayParentPath }; }) ); res.json(projects); } catch (error) { res.status(500).json({ error: error.message }); } }); // List conversations in a project app.get('/api/projects/:projectName/conversations', async (req, res) => { try { const projectPath = path.join(PROJECTS_DIR, req.params.projectName); const files = await fs.readdir(projectPath); const conversations = []; const includeWarmup = req.query.includeWarmup === 'true'; const includeMeta = req.query.includeMeta === 'true'; for (const file of files) { if (file.endsWith('.jsonl')) { const filePath = path.join(projectPath, file); const stats = await fs.stat(filePath); const content = await fs.readFile(filePath, 'utf-8'); const lines = content.trim().split('\n').filter(line => line); let firstUserMessage = null; let isWarmup = false; let isMeta = false; let isSidechain = false; // First pass: check flags (sidechain anywhere, meta/warmup only on first user message) let foundFirstUserMessage = false; for (const line of lines) { try { const entry = JSON.parse(line); // Check for sidechain flag (anywhere in conversation) if (entry.isSidechain === true) { isSidechain = true; } // Look for first user message to check for meta and warmup if (!foundFirstUserMessage && entry.type === 'user' && entry.message && entry.message.content) { foundFirstUserMessage = true; // Check for meta flag on first user message only if (entry.isMeta === true) { isMeta = true; } const content = typeof entry.message.content === 'string' ? entry.message.content : entry.message.content[0]?.text || ''; // Check if it's a warmup message if (content === 'Warmup') { isWarmup = true; } } } catch (e) { // Skip malformed lines } } // Skip warmup conversations unless explicitly requested if (isWarmup && !includeWarmup) { continue; } // Skip meta conversations unless explicitly requested if (isMeta && !includeMeta) { continue; } // Skip sidechain conversations unless explicitly requested (treated as warmup) if (isSidechain && !includeWarmup) { continue; } // Second pass: get first user message for preview (skip tool_result messages) for (const line of lines) { try { const entry = JSON.parse(line); if (entry.type === 'user' && entry.message && entry.message.content) { const content = typeof entry.message.content === 'string' ? entry.message.content : entry.message.content[0]?.text || ''; if (content && !content.includes('tool_result')) { firstUserMessage = content.substring(0, 100); break; } } } catch (e) { // Skip malformed lines } } conversations.push({ id: file.replace('.jsonl', ''), filename: file, preview: firstUserMessage || 'No preview available', messageCount: lines.length, modified: stats.mtime, size: stats.size, isWarmup: isWarmup, isMeta: isMeta, isSidechain: isSidechain }); } } conversations.sort((a, b) => b.modified - a.modified); res.json(conversations); } catch (error) { res.status(500).json({ error: error.message }); } }); // Get conversation content app.get('/api/projects/:projectName/conversations/:conversationId', async (req, res) => { try { const filePath = path.join( PROJECTS_DIR, req.params.projectName, `${req.params.conversationId}.jsonl` ); const content = await fs.readFile(filePath, 'utf-8'); const lines = content.trim().split('\n').filter(line => line); const messages = []; for (const line of lines) { try { const entry = JSON.parse(line); if (entry.type === 'user' || entry.type === 'assistant') { messages.push(entry); } } catch (e) { console.error('Failed to parse line:', e); } } res.json(messages); } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(PORT, () => { console.log(`Clogue server running at http://localhost:${PORT}`); console.log(`Exploring Claude projects from: ${PROJECTS_DIR}`); });
wincent/clogue
0
Claude Code log explorer
JavaScript
wincent
Greg Hurrell
DataDog
quant_trading/__init__.py
Python
# coding: utf-8 # flake8: noqa """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # import apis into sdk package from quant_trading.api.bitcoin_futures_manager_api import BitcoinFuturesManagerApi from quant_trading.api.bitcoin_futures_market_maker_api import BitcoinFuturesMarketMakerApi from quant_trading.api.bitcoin_futures_swinger_api import BitcoinFuturesSwingerApi # import ApiClient from quant_trading.api_client import ApiClient from quant_trading.configuration import Configuration # import models into sdk package from quant_trading.models.algo_params_response import AlgoParamsResponse from quant_trading.models.avg_open_position_hours import AvgOpenPositionHours from quant_trading.models.closed_position_hours import ClosedPositionHours from quant_trading.models.current_position_pct import CurrentPositionPct from quant_trading.models.current_unrealised_pct import CurrentUnrealisedPct from quant_trading.models.error import Error from quant_trading.models.exec_algo_response import ExecAlgoResponse from quant_trading.models.exec_position_manager_algo_request import ExecPositionManagerAlgoRequest from quant_trading.models.exec_position_swinger_algo_request import ExecPositionSwingerAlgoRequest from quant_trading.models.last_open_stake_hours import LastOpenStakeHours from quant_trading.models.open_position_hours import OpenPositionHours from quant_trading.models.position_state import PositionState from quant_trading.models.stake_state import StakeState from quant_trading.models.x_rate_limit_limit import XRateLimitLimit from quant_trading.models.x_rate_limit_remaining import XRateLimitRemaining from quant_trading.models.x_rate_limit_reset import XRateLimitReset
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/api/__init__.py
Python
from __future__ import absolute_import # flake8: noqa # import apis into api package from quant_trading.api.bitcoin_futures_manager_api import BitcoinFuturesManagerApi from quant_trading.api.bitcoin_futures_market_maker_api import BitcoinFuturesMarketMakerApi from quant_trading.api.bitcoin_futures_swinger_api import BitcoinFuturesSwingerApi
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/api/bitcoin_futures_manager_api.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from quant_trading.api_client import ApiClient class BitcoinFuturesManagerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_algo_params(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_algo_params_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_algo_params_with_http_info(**kwargs) # noqa: E501 return data def get_algo_params_with_http_info(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_algo_params" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesManager/algo-params', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlgoParamsResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def post_exec_algo(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionManagerAlgoRequest body: A JSON object containing the current position manager algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 else: (data) = self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 return data def post_exec_algo_with_http_info(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionManagerAlgoRequest body: A JSON object containing the current position manager algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ all_params = ['body'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method post_exec_algo" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `post_exec_algo`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesManager/exec-algo', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ExecAlgoResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/api/bitcoin_futures_market_maker_api.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from quant_trading.api_client import ApiClient class BitcoinFuturesMarketMakerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_algo_params(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_algo_params_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_algo_params_with_http_info(**kwargs) # noqa: E501 return data def get_algo_params_with_http_info(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_algo_params" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesMm/algo-params', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlgoParamsResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def post_exec_algo(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionManagerAlgoRequest body: A JSON object containing the current position manager algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 else: (data) = self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 return data def post_exec_algo_with_http_info(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionManagerAlgoRequest body: A JSON object containing the current position manager algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ all_params = ['body'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method post_exec_algo" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `post_exec_algo`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesMm/exec-algo', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ExecAlgoResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/api/bitcoin_futures_swinger_api.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from quant_trading.api_client import ApiClient class BitcoinFuturesSwingerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def get_algo_params(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_algo_params_with_http_info(**kwargs) # noqa: E501 else: (data) = self.get_algo_params_with_http_info(**kwargs) # noqa: E501 return data def get_algo_params_with_http_info(self, **kwargs): # noqa: E501 """get_algo_params # noqa: E501 Get algorithm parameters # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_algo_params_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: AlgoParamsResponse If the method is called asynchronously, returns the request thread. """ all_params = [] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_algo_params" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesSwinger/algo-params', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='AlgoParamsResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def post_exec_algo(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionSwingerAlgoRequest body: A JSON object containing the current position swinger algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 else: (data) = self.post_exec_algo_with_http_info(body, **kwargs) # noqa: E501 return data def post_exec_algo_with_http_info(self, body, **kwargs): # noqa: E501 """post_exec_algo # noqa: E501 Determine algorithm execution # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.post_exec_algo_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool :param ExecPositionSwingerAlgoRequest body: A JSON object containing the current position swinger algorithm information. (required) :return: ExecAlgoResponse If the method is called asynchronously, returns the request thread. """ all_params = ['body'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method post_exec_algo" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params or params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `post_exec_algo`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['ApiKeyAuth'] # noqa: E501 return self.api_client.call_api( '/bitcoinFuturesSwinger/exec-algo', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='ExecAlgoResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/api_client.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import datetime import json import mimetypes from multiprocessing.pool import ThreadPool import os import re import tempfile # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import quote from quant_trading.configuration import Configuration import quant_trading.models from quant_trading import rest class ApiClient(object): """Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates. NOTE: This class is auto generated by the swagger code generator program. Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. :param cookie: a cookie to include in the header when making calls to the API """ PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types NATIVE_TYPES_MAPPING = { 'int': int, 'long': int if six.PY3 else long, # noqa: F821 'float': float, 'str': str, 'bool': bool, 'date': datetime.date, 'datetime': datetime.datetime, 'object': object, } def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None): if configuration is None: configuration = Configuration() self.configuration = configuration self.pool = ThreadPool() self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'Swagger-Codegen/1.0.0/python' def __del__(self): self.pool.close() self.pool.join() @property def user_agent(self): """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value def __call_api( self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None): config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) path_params = self.parameters_to_tuples(path_params, collection_formats) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param) ) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) query_params = self.parameters_to_tuples(query_params, collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) post_params = self.parameters_to_tuples(post_params, collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) # body if body: body = self.sanitize_for_serialization(body) # request url url = self.configuration.host + resource_path # perform request and return response response_data = self.request( method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body, _preload_content=_preload_content, _request_timeout=_request_timeout) self.last_response = response_data return_data = response_data if _preload_content: # deserialize response data if response_type: return_data = self.deserialize(response_data, response_type) else: return_data = None if _return_http_data_only: return (return_data) else: return (return_data, response_data.status, response_data.getheaders()) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ if obj is None: return None elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except # attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) for attr, _ in six.iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in six.iteritems(obj_dict)} def deserialize(self, response, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance if response_type == "file": return self.__deserialize_file(response) # fetch data from response object try: data = json.loads(response.data) except ValueError: data = response.data return self.__deserialize(data, response_type) def __deserialize(self, data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if type(klass) == str: if klass.startswith('list['): sub_kls = re.match(r'list\[(.*)\]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('dict('): sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in six.iteritems(data)} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: klass = getattr(quant_trading.models, klass) if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) elif klass == datetime.date: return self.__deserialize_date(data) elif klass == datetime.datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async_req=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None): """Makes the HTTP request (synchronous) and returns deserialized data. To make an async request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async_req bool: execute request asynchronously :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: If async_req parameter is True, the request will be called asynchronously. The method will return the request thread. If parameter async_req is False or missing, then the method will return the response directly. """ if not async_req: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout) else: thread = self.pool.apply_async(self.__call_api, (resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout)) return thread def request(self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.GET(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) else: raise ValueError( "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ new_params = [] if collection_formats is None: collection_formats = {} for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': new_params.extend((k, value) for value in v) else: if collection_format == 'ssv': delimiter = ' ' elif collection_format == 'tsv': delimiter = '\t' elif collection_format == 'pipes': delimiter = '|' else: # csv is the default delimiter = ',' new_params.append( (k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params def prepare_post_parameters(self, post_params=None, files=None): """Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = [] if post_params: params = post_params if files: for k, v in six.iteritems(files): if not v: continue file_names = v if type(v) is list else [v] for n in file_names: with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream') params.append( tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: return accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' else: return ', '.join(accepts) def select_header_content_type(self, content_types): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ if not content_types: return 'application/json' content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ if not auth_settings: return for auth in auth_settings: auth_setting = self.configuration.auth_settings().get(auth) if auth_setting: if not auth_setting['value']: continue elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' ) def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) os.close(fd) os.remove(path) content_disposition = response.getheader("Content-Disposition") if content_disposition: filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): """Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: return six.text_type(data) except TypeError: return data def __deserialize_object(self, value): """Return a original value. :return: object. """ return value def __deserialize_date(self, string): """Deserializes string to date. :param string: str. :return: date. """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string except ValueError: raise rest.ApiException( status=0, reason="Failed to parse `{0}` as date object".format(string) ) def __deserialize_datatime(self, string): """Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime. """ try: from dateutil.parser import parse return parse(string) except ImportError: return string except ValueError: raise rest.ApiException( status=0, reason=( "Failed to parse `{0}` as datetime object" .format(string) ) ) def __hasattr(self, object, name): return name in object.__class__.__dict__ def __deserialize_model(self, data, klass): """Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ if not klass.swagger_types and not self.__hasattr(klass, 'get_real_child_model'): return data kwargs = {} if klass.swagger_types is not None: for attr, attr_type in six.iteritems(klass.swagger_types): if (data is not None and klass.attribute_map[attr] in data and isinstance(data, (list, dict))): value = data[klass.attribute_map[attr]] kwargs[attr] = self.__deserialize(value, attr_type) instance = klass(**kwargs) if (isinstance(instance, dict) and klass.swagger_types is not None and isinstance(data, dict)): for key, value in data.items(): if key not in klass.swagger_types: instance[key] = value if self.__hasattr(instance, 'get_real_child_model'): klass_name = instance.get_real_child_model(data) if klass_name: instance = self.__deserialize(data, klass_name) return instance
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/configuration.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import copy import logging import multiprocessing import sys import urllib3 import six from six.moves import http_client as httplib class TypeWithDefault(type): def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None def __call__(cls): if cls._default is None: cls._default = type.__call__(cls) return copy.copy(cls._default) def set_default(cls, default): cls._default = copy.copy(default) class Configuration(six.with_metaclass(TypeWithDefault, object)): """NOTE: This class is auto generated by the swagger code generator program. Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. """ def __init__(self): """Constructor""" # Default Base url self.host = "https://www.quant-trading.network/api" # Temp file folder for downloading files self.temp_folder_path = None # Authentication Settings # dict to store API key(s) self.api_key = {} # dict to store API prefix (e.g. Bearer) self.api_key_prefix = {} # function to refresh API key if expired self.refresh_api_key_hook = None # Username for HTTP basic authentication self.username = "" # Password for HTTP basic authentication self.password = "" # Logging Settings self.logger = {} self.logger["package_logger"] = logging.getLogger("quant_trading") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' # Log stream handler self.logger_stream_handler = None # Log file handler self.logger_file_handler = None # Debug file location self.logger_file = None # Debug switch self.debug = False # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API # from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None # client certificate file self.cert_file = None # client key file self.key_file = None # Set this to True/False to enable/disable SSL hostname verification. self.assert_hostname = None # urllib3 connection pool's maximum number of connections saved # per pool. urllib3 uses 1 connection as default value, but this is # not the best value when you are making a lot of possibly parallel # requests to the same host, which is often the case here. # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 # Proxy URL self.proxy = None # Safe chars for path_param self.safe_chars_for_path_param = '' @property def logger_file(self): """The logger file. If the logger_file is None, then add stream handler and remove file handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str """ return self.__logger_file @logger_file.setter def logger_file(self, value): """The logger file. If the logger_file is None, then add stream handler and remove file handler. Otherwise, add file handler and remove stream handler. :param value: The logger_file path. :type: str """ self.__logger_file = value if self.__logger_file: # If set logging file, # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_file_handler) if self.logger_stream_handler: logger.removeHandler(self.logger_stream_handler) else: # If not set logging file, # then add stream handler and remove file handler. self.logger_stream_handler = logging.StreamHandler() self.logger_stream_handler.setFormatter(self.logger_formatter) for _, logger in six.iteritems(self.logger): logger.addHandler(self.logger_stream_handler) if self.logger_file_handler: logger.removeHandler(self.logger_file_handler) @property def debug(self): """Debug status :param value: The debug status, True or False. :type: bool """ return self.__debug @debug.setter def debug(self, value): """Debug status :param value: The debug status, True or False. :type: bool """ self.__debug = value if self.__debug: # if debug status is True, turn on debug logging for _, logger in six.iteritems(self.logger): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` for _, logger in six.iteritems(self.logger): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @property def logger_format(self): """The logger format. The logger_formatter will be updated when sets logger_format. :param value: The format string. :type: str """ return self.__logger_format @logger_format.setter def logger_format(self, value): """The logger format. The logger_formatter will be updated when sets logger_format. :param value: The format string. :type: str """ self.__logger_format = value self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. :return: The token for api key authentication. """ if self.refresh_api_key_hook: self.refresh_api_key_hook(self) key = self.api_key.get(identifier) if key: prefix = self.api_key_prefix.get(identifier) if prefix: return "%s %s" % (prefix, key) else: return key def get_basic_auth_token(self): """Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication. """ return urllib3.util.make_headers( basic_auth=self.username + ':' + self.password ).get('authorization') def auth_settings(self): """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ return { 'ApiKeyAuth': { 'type': 'api_key', 'in': 'header', 'key': 'X-API-KEY', 'value': self.get_api_key_with_prefix('X-API-KEY') }, } def to_debug_report(self): """Gets the essential information for debugging. :return: The report for debugging. """ return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: 1.0.0\n"\ "SDK Package Version: 1.0.0".\ format(env=sys.platform, pyversion=sys.version)
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/__init__.py
Python
# coding: utf-8 # flake8: noqa """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import # import models into model package from quant_trading.models.algo_params_response import AlgoParamsResponse from quant_trading.models.avg_open_position_hours import AvgOpenPositionHours from quant_trading.models.closed_position_hours import ClosedPositionHours from quant_trading.models.current_position_pct import CurrentPositionPct from quant_trading.models.current_unrealised_pct import CurrentUnrealisedPct from quant_trading.models.error import Error from quant_trading.models.exec_algo_response import ExecAlgoResponse from quant_trading.models.exec_position_manager_algo_request import ExecPositionManagerAlgoRequest from quant_trading.models.exec_position_swinger_algo_request import ExecPositionSwingerAlgoRequest from quant_trading.models.last_open_stake_hours import LastOpenStakeHours from quant_trading.models.open_position_hours import OpenPositionHours from quant_trading.models.position_state import PositionState from quant_trading.models.stake_state import StakeState from quant_trading.models.x_rate_limit_limit import XRateLimitLimit from quant_trading.models.x_rate_limit_remaining import XRateLimitRemaining from quant_trading.models.x_rate_limit_reset import XRateLimitReset
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/algo_params_response.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class AlgoParamsResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'position_stake_size_percentage': 'float', 'decision_polling_interval_in_seconds': 'int' } attribute_map = { 'position_stake_size_percentage': 'positionStakeSizePercentage', 'decision_polling_interval_in_seconds': 'decisionPollingIntervalInSeconds' } def __init__(self, position_stake_size_percentage=None, decision_polling_interval_in_seconds=None): # noqa: E501 """AlgoParamsResponse - a model defined in Swagger""" # noqa: E501 self._position_stake_size_percentage = None self._decision_polling_interval_in_seconds = None self.discriminator = None if position_stake_size_percentage is not None: self.position_stake_size_percentage = position_stake_size_percentage if decision_polling_interval_in_seconds is not None: self.decision_polling_interval_in_seconds = decision_polling_interval_in_seconds @property def position_stake_size_percentage(self): """Gets the position_stake_size_percentage of this AlgoParamsResponse. # noqa: E501 The percentage size of each stake to be used with this algorithm. # noqa: E501 :return: The position_stake_size_percentage of this AlgoParamsResponse. # noqa: E501 :rtype: float """ return self._position_stake_size_percentage @position_stake_size_percentage.setter def position_stake_size_percentage(self, position_stake_size_percentage): """Sets the position_stake_size_percentage of this AlgoParamsResponse. The percentage size of each stake to be used with this algorithm. # noqa: E501 :param position_stake_size_percentage: The position_stake_size_percentage of this AlgoParamsResponse. # noqa: E501 :type: float """ self._position_stake_size_percentage = position_stake_size_percentage @property def decision_polling_interval_in_seconds(self): """Gets the decision_polling_interval_in_seconds of this AlgoParamsResponse. # noqa: E501 The interval of time in seconds until the algorithm will provide the next decision. # noqa: E501 :return: The decision_polling_interval_in_seconds of this AlgoParamsResponse. # noqa: E501 :rtype: int """ return self._decision_polling_interval_in_seconds @decision_polling_interval_in_seconds.setter def decision_polling_interval_in_seconds(self, decision_polling_interval_in_seconds): """Sets the decision_polling_interval_in_seconds of this AlgoParamsResponse. The interval of time in seconds until the algorithm will provide the next decision. # noqa: E501 :param decision_polling_interval_in_seconds: The decision_polling_interval_in_seconds of this AlgoParamsResponse. # noqa: E501 :type: int """ self._decision_polling_interval_in_seconds = decision_polling_interval_in_seconds def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(AlgoParamsResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AlgoParamsResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/avg_open_position_hours.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class AvgOpenPositionHours(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """AvgOpenPositionHours - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(AvgOpenPositionHours, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AvgOpenPositionHours): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/closed_position_hours.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ClosedPositionHours(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """ClosedPositionHours - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ClosedPositionHours, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ClosedPositionHours): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/current_position_pct.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class CurrentPositionPct(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """CurrentPositionPct - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(CurrentPositionPct, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CurrentPositionPct): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/current_unrealised_pct.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class CurrentUnrealisedPct(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """CurrentUnrealisedPct - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(CurrentUnrealisedPct, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, CurrentUnrealisedPct): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/error.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class Error(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'message': 'str', 'data': 'list[str]' } attribute_map = { 'message': 'message', 'data': 'data' } def __init__(self, message=None, data=None): # noqa: E501 """Error - a model defined in Swagger""" # noqa: E501 self._message = None self._data = None self.discriminator = None if message is not None: self.message = message if data is not None: self.data = data @property def message(self): """Gets the message of this Error. # noqa: E501 The error message. # noqa: E501 :return: The message of this Error. # noqa: E501 :rtype: str """ return self._message @message.setter def message(self, message): """Sets the message of this Error. The error message. # noqa: E501 :param message: The message of this Error. # noqa: E501 :type: str """ self._message = message @property def data(self): """Gets the data of this Error. # noqa: E501 :return: The data of this Error. # noqa: E501 :rtype: list[str] """ return self._data @data.setter def data(self, data): """Sets the data of this Error. :param data: The data of this Error. # noqa: E501 :type: list[str] """ self._data = data def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(Error, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Error): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/exec_algo_response.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ExecAlgoResponse(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'decision': 'str', 'decision_timestamp': 'datetime', 'next_decision_timestamp': 'datetime', 'milliseconds_to_next_decision': 'int' } attribute_map = { 'decision': 'decision', 'decision_timestamp': 'decisionTimestamp', 'next_decision_timestamp': 'nextDecisionTimestamp', 'milliseconds_to_next_decision': 'millisecondsToNextDecision' } def __init__(self, decision=None, decision_timestamp=None, next_decision_timestamp=None, milliseconds_to_next_decision=None): # noqa: E501 """ExecAlgoResponse - a model defined in Swagger""" # noqa: E501 self._decision = None self._decision_timestamp = None self._next_decision_timestamp = None self._milliseconds_to_next_decision = None self.discriminator = None if decision is not None: self.decision = decision if decision_timestamp is not None: self.decision_timestamp = decision_timestamp if next_decision_timestamp is not None: self.next_decision_timestamp = next_decision_timestamp if milliseconds_to_next_decision is not None: self.milliseconds_to_next_decision = milliseconds_to_next_decision @property def decision(self): """Gets the decision of this ExecAlgoResponse. # noqa: E501 The decision taken by the algorithm. Whether to open a long/short position or to cancel the previous attempt. # noqa: E501 :return: The decision of this ExecAlgoResponse. # noqa: E501 :rtype: str """ return self._decision @decision.setter def decision(self, decision): """Sets the decision of this ExecAlgoResponse. The decision taken by the algorithm. Whether to open a long/short position or to cancel the previous attempt. # noqa: E501 :param decision: The decision of this ExecAlgoResponse. # noqa: E501 :type: str """ allowed_values = ["NONE", "OPEN_LONG", "OPEN_SHORT", "CANCEL_LONG", "CANCEL_SHORT"] # noqa: E501 if decision not in allowed_values: raise ValueError( "Invalid value for `decision` ({0}), must be one of {1}" # noqa: E501 .format(decision, allowed_values) ) self._decision = decision @property def decision_timestamp(self): """Gets the decision_timestamp of this ExecAlgoResponse. # noqa: E501 The timestamp this decision was taken by the algorithm. # noqa: E501 :return: The decision_timestamp of this ExecAlgoResponse. # noqa: E501 :rtype: datetime """ return self._decision_timestamp @decision_timestamp.setter def decision_timestamp(self, decision_timestamp): """Sets the decision_timestamp of this ExecAlgoResponse. The timestamp this decision was taken by the algorithm. # noqa: E501 :param decision_timestamp: The decision_timestamp of this ExecAlgoResponse. # noqa: E501 :type: datetime """ self._decision_timestamp = decision_timestamp @property def next_decision_timestamp(self): """Gets the next_decision_timestamp of this ExecAlgoResponse. # noqa: E501 The timestamp when the user will be able to get a new decision from the algorithm. # noqa: E501 :return: The next_decision_timestamp of this ExecAlgoResponse. # noqa: E501 :rtype: datetime """ return self._next_decision_timestamp @next_decision_timestamp.setter def next_decision_timestamp(self, next_decision_timestamp): """Sets the next_decision_timestamp of this ExecAlgoResponse. The timestamp when the user will be able to get a new decision from the algorithm. # noqa: E501 :param next_decision_timestamp: The next_decision_timestamp of this ExecAlgoResponse. # noqa: E501 :type: datetime """ self._next_decision_timestamp = next_decision_timestamp @property def milliseconds_to_next_decision(self): """Gets the milliseconds_to_next_decision of this ExecAlgoResponse. # noqa: E501 The milliseconds left for the new decision when user will be able to get a new decision from the algorithm. # noqa: E501 :return: The milliseconds_to_next_decision of this ExecAlgoResponse. # noqa: E501 :rtype: int """ return self._milliseconds_to_next_decision @milliseconds_to_next_decision.setter def milliseconds_to_next_decision(self, milliseconds_to_next_decision): """Sets the milliseconds_to_next_decision of this ExecAlgoResponse. The milliseconds left for the new decision when user will be able to get a new decision from the algorithm. # noqa: E501 :param milliseconds_to_next_decision: The milliseconds_to_next_decision of this ExecAlgoResponse. # noqa: E501 :type: int """ self._milliseconds_to_next_decision = milliseconds_to_next_decision def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ExecAlgoResponse, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ExecAlgoResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/exec_position_manager_algo_request.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ExecPositionManagerAlgoRequest(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'long_stake_state': 'StakeState', 'short_stake_state': 'StakeState', 'current_position_pct': 'CurrentPositionPct', 'current_unrealised_pct': 'CurrentUnrealisedPct', 'avg_open_position_hours': 'AvgOpenPositionHours', 'last_open_stake_hours': 'LastOpenStakeHours', 'closed_position_hours': 'ClosedPositionHours' } attribute_map = { 'long_stake_state': 'longStakeState', 'short_stake_state': 'shortStakeState', 'current_position_pct': 'currentPositionPct', 'current_unrealised_pct': 'currentUnrealisedPct', 'avg_open_position_hours': 'avgOpenPositionHours', 'last_open_stake_hours': 'lastOpenStakeHours', 'closed_position_hours': 'closedPositionHours' } def __init__(self, long_stake_state=None, short_stake_state=None, current_position_pct=None, current_unrealised_pct=None, avg_open_position_hours=None, last_open_stake_hours=None, closed_position_hours=None): # noqa: E501 """ExecPositionManagerAlgoRequest - a model defined in Swagger""" # noqa: E501 self._long_stake_state = None self._short_stake_state = None self._current_position_pct = None self._current_unrealised_pct = None self._avg_open_position_hours = None self._last_open_stake_hours = None self._closed_position_hours = None self.discriminator = None self.long_stake_state = long_stake_state self.short_stake_state = short_stake_state self.current_position_pct = current_position_pct self.current_unrealised_pct = current_unrealised_pct self.avg_open_position_hours = avg_open_position_hours self.last_open_stake_hours = last_open_stake_hours self.closed_position_hours = closed_position_hours @property def long_stake_state(self): """Gets the long_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The long_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: StakeState """ return self._long_stake_state @long_stake_state.setter def long_stake_state(self, long_stake_state): """Sets the long_stake_state of this ExecPositionManagerAlgoRequest. :param long_stake_state: The long_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: StakeState """ if long_stake_state is None: raise ValueError("Invalid value for `long_stake_state`, must not be `None`") # noqa: E501 self._long_stake_state = long_stake_state @property def short_stake_state(self): """Gets the short_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The short_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: StakeState """ return self._short_stake_state @short_stake_state.setter def short_stake_state(self, short_stake_state): """Sets the short_stake_state of this ExecPositionManagerAlgoRequest. :param short_stake_state: The short_stake_state of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: StakeState """ if short_stake_state is None: raise ValueError("Invalid value for `short_stake_state`, must not be `None`") # noqa: E501 self._short_stake_state = short_stake_state @property def current_position_pct(self): """Gets the current_position_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The current_position_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: CurrentPositionPct """ return self._current_position_pct @current_position_pct.setter def current_position_pct(self, current_position_pct): """Sets the current_position_pct of this ExecPositionManagerAlgoRequest. :param current_position_pct: The current_position_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: CurrentPositionPct """ if current_position_pct is None: raise ValueError("Invalid value for `current_position_pct`, must not be `None`") # noqa: E501 self._current_position_pct = current_position_pct @property def current_unrealised_pct(self): """Gets the current_unrealised_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The current_unrealised_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: CurrentUnrealisedPct """ return self._current_unrealised_pct @current_unrealised_pct.setter def current_unrealised_pct(self, current_unrealised_pct): """Sets the current_unrealised_pct of this ExecPositionManagerAlgoRequest. :param current_unrealised_pct: The current_unrealised_pct of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: CurrentUnrealisedPct """ if current_unrealised_pct is None: raise ValueError("Invalid value for `current_unrealised_pct`, must not be `None`") # noqa: E501 self._current_unrealised_pct = current_unrealised_pct @property def avg_open_position_hours(self): """Gets the avg_open_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The avg_open_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: AvgOpenPositionHours """ return self._avg_open_position_hours @avg_open_position_hours.setter def avg_open_position_hours(self, avg_open_position_hours): """Sets the avg_open_position_hours of this ExecPositionManagerAlgoRequest. :param avg_open_position_hours: The avg_open_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: AvgOpenPositionHours """ if avg_open_position_hours is None: raise ValueError("Invalid value for `avg_open_position_hours`, must not be `None`") # noqa: E501 self._avg_open_position_hours = avg_open_position_hours @property def last_open_stake_hours(self): """Gets the last_open_stake_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The last_open_stake_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: LastOpenStakeHours """ return self._last_open_stake_hours @last_open_stake_hours.setter def last_open_stake_hours(self, last_open_stake_hours): """Sets the last_open_stake_hours of this ExecPositionManagerAlgoRequest. :param last_open_stake_hours: The last_open_stake_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: LastOpenStakeHours """ if last_open_stake_hours is None: raise ValueError("Invalid value for `last_open_stake_hours`, must not be `None`") # noqa: E501 self._last_open_stake_hours = last_open_stake_hours @property def closed_position_hours(self): """Gets the closed_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :return: The closed_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :rtype: ClosedPositionHours """ return self._closed_position_hours @closed_position_hours.setter def closed_position_hours(self, closed_position_hours): """Sets the closed_position_hours of this ExecPositionManagerAlgoRequest. :param closed_position_hours: The closed_position_hours of this ExecPositionManagerAlgoRequest. # noqa: E501 :type: ClosedPositionHours """ if closed_position_hours is None: raise ValueError("Invalid value for `closed_position_hours`, must not be `None`") # noqa: E501 self._closed_position_hours = closed_position_hours def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ExecPositionManagerAlgoRequest, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ExecPositionManagerAlgoRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/exec_position_swinger_algo_request.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ExecPositionSwingerAlgoRequest(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'position_long_stake_state': 'PositionState', 'position_short_stake_state': 'PositionState', 'current_unrealised_pct': 'CurrentUnrealisedPct', 'open_position_hours': 'OpenPositionHours', 'closed_position_hours': 'ClosedPositionHours' } attribute_map = { 'position_long_stake_state': 'positionLongStakeState', 'position_short_stake_state': 'positionShortStakeState', 'current_unrealised_pct': 'currentUnrealisedPct', 'open_position_hours': 'openPositionHours', 'closed_position_hours': 'closedPositionHours' } def __init__(self, position_long_stake_state=None, position_short_stake_state=None, current_unrealised_pct=None, open_position_hours=None, closed_position_hours=None): # noqa: E501 """ExecPositionSwingerAlgoRequest - a model defined in Swagger""" # noqa: E501 self._position_long_stake_state = None self._position_short_stake_state = None self._current_unrealised_pct = None self._open_position_hours = None self._closed_position_hours = None self.discriminator = None self.position_long_stake_state = position_long_stake_state self.position_short_stake_state = position_short_stake_state self.current_unrealised_pct = current_unrealised_pct self.open_position_hours = open_position_hours self.closed_position_hours = closed_position_hours @property def position_long_stake_state(self): """Gets the position_long_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :return: The position_long_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :rtype: PositionState """ return self._position_long_stake_state @position_long_stake_state.setter def position_long_stake_state(self, position_long_stake_state): """Sets the position_long_stake_state of this ExecPositionSwingerAlgoRequest. :param position_long_stake_state: The position_long_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :type: PositionState """ if position_long_stake_state is None: raise ValueError("Invalid value for `position_long_stake_state`, must not be `None`") # noqa: E501 self._position_long_stake_state = position_long_stake_state @property def position_short_stake_state(self): """Gets the position_short_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :return: The position_short_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :rtype: PositionState """ return self._position_short_stake_state @position_short_stake_state.setter def position_short_stake_state(self, position_short_stake_state): """Sets the position_short_stake_state of this ExecPositionSwingerAlgoRequest. :param position_short_stake_state: The position_short_stake_state of this ExecPositionSwingerAlgoRequest. # noqa: E501 :type: PositionState """ if position_short_stake_state is None: raise ValueError("Invalid value for `position_short_stake_state`, must not be `None`") # noqa: E501 self._position_short_stake_state = position_short_stake_state @property def current_unrealised_pct(self): """Gets the current_unrealised_pct of this ExecPositionSwingerAlgoRequest. # noqa: E501 :return: The current_unrealised_pct of this ExecPositionSwingerAlgoRequest. # noqa: E501 :rtype: CurrentUnrealisedPct """ return self._current_unrealised_pct @current_unrealised_pct.setter def current_unrealised_pct(self, current_unrealised_pct): """Sets the current_unrealised_pct of this ExecPositionSwingerAlgoRequest. :param current_unrealised_pct: The current_unrealised_pct of this ExecPositionSwingerAlgoRequest. # noqa: E501 :type: CurrentUnrealisedPct """ if current_unrealised_pct is None: raise ValueError("Invalid value for `current_unrealised_pct`, must not be `None`") # noqa: E501 self._current_unrealised_pct = current_unrealised_pct @property def open_position_hours(self): """Gets the open_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :return: The open_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :rtype: OpenPositionHours """ return self._open_position_hours @open_position_hours.setter def open_position_hours(self, open_position_hours): """Sets the open_position_hours of this ExecPositionSwingerAlgoRequest. :param open_position_hours: The open_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :type: OpenPositionHours """ if open_position_hours is None: raise ValueError("Invalid value for `open_position_hours`, must not be `None`") # noqa: E501 self._open_position_hours = open_position_hours @property def closed_position_hours(self): """Gets the closed_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :return: The closed_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :rtype: ClosedPositionHours """ return self._closed_position_hours @closed_position_hours.setter def closed_position_hours(self, closed_position_hours): """Sets the closed_position_hours of this ExecPositionSwingerAlgoRequest. :param closed_position_hours: The closed_position_hours of this ExecPositionSwingerAlgoRequest. # noqa: E501 :type: ClosedPositionHours """ if closed_position_hours is None: raise ValueError("Invalid value for `closed_position_hours`, must not be `None`") # noqa: E501 self._closed_position_hours = closed_position_hours def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ExecPositionSwingerAlgoRequest, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ExecPositionSwingerAlgoRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/last_open_stake_hours.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class LastOpenStakeHours(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """LastOpenStakeHours - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(LastOpenStakeHours, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, LastOpenStakeHours): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/open_position_hours.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class OpenPositionHours(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """OpenPositionHours - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(OpenPositionHours, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, OpenPositionHours): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/position_state.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class PositionState(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ allowed enum values """ CLOSED = "CLOSED" OPENING = "OPENING" OPEN = "OPEN" """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """PositionState - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(PositionState, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, PositionState): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/stake_state.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class StakeState(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ allowed enum values """ CLOSED = "CLOSED" OPENING = "OPENING" """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """StakeState - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(StakeState, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, StakeState): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/x_rate_limit_limit.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class XRateLimitLimit(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """XRateLimitLimit - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(XRateLimitLimit, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, XRateLimitLimit): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/x_rate_limit_remaining.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class XRateLimitRemaining(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """XRateLimitRemaining - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(XRateLimitRemaining, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, XRateLimitRemaining): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/models/x_rate_limit_reset.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class XRateLimitReset(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { } attribute_map = { } def __init__(self): # noqa: E501 """XRateLimitReset - a model defined in Swagger""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(XRateLimitReset, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, XRateLimitReset): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
quant_trading/rest.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import io import json import logging import re import ssl import certifi # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import urlencode try: import urllib3 except ImportError: raise ImportError('Swagger python client requires urllib3.') logger = logging.getLogger(__name__) class RESTResponse(io.IOBase): def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason self.data = resp.data def getheaders(self): """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader(self, name, default=None): """Returns a given response header.""" return self.urllib3_response.getheader(name, default) class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs if configuration.verify_ssl: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE # ca_certs if configuration.ssl_ca_cert: ca_certs = configuration.ssl_ca_cert else: # if not set certificate file, use Mozilla's root certificates. ca_certs = certifi.where() addition_pool_args = {} if configuration.assert_hostname is not None: addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 if maxsize is None: if configuration.connection_pool_maxsize is not None: maxsize = configuration.connection_pool_maxsize else: maxsize = 4 # https pool manager if configuration.proxy: self.pool_manager = urllib3.ProxyManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, **addition_pool_args ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) def request(self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None): """Perform requests. :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( "body parameter cannot be used with post_params parameter." ) post_params = post_params or {} headers = headers or {} timeout = None if _request_timeout: if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 timeout = urllib3.Timeout(total=_request_timeout) elif (isinstance(_request_timeout, tuple) and len(_request_timeout) == 2): timeout = urllib3.Timeout( connect=_request_timeout[0], read=_request_timeout[1]) if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( method, url, fields=post_params, encode_multipart=True, preload_content=_preload_content, timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form elif isinstance(body, str): request_body = body r = self.pool_manager.request( method, url, body=request_body, preload_content=_preload_content, timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, fields=query_params, preload_content=_preload_content, timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) if _preload_content: r = RESTResponse(r) # In the python 3, the response.data is bytes. # we need to decode it to string. if six.PY3: r.data = r.data.decode('utf8') # log response body logger.debug("response body: %s", r.data) if not 200 <= r.status <= 299: raise ApiException(http_resp=r) return r def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, query_params=query_params) def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) class ApiException(Exception): def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: self.status = status self.reason = reason self.body = None self.headers = None def __str__(self): """Custom error messages for exception""" error_message = "({0})\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: error_message += "HTTP response headers: {0}\n".format( self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) return error_message
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
setup.py
Python
# coding: utf-8 """ Quant Trading Network API This API will use JSON. JSON looks like this: { \"key\": \"value\", \"anotherKey\": \"anotherValue\" } # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@quant-trading.network Generated by: https://github.com/swagger-api/swagger-codegen.git """ from setuptools import setup, find_packages # noqa: H301 NAME = "quant-trading-api" VERSION = "1.0.1" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"] setup( name=NAME, version=VERSION, license="MIT", description="Quant Trading Network API", author = "Quant-trading.Network", author_email="support@quant-trading.network", url="https://github.com/Quant-Network/python-api-client", download_url = "https://github.com/Quant-Network/python-api-client/archive/v_1.tar.gz", keywords=["Quant Trading Network API", "algorithmic trading", "trading", "bitcoin", "Swagger"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="Python library for connecting to the Quant-trading.Network API.", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Build Tools", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7",], )
wing328/python-api-client
0
Python library for connecting to the Quant-trading.Network API.
wing328
William Cheng
OpenAPITools
.formatter.exs
Elixir
[ import_deps: [:phoenix, :ash, :ash_authentication_phoenix, :ash_postgres], plugins: [Phoenix.LiveView.HTMLFormatter], inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}"] ]
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
assets/css/app.css
CSS
@import "tailwindcss/base"; @import "tailwindcss/components"; @import "tailwindcss/utilities"; /* This file is for your main application CSS */
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
assets/js/app.js
JavaScript
// If you want to use Phoenix channels, run `mix help phx.gen.channel` // to get started and then uncomment the line below. // import "./user_socket.js" // You can include dependencies in two ways. // // The simplest option is to put them in assets/vendor and // import them using relative paths: // // import "../vendor/some-package.js" // // Alternatively, you can `npm install some-package --prefix assets` and import // them using a path starting with the package name: // // import "some-package" // // Include phoenix_html to handle method=PUT/DELETE in forms and buttons. import "phoenix_html" // Establish Phoenix Socket and LiveView configuration. import {Socket} from "phoenix" import {LiveSocket} from "phoenix_live_view" import topbar from "../vendor/topbar" let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}}) // Show progress bar on live navigation and form submits topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"}) window.addEventListener("phx:page-loading-start", info => topbar.delayedShow(200)) window.addEventListener("phx:page-loading-stop", info => topbar.hide()) // connect if there are any LiveViews on the page liveSocket.connect() // expose liveSocket on window for web console debug logs and latency simulation: // >> liveSocket.enableDebug() // >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session // >> liveSocket.disableLatencySim() window.liveSocket = liveSocket
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
assets/tailwind.config.js
JavaScript
// See the Tailwind configuration guide for advanced usage // https://tailwindcss.com/docs/configuration const plugin = require("tailwindcss/plugin") module.exports = { content: [ "./js/**/*.js", "../lib/*_web.ex", "../lib/*_web/**/*.*ex", "../deps/ash_authentication_phoenix/**/*.ex" ], theme: { extend: { colors: { brand: "#FD4F00", } }, }, plugins: [ require("@tailwindcss/forms"), plugin(({ addVariant }) => addVariant("phx-no-feedback", [".phx-no-feedback&", ".phx-no-feedback &"])), plugin(({ addVariant }) => addVariant("phx-click-loading", [".phx-click-loading&", ".phx-click-loading &"])), plugin(({ addVariant }) => addVariant("phx-submit-loading", [".phx-submit-loading&", ".phx-submit-loading &"])), plugin(({ addVariant }) => addVariant("phx-change-loading", [".phx-change-loading&", ".phx-change-loading &"])) ] }
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
config/config.exs
Elixir
# This file is responsible for configuring your application # and its dependencies with the aid of the Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. # General application configuration import Config config :example, ash_apis: [Example.Accounts] config :example, ecto_repos: [Example.Repo] config :ash, :use_all_identities_in_manage_relationship?, false # Configures the endpoint config :example, ExampleWeb.Endpoint, url: [host: "localhost"], render_errors: [ formats: [html: ExampleWeb.ErrorHTML, json: ExampleWeb.ErrorJSON], layout: false ], pubsub_server: Example.PubSub, live_view: [signing_salt: "gY5i/YF5"] # Configures the mailer # # By default it uses the "Local" adapter which stores the emails # locally. You can see the emails in your browser, at "/dev/mailbox". # # For production it's recommended to configure a different adapter # at the `config/runtime.exs`. config :example, Example.Mailer, adapter: Swoosh.Adapters.Local # Configure esbuild (the version is required) config :esbuild, version: "0.14.41", default: [ args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*), cd: Path.expand("../assets", __DIR__), env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)} ] # Configure tailwind (the version is required) config :tailwind, version: "3.2.4", default: [ args: ~w( --config=tailwind.config.js --input=css/app.css --output=../priv/static/assets/app.css ), cd: Path.expand("../assets", __DIR__) ] # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] # Use Jason for JSON parsing in Phoenix config :phoenix, :json_library, Jason # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{config_env()}.exs"
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
config/dev.exs
Elixir
import Config config :example, Example.Repo, username: "postgres", password: "postgres", hostname: "localhost", database: "example_dev", port: 5432, show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with esbuild to bundle .js and .css sources. config :example, ExampleWeb.Endpoint, # Binding to loopback ipv4 address prevents access from other machines. # Change to `ip: {0, 0, 0, 0}` to allow access from other machines. http: [ip: {127, 0, 0, 1}, port: 4000], check_origin: false, code_reloader: true, debug_errors: true, secret_key_base: "Mu98ChtcqHt5rbVABvUyLKvpALN4YirasHrHzhwgERZ/GACneOG1c1aWhlJLkwU3", watchers: [ esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]}, tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]} ] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Watch static and templates for browser reloading. config :example, ExampleWeb.Endpoint, live_reload: [ patterns: [ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$", ~r"priv/gettext/.*(po)$", ~r"lib/example_web/(controllers|live|components)/.*(ex|heex)$" ] ] # Enable dev routes for dashboard and mailbox config :example, dev_routes: true # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime # Disable swoosh api client as it is only required for production adapters. config :swoosh, :api_client, false
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
config/prod.exs
Elixir
import Config # For production, don't forget to configure the url host # to something meaningful, Phoenix uses this information # when generating URLs. # Note we also include the path to a cache manifest # containing the digested version of static files. This # manifest is generated by the `mix phx.digest` task, # which you should run after static files are built and # before starting your production server. config :example, ExampleWeb.Endpoint, cache_static_manifest: "priv/static/cache_manifest.json" # Configures Swoosh API Client config :swoosh, api_client: Swoosh.ApiClient.Finch, finch_name: Example.Finch # Do not print debug messages in production config :logger, level: :info # Runtime production configuration, including reading # of environment variables, is done on config/runtime.exs.
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
config/runtime.exs
Elixir
import Config # config/runtime.exs is executed for all environments, including # during releases. It is executed after compilation and before the # system starts, so it is typically used to load production configuration # and secrets from environment variables or elsewhere. Do not define # any compile-time configuration in here, as it won't be applied. # The block below contains prod specific runtime configuration. # ## Using releases # # If you use `mix release`, you need to explicitly enable the server # by passing the PHX_SERVER=true when you start it: # # PHX_SERVER=true bin/example start # # Alternatively, you can use `mix phx.gen.release` to generate a `bin/server` # script that automatically sets the env var above. if System.get_env("PHX_SERVER") do config :example, ExampleWeb.Endpoint, server: true end if config_env() == :prod do database_url = System.get_env("DATABASE_URL") || raise """ environment variable DATABASE_URL is missing. For example: ecto://USER:PASS@HOST/DATABASE """ config :example, Example.Repo, url: database_url, pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10") # The secret key base is used to sign/encrypt cookies and other secrets. # A default value is used in config/dev.exs and config/test.exs but you # want to use a different value for prod and you most likely don't want # to check this value into version control, so we use an environment # variable instead. secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ host = System.get_env("PHX_HOST") || "example.com" port = String.to_integer(System.get_env("PORT") || "4000") config :example, ExampleWeb.Endpoint, url: [host: host, port: 443, scheme: "https"], http: [ # Enable IPv6 and bind on all interfaces. # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html # for details about using IPv6 vs IPv4 and loopback vs public addresses. ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port ], secret_key_base: secret_key_base # ## SSL Support # # To get SSL working, you will need to add the `https` key # to your endpoint configuration: # # config :example, ExampleWeb.Endpoint, # https: [ # ..., # port: 443, # cipher_suite: :strong, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH") # ] # # The `cipher_suite` is set to `:strong` to support only the # latest and more secure SSL ciphers. This means old browsers # and clients may not be supported. You can set it to # `:compatible` for wider support. # # `:keyfile` and `:certfile` expect an absolute path to the key # and cert in disk or a relative path inside priv, for example # "priv/ssl/server.key". For all supported SSL configuration # options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1 # # We also recommend setting `force_ssl` in your endpoint, ensuring # no data is ever sent via http, always redirecting to https: # # config :example, ExampleWeb.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Configuring the mailer # # In production you need to configure the mailer to use a different adapter. # Also, you may need to configure the Swoosh API client of your choice if you # are not using SMTP. Here is an example of the configuration: # # config :example, Example.Mailer, # adapter: Swoosh.Adapters.Mailgun, # api_key: System.get_env("MAILGUN_API_KEY"), # domain: System.get_env("MAILGUN_DOMAIN") # # For this example you need include a HTTP client required by Swoosh API client. # Swoosh supports Hackney and Finch out of the box: # # config :swoosh, :api_client, Swoosh.ApiClient.Hackney # # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details. end
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
config/test.exs
Elixir
import Config config :example, Example.Repo, username: "postgres", password: "postgres", hostname: "localhost", database: "example_test#{System.get_env("MIX_TEST_PARTITION")}", pool: Ecto.Adapters.SQL.Sandbox, pool_size: 10 # We don't run a server during test. If one is required, # you can enable the server option below. config :example, ExampleWeb.Endpoint, http: [ip: {127, 0, 0, 1}, port: 4002], secret_key_base: "gnpyAW3uvW/QiiPt4WMqWnm84B5uiUvkMyr+yuf4v4CsVc11YpjP1Po8VPKSdMXu", server: false # In test we don't send emails. config :example, Example.Mailer, adapter: Swoosh.Adapters.Test # Disable swoosh api client as it is only required for production adapters. config :swoosh, :api_client, false # Print only warnings and errors during test config :logger, level: :warning # Initialize plugs at runtime for faster test compilation config :phoenix, :plug_init_mode, :runtime
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
lib/example.ex
Elixir
defmodule Example do @moduledoc """ Example keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
lib/example/accounts.ex
Elixir
defmodule Example.Accounts do use Ash.Api resources do registry Example.Accounts.Registry end end
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
lib/example/accounts/registry.ex
Elixir
defmodule Example.Accounts.Registry do use Ash.Registry, extensions: [Ash.Registry.ResourceValidations] entries do entry Example.Accounts.User entry Example.Accounts.Token end end
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting
lib/example/accounts/token.ex
Elixir
defmodule Example.Accounts.Token do use Ash.Resource, data_layer: AshPostgres.DataLayer, extensions: [AshAuthentication.TokenResource] token do api Example.Accounts end postgres do table "tokens" repo Example.Repo end end
wintermeyer/ash-authentication-phoenix-example
0
This repo is the resulting source code of the Getting Started Ash Authentication Phoenix tutorial.
Elixir
wintermeyer
Stefan Wintermeyer
Wintermeyer Consulting