static Either <Exception, VibrateCommand> ParseVibrateLine(string s) { Arr <string> parts = new Arr <string>(s.ToLower().Split(' ')); if (parts.Contains("start")) { Map <string, string> dict = new Map <string, string>(parts.Filter(s_ => s_.Contains("=")).Map(p => { string[] pp = p.Split('='); return(pp.First(), pp.Last()); })); try { return(Right <VibrateCommand>(new VibrateStart( dict["type"], dict.Find("time").Map(Double.Parse), dict.Find("interval").Map(Double.Parse), Double.Parse(dict["strength"])))); } catch (Exception e) { return(Left(e)); } } else if (parts.Contains("stop")) { return(Right <VibrateCommand>(new VibrateStop())); } else { return(Right <VibrateCommand>(new VibrateNone())); } }
private void AssignDefaultUnitDescription(Arr <ISymbolInfo> symbolInfos) { if (Description.IsntAString() || Unit.IsntAString()) { var reversed = symbolInfos .Filter(si => si.Comment.IsAString() || si.Unit.IsAString()) .Rev(); var symbolInfo = reversed.Find(si => si.Symbol == Name); if (symbolInfo.IsNone) { // not found so look for symbol with single character prefix e.g. Rsymbol or dsymbol symbolInfo = reversed.Find( si => si.Symbol?.Length == Name.Length + 1 && si.Symbol.EndsWith(Name, StringComparison.InvariantCulture) ); } if (symbolInfo.IsNone) { var re = new Regex($"^\\w?{Name}\\W*=[^=]"); symbolInfo = reversed.Filter(si => si.Code.IsAString()).Find(si => re.IsMatch(si.Code !)); } symbolInfo.IfSome(si => { Description ??= si.Comment; Unit ??= si.Unit; }); } }
public static Arr <ParameterCandidate> CreateForExec(ISymbolInfo formal, Arr <ISymbolInfo> symbolInfos) { RequireTrue(formal.Value?.NColumns > 0); RequireTrue(formal.Value.NRows == 1); var parameterCandidates = formal.Value.NumDataColumns .Map(ndc => new ParameterCandidate(ndc.Name, ndc[0])) .OrderBy(pc => pc.Name) .ToArr(); foreach (var parameterCandidate in parameterCandidates) { if (parameterCandidate.Description.IsntAString() || parameterCandidate.Unit.IsntAString()) { var labelled = symbolInfos.Filter(si => si.Comment.IsAString() || si.Unit.IsAString()); var symbolInfo = labelled.Find(si => si.Symbol == parameterCandidate.Name); if (symbolInfo.IsNone) { var re = new Regex($"^{parameterCandidate.Name}\\W*=[^=]"); symbolInfo = labelled.Filter(si => si.Code.IsAString()).Find(si => re.IsMatch(si.Code !)); } symbolInfo.IfSome(si => { parameterCandidate.Description ??= si.Comment; parameterCandidate.Unit ??= si.Unit; }); } } return(parameterCandidates); }
/// <summary> /// 获取指定基类的所有子类的名称。 /// </summary> /// <param name="typeBase">基类类型。</param> /// <returns>指定基类的所有子类的名称。</returns> internal static string[] GetSubTypeNames(this Type typeBase) { var assembiles = Arr.Filter(AppDomain.CurrentDomain.GetAssemblies(), InspectorTool.TestCheckInAssembiles); List <string> typeNames = new List <string>(); foreach (var assembly in assembiles) { if (assembly == null) { continue; } Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.IsClass && !type.IsAbstract && typeBase.IsAssignableFrom(type)) { typeNames.Add(type.FullName); } } } typeNames.Sort(); return(typeNames.ToArray()); }
public void TestFilterIEnumerable() { var actual = Arr.Filter( new List <string>(foobar), (f) => f == "foo"); CollectionAssert.AreEqual(foo, actual); }
public TraceViewModel( IAppState appState, IAppService appService, IAppSettings appSettings, Arr <ParameterViewModel> parameterViewModels, ModuleState moduleState, OutputGroupStore outputGroupStore ) { RequireNotNull(SynchronizationContext.Current); _appState = appState; _appService = appService; _parameterViewModels = parameterViewModels; _moduleState = moduleState; _outputGroupStore = outputGroupStore; _simulation = appState.Target.AssertSome("No simulation"); TraceDataPlotViewModels = Range(1, ModuleState.N_TRACES) .Map(i => new TraceDataPlotViewModel( appState, appService, appSettings, moduleState.TraceDataPlotStates[i - 1] ) ) .ToArr <ITraceDataPlotViewModel>(); var nTracesVisible = _moduleState.TraceDataPlotStates.Count(s => s.IsVisible); ChartGridLayout = nTracesVisible - 1; WorkingSet = new ObservableCollection <IParameterViewModel>( parameterViewModels.Filter(vm => vm.IsSelected) ); UndoWorkingChange = ReactiveCommand.Create( HandleUndoWorkingChange, this.WhenAny(vm => vm.SessionEdits, _ => SessionEdits.Count > 1) ); PlotWorkingChanges = ReactiveCommand.Create( HandlePlotWorkingChanges, this.WhenAny(vm => vm.HasPendingWorkingChanges, _ => HasPendingWorkingChanges) ); _isWorkingSetPanelOpen = _moduleState.TraceState.IsWorkingSetPanelOpen ? 0 : -1; var(ms, _) = _appState.SimData .GetExecutionInterval(_simulation) .IfNone((304, default));
/// <summary> /// Propagates a decision on a literal to all rules watching the literal. /// </summary> /// <remarks> /// If a decision, e.g. +A has been made, then all rules containing -A, e.g. /// (-A|+B|+C) now need to satisfy at least one of the other literals, so /// that the rule as a whole becomes true, since with +A applied the rule /// is now (false|+B|+C) so essentially (+B|+C). /// This means that all rules watching the literal -A need to be updated to /// watch 2 other literals which can still be satisfied instead. So literals /// that conflict with previously made decisions are not an option. /// Alternatively it can occur that a unit clause results: e.g. if in the /// above example the rule was (-A|+B), then A turning true means that /// B must now be decided true as well. /// </remarks> /// <param name="decidedLiteral">The literal which was decided.</param> /// <param name="level">The level at which the decision took place and at which all resulting decisions should be made.</param> /// <param name="decisions">Used to check previous decisions and to register decisions resulting from propagation.</param> /// <returns>If a conflict is found the conflicting rule is returned.</returns> public Rule PropagateLiteral(int decidedLiteral, int level, Decisions decisions) { // we invert the decided literal here, example: // A was decided => (-A|B) now requires B to be true, so we look for // rules which are fulfilled by -A, rather than A. // This means finding out the conflicts or requires. var literal = -decidedLiteral; if (!watchChains.TryGetValue(literal, out LinkedList <RuleWatchNode> chain)) { return(null); } foreach (var node in chain.ToArray()) { var otherWatch = node.GetOtherWatch(literal); if (!node.GetRule().Enable || decisions.IsSatisfy(otherWatch)) { continue; } var ruleLiterals = node.GetRule().GetLiterals(); var alternativeLiterals = Arr.Filter(ruleLiterals, (ruleLiteral) => { // Guaranteed selection decision is not at the same time // as Watch1 and Watch2, guaranteeing no conflict. return(literal != ruleLiteral && otherWatch != ruleLiteral && !decisions.IsConflict(ruleLiteral)); }); if (alternativeLiterals.Length > 0) { var toLiteral = alternativeLiterals[0]; if (!watchChains.TryGetValue(toLiteral, out LinkedList <RuleWatchNode> toChain)) { watchChains[toLiteral] = toChain = new LinkedList <RuleWatchNode>(); } node.MoveWatch(literal, toLiteral); chain.Remove(node); toChain.AddFirst(node); continue; } if (decisions.IsConflict(otherWatch)) { return(node.GetRule()); } decisions.Decide(otherWatch, level, node.GetRule()); } return(null); }
public void TestFilterExpected() { var result = Arr.Filter(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, (i) => i % 2 == 0, false); Assert.AreEqual(1, result[0]); Assert.AreEqual(3, result[1]); Assert.AreEqual(5, result[2]); Assert.AreEqual(7, result[3]); Assert.AreEqual(9, result[4]); Assert.AreEqual(5, result.Length); }
public void TestFilter() { var result = Arr.Filter(new [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, (i) => i % 2 == 0); Assert.AreEqual(2, result[0]); Assert.AreEqual(4, result[1]); Assert.AreEqual(6, result[2]); Assert.AreEqual(8, result[3]); Assert.AreEqual(0, result[4]); Assert.AreEqual(5, result.Length); }
internal ParametersViewModel(Arr <ParameterViewModel> viewModels) { UnselectedParameters = new ObservableCollection <IParameterViewModel>( viewModels.Filter(vm => !vm.IsSelected) ); SelectedParameters = new ObservableCollection <IParameterViewModel>( viewModels.Filter(vm => vm.IsSelected) ); var disposables = viewModels.Map( p => p .ObservableForProperty(vm => vm.IsSelected) .Subscribe( _ => ObserveParameterViewModelIsSelected(p) ) ); _subscriptions = new CompositeDisposable(disposables); }
/// <summary> /// Processes a file containing exclude rules of different formats per line. /// </summary> /// <param name="lines">A list of lines to be parsed.</param> /// <param name="parser">The parser to be used on each line.</param> /// <returns>Exclude patterns to be used in <see cref="Filter" />.</returns> protected virtual IEnumerable <string> ParseLines(IEnumerable <string> lines, LineParser parser) { string InternalParser(string line) { line = line?.Trim(); if (string.IsNullOrEmpty(line) || line.StartsWith("#", StringComparison.Ordinal)) { return(null); } return(parser(line)); } return(Arr.Filter(Arr.Map(lines, InternalParser), (pattern) => pattern != null)); }
/// <summary> /// 获取GUI支持的服务提供者 /// </summary> /// <returns>编辑器框架</returns> private static void LoadAllServiceProviders(IDictionary <Type, Component> result) { var targetProvider = typeof(IServiceProvider); var targetComponent = typeof(Component); var assembiles = Arr.Filter(AppDomain.CurrentDomain.GetAssemblies(), InspectorTool.TestCheckInAssembiles); foreach (var assembly in assembiles) { foreach (var type in assembly.GetTypes()) { if (targetProvider.IsAssignableFrom(type) && targetComponent.IsAssignableFrom(type)) { result.Add(type, null); } } } }
private static EditorFramework GetEditorFramework() { var target = typeof(EditorFramework); var assembiles = Arr.Filter(AppDomain.CurrentDomain.GetAssemblies(), TestCheckInAssembiles); foreach (var assembly in assembiles) { foreach (var type in assembly.GetTypes()) { if (type != target && target.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract) { return((EditorFramework)Activator.CreateInstance(type)); } } } return(new EditorFramework()); }
public static NestedText GenTypeTagDeserialize(string tagName, Arr <Arg> args) { Text GenArgDeserializer(Arg arg) => arg.Kind.Match( required: _ => GenTypeDeserializer(arg.Type), flags: _ => GenTypeDeserializer(arg.Type), optional: x => Concat( "ReadOption(", Join(", ", new Text[] { Helpers.LowerFirst(x.Flag.ArgName), x.Flag.Bit.ToString() }, arg.Type == TgType.OfPrimitive(PrimitiveType.True) ? None : Some(GenTypeDeserializer(arg.Type)) ), ")" ) ).Apply(s => Concat($"var {Helpers.LowerFirst(arg.Name)} = Read(br, ", s, ");") ); var argsWithoutFlags = args.Filter(x => x.Kind.Match(_: () => true, flags: _ => false)); var body = Scope( args.Map(GenArgDeserializer).Map(Line).Scope(), Line(Concat( $"return new {tagName}(", argsWithoutFlags.Map(x => x.Name).Map(Helpers.LowerFirst).Map(String).Apply(xs => Join(", ", xs)), ");" )) ); var def = Scope( Line($"internal static {tagName} DeserializeTag(BinaryReader br)"), Line("{"), Indent(1, body), Line("}") ); return(def); }
public void TestIsArr() { var assembiles = new string[] { "CatLib.Core", "CatLib.ILRuntime", "CatLib.Route", "Hello.World" }; var checkin = new string[] { "CatLib.*" }; var result = Arr.Filter(assembiles, (assembly) => Str.Is(checkin, assembly)); Assert.AreEqual(3, result.Length); Assert.AreEqual("CatLib.Core", result[0]); Assert.AreEqual("CatLib.ILRuntime", result[1]); Assert.AreEqual("CatLib.Route", result[2]); }
public ChangeDescriptionUnitViewModel(string name, string?description, string?unit, Arr <ISymbolInfo> symbolInfos) { _targetSymbol = name; _description = description; _unit = unit; var choices = symbolInfos .Filter(si => si.Symbol.IsAString() && (si.Comment.IsAString() || si.Unit.IsAString())) .OrderBy(si => si.Symbol); LineSymDescUnit = choices .Select(si => new object?[] { 0 == si.LineNo ? string.Empty : si.LineNo.ToString(InvariantCulture), si.Symbol, si.Comment, si.Unit }) .ToArray(); OK = ReactiveCommand.Create(() => DialogResult = true); Cancel = ReactiveCommand.Create(() => DialogResult = false); }
public void TestIsArray() { var actual = Arr.Filter( new string[] { "CatLib.Core", "CatLib.ILRuntime", "CatLib.Route", "Hello.World", }, (assembly) => Str.Is( new string[] { "CatLib.*", }, assembly)); CollectionAssert.AreEqual( new[] { "CatLib.Core", "CatLib.ILRuntime", "CatLib.Route", }, actual); }
/// <summary> /// Get the last available version. /// </summary> /// <remarks>This means that the highest version that can be rolled back will be obtained.</remarks> /// <returns>The backup file name. exclude <see cref="BackupExtensionName"/>.</returns> protected virtual string GetLastVersionWithBackup(string backupDir, bool desc = true) { var direction = desc ? -1 : 1; var files = fileSystem.GetContents(backupDir).GetFiles(); if (files.Length <= 0) { return(null); } var processedFiles = Arr.Map(files, (file) => { if (string.IsNullOrEmpty(file) || !file.EndsWith(BackupExtensionName, StringComparison.OrdinalIgnoreCase)) { return(null); } return(new { ModifiedTime = fileSystem.GetMetaData(file).LastModified, File = file, }); }); processedFiles = Arr.Filter(processedFiles, (processedFile) => processedFile != null); if (processedFiles.Length <= 0) { return(null); } Array.Sort(processedFiles, (x, y) => x.ModifiedTime < y.ModifiedTime ? -direction : direction); var filename = Path.GetFileName(processedFiles[0].File); return(filename.Substring(0, filename.Length - BackupExtensionName.Length)); }
/// <inheritdoc /> public override void Install(IPackage package, string cwd, bool output) { if (output) { io.WriteError($" - Installing <info>{package.GetName()}</info> (<comment>{package.GetVersionPrettyFull()}</comment>): Extracting archive"); } else { io.WriteError("Extracting archive", false); } fileSystem.Delete(cwd); var temporaryDir = Path.Combine( GetTempDirectory(), "extract", Security.Md5(Guid.NewGuid().ToString()).Substring(0, 7)); var downloadedFilePath = GetDownloadedFilePath(package, cwd); try { FileSystemLocal.EnsureDirectory(temporaryDir); try { Extract(package, downloadedFilePath, temporaryDir); } catch { // remove cache if the file was corrupted. ClearLastCacheWrite(package); throw; } // Expand a single top-level directory for a // better experience. string ExtractSingleDirAtTopLevel(string path) { var contents = fileSystem.GetContents(path); var files = contents.GetFiles(); var dirs = contents.GetDirectories(); files = Arr.Filter(files, (file) => !file.EndsWith(".DS_Store", StringComparison.Ordinal)); if ((dirs.Length + files.Length) != 1 || files.Length == 1) { return(path); } return(ExtractSingleDirAtTopLevel(dirs[0])); } fileSystem.Move(ExtractSingleDirAtTopLevel(temporaryDir), cwd); } catch { fileSystem.Delete(cwd); throw; } finally { fileSystem.Delete(temporaryDir); fileSystem.Delete(downloadedFilePath); } }
/// <inheritdoc /> /// <exception cref="InvalidPackageException">Triggered when validation fails.</exception> public IPackage Load(ConfigBucketBase config, Type expectedClass) { warnings.Clear(); errors.Clear(); // valid package name. if (string.IsNullOrEmpty(config.Name)) { errors.Add("The \"name\" property not allowed to be empty."); } else { var warning = GetPackageNamingDeprecationWarnings(config.Name); if (!string.IsNullOrEmpty(warning)) { warnings.Add(warning); } } // valid version. if (string.IsNullOrEmpty(config.Version)) { errors.Add("The \"version\" property not allowed to be empty."); } else { try { versionParser.Normalize(config.Version); } #pragma warning disable CA1031 catch (System.Exception ex) #pragma warning restore CA1031 { errors.Add($"Property \"version\" is invalid value ({config.Version}): {ex.Message}."); config.Version = null; config.VersionNormalized = null; } } // valid type. if (!string.IsNullOrEmpty(config.PackageType) && !ValidateRegex(config.PackageType, "type", "[A-Za-z0-9-]+")) { config.PackageType = null; } // valid authors. config.Authors = Arr.Filter(config.Authors ?? Array.Empty <ConfigAuthor>(), (author) => { if (!string.IsNullOrEmpty(author.Email) && !ValidateEmail(author.Email, $"Authors {author.Name}")) { author.Email = null; } return(!string.IsNullOrEmpty(author.Name)); }); // valid support. config.Support = Arr.Filter(config.Support, (support) => { var legal = new[] { "email", "issues", "forum", "source", "docs", "wiki" }; var channel = support.Key; if (!Array.Exists(legal, (item) => item == channel)) { warnings.Add($"Property \"{channel}\" is invalid, please use: {string.Join(", ", legal)}"); return(false); } if (channel == "email" && !ValidateEmail(support.Value, "Support")) { return(false); } return(true); }).ToDictionary(item => item.Key, item => item.Value); // valid link. IDictionary <string, string> ValidateLinks(IDictionary <string, string> collection, string linkType) { return(Arr.Filter(collection, (require) => { return ValidateLink(require.Key, require.Value, linkType); }).ToDictionary(item => item.Key, item => item.Value)); } config.Requires = ValidateLinks(config.Requires, "require"); config.RequiresDev = ValidateLinks(config.RequiresDev, "require-dev"); config.Replaces = ValidateLinks(config.Replaces, "replace"); config.Provides = ValidateLinks(config.Provides, "provide"); config.Conflicts = ValidateLinks(config.Conflicts, "conflict"); if (errors.Count > 0) { throw new InvalidPackageException(errors.ToArray(), warnings.ToArray(), config); } return(loader.Load(config, expectedClass)); }
public void TestFilterExpected() { var actual = Arr.Filter(foobar, (f) => f == "foo", false); CollectionAssert.AreEqual(bar, actual); }
public void TestFilter() { var actual = Arr.Filter(foobar, (f) => f == "foo"); CollectionAssert.AreEqual(foo, actual); }