static void Main(string[] args) { var car = new Car(4, "Supacars", Tuple.Create(1.5, 3.5)); var wheeles = car.Wheels; var bike = Vehicle.NewMotorbike("Harley", 4.0); var car2 = Vehicle.NewMotorcar(car); Console.WriteLine("A car: {0}", car); Console.WriteLine("A bike: {0}", bike); Functions.Describe(bike); Functions.Describe(car2); var car3 = Functions.CreateCar(4, "Chevy", 1.5, 3.5); var car4 = Functions.CreateFourWheeledCar .Invoke("Chevy") .Invoke(1.5) .Invoke(3.5); // Woring with Options var optionalCar = FSharpOption <Car> .Some(car); var isNone = FSharpOption <Car> .get_IsNone(car); var isNotSome = FSharpOption <Car> .get_IsSome(optionalCar); Console.WriteLine("{0} : {1} : {2}", optionalCar, isNone, isNotSome); }
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); }
static void Main(string[] args) { var car = new Car(4, "Supacars", Tuple.Create(1.5, 3.5)); var bike = Vehicle.NewMotorbike("MyBike", 1.5); var motorcar = Vehicle.NewMotorcar(car); Functions.Describe(bike); Functions.Describe(motorcar); var someWheeledCar = Functions.CreateCar(4, "Supacars", 1.5, 3.5); var fourWheeledCar = Functions.CreateFourWheeledCar .Invoke("Supacars") .Invoke(1.5) .Invoke(3.5); // Working with Options var optionalCar = FSharpOption <Car> .Some(car); var isNone = FSharpOption <Car> .get_IsNone(optionalCar); var isNotSome = FSharpOption <Car> .get_IsSome(optionalCar); // With extension methods var optionalCarExt = car.AsOption(); var isNoneExt = optionalCarExt.IsNone(); var isSomeExt = optionalCarExt.IsSome(); }
public void CanCompileSecureTokenCodeFromTemplate() { var tpl = GetTemplate("SecureToken"); var destinationAddress = Wallet.core.Data.Key.Create().Address.Bytes; var destination = Convert.ToBase64String(destinationAddress); var metadata = new { contractType = "securetoken", destination = destination }; var jsonHeader = "//" + JsonConvert.SerializeObject(metadata); var code = tpl.Replace("__ADDRESS__", destination); code += "\n" + jsonHeader; var compiled = ContractExamples.Execution.compile(code); Assert.That(compiled, Is.Not.Null, "should compile code"); Assert.That(FSharpOption <byte[]> .get_IsNone(compiled), Is.False, "should compile code"); var metadataParsed = ContractExamples.Execution.metadata(code); Assert.That(FSharpOption <ContractExamples.Execution.ContractMetadata> .get_IsNone(metadataParsed), Is.False, "should parse metadata"); Assert.That(metadataParsed.Value, Is.TypeOf(typeof(ContractExamples.Execution.ContractMetadata.SecureToken))); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.SecureToken).Item.destination, Is.EquivalentTo(destinationAddress)); object deserialized = null; try { deserialized = ContractExamples.Execution.deserialize(compiled.Value); } catch { } Assert.That(deserialized, Is.Not.Null); }
///<summary> /// Converts an <see cref="FSharpOption{T}"/> to an equivalent <see cref="Option{TOption}"/>. ///</summary> ///<param name="fSharpOption">The <see cref="FSharpOption{T}"/> to convert</param> ///<typeparam name="TOption">The internal value of <paramref name="fSharpOption"/></typeparam> ///<returns>An <see cref="Option{TOption}"/> equivalent to <paramref name="fSharpOption"/></returns> public static Option <TOption> FromFSharp <TOption>(FSharpOption <TOption> fSharpOption) { if (fSharpOption == null || FSharpOption <TOption> .get_IsNone(fSharpOption)) { return(Create <TOption>()); } return(new Option <TOption>(fSharpOption.Value)); }
public void Serialize(ref JsonWriter <TSymbol> writer, FSharpOption <T> value, int nestingLimit) { if (FSharpOption <T> .get_IsNone(value)) { writer.WriteNull(); return; } elementFormatter.Serialize(ref writer, value.Value, nestingLimit); }
public void Option() { IsTrue(FSharpOption <int> .get_IsNone(FSharpOption <int> .None)); Equal(FSharpOption <int> .None, null); Equal(FSharpOption <int> .GetTag(FSharpOption <int> .None), 0); Equal(FSharpOption <int> .GetTag(FSharpOption <int> .Some(2)), 1); Equal(FSharpOption <int> .Some(3).Value, 3); Equal(FSharpOption <int> .Some(1), FSharpConvert.Some(1)); Equal(FSharpConvert.Option((int?)1), FSharpOption <int> .Some(1)); }
public ContractFunction GetContractFunction(TransactionContext dbTx, byte[] contractHash) { var acsItem = Get(dbTx, contractHash); if (acsItem == null) { return(null); } var deserialization = FSharpOption <Tuple <ContractFunction, ContractCostFunction> > .None; try { deserialization = ContractExamples.FStarExecution.deserialize(acsItem.Value.Serialized); } catch { BlockChainTrace.Information("Error deserializing contract"); } if (FSharpOption <Tuple <ContractFunction, ContractCostFunction> > .get_IsNone(deserialization) || deserialization == null) { BlockChainTrace.Information("Reserializing contract"); try { var compilation = ContractExamples.FStarExecution.compile(acsItem.Value.Extracted); if (FSharpOption <byte[]> .get_IsNone(compilation)) { return(null); } acsItem.Value.Serialized = compilation.Value; Add(dbTx, acsItem.Value); deserialization = ContractExamples.FStarExecution.deserialize(compilation.Value); if (FSharpOption <Tuple <ContractFunction, ContractCostFunction> > .get_IsNone(deserialization)) { BlockChainTrace.Error("Error deserializing contract"); return(null); } } catch (Exception e) { BlockChainTrace.Error("Error recompiling contract", e); return(null); } } return(deserialization.Value.Item1); }
public void GetCacheTime_WithNoHeaders_ReturnsNone() { // arrange var cacheHeaders = BuildHeaders(cacheControlIsNull: true); // act var result = build(cacheHeaders); // assert Assert.True(FSharpOption <CacheSettings> .get_IsNone(result)); }
public int Serialize(ref byte[] bytes, int offset, FSharpOption <T> value, IFormatterResolver formatterResolver) { if (FSharpOption <T> .get_IsNone(value)) { return(MessagePackBinary.WriteNil(ref bytes, offset)); } else { return(formatterResolver.GetFormatterWithVerify <T>().Serialize(ref bytes, offset, value.Value, formatterResolver)); } }
public void Serialize(ref MessagePackWriter writer, FSharpOption <T> value, MessagePackSerializerOptions options) { if (FSharpOption <T> .get_IsNone(value)) { writer.WriteNil(); return; } else { IFormatterResolver resolver = options.Resolver; resolver.GetFormatterWithVerify <T>().Serialize(ref writer, value.Value, options); } }
public void FSharpConversion([Random(int.MinValue, int.MaxValue, 1)] int random) { var ourSome = new Option <int>(random); var fSharpSome = ourSome.ToFSharp(); Assert.That(FSharpOption <int> .get_IsSome(fSharpSome), "F# option should be some"); Assert.That(fSharpSome.Value, Is.EqualTo(random)); var ourNone = Option.Create <int>(); var fSharpNone = ourNone.ToFSharp(); Assert.That(FSharpOption <int> .get_IsNone(fSharpNone), "F# option should be None"); }
public bool TryActivate(TransactionContext dbTx, string contractCode, ulong kalapas, byte[] contractHash, uint blockNumber) { if (IsActive(dbTx, contractHash)) { return(false); } //TODO: module name var extration = ContractExamples.FStarExecution.extract(contractCode); if (FSharpOption <string> .get_IsNone(extration)) { BlockChainTrace.Information("Could not extract contract"); return(false); } var compilation = ContractExamples.FStarExecution.compile(extration.Value); if (FSharpOption <byte[]> .get_IsNone(compilation)) { BlockChainTrace.Information("Could not complie contract"); return(false); } var kalapasPerBlock = KalapasPerBlock(contractCode); if (kalapas < kalapasPerBlock) { return(false); } var blocks = Convert.ToUInt32(kalapas / kalapasPerBlock); Add(dbTx, new ACSItem() { Hash = contractHash, KalapasPerBlock = kalapasPerBlock, LastBlock = blockNumber + blocks, Extracted = extration.Value, Serialized = compilation.Value }); BlockChainTrace.Information($"Contract activated for {blocks} blocks", contractHash); return(true); }
public BallsModel.State calcNextState() { BallsModel.State latestState = statesBuffer.Count > 0 ? statesBuffer.Last() : currentState; FSharpOption <BallsModel.State> state = latestState.nextState(bounceGate); solved = FSharpOption <BallsModel.State> .get_IsNone(state); if (!solved) { statesBuffer.Add(state.Value); return(state.Value); } else { return(latestState); } }
public Analysis inProcessAnalysis(long max_duration_in_ms, ExceLint.FeatureConf config, Graph g, Progress p) { // sanity check if (g.NumFormulas == 0) { return(new Analysis { scores = null, ranOK = false, cutoff = 0 }); } else { // run analysis FSharpOption <ExceLint.ErrorModel> mopt; try { mopt = ExceLint.ModelBuilder.analyze(_app, config, g, 0, p); } catch (ExceLint.CommonTypes.NoFormulasException e) { System.Windows.Forms.MessageBox.Show(e.Message); throw new AnalysisCancelled(); } if (FSharpOption <ExceLint.ErrorModel> .get_IsNone(mopt)) { throw new AnalysisCancelled(); } else { var model = mopt.Value; Score[] scores = model.ranking(); int cutoff = model.Cutoff; return(new Analysis { scores = scores, ranOK = true, cutoff = cutoff, model = model, hasRun = true, dag = g }); } } }
public async Task <ActionResult> Action() { var action = Request["Action"]; var args = new Dictionary <string, string>(); byte opcode = 0x01; var address = Request["Address"]; var contractHash = new Address(address).Bytes; string key = HttpServerUtility.UrlTokenEncode(contractHash); var file = $"{key}"; string contractCode = null; var codeFile = Path.ChangeExtension(Path.Combine("db", "contracts", file), ".txt"); if (System.IO.File.Exists(codeFile)) { contractCode = System.IO.File.ReadAllText(codeFile); } var contractInteraction = new ContractInteraction() { Action = action, Address = new Address(contractHash, AddressType.Contract).ToString() }; ContractMetadata contractMetadata = null; try { var _metadata = ContractExamples.Execution.metadata(contractCode); if (FSharpOption <ContractMetadata> .get_IsNone(_metadata)) { contractInteraction.Message = "No metadata"; } else { contractMetadata = _metadata.Value; } } catch { contractInteraction.Message = "Error getting metadata"; return(View(contractInteraction)); } if (contractMetadata.IsCallOption) { var callOptionParameters = (ContractExamples.Execution.ContractMetadata.CallOption)contractMetadata; switch (action) { case "Collateralize": //var pkAddress = new PKAddressField(); //pkAddress.SetValue(Request["return-address"]); //if (pkAddress.Invalid) //{ // contractInteraction.Message = "Invalid return address"; // return View(contractInteraction); //} //args.Add("returnPubKeyAddress", pkAddress.Value); opcode = OPCODE_COLLATERALIZE; break; case "Exercise": var pkExerciseReturnAddress = new PKAddressField(); pkExerciseReturnAddress.SetValue(Request["exercise-return-address"]); if (pkExerciseReturnAddress.Invalid) { contractInteraction.Message = "Invalid send address"; return(View(contractInteraction)); } args.Add("returnPubKeyAddress", pkExerciseReturnAddress.Value); string oracleData; //GetOracleCommitmentData(callOptionParameters.Item.underlying, DateTime.Now.ToUniversalTime()).Result; if (GetLastData(callOptionParameters.Item.underlying, out oracleData)) { args.Add("oracleRawData", oracleData); } else { contractInteraction.Message = "Error getting oracle data"; return(View(contractInteraction)); } opcode = OPCODE_EXERCISE; break; case "Buy": var pkSendAddress = new PKAddressField(); pkSendAddress.SetValue(Request["buy-send-address"]); if (pkSendAddress.Invalid) { contractInteraction.Message = "Invalid send address"; return(View(contractInteraction)); } args.Add("returnPubKeyAddress", pkSendAddress.Value); opcode = OPCODE_BUY; break; //case "Close": // opcode = OPCODE_CLOSE; // break; } } var argsMap = new FSharpMap <string, string>(args.Select(t => new Tuple <string, string>(t.Key, t.Value))); var result = await Client.Send <GetContractPointedOutputsResultPayload>(_address, new GetContractPointedOutputsPayload() { ContractHash = contractHash }); var utxos = GetContractPointedOutputsResultPayload.Unpack(result.PointedOutputs); var data = ContractUtilities.DataGenerator.makeJson(contractMetadata, utxos, opcode, argsMap); if (data.IsError) { contractInteraction.Message = data.ErrorValue.ToString(); } else { contractInteraction.Data = data.ResultValue.JsonValue.ToString(); } return(View(contractInteraction)); }
public static LTLAnalysisResult Simulate(LTLSimulationAnalysisInputDTO input) { LogService log = new LogService(); try { string formula = input.Formula; string num_of_steps = input.Number_of_steps; IAnalyzer analyzer = new UIMain.Analyzer(); if (input.EnableLogging) { analyzer.LoggingOn(log); } else { analyzer.LoggingOff(); log.LogDebug("Logging is disabled."); } Stopwatch sw = new Stopwatch(); sw.Start(); var result = analyzer.checkLTLSimulation(input, formula, num_of_steps); sw.Stop(); log.LogDebug(string.Format("The LTL simulation took {0}", sw.Elapsed)); if (FSharpOption <LTLAnalysisResultDTO> .get_IsNone(result)) { return(new LTLAnalysisResult { Error = null, Ticks = null, Status = LTLStatus.Unknown, Loop = -1, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }); } else { var res = result.Value; var status = res.Status; return(new LTLAnalysisResult { Error = res.Error, Ticks = res.Ticks, Status = status ? LTLStatus.True : LTLStatus.False, Loop = res.Loop, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }); } } catch (Exception ex) { var version = typeof(Analysis).Assembly.GetName().Version; log.LogError(String.Format("LTL simulation failed. Assembly version: {0}. Exception: {1}", version, ex)); return(new LTLAnalysisResult { Error = ex.Message, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }); } }
public static Tuple <LTLAnalysisResult, LTLAnalysisResult> Polarity(LTLPolarityAnalysisInputDTO input) { LogService log = new LogService(); try { string formula = input.Formula; string num_of_steps = input.Number_of_steps; FSharpOption <bool> polarity = FSharpOption <bool> .None; if (input.Polarity != LTLStatus.Unknown) { polarity = new FSharpOption <bool>(input.Polarity == LTLStatus.True); } IAnalyzer analyzer = new UIMain.Analyzer(); if (input.EnableLogging) { analyzer.LoggingOn(log); } else { analyzer.LoggingOff(); log.LogDebug("Logging is disabled."); } Stopwatch sw = new Stopwatch(); sw.Start(); var result = analyzer.checkLTLPolarity(input, formula, num_of_steps, polarity); sw.Stop(); log.LogDebug(string.Format("The LTL polarity check took {0}", sw.Elapsed)); var positive = new LTLAnalysisResult { Error = result.Item1.Error, Ticks = result.Item1.Ticks, Status = result.Item1.Status ? LTLStatus.True : LTLStatus.False, Loop = result.Item1.Loop, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }; LTLAnalysisResult negative = null; if (result.Item2 != null && !FSharpOption <LTLAnalysisResultDTO> .get_IsNone(result.Item2)) { negative = new LTLAnalysisResult { Error = result.Item2.Value.Error, Ticks = result.Item2.Value.Ticks, Status = result.Item2.Value.Status ? LTLStatus.True : LTLStatus.False, Loop = result.Item2.Value.Loop, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }; } return(new Tuple <LTLAnalysisResult, LTLAnalysisResult>(positive, negative)); } catch (Exception ex) { var version = typeof(Analysis).Assembly.GetName().Version; log.LogError(String.Format("LTL Polarity check failed. Assembly version: {0}. Exception: {1}", version, ex)); return(new Tuple <LTLAnalysisResult, LTLAnalysisResult>(new LTLAnalysisResult { Error = ex.Message, ErrorMessages = log.ErrorMessages.Length > 0 ? log.ErrorMessages.ToArray() : null, DebugMessages = log.DebugMessages.Length > 0 ? log.DebugMessages.ToArray() : null }, null)); } }
internal static Option <TValue> FromFSharpOption(FSharpOption <TValue> option) { return(FSharpOption <TValue> .get_IsNone(option) ? Option <TValue> .None : Option <TValue> .Some(option.Value)); }
public static bool IsNone(this FSharpOption <Basic.Position> option) { return(FSharpOption <Basic.Position> .get_IsNone(option)); }
public void CanCompileCallOptionCodeFromTemplate() { var tpl = GetTemplate("CallOption"); var controlAssetReturn = Wallet.core.Data.Key.Create().Address.Bytes; var controlAsset = Wallet.core.Data.Key.Create().Address.Bytes; var oracleAddress = Wallet.core.Data.Key.Create().Address.Bytes; var underlying = "GOOG"; var price = 10M; var strike = 900M; var minimumCollateralRatio = 1; var ownerPubKey = Wallet.core.Data.Key.Create().Public; var callOptionsParams = new ContractExamples.QuotedContracts.CallOptionParameters( Consensus.Tests.zhash, controlAsset, controlAssetReturn, oracleAddress, underlying, price, strike, minimumCollateralRatio, ownerPubKey ); var code = tpl .Replace("__numeraire__", Convert.ToBase64String(callOptionsParams.numeraire)) .Replace("__controlAsset__", Convert.ToBase64String(callOptionsParams.controlAsset)) .Replace("__controlAssetReturn__", Convert.ToBase64String(callOptionsParams.controlAssetReturn)) .Replace("__oracle__", Convert.ToBase64String(callOptionsParams.oracle)) .Replace("__underlying__", callOptionsParams.underlying) .Replace("__price__", "" + callOptionsParams.price) .Replace("__strike__", "" + callOptionsParams.strike) .Replace("__minimumCollateralRatio__", "" + callOptionsParams.minimumCollateralRatio) .Replace("__ownerPubKey__", Convert.ToBase64String(callOptionsParams.ownerPubKey)); var metadata = new { contractType = "calloption", numeraire = Convert.ToBase64String(callOptionsParams.numeraire), controlAsset = Convert.ToBase64String(callOptionsParams.controlAsset), controlAssetReturn = Convert.ToBase64String(callOptionsParams.controlAssetReturn), oracle = Convert.ToBase64String(callOptionsParams.oracle), underlying = callOptionsParams.underlying, price = "" + callOptionsParams.price, strike = "" + callOptionsParams.strike, minimumCollateralRatio = "" + callOptionsParams.minimumCollateralRatio, ownerPubKey = Convert.ToBase64String(callOptionsParams.ownerPubKey) }; var jsonHeader = "//" + JsonConvert.SerializeObject(metadata); code += "\n" + jsonHeader; var compiled = ContractExamples.Execution.compile(code); Assert.That(compiled, Is.Not.Null, "should compile code"); Assert.That(FSharpOption <byte[]> .get_IsNone(compiled), Is.False, "should compile code"); var metadataParsed = ContractExamples.Execution.metadata(code); Assert.That(FSharpOption <ContractExamples.Execution.ContractMetadata> .get_IsNone(metadataParsed), Is.False, "should parse metadata"); Assert.That(metadataParsed.Value, Is.TypeOf(typeof(ContractExamples.Execution.ContractMetadata.CallOption))); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.numeraire, Is.EquivalentTo(Consensus.Tests.zhash)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.controlAsset, Is.EquivalentTo(controlAsset)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.controlAssetReturn, Is.EquivalentTo(controlAssetReturn)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.oracle, Is.EquivalentTo(oracleAddress)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.underlying, Is.EquivalentTo(underlying)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.price, Is.EqualTo(price)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.strike, Is.EqualTo(strike)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.minimumCollateralRatio, Is.EqualTo(minimumCollateralRatio)); Assert.That((metadataParsed.Value as ContractExamples.Execution.ContractMetadata.CallOption).Item.ownerPubKey, Is.EqualTo(ownerPubKey)); object deserialized = null; try { deserialized = ContractExamples.Execution.deserialize(compiled.Value); } catch { } Assert.That(deserialized, Is.Not.Null); }
public static void IsNone <T>(FSharpOption <T> value) { Assert.False(FSharpOption <T> .get_IsNone(value)); }
bool IsTransactionValid(TransactionValidation.PointedTransaction ptx) { if (!HasUtxos(ptx)) { MinerTrace.Information("could not validate tx - utxo missing"); return(false); } var utxoLookup = UtxoLookup.FromConverter(outpoint => { var outputs = _UtxoSet.Where(t => t.Item1.Equals(outpoint)).Select(t => t.Item2); return(!outputs.Any() ? FSharpOption <Types.Output> .None : new FSharpOption <Types.Output>(outputs.First())); }); var contractLookup = FSharpFunc <byte[], FSharpOption <ContractFunction> > .FromConverter(contractHash => { if (!_ActiveContracts.Contains(contractHash)) { return(FSharpOption <ContractFunction> .None); } try { var code = new GetContractCodeAction(contractHash).Publish().Result; //TODO: module name var extration = ContractExamples.FStarExecution.extract(System.Text.Encoding.ASCII.GetString(code)); if (FSharpOption <string> .get_IsNone(extration)) { MinerTrace.Information("Could not extract contract"); return(null); } var compilation = ContractExamples.FStarExecution.compile(extration.Value); if (FSharpOption <byte[]> .get_IsNone(compilation)) { MinerTrace.Information("Could not complie contract"); return(null); } return(ContractExamples.FStarExecution.deserialize(compilation.Value).Value.Item1); } catch (Exception e) { MinerTrace.Error("Could not compile contract " + Convert.ToBase64String(contractHash), e); return(null); } }); if (!TransactionValidation.validateNonCoinbaseTx( ptx, utxoLookup, contractLookup )) { MinerTrace.Information("could not validate tx"); return(false); } MinerTrace.Information("validated tx"); //TODO: memory management issues. trying to explicitly collect DynamicMethods GC.Collect(); GC.WaitForPendingFinalizers(); return(true); }
public void Create_none() { var expected = FSharpOptionHelper.None(FSharpOptionHelper.GetUnderlyingType(TestData.PropertyType)); FSharpOption <string> .get_IsNone((FSharpOption <string>) expected).Should().BeTrue(); }
public static bool IsNone <T>(this FSharpOption <T> o) => FSharpOption <T> .get_IsNone(o);
/// <summary> /// Converts <see cref="FSharpOption{T}"/> to <see cref="Nullable"/>. /// </summary> private static T?AsNullable <T>(this FSharpOption <T> opt) where T : struct { return(FSharpOption <T> .get_IsNone(opt) ? new T?() : opt.Value); }
public static bool IsNone <T>(this FSharpOption <T> option) { return(FSharpOption <T> .get_IsNone(option)); }
public static Boolean IsNone <T>(this FSharpOption <T> optionType) { return(FSharpOption <T> .get_IsNone(optionType)); }