text
stringlengths
0
601k
let a_to_b_exc_int64 ~ a ~ b : int64 Seq . t = let rec aux cur n = if cur < n then fun ( ) -> Seq . Cons ( cur , aux ( cur +^ 1L ) n ) else Seq . empty in aux a b
let a_to_b_inc_int64 ~ a ~ b : int64 Seq . t = a_to_b_exc_int64 ~ a ~ b ( : b +^ 1L )
let zero_to_n_exc_int64 n : int64 Seq . t = a_to_b_exc_int64 ~ a : 0L ~ b : n
let zero_to_n_inc_int64 n = zero_to_n_exc_int64 ( n +^ 1L )
let mod_int n = let rec aux cur n = if cur < n then fun ( ) -> Seq . Cons ( cur , aux ( cur + 1 ) n ) else aux 0 n in aux 0 n
let collect_round_robin ( type a ) ( ~ f_le : a -> a -> bool ) ( batches : a Seq . t list ) : a option list Seq . t = let rec get_usable_part ( cur : a ) ( seq : a Seq . t ) : a Seq . t = match seq ( ) with | Seq . Nil -> Seq . empty | Seq . Cons ( x , rest ) as s -> if f_le cur x then fun ( ) -> s else get_usable_part...
let check_if_f_holds_for_immediate_neighbors ( type a ) ( ~ f : a -> a -> bool ) ( ~ f_exn : a -> a -> exn ) ( s : a Seq . t ) : a Seq . t = let rec aux f f_exn ( cur : a option ) ( s : a Seq . t ) : a Seq . t = match s ( ) with | Seq . Nil -> ( match cur with None -> Seq . empty | Some x -> Seq . return x ) | Seq . Co...
let get_ok_error_list ( s : ( ' a , ' b ) result Seq . t ) : ( ' a list , ' b ) result = let rec aux acc ( s : ( ' a , ' b ) result Seq . t ) : ( ' a list , ' b ) result = match s ( ) with | Seq . Nil -> Ok ( List . rev acc ) | Seq . Cons ( x , rest ) -> ( match x with Ok x -> aux ( x :: acc ) rest | Error s -> Error s...
let last_element_of_seq ( s : ' a Seq . t ) : ' a option = let rec aux s = match s ( ) with | Seq . Nil -> None | Seq . Cons ( x , rest ) -> ( match rest ( ) with Seq . Nil -> Some x | Seq . Cons _ -> aux rest ) in aux s
module Make ( Key : Binable . S ) S ( Value : Binable . S ) S : Key_value_database . Intf . S with module M := Key_value_database . Monad . Ident and type key := Key . t and type value := Value . t and type config := string = struct type t = Database . t let create directory = Database . create directory let close = Da...
module GADT = struct module type Database_intf = sig type t type ' a g val set : t -> key : ' a g -> data : ' a -> unit val set_raw : t -> key : ' a g -> data : Bigstring . t -> unit val remove : t -> key : ' a g -> unit end module type S = sig include Database_intf module T : sig type nonrec t = t end val create : str...
module type S = sig include Caml . Map . S val set : ' a t -> key : key -> data ' : a -> ' a t val t_of_sexp : ( Sexp . t -> ' a ) -> Sexp . t -> ' a t val sexp_of_t : ( ' a -> Sexp . t ) -> ' a t -> Sexp . t val hash_fold_t : ( Hash . state -> ' a -> Hash . state ) -> Hash . state -> ' a t -> Hash . state val pp : ( F...
module type OrderedType = sig include Caml . Map . OrderedType val t_of_sexp : Sexp . t -> t val sexp_of_t : t -> Sexp . t val hash_fold_t : Hash . state -> t -> Hash . state val pp : Formatter . t -> t -> unit end
module Make ( Ordered : OrderedType ) : S with type key = Ordered . t = struct include Caml . Map . Make ( Ordered ) module Key = struct include Ordered type ' a assoc = t * ' a [ @@ deriving compare , sexp , show , hash ] end let set map ~ key ~ data = add key data map let t_of_sexp a_of_sexp sexp = Core . List . t_of...
module type S = sig include Caml . Set . S val t_of_sexp : Sexp . t -> t val sexp_of_t : t -> Sexp . t val hash_fold_t : Hash . state -> t -> Hash . state val pp : Formatter . t -> t -> unit val show : t -> string end
module type OrderedType = sig include Caml . Set . OrderedType val t_of_sexp : Sexp . t -> t val sexp_of_t : t -> Sexp . t val hash_fold_t : Hash . state -> t -> Hash . state val pp : Formatter . t -> t -> unit val show : t -> string end
module Make ( Ordered : OrderedType ) : S with type elt = Ordered . t = struct include Caml . Set . Make ( Ordered ) let t_of_sexp sexp = Core . List . t_of_sexp Ordered . t_of_sexp sexp |> of_list let sexp_of_t set = elements set |> Core . List . sexp_of_t Ordered . sexp_of_t let hash_fold_t hash_state set = elements ...
module Deserialization_error = struct type t = | Version_mismatch of int | Parse_error end
module type Serializable = sig type t val serialize : t -> String . t val deserialize : String . t -> ( t , Deserialization_error . t ) Result . t end
module type T = Serializable
module type S = sig include Sexpable val version : int end
module Make ( TypeToSerialize : S ) : T with type t := TypeToSerialize . t = struct open TypeToSerialize let parsing_error_of_option : _ Option . t -> ( _ , Deserialization_error . t ) Result . t = function | Some data -> Ok data | None -> Error Parse_error let serialize t = Sexp . ( List [ Atom " version " ; Atom ( In...
let write_and_read tensor ~ print_tensor = let filename = Caml . Filename . temp_file " torchtest " " . ot " in Serialize . save tensor ~ filename ; let y = Serialize . load ~ filename in let l2 = Tensor . ( ( tensor - y ) * ( tensor - y ) ) |> Tensor . sum in print_tensor l2 ; Unix . unlink filename let print_tensor t...
let write_and_read named_tensors = let filename = Caml . Filename . temp_file " torchtest " " . ot " in Serialize . save_multi ~ named_tensors ~ filename ; let ys = Serialize . load_multi ~ names ( : List . map named_tensors ~ f : fst ) ~ filename in List . iter2_exn named_tensors ys ~ f ( : fun ( name , tensor ) y -> ...
module Wire = struct let write_byte t byte = Faraday . write_uint8 t byte let write_boolean t b = Faraday . write_uint8 t ( if b then 1 else 0 ) let write_uint32 t uint32 = Faraday . BE . write_uint32 t uint32 let write_uint64 t uint64 = Faraday . BE . write_uint64 t uint64 let write_string t s = Faraday . BE . write_u...
let with_faraday ( f : Faraday . t -> unit ) : string = let buf = Faraday . create 1024 in f buf ; Faraday . serialize_to_string buf
let write_tuple t ( name , data ) = Wire . write_string t name ; Wire . write_string t data
let write_tuples t tuples = List . iter ( write_tuple t ) tuples
let rec write_ssh_rsa_cert_tbs t { Pubkey . nonce ; pubkey = { e ; n } ; serial ; typ ; key_id ; valid_principals ; valid_after ; valid_before ; critical_options ; extensions ; reserved ; signature_key ; } = Wire . write_string t " ssh - rsa - cert - v01 @ openssh . com " ; Wire . write_string t nonce ; Wire . write_mp...
let write_privkey t key = let open Privkey in match key with | Ssh_dss { p ; q ; gg ; x ; y } -> Wire . write_string t " ssh - dss " ; Wire . write_mpint t p ; Wire . write_mpint t q ; Wire . write_mpint t gg ; Wire . write_mpint t y ; Wire . write_mpint t x | Ssh_rsa { e ; d ; n ; p ; q ; dp = _ ; dq = _ ; q ' } -> Wi...
let write_protocol_number t ssh_agent = Wire . write_byte t ( Protocol_number . ssh_agent_to_int ssh_agent )
let write_sign_flags t sign_flags = let flags = List . fold_left ( fun acc sign_flag -> Protocol_number . sign_flag_to_int sign_flag lor acc ) 0 sign_flags in flags |> Int32 . of_int |> Wire . write_uint32 t
let write_key_constraints t constraints = List . iter ( function | Lifetime secs -> Faraday . write_uint8 t 1 ; Wire . write_uint32 t secs | Confirm -> Faraday . write_uint8 t 2 ) constraints
let write_ssh_agent_request t ( type a ) ( req : a ssh_agent_request ) = let message = with_faraday ( fun t -> match req with | Ssh_agentc_request_identities -> write_protocol_number t SSH_AGENTC_REQUEST_IDENTITIES | Ssh_agentc_sign_request ( pubkey , data , flags ) -> write_protocol_number t SSH_AGENTC_SIGN_REQUEST ; ...
let write_ssh_agent_response t ( type a ) ( resp : a ssh_agent_response ) = let message = with_faraday ( fun t -> match resp with | Ssh_agent_failure -> write_protocol_number t SSH_AGENT_FAILURE | Ssh_agent_success -> write_protocol_number t SSH_AGENT_SUCCES | Ssh_agent_extension_failure -> write_protocol_number t SSH_...
module type SERIES = sig val ones : int Stream . str val numsFrom : int -> int Stream . str val fibonacci_series : int Stream . str val hamming_series : int Stream . str
module Series : SERIES = struct open Stream let rec ones = { hd = 1 ; tl = Susp ( fun ( ) -> ones ) } ; ; let rec numsFrom n = { hd = n ; tl = Susp ( fun ( ) -> numsFrom ( n + 1 ) ) } let nats = numsFrom 0 let rec fibs = { hd = 0 ; tl = Susp ( fun ( ) -> fibs ' ) } and fibs ' = { hd = 1 ; tl = Susp ( fun ( ) -> add fib...
let info ppf = pf ppf " [ explore . ocaml ] % a \ n " %!
let router ( ? top_dir = " content " ) = let open Explore in function | [ " " ; " " ] | [ " " ] | [ " " / ] -> Files . read_file ( " . " / ^ top_dir ^ " / index . html " ) | f -> ( let path = " . " / ^ top_dir ^ String . concat " " / f in try Files . read_file path with Sys_error _ -> Files . read_file ( path ^ " / ind...
let get_content_type s = let ct s = ( " Content - Type " , s ) in match Filename . extension s with | " . html " -> ct " text / html " | " . css " -> ct " text / css " | " . js " -> ct " text / javascript " | " . png " -> ct " image / png " | " . jpg " | " . jpeg " -> ct " image / jpeg " | " . svg " -> ct " image / svg...
let handle_get reqd = match Reqd . request reqd with | { Request . meth = ` GET ; Request . target = t ; _ } -> Build . build_phase ( ) ; let str = router ( String . split_on_char ' ' / t ) in let resp = let content_type = get_content_type t in Response . create ~ headers : ( Headers . of_list [ content_type ; ( " Cont...
let error_handler ? request : _ error start_response = let response_body = start_response Headers . empty in ( match error with | ` Exn exn -> Body . write_string response_body ( Base . Exn . to_string exn ) ; Body . write_string response_body " \ n " | # Status . standard as error -> Body . write_string response_body ...
let serve port : int = info stdout ( fun ppf a -> pf ppf " Starting server at : http :// localhost :% i " a ) port ; let promise , _resolver = Lwt . wait ( ) in let request_handler ( _ : Unix . sockaddr ) = handle_get in let error_handler ( _ : Unix . sockaddr ) = error_handler in let localhost = Unix . inet_addr_loopb...
let run port = serve port
let port = let docv = " PORT " in let doc = " Specifiy the port the local server should run on . " in Arg . ( value & pos 0 int 8000 & info ~ doc ~ docv [ ] )
let info = let doc = " Run a local server which serves the contents of content . It rebuilds the \ entire site for each page load so changes made will be automatically \ synced . " in Term . info ~ doc " serve "
let cmd = ( Term . ( pure run $ port ) , info )
module Server = struct let boards = [ | " 500640908002000000900002000800320010040105080060078005000200009000000700304089006 " ; " 071600900400000301000802070050000400200105003003000090010204000608000002004009150 " ; " 076305908001000000002001030000510700200000005003078000090400300000000500708902160 " ; " 07600500808000...
let service handler = let process ( cgi : Netcgi_types . cgi_activation ) = let res = try handler ( cgi # argument " BODY " ) # value with Not_found -> raise ( Invalid_argument " bad_request " ) in cgi # set_header ~ content_type " : text / plain ; charset = utf - 8 " ~ cache ` : No_cache ( ) ; cgi # output # output_st...
let start ( ) = let ( opt_list , cmdline_cfg ) = Netplex_main . args ( ) in Arg . parse opt_list ( fun s -> raise ( Arg . Bad ( " Don ' t know what to do with : " ^ s ) ) ) " usage : netplex [ options ] " ; let config_cgi = { Netcgi_env . default_config with Netcgi_env . permitted_input_content_types = " text / plain "...
module Make ( MakeLog : S . LOG ) LOG ( LOGFilesystem : Filesystem . S ) S = struct module S = Protocol_9p . Server . Make ( MakeLog ) MakeLog ( MakeLogFlow_lwt_unix ) MakeLogFlow_lwt_unix ( MakeLogFlow_lwt_unixFilesystem ) MakeLogFlow_lwt_unixFilesystem let finally f g = Lwt . catch ( fun ( ) -> f ( ) >>= fun result -...
module ServerConfiguration = struct type t = { base : CommandStartup . BaseConfiguration . t ; socket_path : PyrePath . t ; strict : bool ; show_error_traces : bool ; additional_logging_sections : string list ; watchman_root : PyrePath . t option ; taint_model_paths : PyrePath . t list ; store_type_check_resolution : b...
let run_server configuration_file = match CommandStartup . read_and_parse_json configuration_file ~ f : ServerConfiguration . of_yojson with | Result . Error message -> Log . error " % s " message ; exit 1 | Result . Ok ( { ServerConfiguration . base = { CommandStartup . BaseConfiguration . log_path ; global_root ; loc...
let command = let filename_argument = Command . Param . ( anon ( " filename " %: Filename . arg_type ) ) in Command . basic ~ summary " : Starts a new Pyre server . " ( Command . Param . map filename_argument ~ f ( : fun filename ( ) -> run_server filename ) )
module Subscriptions = struct type t = Subscription . t String . Table . t let create ( ) = String . Table . create ( ) let add ~ name ~ subscription subscriptions = Hashtbl . set subscriptions ~ key : name ~ data : subscription let get ~ name subscriptions = Hashtbl . find subscriptions name let remove ~ name subscrip...
type t = { build_system : BuildSystem . t ; type_environment : TypeEnvironment . t ; error_table : AnalysisError . t list Reference . Table . t ; subscriptions : Subscriptions . t ; }
let create ? error_table ? subscriptions ~ build_system ~ type_environment ( ) = { build_system ; type_environment ; error_table = Option . value error_table ~ default ( : Reference . Table . create ( ) ) ; subscriptions = Option . value subscriptions ~ default ( : Subscriptions . create ( ) ) ; }
module StoredConfiguration = Memory . Serializer ( struct type t = Configuration . Analysis . t module Serialized = struct type t = Configuration . Analysis . t let prefix = Prefix . make ( ) let description = " Configuration " end let serialize = Fn . id let deserialize = Fn . id end )
module ServerErrors = Memory . Serializer ( struct type t = Analysis . AnalysisError . t list Reference . Table . t module Serialized = struct type t = ( Reference . t * Analysis . AnalysisError . t list ) list let prefix = Prefix . make ( ) let description = " All errors " end let serialize = Hashtbl . to_alist let de...
let load ~ configuration ~ build_system ( ) = let module_tracker = Analysis . ModuleTracker . Serializer . from_stored_layouts ~ configuration ( ) in let ast_environment = Analysis . AstEnvironment . load module_tracker in let type_environment = Analysis . AnnotatedGlobalEnvironment . create ast_environment |> Analysis...
let store ~ path ~ configuration { type_environment ; error_table ; build_system ; _ } = Memory . SharedMemory . collect ` aggressive ; Analysis . TypeEnvironment . module_tracker type_environment |> Analysis . ModuleTracker . Serializer . store_layouts ; Analysis . TypeEnvironment . ast_environment type_environment |>...
module Client = struct type t = { context : test_ctxt ; server_properties : ServerProperties . t ; server_state : ServerState . t ; input_channel : Lwt_io . input_channel ; output_channel : Lwt_io . output_channel ; } let get_server_properties { server_properties ; _ } = server_properties let current_server_state { ser...
module ScratchProject = struct type t = { context : test_ctxt ; configuration : Configuration . Analysis . t ; start_options : StartOptions . t ; watchman : Watchman . Raw . t option ; build_system_initializer : BuildSystem . Initializer . t ; } let setup ~ context ( ? external_sources = [ ] ) ( ? include_typeshed_stub...
let if_modified_since h = let f s = match Netdate . since_epoch & Netdate . parse s with | n -> ` Ok n | exception _e -> ` Error ( ` Date_parse_failed s ) in Option . fmap f & Cohttp . Header . get h " If - Modified - Since "
let file_in_memory p = let open Unix in let mtime = ref 0 . 0 in let s = ref " " in let update ( ) = let st = stat p in if ! mtime = st . st_mtime then ! s , ! mtime else begin mtime := st . st_mtime ; s := from_Ok & File . to_string p ; ! s , ! mtime end in ignore & update ( ) ; update
let respond_file_in_memory p ctype h = let file = file_in_memory p in let f = function | None -> Server . respond_string ~ status : ` Not_modified ~ headers : ( Cohttp . Header . of_list [ ] ) ~ body : " " ( ) | Some ( s , n ) -> Server . respond_string ~ status : ` OK ~ headers ( : Cohttp . Header . of_list [ " Conten...
module Json_codec = struct let decode enc s = Js . _JSON ( ## parse ( Js . string s ) ) |> Json_repr_browser . Json_encoding . destruct enc let encode ? minify : _ enc x = let json = Json_repr_browser . Json_encoding . construct enc x in Js . to_string Js . _JSON ( ## stringify json ) end
module Api_client = Learnocaml_api . Client ( Json_codec )
type request_error = [ | ` Unreachable of string | ` Not_found of string | ` Http_error of int * string | ` Exception of exn | ` Invalid_response of exn ]
let string_of_error = function | ` Unreachable " " -> " Server unreachable " | ` Unreachable s -> " Server unreachable : " ^ s | ` Not_found s -> " URL not found : " ^ s | ` Http_error ( code , s ) -> Printf . sprintf " HTTP error ( % d ) : % s " code s | ` Exception e -> " Server request failed : " ^ Printexc . to_str...
let ( ) = Printexc . register_printer @@ function | Json_encoding . Cannot_destruct ( path , e ) -> Some ( Printf . sprintf " JSON error at % s : % s " ( Json_query . json_pointer_of_path path ) ( Printexc . to_string e ) ) | _ -> None
let urlpath p = String . concat " " / ( Learnocaml_config . api_server :: p )
let request req = let do_req = function | { Learnocaml_api . meth = ` GET ; path ; args } -> Lwt_request . get ? headers : None ~ url ( : urlpath path ) ~ args : args ( ) | { Learnocaml_api . meth = ` POST body ; path ; args } -> let get_args = match args with [ ] -> None | a -> Some a in Lwt_request . post ? headers :...
let request_exn req = request req >>= function | Ok x -> Lwt . return x | Error e -> Lwt . fail ( Cannot_fetch ( string_of_error e ) )
let fetch_lesson_index ( ) = request_exn ( Learnocaml_api . Lesson_index ( ) )
let fetch_lesson id = request_exn ( Learnocaml_api . Lesson id )
let fetch_exercise token id = request_exn ( Learnocaml_api . Exercise ( token , id ) )
let fetch_tutorial_index ( ) = request_exn ( Learnocaml_api . Tutorial_index ( ) )
let fetch_tutorial id = request_exn ( Learnocaml_api . Tutorial id )
module Queue = struct include Queue let peek_exn = peek let peek t = if is_empty t then None else Some ( peek_exn t ) t end
type request_handler = Reqd . t -> unit
type error = [ ` Bad_gateway | ` Bad_request | ` Internal_server_error | ` Exn of exn ] exn
type error_handler = ? request : Request . t -> error -> ( Headers . t -> Body . Writer . t ) t -> unit
type t = { reader : Reader . request ; writer : Writer . t ; response_body_buffer : Bigstringaf . t ; request_handler : request_handler ; error_handler : error_handler ; request_queue : Reqd . t Queue . t ; mutable is_errored : bool ; mutable wakeup_reader : Optional_thunk . t }
let is_closed t = Reader . is_closed t . reader && Writer . is_closed t . writer
let is_active t = not ( Queue . is_empty t . request_queue ) request_queue
let current_reqd_exn t = Queue . peek_exn t . request_queue
let yield_reader t k = if is_closed t then failwith " yield_reader on closed conn " else if Optional_thunk . is_some t . wakeup_reader then failwith " yield_reader : only one callback can be registered at a time " else t . wakeup_reader <- Optional_thunk . some k ; ;
let wakeup_reader t = let f = t . wakeup_reader in t . wakeup_reader <- Optional_thunk . none ; Optional_thunk . call_if_some f ; ;
let yield_writer t k = if Writer . is_closed t . writer then k ( ) else Writer . on_wakeup t . writer k ; ;
let wakeup_writer t = Writer . wakeup t . writer
let default_error_handler ? request : _ error handle = let message = match error with | ` Exn exn -> Printexc . to_string exn | ( # Status . client_error | # Status . server_error ) server_error as error -> Status . to_string error in let body = handle Headers . empty in Body . Writer . write_string body message ; Body...
let create ( ? config = Config . default ) default ( ? error_handler = default_error_handler ) default_error_handler request_handler = let { Config . response_buffer_size ; response_body_buffer_size ; _ } = config in let writer = Writer . create ~ buffer_size : response_buffer_size ( ) in let request_queue = Queue . cr...
let shutdown_reader t = if is_active t then Reqd . close_request_body ( current_reqd_exn t ) t ; Reader . force_close t . reader ; wakeup_reader t
let shutdown_writer t = if is_active t then ( let reqd = current_reqd_exn t in Reqd . close_request_body reqd ; Reqd . flush_response_body reqd ) reqd ; Writer . close t . writer ; wakeup_writer t
let error_code t = if is_active t then Reqd . error_code ( current_reqd_exn t ) t else None
let shutdown t = shutdown_reader t ; shutdown_writer t
let set_error_and_handle ? request t error = if is_active t then begin assert ( request = None ) None ; let reqd = current_reqd_exn t in Reqd . report_error reqd error end else begin t . is_errored <- true ; let status = match ( error :> [ error | Status . standard ] standard ) standard with | ` Exn _ -> ` Internal_ser...
let report_exn t exn = set_error_and_handle t ( ` Exn exn ) exn
let advance_request_queue t = ignore ( Queue . take t . request_queue ) request_queue ; if not ( Queue . is_empty t . request_queue ) request_queue then t . request_handler ( Queue . peek_exn t . request_queue ) request_queue ; ; ;