public static FSharpMailboxProcessor <TMsg> Mailbox <TMsg>(CancellationToken cancelToken, Action <TMsg> handler) { var body = FuncConvert.ToFSharpFunc <FSharpMailboxProcessor <TMsg>, FSharpAsync <Microsoft.FSharp.Core.Unit> >( mbox => CreateAsync <Microsoft.FSharp.Core.Unit>(async() => { while (!cancelToken.IsCancellationRequested) { try { var msg = await FSharpAsync.StartAsTask(mbox.Receive(FSharpOption <int> .None), FSharpOption <TaskCreationOptions> .None, FSharpOption <CancellationToken> .Some(cancelToken)); if (msg != null && !cancelToken.IsCancellationRequested) { handler(msg); } } catch (TaskCanceledException) { // We're being shutdown, ignore. } catch (Exception e) { logSysErr(e); } } return(null); }) ); return(FSharpMailboxProcessor <TMsg> .Start(body, FSharpOption <CancellationToken> .None)); }
public bool BuildTargetGaugeProject() { var projectFullPath = GetProjectFullPath(); var projectConfig = GetProjectConfiguration(); var projectPlatform = GetProjectPlatform(); var gaugeBinDir = Utils.GetGaugeBinDir(); try { var properties = new FSharpList <Tuple <string, string> >(Tuple.Create("Configuration", projectConfig), FSharpList <Tuple <string, string> > .Empty); properties = new FSharpList <Tuple <string, string> >(Tuple.Create("Platform", projectPlatform), properties); properties = new FSharpList <Tuple <string, string> >(Tuple.Create("OutputPath", gaugeBinDir), properties); MSBuildHelper.build(FuncConvert.ToFSharpFunc(delegate(MSBuildHelper.MSBuildParams input) { input.Verbosity = FSharpOption <MSBuildHelper.MSBuildVerbosity> .Some(MSBuildHelper.MSBuildVerbosity.Quiet); input.Targets = new FSharpList <string>("Build", FSharpList <string> .Empty); input.Properties = properties; return(input); }), projectFullPath); } catch (Exception ex) { Logger.Error(ex, "C# Project build failed {0}", ex.Message); return(false); } return(true); }
public static void MapOne() { // define a list of names List <string> names = new List <string>( new string[] { "Stefany", "Oussama", "Sebastien", "Frederik" }); // define a predicate delegate/function Converter <string, bool> pred = delegate(string s) { return(s.StartsWith("S")); }; // convert to a FastFunc FSharpFunc <string, bool> ff = FuncConvert.ToFSharpFunc <string, bool>(pred); // call the F# demo function IEnumerable <string> results = DemoModule2.filterStringList(ff, names); // write the results to the console foreach (var name in results) { Console.WriteLine(name); } }
public Task <VariogramModule.IVariogram> GetSpatialVariogramAsync(LinearCombination.RealValueNodes nodes) { var task = taskFactory.StartNew(new Func <object, VariogramModule.IVariogram>(obj => { Stopwatch sw = Stopwatch.StartNew(); LinearCombination.RealValueNodes localNodes = (LinearCombination.RealValueNodes)obj; var variogramFitter = new LMDotNetVariogramFitter.Fitter() as VariogramModule.IVariogramFitter; traceSource.TraceEvent(TraceEventType.Start, 1, "Starting build of emperical variogram"); var pointSet = new EmpVariogramBuilder.PointSet(localNodes.Lats, localNodes.Lons, localNodes.Values); var dist = FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, FSharpFunc <Tuple <double, double>, double> >(t1 => FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, double>(t2 => SphereMath.GetDistance(t1.Item1, t1.Item2, t2.Item1, t2.Item2))))); var empVar = EmpVariogramBuilder.EmpiricalVariogramBuilder.BuildEmpiricalVariogram(pointSet, dist); sw.Stop(); traceSource.TraceEvent(TraceEventType.Stop, 1, string.Format("Emperical variogram is build in {0}", sw.Elapsed)); sw = Stopwatch.StartNew(); traceSource.TraceEvent(TraceEventType.Start, 2, "Starting variogram fitting"); var variogramRes = variogramFitter.Fit(empVar); sw.Stop(); traceSource.TraceEvent(TraceEventType.Stop, 2, string.Format("Emperical variogram is build in {0}", sw.Elapsed)); if (FSharpOption <VariogramModule.IDescribedVariogram> .get_IsNone(variogramRes)) { traceSource.TraceEvent(TraceEventType.Error, 3, "Fariogram fitting failed. Falling back to coarse variogram approximation"); return(variogramFitter.GetFallback(empVar)); } else { return(variogramRes.Value); } }), nodes); return(task); }
public static Tuple <Action, FSharpMailboxProcessor <UserControlMessage> > StartUserMailbox <S, T>(IProcess self, ProcessId supervisor, Func <S, T, S> actor, Func <S> setup) { bool active = true; S state = default(S); Action quit = () => active = false; var body = FuncConvert.ToFSharpFunc <FSharpMailboxProcessor <UserControlMessage>, FSharpAsync <Microsoft.FSharp.Core.Unit> >( mbox => CreateAsync <Microsoft.FSharp.Core.Unit>(async() => { ActorContext.SetContext(self, ActorContext.NoSender); state = setup(); while (active) { var msg = await FSharpAsync.StartAsTask(mbox.Receive(FSharpOption <int> .None), FSharpOption <TaskCreationOptions> .None, FSharpOption <CancellationToken> .None); if (msg == null || !active) { active = false; } else { if (msg.MessageType == Message.Type.User) { var umsg = (UserMessage)msg; ActorContext.SetContext(self, umsg.Sender); state = actor(state, (T)((UserMessage)msg).Content); } else if (msg.MessageType == Message.Type.UserControl) { switch (msg.Tag) { case UserControlMessageTag.Shutdown: self.Shutdown(); active = false; break; } } } } (state as IDisposable)?.Dispose(); return(null); }) ); var mailbox = FSharpMailboxProcessor <UserControlMessage> .Start(body, FSharpOption <CancellationToken> .None); mailbox.Error += (object sender, Exception args) => { Process.tell(supervisor, SystemMessage.ChildIsFaulted(self.Id, args)); (state as IDisposable)?.Dispose(); }; return(tuple(quit, mailbox)); }
public static FSharpFunc <T1, FSharpFunc <T2, Unit> > ToFSharpFunc <T1, T2>(Action <T1, T2> action) { var tupled = FuncConvert.ToFSharpFunc <Tuple <T1, T2> >( t => action(t.Item1, t.Item2)); var curried = FuncConvert.FuncFromTupled(tupled); return(curried); }
static FSharpFunc <A, B> ToFSharpFunc <A, B>(Func <A, B> f) { #if COREFX return((FSharpFunc <A, B>) typeof(FSharpFunc <A, B>).GetTypeInfo().GetDeclaredMethod("op_Implicit").Invoke(null, new[] { f })); #else return(FuncConvert.ToFSharpFunc <A, B>(new Converter <A, B>(f))); #endif }
static string Run(RestorePackageHelper.RestoreSinglePackageParams packageParams) { Func <RestorePackageHelper.RestoreSinglePackageParams, RestorePackageHelper.RestoreSinglePackageParams> f = _ => packageParams; var fs = FuncConvert.ToFSharpFunc(new Converter <RestorePackageHelper.RestoreSinglePackageParams, RestorePackageHelper.RestoreSinglePackageParams>(f)); var result = RestorePackageHelper.buildNuGetArgs(fs, "thePackage"); return(result); }
// curried style implementation public int CurriedStyle(int x, int y) { // curried style implementation // create a delegate to return Converter <int, int> d = delegate(int z) { return(x + z); }; // convert delegate to a FSharpFunc return(FuncConvert.ToFSharpFunc(d).Invoke(y)); }
public IWorkflowBuilder Attach(ISchedulable[] schedulables, Func <Dictionary <int, string>, string> reducer) { var fsharpReducer = FuncConvert.ToFSharpFunc(new Converter <Dictionary <int, string>, string>(reducer)); var stageAction = StageAction.NewParallelActions(schedulables, fsharpReducer); var stage = new Stage(stages.Count, stageAction); stages.Add(stage); return(this); }
public static void StartSlackClient() { // Start Slack client SlackIncommingMailbox = startSlackRTM(SlackBotToken, FuncConvert.ToFSharpFunc <Tuple <SlackMessageWithContext, ISlackConnection> >(msg => { var x = msg.Item1; var conn = msg.Item2; if (x.IsIncomming) { var m = x as SlackMessageWithContext.Incomming; var val = m.Item; var r = val.ActionResults[0]; var selVal = !string.IsNullOrWhiteSpace(r.Value) ? r.Value : r.SelectedOptions.Any() ? r.SelectedOptions[0].Value : ""; // Reply var res = new BotMessage { //Text = $"```\n {JsonConvert.SerializeObject(val)} \n```", Text = $"Selected: {selVal}", ChatHub = new SlackChatHub { Id = val.Channel.Id } }; conn.Say(res); } else if (x.IsRTMMessage) { var m = x as SlackMessageWithContext.RTMMessage; var val = m.Item; var d = JsonConvert.DeserializeObject <Message>(val.RawData); if (d.file != null) { // Process file (image) var request = WebRequest.Create(d.file.url_private_download); request.Headers.Add("Authorization", $"Bearer {SlackBotToken}"); using (var imgStream = request.GetResponse().GetResponseStream()) { var text = FccBot.RecognizeEmotionsFromPortraitImage(imgStream).Result; var res = new BotMessage { ChatHub = val.ChatHub, Text = $"```{text.Replace("\r", "")}```" }; conn.Say(res); } } else { // Process text var res = GetReplay(val); conn.Say(res); } } })); }
public T RunParser <T>(Func <State <Unit>, Primitives.Reply <T, Unit> > parser, string text) { var f = FuncConvert.ToFSharpFunc <State <Unit>, Primitives.Reply <T, Unit> >(s => parser(s)); var r = CharParsers.run <T>(f, text); if (r.IsSuccess) { return(((CharParsers.ParserResult <T, Unit> .Success)r).Item1); } return(default(T)); }
public GraphVm() { WbImageVm = new WbImageVm(); GraphData = Id.MakeGraphData( title: "Title", titleX: "titleX", titleY: "titleY", xLabeler: FuncConvert.ToFSharpFunc <float, string>(x => x.ToString()), yLabeler: FuncConvert.ToFSharpFunc <float, string>(x => x.ToString()) ); }
public static FSharpAsync <A> CreateAsync <A>(Func <Task <A> > f) => FSharpAsync.FromContinuations( FuncConvert.ToFSharpFunc <Tuple <FSharpFunc <A, Microsoft.FSharp.Core.Unit>, FSharpFunc <Exception, Microsoft.FSharp.Core.Unit>, FSharpFunc <OperationCanceledException, Microsoft.FSharp.Core.Unit> > >( conts => { f().ContinueWith(task => { try { conts.Item1.Invoke(task.Result); } catch (Exception e) { conts.Item2.Invoke(e); } }); }));
public static Tuple <Action, FSharpMailboxProcessor <SystemMessage> > StartSystemMailbox(IProcess self, ProcessId supervisor) { bool active = true; Action quit = () => active = false; var body = FuncConvert.ToFSharpFunc <FSharpMailboxProcessor <SystemMessage>, FSharpAsync <Microsoft.FSharp.Core.Unit> >( mbox => CreateAsync <Microsoft.FSharp.Core.Unit>(async() => { while (active) { var msg = await FSharpAsync.StartAsTask(mbox.Receive(FSharpOption <int> .None), FSharpOption <TaskCreationOptions> .None, FSharpOption <CancellationToken> .None); if (msg == null || !active) { active = false; } else { switch (msg.GetType().Name) { case "SystemShutdownMessage": self.Shutdown(); active = false; break; case "SystemChildIsFaultedMessage": ((IProcessInternal)self).HandleFaultedChild((SystemChildIsFaultedMessage)msg); break; case "SystemRestartMessage": self.Restart(); break; case "SystemUnLinkChildMessage": ((IProcessInternal)self).UnlinkChild(((SystemUnLinkChildMessage)msg).ChildId); break; } } } return(null); }) ); var mailbox = FSharpMailboxProcessor <SystemMessage> .Start(body, FSharpOption <CancellationToken> .None); mailbox.Error += (object sender, Exception args) => Process.tell(supervisor, SystemMessage.ChildIsFaulted(self.Id, args)); return(tuple(quit, mailbox)); }
static void Main(string[] args) { var fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), "test.md"); var data = File.ReadAllText(fullFilePath); var metadata = MarkdownParser.ParseMetadata(data); var res = MarkdownParser.ParseString(data); //var renderer = new TextRenderer(); IRenderer <string> renderer = new TextRenderer(); var lookup = FuncConvert.ToFSharpFunc <string, FSharpFunc <string, string> >(action => FuncConvert.ToFSharpFunc <string, string>(args => "Hello")); var result = renderer.Render(res, lookup); Console.WriteLine("Hello World!"); }
public IActivity Complete() { var processor = FuncConvert.ToFSharpFunc(new Converter <TInput, TOutput>(Processor)); return(new Activity <TInput, TOutput>( Name, Description, processor, TaskHeartbeatTimeout, TaskScheduleToStartTimeout, TaskStartToCloseTimeout, TaskScheduleToCloseTimeout, Version.AsOption(string.IsNullOrWhiteSpace), TaskList.AsOption(string.IsNullOrWhiteSpace), MaxAttempts.AsOption())); }
static void Main(string[] args) { var maxWeight = 20.0; var baseItems = new[] { new KnapSack.Item(10, 5, false), new KnapSack.Item(5, 2.5, false), new KnapSack.Item(5, 2.5, false), new KnapSack.Item(1, 10, false), new KnapSack.Item(1, 10, false), new KnapSack.Item(3, 7, false), new KnapSack.Item(23, 4, false), new KnapSack.Item(3, 1, false), new KnapSack.Item(15, 19, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(3, 7, false), new KnapSack.Item(23, 4, false), new KnapSack.Item(3, 1, false), new KnapSack.Item(15, 19, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(3, 7, false), new KnapSack.Item(23, 4, false), new KnapSack.Item(3, 1, false), new KnapSack.Item(15, 19, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), new KnapSack.Item(0, 10, false), }; var pop = Enumerable.Repeat(0, 200).Select(x => KnapSack.Randomize(maxWeight, baseItems)).ToArray(); var fitness = FuncConvert.ToFSharpFunc <KnapSack, double>(KnapSack.Fitness); var crossover = new Func <KnapSack, KnapSack, KnapSack>(KnapSack.Crossover).ToFSharpFunc(); var mutation = FuncConvert.ToFSharpFunc <KnapSack, KnapSack>(KnapSack.Mutate); var ga = new GeneticAlgorithm <KnapSack>(pop, fitness, crossover, mutation, .05); var result = ga.Run(); Console.WriteLine($"Best Fitness: {KnapSack.Fitness(result)} Weight: {result.Weight}"); Console.ReadKey(); }
public void FSharpFunc() { Equal(I.Module.ReturnsFunc().Invoke(3), 3); Equal(I.Module.ReturnsFunc2().Invoke(1).Invoke(2), 3); Func <int, int> f = I.Module.ReturnsFunc().Invoke; Equal(f(3), 3); Equal(I.Module.InvokeFunc(FSharpConvert.Fun((int x) => x + 1), 1), 2); Equal(I.Module.InvokeFunc2(FSharpConvert.Fun((int x, int y) => x + y), 1, 2), 3); Equal(I.Module.InvokeFunc(FuncConvert.FromFunc((int x) => x + 1), 1), 2); Equal(I.Module.InvokeFunc2(FuncConvert.FromFunc((int x, int y) => x + y), 1, 2), 3); Equal(I.Module.InvokeFunc(FuncConvert.ToFSharpFunc((int x) => x + 1), 1), 2); var c = FSharpFunc <int, int> .ToConverter(I.Module.ReturnsFunc()); Equal(c(3), 3); var f2 = FSharpFunc <int, int> .FromConverter(c); Equal(f2.Invoke(3), 3); }
private void init() { //FSharpFunc<string, Unit> f_set_text = FuncConvert.ToFSharpFunc((Action<string>)SetTextProc); FSharpFunc <string, Unit> f_set_text = FuncConvert.ToFSharpFunc(new Action <string>(SetTextProc)); //FSharpFunc<string, Unit> f_set_text = FuncConvert.ToFSharpFunc(delegate(string text) { textBoxABC.Text = text; }); Action close_action = new Action(CloseProc); //Action<Unit> close_action2 = new Action<Unit>(CloseProc); //Converter<Unit, Unit> close_action_2 = new Converter<Unit, Unit>(close_action); FSharpFunc <Unit, Unit> f_close = FuncConvert.ToFSharpFunc(close_action); Action <int> close_action_1 = new Action <int>(CloseProc1); FSharpFunc <int, Unit> f_close_1 = FuncConvert.ToFSharpFunc(close_action_1); //FSharpFunc<Unit, Unit> f_close = FuncConvert.ToFSharpFunc(close_action); //FSharpFunc<Unit, Unit> f_close = (FSharpFunc<Unit, Unit>)close_action; //FSharpFunc<Unit, Unit> f_close = FuncConvert.ToFSharpFunc<Unit>(new Action<Unit>(new Action(CloseProc))); abc_editor_fs = new ABCEditorFSharp.ABCEditor(f_set_text, f_close); //var f_close = (FSharpFunc<Unit, Unit>)CloseProc; //var f = new Converter<string, Unit>(SetTextProc); //abc_editor_fs = new ABCEditorFSharp.ABCEditor((FSharpFunc<string, Unit>)delegate(string text) { textBoxABC.Text = text; }, (FSharpFunc<Unit, Unit>)delegate() { Close(); }); //abc_editor_fs = new ABCEditorFSharp.ABCEditor((FSharpFunc<string, Unit>)SetTextProc, (FSharpFunc<Unit, Unit>)CloseProc); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter if (!rootFrame.Navigate(typeof(MenuPage), args.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested; var dispatcher = Window.Current.Dispatcher; ObservableObject.Post = FuncConvert.ToFSharpFunc <FSharpFunc <Unit, Unit> >( async callback => await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, (Windows.UI.Core.DispatchedHandler)(() => { callback.Invoke((Unit)null); }))); }
private HomeItemViewModel Parse(string source, long timer, bool generateAssembly = false) { string error = null; var vm = new HomeItemViewModel { Source = source, Timer = timer }; var input = InputModule.create(vm.Source); var tokensResult = Lexer.tokenize(input); if (tokensResult.IsError) { error = tokensResult.ErrorValue; goto End; } var tokens = tokensResult.ResultValue; var programResult = Parser.parse(tokens); if (programResult.IsError) { error = programResult.ErrorValue; goto End; } var program = programResult.ResultValue; vm.Ast = JsonConvert.SerializeObject(_astBuilder.Build(program)); var symbolTableResult = SymbolCollector.create(program); if (symbolTableResult.IsError) { error = symbolTableResult.ErrorValue; goto End; } var symbolTable = symbolTableResult.ResultValue; var typeCheckerResult = TypeChecker.check(symbolTable, program); if (typeCheckerResult.IsError) { error = typeCheckerResult.ErrorValue; goto End; } var variableInitializationCheckerResult = VariableInitializationChecker.check(program); if (variableInitializationCheckerResult.IsError) { error = variableInitializationCheckerResult.ErrorValue; goto End; } var writeLineFunc = FuncConvert.ToFSharpFunc <int>(i => vm.PrintfnLog += i + "\n"); var environment = EnvironmentModule.create(symbolTable, program, writeLineFunc, vm.Timer); var interpreterResult = Interpreter.interpret(environment); if (interpreterResult.IsError) { error = interpreterResult.ErrorValue; goto End; } var assemblyResult = ILBuilder.build(symbolTable, program); if (assemblyResult.IsError) { error = assemblyResult.ErrorValue; goto End; } var assembly = assemblyResult.ResultValue; vm.Il = JsonConvert.SerializeObject(_ilBuilder.Build(assembly)); if (generateAssembly) { var applicationResult = CodeGenerator.generate(assembly); if (applicationResult.IsError) { error = applicationResult.ErrorValue; goto End; } vm.Application = applicationResult.ResultValue; } End: if (error != null) { vm.Error = error; } return(vm); }
void explorer_BeforeItemPaste_safe(ref object clipboardContent, MAPIFolder Target, ref bool Cancel) { try { if (!this.trackItemMove) //prevent infinite loop { return; } if (clipboardContent is Selection) { var mailsToMove = new List <MailItem>(); var selection = (Selection)clipboardContent; foreach (object itemObj in selection) { var obj = itemObj as MailItem; if (obj != null) { mailsToMove.Add(obj); } } if (mailsToMove.Count == 0) { return; } try { bool mailMovedToDifferentStore = u.c(() => { foreach (MailItem mail in mailsToMove) { if (string.IsNullOrEmpty(mail.Categories)) { continue; } if (mail.Parent is Folder) { var parent = (Folder)mail.Parent; if (parent.StoreID != Target.StoreID) { return(true); } } } return(false); }); if (!mailMovedToDifferentStore) { return; } Cancel = true; // because I am doing the move myself with mail.Move() this.trackItemMove = false; var pairs = new List <EntryIdChange>(); foreach (MailItem mail in mailsToMove) { var mailAfterMove = (MailItem)mail.Move(Target); Log.log("moved mail. old id = " + ThisAddIn.getEntryIdDebug(mail, "bljbkghjrhje") + " ---- new id = " + mailAfterMove.EntryID); pairs.Add(new EntryIdChange { OldId = ThisAddIn.getEntryIdDebug(mail, "gflibfkhjdsbnmdbfjdhjg"), NewId = mailAfterMove.EntryID, Subject = mail.Subject ?? "" }); Utils.ReleaseComObject(mailAfterMove); } this.trackItemMove = true; CrashReportFsharp.execInThreadForceNewThreadDur(false, logError, FuncConvert.ToFSharpFunc <Unit>(aa => { try { var emails = (from m in pairs let atSubj = new XAttribute("subject", m.Subject ?? "") let atOldId = new XAttribute("old_cmd_line", outlookPrefix + m.OldId) let atNewId = new XAttribute("new_cmd_line", outlookPrefix + m.NewId) let ats = new[] { atSubj, atOldId, atNewId } select new XElement("id_change", ats)).ToArray(); var xelRoot = new XElement("update_email_ids", emails); var xdoc = new XDocument(xelRoot); var tabblesWasRunning = sendXmlToTabbles(xdoc); if (!tabblesWasRunning) { Utils.appendToXml(xelRoot); } } catch (Exception ecc) { try { var crashId = "outlook-addin: error in explorer before item paste subthread"; var stackTrace = ThisAddIn.AssemblyVer_safe() + CrashReportFsharp.stringOfException(ecc); var str = crashId + stackTrace; Log.log(str); } catch { } } })); } finally { foreach (MailItem mail in mailsToMove) { Utils.ReleaseComObject(mail); } } } } catch (Exception eOuter) { try { var crashId = "outlook-addin: error before item paste "; var stackTrace = ThisAddIn.AssemblyVer_safe() + CrashReportFsharp.stringOfException(eOuter); var str = crashId + stackTrace; Log.log(str); } catch { } } }
// Run the decision method, letting it decide whether or not the Command's intent should manifest as Events public async Task <Unit> Execute(Action <Context <TEvent, TState> > decide) => await FSharpAsync.StartAsTask(Decide(FuncConvert.ToFSharpFunc(decide)), null, null);
static int Main() { // Some typical code { Microsoft.FSharp.Core.FSharpOption <int> x = Microsoft.FSharp.Core.FSharpOption <int> .Some(3); System.Console.WriteLine("{0}", x.Value); Microsoft.FSharp.Collections.FSharpList <int> x2 = Microsoft.FSharp.Collections.FSharpList <int> .Cons(3, Microsoft.FSharp.Collections.FSharpList <int> .Empty); System.Console.WriteLine("{0}", x2.Head); } { FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty)); Console.WriteLine("x - IsCons = {0}", x != null); Console.WriteLine("x - IsNil = {0}", x == null); Console.WriteLine("x.Head = {0}", x.Head); Console.WriteLine("x.Tail = {0}", x.Tail); Console.WriteLine("x.Tail - IsNil = {0}", x.Tail); switch (x.Tag) { case FSharpList <int> .Tags.Cons: Console.WriteLine("Cons({0},{1})", x.Head, x.Tail); break; case FSharpList <int> .Tags.Empty: Console.WriteLine("[]"); break; } } { FSharpList <int> x = FSharpList <int> .Cons(3, (FSharpList <int> .Empty)); foreach (int i in x) { Console.WriteLine("i = {0}", i); } } { FSharpList <int> myList = ListModule.OfArray(new int[] { 4, 5, 6 }); ListModule.Iterate (FuncConvert.ToFSharpFunc((Action <int>) delegate(int i) { Console.WriteLine("i = {0}", i); }), myList); // tests op_Implicit ListModule.Iterate <int> ((Converter <int, Unit>) delegate(int i) { Console.WriteLine("i = {0} (2nd technique)", i); return(null); }, myList); // tests op_Implicit FSharpList <string> myList2 = ListModule.Map (FuncConvert.ToFSharpFunc((Converter <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }), myList); // tests op_Implicit ListModule.Iterate (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s) { Console.WriteLine("i after duplication = {0}", s); }), myList2); // tests op_Implicit myList2 = ListModule.Map <int, string> ((Converter <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }, myList); ListModule.Iterate <string> (FuncConvert.ToFSharpFunc((Action <string>) delegate(string s) { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2); myList2 = ListModule.Map <int, string> (FuncConvert.ToFSharpFunc(delegate(int i) { return(i.ToString() + i.ToString()); }), myList); myList2 = ListModule.Map <int, string> (FuncConvert.FromFunc((Func <int, string>) delegate(int i) { return(i.ToString() + i.ToString()); }), myList); ListModule.Iterate <string>(FuncConvert.ToFSharpFunc <string>(s => { Console.WriteLine("s = {0}", s); }), myList2); ListModule.Iterate <string>(FuncConvert.FromAction <string>(s => { Console.WriteLine("s = {0}", s); }), myList2); ListModule.Iterate <string>(FuncConvert.FromFunc <string, Microsoft.FSharp.Core.Unit>(s => null), myList2); myList2 = ListModule.Map <int, string>(FuncConvert.ToFSharpFunc <int, string>(i => i.ToString() + i.ToString()), myList); myList2 = ListModule.Map <int, string>(FuncConvert.FromFunc <int, string>(i => i.ToString() + i.ToString()), myList); myList2 = ListModule.MapIndexed <int, string>(FuncConvert.FromFunc <int, int, string>((i, j) => i.ToString() + j), myList); var trans3 = FuncConvert.FromFunc <int, int, int, int>((i, j, k) => i + j + k); var trans4 = FuncConvert.FromFunc <int, int, int, int, int>((i, j, k, l) => i + j + k + l); var trans5 = FuncConvert.FromFunc <int, int, int, int, int, int>((i, j, k, l, m) => i + j + k + l + m); var action3 = FuncConvert.FromAction <int, int, int>((i, j, k) => System.Console.WriteLine("action! {0}", i + j + k)); var action4 = FuncConvert.FromAction <int, int, int, int>((i, j, k, l) => System.Console.WriteLine("action! {0}", i + j + k + l)); var action5 = FuncConvert.FromAction <int, int, int, int, int>((i, j, k, l, m) => System.Console.WriteLine("action! {0}", i + j + k + l + m)); ListModule.Iterate <string>(FuncConvert.ToFSharpFunc <string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2); ListModule.Iterate <string>(FuncConvert.FromAction <string>(s => { Console.WriteLine("i after duplication (2nd technique) = {0}", s); }), myList2); } // Construct a value of each type from the library Lib.Recd1 r1 = new Lib.Recd1(3); Lib.Recd2 r2 = new Lib.Recd2(3, "a"); Lib.RevRecd2 rr2 = new Lib.RevRecd2("a", 3); Lib.Recd3 <string> r3 = new Lib.Recd3 <string>(4, "c", null); r3.recd3field3 = r3; Lib.One d10a = Lib.One.One; Lib.Int d11a = Lib.Int.NewInt(3); Lib.IntPair ip = Lib.IntPair.NewIntPair(3, 4); Console.WriteLine("{0}", ip.Item1); Console.WriteLine("{0}", ip.Item2); Lib.IntPear ip2 = Lib.IntPear.NewIntPear(3, 4); Console.WriteLine("{0}", ip2.Fst); Console.WriteLine("{0}", ip2.Snd); Lib.Bool b = Lib.Bool.True; Console.WriteLine("{0}", Lib.Bool.True); Console.WriteLine("{0}", Lib.Bool.False); //Console.WriteLine("{0}", Lib.Bool.IsTrue(b)); //Console.WriteLine("{0}", Lib.Bool.IsFalse(b)); switch (b.Tag) { case Lib.Bool.Tags.True: Console.WriteLine("True"); break; case Lib.Bool.Tags.False: Console.WriteLine("False"); break; } Lib.OptionalInt oint = Lib.OptionalInt.NewSOME(3); Console.WriteLine("oint - IsSOME = {0}", oint != null); Console.WriteLine("oint - IsNONE = {0}", oint == null); Console.WriteLine("{0}", (oint as Lib.OptionalInt.SOME).Item); switch (oint.Tag) { case Lib.OptionalInt.Tags.SOME: var c = oint as Lib.OptionalInt.SOME; Console.WriteLine("SOME({0})", c.Item); break; case Lib.OptionalInt.Tags.NONE: Console.WriteLine("NONE"); break; } Lib.IntOption iopt = Lib.IntOption.Nothing; Console.WriteLine("iopt - IsSomething = {0}", iopt != null); Console.WriteLine("iopt - IsNothing = {0}", iopt == null); switch (iopt.Tag) { case Lib.IntOption.Tags.Something: Console.WriteLine("Something({0})", (iopt as Lib.IntOption.Something).Item); break; case Lib.IntOption.Tags.Nothing: Console.WriteLine("Nothing"); break; } Lib.GenericUnion <int, string> gu1 = Lib.GenericUnion <int, string> .Nothing; Lib.GenericUnion <int, string> gu2 = Lib.GenericUnion <int, string> .NewSomething(3, "4"); Lib.GenericUnion <int, string> gu3 = Lib.GenericUnion <int, string> .NewSomethingElse(3); Lib.GenericUnion <int, string> gu4 = Lib.GenericUnion <int, string> .NewSomethingElseAgain(4); //Console.WriteLine("{0}", (gu1 as Lib.GenericUnion<int,string>.Cases.Nothing)); Console.WriteLine("{0}", (gu2 as Lib.GenericUnion <int, string> .Something).Item1); Console.WriteLine("{0}", (gu3 as Lib.GenericUnion <int, string> .SomethingElse).Item); Console.WriteLine("{0}", (gu4 as Lib.GenericUnion <int, string> .SomethingElseAgain).Item); switch (gu1.Tag) { case Lib.GenericUnion <int, string> .Tags.Nothing: Console.WriteLine("OK"); break; case Lib.GenericUnion <int, string> .Tags.Something: case Lib.GenericUnion <int, string> .Tags.SomethingElse: case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } switch (gu2.Tag) { case Lib.GenericUnion <int, string> .Tags.Something: Console.WriteLine("OK"); break; case Lib.GenericUnion <int, string> .Tags.Nothing: case Lib.GenericUnion <int, string> .Tags.SomethingElse: case Lib.GenericUnion <int, string> .Tags.SomethingElseAgain: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.BigUnion bu1 = Lib.BigUnion.NewA1(3); Lib.BigUnion bu2 = Lib.BigUnion.NewA2(3); Lib.BigUnion bu3 = Lib.BigUnion.NewA3(3); Lib.BigUnion bu4 = Lib.BigUnion.NewA4(3); Lib.BigUnion bu5 = Lib.BigUnion.NewA5(3); Lib.BigUnion bu6 = Lib.BigUnion.NewA6(3); Lib.BigUnion bu7 = Lib.BigUnion.NewA7(3); Lib.BigUnion bu8 = Lib.BigUnion.NewA8(3); Lib.BigUnion bu9 = Lib.BigUnion.NewA9(3); switch (bu1.Tag) { case Lib.BigUnion.Tags.A1: Console.WriteLine("OK"); break; case Lib.BigUnion.Tags.A2: case Lib.BigUnion.Tags.A3: case Lib.BigUnion.Tags.A4: case Lib.BigUnion.Tags.A5: case Lib.BigUnion.Tags.A6: case Lib.BigUnion.Tags.A7: case Lib.BigUnion.Tags.A8: case Lib.BigUnion.Tags.A9: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.BigEnum be1 = Lib.BigEnum.E1; Lib.BigEnum be2 = Lib.BigEnum.E2; Lib.BigEnum be3 = Lib.BigEnum.E3; Lib.BigEnum be4 = Lib.BigEnum.E4; Lib.BigEnum be5 = Lib.BigEnum.E5; Lib.BigEnum be6 = Lib.BigEnum.E6; Lib.BigEnum be7 = Lib.BigEnum.E7; Lib.BigEnum be8 = Lib.BigEnum.E8; Lib.BigEnum be9 = Lib.BigEnum.E9; switch (be1.Tag) { case Lib.BigEnum.Tags.E1: Console.WriteLine("OK"); break; case Lib.BigEnum.Tags.E2: case Lib.BigEnum.Tags.E3: case Lib.BigEnum.Tags.E4: case Lib.BigEnum.Tags.E5: case Lib.BigEnum.Tags.E6: case Lib.BigEnum.Tags.E7: case Lib.BigEnum.Tags.E8: case Lib.BigEnum.Tags.E9: Console.WriteLine("NOT OK"); throw (new System.Exception("ERROR - INCORRECT CASE TAG")); } Lib.Index d211a = Lib.Index.NewIndex_A(3); Lib.Bool d200b = Lib.Bool.False; Lib.OptionalInt d210b = Lib.OptionalInt.NONE; Lib.IntOption d201b = Lib.IntOption.NewSomething(3); Lib.Index d211b = Lib.Index.NewIndex_B(4); /* * * type discr2_0_0 = True | False * type discr2_0_1 = Nothing | Something of int * type discr2_1_0 = SOME of int | NONE * type discr2_1_1 = Index_A of int | Index_B of int * * type discr3_0_0_0 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C * type discr3_0_1_0 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C * type discr3_1_0_0 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C * type discr3_1_1_0 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C * type discr3_0_0_1 = Discr3_0_0_0_A | Discr3_0_0_0_B | Discr3_0_0_0_C of string * type discr3_0_1_1 = Discr3_0_1_0_A | Discr3_0_1_0_B of int | Discr3_0_0_0_C of string * type discr3_1_0_1 = Discr3_1_0_0_A of int | Discr3_1_0_0_B | Discr3_0_0_0_C of string * type discr3_1_1_1 = Discr3_1_1_0_A of int | Discr3_1_1_0_B of int | Discr3_0_0_0_C of string */ // Toplevel functions * int f_1 = Lib.f_1(1); int f_1_1 = Lib.f_1_1(1, 2); int f_1_1_1 = Lib.f_1_1_1(1, 2, 3); int f_1_1_1_1 = Lib.f_1_1_1_1(1, 2, 3, 4); int f_1_1_1_1_1 = Lib.f_1_1_1_1_1(1, 2, 3, 4, 5); #if DELEGATES int f_1_effect_1 = Lib.f_1_effect_1(1)(2); #else int f_1_effect_1 = Lib.f_1_effect_1(1).Invoke(2); #endif //let f_2 x y = x+y //let f_3 x y z = x+y+z //let f_4 x1 x2 x3 x4 = x1+x2+x3+x4 //let f_5 x1 x2 x3 x4 x5 = x1+x2+x3+x4+x5 // Function returning a function //let f_1_1 x = let x = ref 1 in fun y -> !x+y+1 // Tuple value //let tup2 = (2,3) //let tup3 = (2,3,4) //let tup4 = (2,3,4,5) System.Console.WriteLine("Test Passed."); return(0); }
protected override async Task <double[]> EvaluateCellsBatchAsync(IRequestContext context, ComputationalContext computationalContext, IEnumerable <GeoCellTuple> cells) { await SaveObservationsAndDalanayDiagsForCells(context, computationalContext, cells); VariogramModule.IVariogramFitter variogramFitter = new LMDotNetVariogramFitter.Fitter(); Dictionary <ITimeSegment, VariogramModule.IVariogram> variograms = new Dictionary <ITimeSegment, VariogramModule.IVariogram>(); Dictionary <ITimeSegment, IObservationsInformation> observations = (Dictionary <ITimeSegment, IObservationsInformation>)computationalContext["observations"]; LimitedConcurrencyLevelTaskScheduler lclts = new LimitedConcurrencyLevelTaskScheduler(Environment.ProcessorCount); TaskFactory taskFactory = new TaskFactory(lclts); var variogramTasks = observations.Select(pair => taskFactory.StartNew(() => { ITimeSegment ts = pair.Key; TraceVerbose(string.Format("Fitting variogram for {0} ({1} observations)", ts, pair.Value.Observations.Length)); Stopwatch sw1 = Stopwatch.StartNew(); var lats = pair.Value.Observations.Select(o => o.Latitude).ToArray(); var lons = pair.Value.Observations.Select(o => o.Longitude).ToArray(); var vals = pair.Value.Observations.Select(o => o.Value).ToArray(); var pointSet = new EmpVariogramBuilder.PointSet(lats, lons, vals); var dist = FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, FSharpFunc <Tuple <double, double>, double> >(t1 => FuncConvert.ToFSharpFunc(new Converter <Tuple <double, double>, double>(t2 => SphereMath.GetDistance(t1.Item1, t1.Item2, t2.Item1, t2.Item2))))); var empVar = EmpVariogramBuilder.EmpiricalVariogramBuilder.BuildEmpiricalVariogram(pointSet, dist); var fitted_variogram = variogramFitter.Fit(empVar); VariogramModule.IVariogram effectiveVariogram = null; sw1.Stop(); if (FSharpOption <VariogramModule.IDescribedVariogram> .get_IsSome(fitted_variogram)) { effectiveVariogram = fitted_variogram.Value; TraceVerbose(string.Format("Variogram fited for {0} ({1} observations) in {2}", ts, pair.Value.Observations.Length, sw1.Elapsed)); } else { TraceWarning(string.Format("Variogram fitting failed for {0} ({1} observations) in {2}. Using fallback variogram", ts, pair.Value.Observations.Length, sw1.Elapsed)); effectiveVariogram = variogramFitter.GetFallback(empVar); } lock ("saving_variograms") { variograms.Add(ts, effectiveVariogram); } })); TraceVerbose(string.Format("Starting calculations of linear weights for all cells")); Stopwatch sw2 = Stopwatch.StartNew(); var weigths = CalcLinearWeights(computationalContext, cells); sw2.Stop(); TraceVerbose(string.Format("calculations of linear weights for all cells ended in {0}", sw2.Elapsed)); TraceVerbose(string.Format("Waiting for all variograms to be computed")); await Task.WhenAll(variogramTasks); TraceVerbose(string.Format("All variograms are computed. Calculating variances and values")); Stopwatch sw3 = Stopwatch.StartNew(); var resultValues = cells.Zip(weigths, (cell, weightTuple) => { ITimeSegment ts = cell.Time; var weight = weightTuple.Item2; VariogramModule.IVariogram variogram = variograms[ts]; var observation = observations[ts].Observations; Debug.Assert(Math.Abs(weight.Sum(w => w.Weight) - 1.0) < 1e-10); double sill = variogram.Sill; double cellLat = (cell.LatMax + cell.LatMin) * 0.5; double cellLon = (cell.LonMax + cell.LonMin) * 0.5; //var = cov(0)+ sum sum (w[i]*w[j]*cov(i,j))-2.0*sum(w[i]*cov(x,i)) double cov_at_0 = sill; double acc = cov_at_0; //cov(0) for (int i = 0; i < weight.Length; i++) { double w = weight[i].Weight; int idx1 = weight[i].DataIndex; double lat1 = observation[idx1].Latitude; double lon1 = observation[idx1].Longitude; for (int j = 0; j < i; j++) { int idx2 = weight[j].DataIndex; double lat2 = observation[idx2].Latitude; double lon2 = observation[idx2].Longitude; double dist = SphereMath.GetDistance(lat1, lon1, lat2, lon2); double cov = sill - variogram.GetGamma(dist); acc += 2.0 * w * weight[j].Weight * cov; } acc += w * w * cov_at_0; //diagonal elements double dist2 = SphereMath.GetDistance(lat1, lon1, cellLat, cellLon); double cov2 = sill - variogram.GetGamma(dist2); acc -= 2.0 * w * cov2; } return(Tuple.Create(cell, Math.Sqrt(acc), weight.Sum(w => observation[w.DataIndex].Value * w.Weight))); }).ToArray(); sw3.Stop(); TraceVerbose(string.Format("All sigmas calulated in {0}", sw3.Elapsed)); computationalContext.Add("results", resultValues); return(resultValues.Select(r => r.Item2).ToArray()); }
public static FSharpFunc <Tuple <A1, A2, A3>, Result> ToTupledFSharpFunc <A1, A2, A3, Result>(this Func <A1, A2, A3, Result> f) { return(FuncConvert.ToFSharpFunc(new Converter <Tuple <A1, A2, A3>, Result>(t => f(t.Item1, t.Item2, t.Item3)))); }
public static FSharpFunc <A, Result> ToFSharpFunc <A, Result>(this Func <A, Result> f) { return(FuncConvert.ToFSharpFunc(new Converter <A, Result>(f))); }
public void TestTrendingManagerHosting() { var repository = new VolatileRepository <int, SiteTrendingSeries>( FuncConvert.ToFSharpFunc <SiteTrendingSeries, int>(sts => sts.Id)) as IRepository <int, SiteTrendingSeries>; int seriesId = 1; var matrix = new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; repository.Create( new SiteTrendingSeries() { Id = seriesId, Label = seriesId.ToString(), Protocol = new TrendingProtocol() { Algorithm = "trend", Tolerance = 1.0, }, SeriesItems = ListModule.OfSeq( new List <TrendingSeriesItem> { new TrendingSeriesItem( allResults: FSharpList <RegistrationResult> .Empty, selectedResult: new RegistrationResult(matrix: matrix, label: "")) }), Shift = new double[] { 1.0, 2.0, 3.0 } }); var container = Hosting.createHostContainer(); ComponentRegistration.registerService_(typeof(ITrendingManager), typeof(TrendingManagerService), container); ComponentRegistration.registerService_(typeof(ITrendingEngine), typeof(TrendingEngineService), container); ComponentRegistration.registerService_(typeof(ITrendingDataAccess), typeof(TrendingDataAccess), container); ComponentRegistration.registerFunction <ITrendCalculationFunction, TrendCalculation>(container); ComponentRegistration.registerRepositoryInstance(repository, container); Hosting.startServices(container); var ipm = container.Resolve <IProxyManager>(); using (var proxyContext = ipm.GetTransientContext()) { var proxy = ipm.GetProxy <ITrendingManager>(); var series = proxy.GetSeries(seriesId); Assert.IsTrue(series != null); var updatedSeries = proxy.UpdateSeries(series); Assert.IsTrue(updatedSeries.Id == series.Id); } using (var proxyContext = ipm.GetTransientContext()) { var proxy = ipm.GetProxy <ITrendingManager>(); var series = proxy.GetSeries(seriesId); Assert.IsTrue(series != null); var updatedSeries = proxy.UpdateSeries(series); Assert.IsTrue(updatedSeries.Id == series.Id); } Hosting.stopServices(container); }
public static FSharpFunc <Tuple <A1, A2>, Result> ToTupledFSharpFunc <A1, A2, Result>(this Func <A1, A2, Result> f) => FuncConvert.ToFSharpFunc(new Converter <Tuple <A1, A2>, Result>(t => f(t.Item1, t.Item2)));