static void ParseInput() { n = int.Parse(Console.ReadLine()); stationsInfo = Regex.Matches( ("0 --> " + Console.ReadLine()).Replace(" --> ", "►"), "([^►]+)►([^►]+)" ).Cast<Match>() .Select(match => new KeyValuePair<string, int>( match.Groups[2].Value, int.Parse(match.Groups[1].Value) ) ).ToArray(); int id = 0; stationsByName = stationsInfo.ToDictionary( info => info.Key, info => id++ ); stationsByIndex = stationsByName.ToDictionary( kvp => kvp.Value, kvp => kvp.Key ); var separator = new string[] { " | " }; camerasInfo = Enumerable.Range(0, int.Parse(Console.ReadLine())) .Select(_ => Console.ReadLine()) .Select(line => line.Split(separator, StringSplitOptions.None)) .Select(match => new Tuple<DateTime, int, int, int, char>( DateTime.ParseExact(match[0], DateFormat, CultureInfo.InvariantCulture), stationsByName[match[1]], int.Parse(match[2]), int.Parse(match[3]), match[4][0] ) ).ToArray(); trainCapacity = int.Parse(Console.ReadLine()); #if DEBUG //Console.WriteLine("# INPUT"); //Console.WriteLine(string.Join(Environment.NewLine, stationsInfo)); //Console.WriteLine(); //Console.WriteLine(string.Join(Environment.NewLine, camerasInfo)); //Console.WriteLine(); //Console.WriteLine(trainCapacity); //Console.WriteLine(); #endif }
private Font(int height, Dictionary<char, byte[]> characters) { Height = height; this.characters = characters.ToDictionary( keyValue => keyValue.Key, keyValue => new Character(keyValue.Value, height)); }
public async Task<IDictionary<string, Result>> GetBatchSentimentAsync(Dictionary<string, string> textBatch) { ValidateBatchRequest(textBatch); if (!textBatch.Any()) { return new Dictionary<string, Result>(); } string content; using (var response = await _requestor.PostAsync(Constants.SentimentBatchRequest, BuildInputString(textBatch))) { content = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return textBatch.ToDictionary(r => r.Key, r => AzureMachineLearningResult.Build(_errorMessageGenerator.GenerateError(response.StatusCode, content))); } } var result = JsonConvert.DeserializeObject<SentimentBatchResult>(content); var parsedResults = result.SentimentBatch.ToDictionary(sr => sr.Id, sr => AzureMachineLearningResult.Build(sr.Score, ScoreToSentiment(sr.Score))); foreach (var error in result.Errors) { parsedResults.Add(error.Id, AzureMachineLearningResult.Build(error.Message)); } return parsedResults; }
public Dictionary<SportType, Dictionary<GameInfo, List<Game>>> GroupGamesByGameInfo( Dictionary<SportType, List<Game>> games) { return games.ToDictionary( gamesOfSport => gamesOfSport.Key, gamesOfSport => { var resultDict = new Dictionary<GameInfo, List<Game>>(); for (var i = 0; i < gamesOfSport.Value.Count; i++) { if (resultDict.Keys.All(info => info != gamesOfSport.Value[i].Info)) { var tempList = new List<Game> { gamesOfSport.Value[i] }; for (var j = i + 1; j < gamesOfSport.Value.Count; j++) { if (gamesOfSport.Value[i].BetsName != gamesOfSport.Value[j].BetsName & gamesOfSport.Value[i].Info == gamesOfSport.Value[j].Info) { tempList.Add(gamesOfSport.Value[j]); } } resultDict.Add(gamesOfSport.Value[i].Info, tempList); } } return resultDict.Where(x => x.Value.Count > 1).ToDictionary(t => t.Key, t => t.Value); }); }
private static IDictionary<string, QiMethod> GetMethods(QiObject qiObj) { //観察事実としてmObjは4要素タプルであり、第0要素にメソッド一覧が入ってる var mObj = qiObj.MetaObject; if (mObj.Count == 0) { throw new InvalidOperationException("meta object does not contains info"); } var qKeys = mObj[0].GetKeys(); var methodInfos = Enumerable .Range(0, qKeys.Count) .Select(i => qKeys[i]) .Select(k => new QiMethodInfo(mObj[0][k])); var methodOverloads = new Dictionary<string, List<QiMethodInfo>>(); foreach (var mi in methodInfos) { if (methodOverloads.ContainsKey(mi.Name)) { methodOverloads[mi.Name].Add(mi); } else { methodOverloads[mi.Name] = new List<QiMethodInfo>() { mi }; } } return methodOverloads.ToDictionary( p => p.Key, p => new QiMethod(qiObj, p.Value) ); }
public void IndependentMovements() { /* take a grid and populate with organisms: |___|_A_|___|_B_|___|___|___|___|___|___| * make A choose rightmost stimulus & make B choose leftmost stimulus * no conflict, both organisms should move where they chose to go * result of test: |_A_|___|___|___|_B_|___|___|___|___|___| */ var organismHabitats = new Dictionary<Organism, Habitat> { { this.organisms["A"], this.habitats[1, 0] }, { this.organisms["B"], this.habitats[3, 0] } }; var organismIntendedDestinations = new Dictionary<Organism, Habitat> { { this.organisms["A"], this.habitats[0, 0] }, { this.organisms["B"], this.habitats[4, 0] } }; var expectedOrganismDestinations = organismIntendedDestinations.ToDictionary( intendedDestination => intendedDestination.Key, intendedDestination => intendedDestination.Value); var updateSummary = this.CreateAndUpdateEcosystem(organismHabitats, organismIntendedDestinations); var expectedCoordinates = expectedOrganismDestinations.Values.Select(expectedDestination => this.habitatCoordinates[expectedDestination]).ToList(); var actualCoordinates = updateSummary.PostUpdateOrganismLocations.Values.ToList(); Assert.That(actualCoordinates, Is.EqualTo(expectedCoordinates)); }
/// <summary> /// Initializes a new instance of the <see cref="Lexer" /> class. /// </summary> public Lexer() { // regex special characters (should be escaped if needed): .$^{[(|)*+?\ var patterns = new Dictionary<TokenType, string> { {TokenType.AND, @"&&"}, {TokenType.OR, @"\|\|"}, {TokenType.LEFT_BRACKET, @"\("}, {TokenType.RIGHT_BRACKET, @"\)"}, {TokenType.GE, @">="}, {TokenType.LE, @"<="}, {TokenType.GT, @">"}, {TokenType.LT, @"<"}, {TokenType.EQ, @"=="}, {TokenType.NEQ, @"!="}, {TokenType.NOT, @"!"}, {TokenType.NULL, @"null"}, {TokenType.COMMA, @","}, {TokenType.INC, @"\+{2}"}, // Despite the fact our language does not support ++ and -- prefix/postfix operations yet, these unary tokens are explicitly designated as illegal. We're detecting them to prevent unification which is done for consecutive plus or minus operators (e.g. + + - - +-+- => +). {TokenType.DEC, @"\-{2}"}, // Unification of such unary operators breaks compatibility - such mixed 1++ + 2 operations are illegal in both C# and JavaScript (since we control C# side there is not pain here, but JavaScript would fail since we're sending raw expressions to client-side). {TokenType.ADD, @"\+"}, {TokenType.SUB, @"-"}, {TokenType.MUL, @"\*"}, {TokenType.DIV, @"/"}, {TokenType.FLOAT, @"[0-9]*\.[0-9]+(?:[eE][\+-]?[0-9]+)?"}, // 1.0, 0.3e-2 {TokenType.INT, @"[0-9]+"}, {TokenType.BOOL, @"(?:true|false)"}, {TokenType.STRING, @"(['])(?:\\\1|.)*?\1"}, // '1234', 'John\'s cat' {TokenType.FUNC, @"[a-zA-Z_]+(?:(?:(?:\[[0-9]+\])?\.[a-zA-Z_])?[a-zA-Z0-9_]*)*(?:\[[0-9]+\])?"} // field, field.field, arr[0], func(...) }; RegexMap = patterns.ToDictionary( kvp => kvp.Key, kvp => new Regex(string.Format("^{0}", kvp.Value))); // in general, for compiled version of regular expressions their construction and initialization time is amortized out over many runs }
public async Task<Dictionary<string, string>> GenerateTextWithKey(CancellationToken cancellationToken) { var generatedTaskObjects = new Dictionary<string, Task<string>>(); foreach (ExpressionWithSource expressionWithSource in _expressionsWithSources) { Expression expression = expressionWithSource.Expression; ExpressionSourceType source = expressionWithSource.Source; Task<string> generatedTextTask = GenerateTextAsync(expression, source, cancellationToken); string expressionNameResolvedDuplicates; if (generatedTaskObjects.Keys.Contains(expression.Name)) { int count = generatedTaskObjects.Keys.Count(x => x.StartsWith(expression.Name + " (")) + 1; expressionNameResolvedDuplicates = expression.Name + " (" + count + ")"; } else { expressionNameResolvedDuplicates = expression.Name; } generatedTaskObjects.Add(expressionNameResolvedDuplicates, generatedTextTask); } await Task.WhenAll(generatedTaskObjects.Values); Dictionary<string, string> generatedObjects = generatedTaskObjects.ToDictionary(x => x.Key, y => y.Value.Result); return generatedObjects; }
public static void SomeFunction() { Dictionary<int, int> dict = new Dictionary<int, int>(); dict.Add(4, 3); Console.WriteLine(dict[4]); Console.WriteLine(dict.ContainsKey(8)); dict.Remove(4); foreach(int key in dict.Keys) Console.WriteLine(key); foreach(int val in dict.Values) Console.WriteLine(val); foreach(var kv in dict) Console.WriteLine(kv.Key + " " + kv.Value); var dict2 = dict.ToDictionary(o => o.Key, o => o.Value); var vals = dict.Values; HashSet<int> hash = new HashSet<int>(); hash.Add(999); Console.WriteLine(hash.Contains(999)); hash.Remove(999); Console.WriteLine(hash.Contains(999)); foreach(int hashItem in hash) Console.WriteLine(hashItem); var z = hash.Select(o => 3).ToArray(); var g = hash.GroupBy(o => o).Select(o => o.Count()).Min(); }
public void FiltrateFighters() { var pretendents = new Dictionary<string, int>(); foreach (var e in Fighters) if (!pretendents.ContainsKey(e.Item1)) pretendents[e.Item1] = 0; var temp = pretendents.ToDictionary(x => x.Key, y => y.Value); foreach (var e in temp) { try { var process = new Process(); process.StartInfo.FileName = "Checkers.Tournament.exe"; process.StartInfo.Arguments = e.Key + " " + "testPlayer.dll"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.CreateNoWindow = true; process.Start(); var winner = process.StandardOutput.ReadLine()[0]; if (winner == 'W') pretendents[e.Key]++; } catch { pretendents[e.Key] = -10; } } Fighters = Fighters.Where(x => pretendents.ContainsKey(x.Item1) && pretendents.ContainsKey(x.Item2)) .ToList(); //добавить ограничение по победам // фильтруем некорректные дллс }
public BookPurchaseInfo BookPurchaseInfo(string totalBudget, Dictionary<string, string> purchaseBook) { BookPurchaseInfo thisPurchaseInfo = new BookPurchaseInfo(); if (String.IsNullOrWhiteSpace(totalBudget)) { throw new NullReferenceException("Input field(s) is empty."); } else { try { thisPurchaseInfo.budget = float.Parse(totalBudget); thisPurchaseInfo.items = purchaseBook.ToDictionary( x => int.Parse(x.Key), x => int.Parse(x.Value) ); } catch (Exception Ex) { throw new Exception(Ex.Message); } } return thisPurchaseInfo; }
public HistoryTickerStream(Dictionary<string, List<CandleDataBidAsk>> quotes) { this.quotes = quotes; if (quotes.Count == 0) return; currentIndex = quotes.ToDictionary(q => q.Key, q => 0); timeNow = quotes.Select(q => q.Value.Count == 0 ? DateTime.MaxValue : q.Value[0].timeClose).Min(); }
internal override void Prepare() { Contract.Requires(!String.IsNullOrWhiteSpace(Database)); Contract.Requires(!String.IsNullOrWhiteSpace(Username)); var parameters = new Dictionary<String, String> { { "database", Database }, { "user", Username }, { "client_encoding", "UTF8" }, }; if (ApplicationName != null) { parameters.Add("application_name", ApplicationName); } if (SearchPath != null) { parameters.Add("search_path", SearchPath); } // TODO: Is this really UTF8 or can be ASCII? _parameters = parameters.ToDictionary(kv => PGUtil.UTF8Encoding.GetBytes(kv.Key), kv => PGUtil.UTF8Encoding.GetBytes(kv.Value)); _length = 4 + // len 4 + // protocol version _parameters.Select(kv => kv.Key.Length + kv.Value.Length + 2).Sum() + 1; // trailing zero byte }
public static Dictionary<string, List<SmallRNASequence>> ConvertFrom(List<ChromosomeCountSlimItem> items) { var result = new Dictionary<string, Dictionary<string, SmallRNASequence>>(); foreach (var c in items) { foreach (var q in c.Queries) { Dictionary<string, SmallRNASequence> seqList; if (!result.TryGetValue(q.Sample, out seqList)) { seqList = new Dictionary<string, SmallRNASequence>(); result[q.Sample] = seqList; } if (!seqList.ContainsKey(q.Sequence)) { seqList[q.Sequence] = new SmallRNASequence() { Sample = q.Sample, Sequence = q.Sequence, Count = q.QueryCount }; } } } return result.ToDictionary(l => l.Key, l => l.Value.Values.ToList()); }
/// <summary> /// A method for loading humans annotations from textual annotation files /// </summary> /// <param name="annotationsPath">Path to the file containing annotations</param> /// <param name="codingsPath">Path to the file in which it is coded which annotation corresponds to a simplification of which system</param> /// <param name="meaningPreservation">Flag that indicates if the annotations are for simplicity/grammaticality or meaning preservation (different format)</param> /// <returns>A dictionary containin annotations for simplifications of all systems being evaluated. Key is the identifier of the system (Biran et al.'s 2011 system, our system, human simplifications)</returns> public static Dictionary<string, double> EvaluateHuman(string annotationsPath, string codingsPath, bool meaningPreservation = false) { AllAnnotatorScores = new List<double>(); var codings = TakeLab.Utilities.IO.StringLoader.LoadDictionaryStrings(codingsPath); var annotationLines = (new StreamReader(annotationsPath)).ReadToEnd().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList(); var index = 0; if (meaningPreservation) { annotationLines = annotationLines.Where(x => x.StartsWith("Simplified")).ToList(); index++; } Dictionary<string, List<double>> systemScores = new Dictionary<string, List<double>>(); annotationLines.ForEach(l => { var spl = l.Split(); var system = codings[spl[index]]; if (!systemScores.ContainsKey(system)) systemScores.Add(system, new List<double>()); var score = Double.Parse(spl[index + 1]); systemScores[system].Add(score); AllAnnotatorScores.Add(score); }); return systemScores.ToDictionary(x => x.Key, x => x.Value.Average()); }
public async Task<bool> IdentifyCustomer(string customerId, string email, DateTime? dateCreatedUtc = null, Dictionary<string, string> extraData = null) { if (string.IsNullOrWhiteSpace(customerId)) throw new ArgumentNullException("customerId may not be null or empty"); if (string.IsNullOrWhiteSpace(email)) throw new ArgumentNullException("email may not be null or empty"); var request = new HttpRequestMessage(HttpMethod.Put, new Uri(ApiUrl + customerId)); request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", SiteId, ApiKey)))); var dict = extraData == null ? new Dictionary<string, string>() : extraData.ToDictionary(d => d.Key, d => d.Value); if (dict.ContainsKey("email")) { throw new ArgumentOutOfRangeException("extraData may not contain a key called 'email'"); } dict.Add("email", email); dict.Add("created_at", dateCreatedUtc != null ? DateTimeToUnixTimestamp(dateCreatedUtc.Value).ToString("####") : DateTimeToUnixTimestamp(DateTime.UtcNow).ToString("####")); request.Content = new FormUrlEncodedContent(dict); var response = await Client.SendAsync(request).ConfigureAwait(false); return ProcessResponseAsync(response); }
private InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs, InputState prev) { Mouse = ms; Keyboard = ks; TouchPanel = ts; GamePad = gs; if (Mouse.LeftButton == ButtonState.Pressed) { IsDown = true; PointerPosition = adapter.PointToScreen(Mouse.Position); } else if (TouchPanel.Count > 0) { IsDown = true; PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint()); } else { IsDown = false; PointerPosition = prev.PointerPosition; } IsJustDown = IsDown && !prev.IsDown; IsJustUp = !IsDown && prev.IsDown; lastKeyState = prev.currentKeyState; currentKeyState = lastKeyState.ToDictionary(p => p.Key, p => ks.IsKeyDown(p.Key)); }
public void Execute() { TypeModel model = RuntimeTypeModel.Default; using (var ms = new MemoryStream()) { var tagToType = new Dictionary<int, Type> { {1, typeof(B)}, {2, typeof(C)} }; var typeToTag = tagToType.ToDictionary(pair => pair.Value, pair => pair.Key); object b = new B { Y = 2 }; object c = new C { Y = 4 }; // in v1, comparable to Serializer.NonGeneric.SerializeWithLengthPrefix(ms, b, PrefixStyle.Base128, typeToTag[b.GetType()]); model.SerializeWithLengthPrefix(ms, b, null, PrefixStyle.Base128, typeToTag[b.GetType()]); model.SerializeWithLengthPrefix(ms, c, null, PrefixStyle.Base128, typeToTag[c.GetType()]); ms.Position = 0; // in v1, comparable to Serializer.NonGeneric.TryDeserializeWithLengthPrefix(ms, PrefixStyle.Base128, key => tagToType[key], out b2); object b2 = model.DeserializeWithLengthPrefix(ms, null, null, PrefixStyle.Base128, 0, key => tagToType[key]); object c2 = model.DeserializeWithLengthPrefix(ms, null, null, PrefixStyle.Base128, 0, key => tagToType[key]); Assert.AreEqual(((B)b).Y, ((B)b2).Y); Assert.AreEqual(((C)c).Y, ((C)c2).Y); } }
public Translation Translate(Expression expression) { var queryVisitor = new QueryParser(); // parameters are indexed by value to ease reusing params by value var parameters = new Dictionary<object, string>(); queryVisitor.Visit(expression); var selectSql = new StringBuilder(); if (queryVisitor.Select != null) new SqlCodeGenerator(selectSql, parameters).Visit(queryVisitor.Select); var whereSql = new StringBuilder(); if (queryVisitor.Where != null) new SqlCodeGenerator(whereSql, parameters).Visit(queryVisitor.Where); var orderBySql = new StringBuilder(); if (queryVisitor.OrderBy != null) new SqlCodeGenerator(orderBySql, parameters).Visit(queryVisitor.OrderBy); return new Translation { Select = selectSql.ToString(), Where = whereSql.ToString(), OrderBy = orderBySql.ToString(), Skip = queryVisitor.Skip, Take = queryVisitor.Take, ProjectAs = queryVisitor.ProjectAs, Parameters = parameters.ToDictionary(x => x.Value, x => x.Key), ExecutionMethod = queryVisitor.Execution }; }
public SimpleAppClient(IRequester requester, Dictionary<Type, object> services) : base(requester) { foreach (var pair in services) { Type iface = pair.Key; if (iface == null) { throw new ApplicationException(); // todo2[ak] } if (!iface.IsInterface) { throw new ApplicationException(); // todo2[ak] } object instance = pair.Value; if (instance == null) { throw new ApplicationException(); // todo2[ak] } if (!iface.IsAssignableFrom(instance.GetType())) { throw new ApplicationException(); // todo2[ak] } } _proxies = services.ToDictionary( pair => pair.Key.FullName, pair => new Tuple<Type, object>(pair.Key, pair.Value)); }
public static IReadOnlyDictionary <String, IReadOnlyList <TInto> > SetSymbol <TInto, TFrom>( this Dictionary <String, List <TFrom>?>?dictionary) where TFrom : TInto, ISymbolMutable => dictionary?.ToDictionary( _ => _.Key, _ => _.Value.SetSymbol(_.Key).EmptyIfNull <TInto, TFrom>(), StringComparer.Ordinal) ?? new Dictionary <String, IReadOnlyList <TInto> >(StringComparer.Ordinal);
static AsmHelper() { _registersIds = REGISTERS.ToDictionary( s => s.Split(':')[1].Trim(), s => (RegisterName)Enum.Parse(typeof(RegisterName), s.Split(':')[0].Trim())); _registerCaptions = _registersIds.ToDictionary(p => p.Value, p => p.Key); }
public EmbeddedResourceManager(IEmbeddedResourceBuilder builder, IWebContext webContext) { _assemblyPathPrefixes = builder.ResourceSettings.AssemblyPathPrefixes; _reverseAssemblyPathPrefixes = _assemblyPathPrefixes.ToDictionary(kvp => kvp.Value, kvp => kvp.Key); _clientResourcePrefixes = builder.ResourceSettings.ClientResourcePrefixes; _files = new Dictionary<string, EmbeddedResourceVirtualFile>(); _webContext = webContext; }
public HttpRemoteResponse(HttpStatusCode statusCode, Dictionary<string, string> headers, string content) { if (headers == null) throw new ArgumentNullException("headers"); StatusCode = statusCode; Headers = headers.ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase); // make a copy for better comparisons Content = content; }
private TpProfilerStatistics(Dictionary<ProfilerTarget, string> data) { _data = data.ToDictionary(x => x.Key, x => new TpProfilerStatisticRecord { Target = x.Key, Name = x.Key.GetDescription(), Data = x.Value }); }
/// <param name="confidences"></param> /// <returns>message.ID -> (Topic.ID, Topic.Confidence)</returns> public static Dictionary<long, TopicIdAndConfidenceInItTuple[]> CleanConfidences(Dictionary<long, double[]> confidences) { var q = confidences.ToDictionary(k => k.Key, k => k.Value .Select((a,i) => Tuple.Create(i,a)) .OrderByDescending(d => d.Item2) .Take(3) .ToArray()); return q; }
public DeploymentExecutionDefinition( string packageId, string targetDirectoryPath, MayBe <SemanticVersion> semanticVersion, string nuGetConfigFile = null, string nuGetPackageSource = null, string iisSiteName = null, bool isPreRelease = false, bool force = false, string environmentConfig = null, string publishSettingsFile = null, Dictionary <string, string[]> parameters = null, string excludedFilePatterns = null, bool requireEnvironmentConfig = false, string webConfigTransformFile = null, string publishType = null, string ftpPath = null, string nugetExePath = null, string packageListPrefix = null, bool?packageListPrefixEnabled = null) { SemanticVersion = semanticVersion ?? MayBe <SemanticVersion> .Nothing; if (string.IsNullOrWhiteSpace(packageId)) { throw new ArgumentNullException(nameof(packageId)); } ExcludedFilePatterns = excludedFilePatterns?.Split(';').ToImmutableArray() ?? ImmutableArray <string> .Empty; PackageId = packageId; TargetDirectoryPath = targetDirectoryPath; NuGetConfigFile = nuGetConfigFile; NuGetPackageSource = nuGetPackageSource; IisSiteName = iisSiteName; IsPreRelease = SemanticVersion?.IsPrerelease ?? isPreRelease; Force = force; EnvironmentConfig = environmentConfig; PublishSettingsFile = publishSettingsFile; RequireEnvironmentConfig = requireEnvironmentConfig; WebConfigTransformFile = webConfigTransformFile; Parameters = parameters?.ToDictionary(pair => pair.Key, pair => new StringValues(pair.Value ?? Array.Empty <string>())) .ToImmutableDictionary() ?? ImmutableDictionary <string, StringValues> .Empty; _ = PublishType.TryParseOrDefault(publishType, out PublishType publishTypeValue); _ = FtpPath.TryParse(ftpPath, FileSystemType.Directory, out FtpPath path); FtpPath = path; PublishType = publishTypeValue; ExcludedFilePatternsCombined = excludedFilePatterns; NuGetExePath = nugetExePath; PackageListPrefix = packageListPrefix; PackageListPrefixEnabled = packageListPrefixEnabled; }
public ActionMapper() { actionHandlerTypes = Assembly.GetEntryAssembly()?.GetTypes() .Where(t => typeof(ActionHandlerBase).IsAssignableFrom(t) && t.Name.EndsWith("Actions")) .ToDictionary(t => t.Name.Substring(0, t.Name.LastIndexOf("Actions", StringComparison.Ordinal)).ToCamelCase(), t => t); actionHandlerActions = actionHandlerTypes?.ToDictionary(t => t.Value, t => t.Value.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)); }
public string Encrypt(string text, Dictionary<string, string> publicKeyIdAndPublicKeyMap, out Dictionary<string, string> publicKeyIdAndEncryptedKeyMap) { Dictionary<string, byte[]> publicKeyIdAndEncryptedKeyMapByted; var result = Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text), publicKeyIdAndPublicKeyMap.ToDictionary(i => i.Key, i => Convert.FromBase64String(i.Value)), out publicKeyIdAndEncryptedKeyMapByted)); publicKeyIdAndEncryptedKeyMap = publicKeyIdAndEncryptedKeyMapByted.ToDictionary(i => i.Key, i => Convert.ToBase64String(i.Value)); return result; }
private ProfilerStatistics(Dictionary<ProfilerTarget, string> data) { _data = data.ToDictionary(x => x.Key, x => new TpProfilerStatisticRecord { Target = x.Key, Name = x.Key.GetMetadata<ProfilerTarget, HttpHeaderAttribute>(), Data = x.Value }); }
public ProductCategoryObject( Dictionary <string, string> singleProperties , Dictionary <string, string[]> pluralProperties = null , bool isCategory = false) { SingleProperties = singleProperties.ToDictionary(x => x.Key, x => x.Value); PluralProperties = pluralProperties?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary <string, string[]>(); IsCategory = isCategory; }
static ScriptEngineFactory() { languageType = Assembly.GetExecutingAssembly() .GetTypes() .Where(x => x.IsClass && !x.IsAbstract && typeof(ScriptEngineBase).IsAssignableFrom(x)) .ToDictionary(x => ((LanguageAttribute)x.GetCustomAttributes(typeof(LanguageAttribute), true).First()).Language); languageExtensions = languageType.ToDictionary( x => ((AllowedExtensionAttribute)x.Value .GetCustomAttributes(typeof(AllowedExtensionAttribute), true) .Single()) .Extension, x => x.Key); languageSyntaxHighlighting = languageType.ToDictionary( x => x.Key, x => GetSyntaxHighlighting(x.Key)); languageExampleScript = languageType.ToDictionary( x => x.Key, x => GetExampleScript(x.Key)); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var dict = new Dictionary<string, Dictionary<string, Dictionary<string, IndexSettings>>>(); serializer.Populate(reader, dict); var response = new IndexSettingsResponse(); if (!dict.HasAny() || !dict.First().Value.HasAny() || !dict.First().Value.First().Value.HasAny()) return response; response.Nodes = dict.ToDictionary(k => k.Key, v => v.Value.First().Value.First().Value); return response; }
public Dictionary<string, decimal> GetPromoted( Dictionary<string, int> boughtDictionary) { return boughtDictionary.ToDictionary(bd => bd.Key, bd => promotionBarcodes.Contains(bd.Key) ? bd.Value/3* productRepository.GetByBarcodes(bd.Key).First().Price : 0); }
/// <param name="operationId"> /// Lookup operation ID, use swagger operation ID of action to call /// </param> /// <param name="parameters"> /// Parameter value to pass to operation /// Dictionary key - parameter name in lookup operation /// Dictionary value - property from object, returned by lookup operation, /// whose value will be used /// if null - don't generate parameters section in swagger /// </param> public FilePickerOperationModel(string operationId, Dictionary <string, string> parameters) { //no operation - dont create parameters if (string.IsNullOrEmpty(operationId)) { return; } OperationId = operationId; Parameters = parameters?.ToDictionary(x => x.Key, x => new FilePickerParameterValue(x.Value)); }
public TO_AssetFxModel ToTransportObject() => new TO_AssetFxModel { AssetCurves = _assetCurves?.ToDictionary(x => x.Key, x => x.Value.GetTransportObject()), AssetVols = _assetVols?.ToDictionary(x => x.Key.GetTransportObject(), x => x.Value.GetTransportObject()), BuildDate = BuildDate, CorrelationMatrix = CorrelationMatrix?.GetTransportObject(), Fixings = _fixings?.ToDictionary(x => x.Key, x => x.Value.GetTransportObject()), FundingModel = _fundingModel.GetTransportObject(), Portfolio = _portfolio?.ToTransportObject(), };
/// <summary> /// Log a custom event. /// A custom event log provides insight to system administrators by logging information that may not be captured by other log levels. /// </summary> /// <typeparam name="TEvent">Type of event name</typeparam> /// <typeparam name="TKey">Type of dictionary key</typeparam> /// <param name="logger">The logger</param> /// <param name="event">The information message</param> /// <param name="properties">[Optional] A collection of properties that should be associated to the telemetry entry</param> /// <param name="metrics">[Optional] The metrics</param> /// <param name="correlationId">[Optional] This is used for tracing a series of events. If this is left null then a new ID will be created and returned by this method. Otherwise pass in an ID from a previous logging event</param> /// <param name="callerName">[Optional] source name; set to caller's name if not specified</param> /// <param name="callerPath">[Optional] source path; set to caller's path if not specified</param> /// <param name="callerLineNumber">[Optional] source line number; set to caller's source line number if not specified</param> /// <returns>The correlation Id for this logging event if a value was provided in the method call this will return the value provided otherwise a new Guid will be generated</returns> public static Guid LogEvent <TEvent, TKey>(this ILogProvider logger, TEvent @event, Dictionary <TKey, string> properties = null, Dictionary <TKey, double> metrics = null, Guid?correlationId = null, [CallerMemberName] string callerName = null, [CallerFilePath] string callerPath = null, [CallerLineNumber] int callerLineNumber = 0) where TEvent : struct { return(logger.LogEvent( @event.ToString(), properties?.ToDictionary(kv => kv.Key.ToString(), kv => kv.Value), metrics?.ToDictionary(kv => kv.Key.ToString(), kv => kv.Value), correlationId, callerName, callerPath, callerLineNumber)); }
public static IReadOnlyDictionary <String, IReadOnlyList <TInto> > EmptyIfNull <TInto, TFrom>( this Dictionary <String, List <TFrom>?>?dictionary, Action <String, List <TFrom>?>?transformer = null) where TFrom : TInto => dictionary?.ToDictionary( _ => _.Key, _ => { transformer?.Invoke(_.Key, _.Value); return(_.Value.EmptyIfNull <TInto, TFrom>()); }, StringComparer.Ordinal) ?? new Dictionary <String, IReadOnlyList <TInto> >(StringComparer.Ordinal);
public static HtmlBuilder FieldDropDown( this HtmlBuilder hb, string fieldId = null, string controlId = null, string fieldCss = null, string labelCss = null, string controlContainerCss = null, string controlCss = null, string labelText = null, string labelTitle = null, Dictionary <string, string> optionCollection = null, string selectedValue = null, bool multiple = false, bool addSelectedValue = true, bool insertBlank = false, bool disabled = false, string onChange = null, bool validateRequired = false, string action = null, string method = null, Column column = null, bool _using = true) { return(_using ? hb.Field( fieldId: fieldId, controlId: controlId, fieldCss: fieldCss, labelCss: labelCss, controlContainerCss: controlContainerCss, labelText: labelText, labelTitle: labelTitle, controlAction: () => hb .DropDown( controlId: controlId, controlCss: controlCss, optionCollection: optionCollection?.ToDictionary( o => o.Key, o => new ControlData(o.Value)), selectedValue: selectedValue, multiple: multiple, addSelectedValue: addSelectedValue, insertBlank: insertBlank, disabled: disabled, onChange: onChange, validateRequired: validateRequired, action: action, method: method, column: column)) : hb); }
public ProductCategoryObject( Dictionary <string, string> singleProperties , List <ArgumentObject> subcatalogs , List <ArgumentObject> products , Dictionary <string, string[]> pluralProperties = null , bool isCategory = true) { SingleProperties = singleProperties.ToDictionary(x => x.Key, x => x.Value); PluralProperties = pluralProperties?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary <string, string[]>(); Subcatalogs = subcatalogs.ToList(); Products = products.ToList(); IsCategory = isCategory; }
public AlternaClass(string blockExp, string refProductExp , Dictionary <string, Search <string> > propertiesCategory , Dictionary <string, Search <string> > singlePropertiesProduct, Dictionary <string, Search <string[]> > pluralPropertiesProduct = null, bool debug = true, string url = "") { BlockExp = blockExp; RefProductExp = refProductExp; PropertiesCategory = propertiesCategory.ToDictionary(x => x.Key, x => x.Value); PluralPropertiesProduct = pluralPropertiesProduct?.ToDictionary(x => x.Key, x => x.Value); SinglePropertiesProduct = singlePropertiesProduct.ToDictionary(x => x.Key, x => x.Value); Debug = debug; Url = url; }
public SimpleData SomeClassB; // Classes are automatically implemented in the UI. // See ??? for an example of a class with a CustomUI. // Proper cloning of reference types is required because behind the scenes many instances of ModConfig classes co-exist. public override ModConfig Clone() { // Since ListOfInts is a reference type, we need to clone it manually so our config works properly. var clone = (ModConfigShowcaseDataTypes)base.Clone(); // We use ?. and ?: here because many of these fields can be null. // clone.SomeList = SomeList != null ? new List<int>(SomeList) : null; clone.SomeArray = (int[])SomeArray.Clone(); clone.SomeList = SomeList?.ToList(); clone.SomeDictionary = SomeDictionary?.ToDictionary(i => i.Key, i => i.Value); clone.SomeSet = SomeSet != null ? new HashSet <string>(SomeSet) : null; clone.SomeClassA = SomeClassA == null ? null : new ItemDefinition(SomeClassA.mod, SomeClassA.name); clone.SomeClassB = SomeClassB?.Clone(); return(clone); }
public SirenEntity Build() { SirenEntity entity = new SirenEntity() { Class = _class?.ToArray(), Properties = _properties?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), Entities = _subEntityBuilders?.Select(x => x.Build()).ToArray(), Links = _linkBuilders?.Select(x => x.Build()).ToArray(), Actions = _actionBuilders?.Select(x => x.Build()).ToArray(), Title = _title }; if (entity.Actions != null && new HashSet <string>(entity.Actions.Select(x => x.Name)).Count != entity.Actions.Count) { throw new ArgumentException("Action names MUST be unique within the set of actions for an entity."); } return(entity); }
public async Task <TableResponse> GetAsync(string databaseCode, string datatableCode, Dictionary <string, List <string> > rowFilter = null, List <string> columnFilter = null, string nextCursorId = null, CancellationToken token = default(CancellationToken)) { try { var massagedRowFilters = rowFilter?.ToDictionary(kvp => kvp.Key, kvp => string.Join(",", kvp.Value)); string massagedColumnFilters = columnFilter != null?string.Join(",", columnFilter) : null; return(await $"{Constant.HostUri}/datatables/{databaseCode}/{datatableCode}.json" .SetQueryParamForEach(massagedRowFilters) .SetQueryParam("qopts.columns", massagedColumnFilters) .SetQueryParam("qopts.cursor_id", nextCursorId) .SetQueryParam("api_key", _apiKey) .GetAsync(token) .ReceiveJson <TableResponse>() .ConfigureAwait(false)); } catch (FlurlHttpException ex) { throw await ex.ToQuandlException(); } }
public LiquiMolyClass( Func <HtmlNode, bool> isCategory, Dictionary <string, Search <string> > singlePropertiesProduct, Search <ArgumentObject[]> findSubcatalogs = null, Search <ArgumentObject[]> findProducts = null, Dictionary <string, Search <string[]> > pluralPropertiesProduct = null, Dictionary <string, Search <string[]> > pluralPropertiesCategory = null, Dictionary <string, Search <string> > singlePropertiesCategory = null, Search <ArgumentObject[]> xPathPagination = null, bool debug = true, Encoding encoding = null) { SinglePropertiesProduct = singlePropertiesProduct.ToDictionary(x => x.Key, x => x.Value); SinglePropertiesCategory = singlePropertiesCategory?.ToDictionary(x => x.Key, x => x.Value); PluralPropertiesCategory = pluralPropertiesCategory?.ToDictionary(x => x.Key, x => x.Value); PluralPropertiesProduct = pluralPropertiesProduct?.ToDictionary(x => x.Key, x => x.Value); IsCategory = isCategory; _findProducts = findProducts ?? ((node, o) => new ArgumentObject[0]); _findSubcatalogs = findSubcatalogs ?? ((node, o) => new ArgumentObject[0]); _xPathPagintaion = xPathPagination ?? ((node, o) => new ArgumentObject[0]); Debug = debug; _encoding = encoding ?? Encoding.UTF8; }
/// <summary> /// This method is called by browser clients to update a view model's value. /// </summary> /// <param name="vmId">Identifies the view model.</param> /// <param name="vmData">View model update data, where key is the property path and value is the property's new value.</param> public void Update_VM(string vmId, Dictionary <string, object> vmData) { var data = vmData?.ToDictionary(x => x.Key, x => NormalizeType(x.Value)); try { _hubContext = new DotNetifyHubContext(Context, nameof(Request_VM), vmId, data, null, Principal); _hubPipeline.RunMiddlewares(_hubContext, ctx => { Principal = ctx.Principal; VMController.OnUpdateVM(ctx.CallerContext.ConnectionId, ctx.VMId, ctx.Data as Dictionary <string, object>); return(Task.FromResult(0)); }); } catch (Exception ex) { var finalEx = _hubPipeline.RunExceptionMiddleware(Context, ex); if (finalEx is OperationCanceledException == false) { Response_VM(Context.ConnectionId, vmId, SerializeException(finalEx)); } } }
public async Task UpdateVMAsync(string vmId, Dictionary <string, object> vmData) { var data = vmData?.ToDictionary(x => x.Key, x => NormalizeType(x.Value)); try { _callerContext = Context; _hubContext = new DotNetifyHubContext(_callerContext, nameof(IDotNetifyHubMethod.Update_VM), vmId, data, null, Principal); await _hubPipeline.RunMiddlewaresAsync(_hubContext, async ctx => { Principal = ctx.Principal; await VMController.OnUpdateVMAsync(ctx.CallerContext.ConnectionId, ctx.VMId, ctx.Data as Dictionary <string, object>); }); } catch (Exception ex) { var finalEx = await _hubPipeline.RunExceptionMiddlewareAsync(Context, ex); if (finalEx is OperationCanceledException == false) { await ResponseVMAsync(Context.ConnectionId, vmId, SerializeException(finalEx)); } } }
private Dictionary <string, List <string> > GetGenericsDictonary(Dictionary <Type, ICollection <Type> > dictionary) { return(dictionary? .ToDictionary(pair => pair.Key.ToString(), pair => pair.Value.Select(type1 => type1.FullName).ToList())); }
public Dictionary <RelationshipAttribute, HashSet <TDependent> > AllByRelationships() { return(_groups?.ToDictionary(p => p.Key.Attribute, p => p.Value)); }
public AssetBuilder AddItems(Dictionary <string, Stream> assets) => AddItems(assets?.ToDictionary(a => a.Key, a => new ContentItem(a.Value)));
public static Dictionary <string, BacktestJobLightModel> ToBacktestJobLightModels(this Dictionary <string, BacktestJobLight> jobs) { return(jobs?.ToDictionary(j => j.Key, j => j.Value.ToBacktestJobLightModel())); }
public ContentModelData ResolveContent(IContent content, string propertyGroupAlias, Dictionary <string, object>?options = null) { try { if (content is null) { return(new ContentModelData()); } var contentType = _contentTypeService.Get(content.ContentType.Alias); var contentModel = new ContentModelData { Item = new ContentModelItemData { Id = content.Key, ContentType = content.ContentType.Alias, Name = content.Name, Type = content.ContentType.Name, EditedAt = content.UpdateDate } }; var contentDictionary = new Dictionary <string, object>(); // Add blocks to content if applicable (loops through all nested content) if (_contentService.HasChildren(content.Id)) { List <ContentModelData> contentModelDataList = new(); long totalChildren; var children = _contentService.GetPagedChildren(content.Id, 0, int.MaxValue, out totalChildren); foreach (var child in children.Where(x => x.ContentType.Alias is not GeneralWebPage.ModelTypeAlias)) { contentModelDataList.Add(ResolveContent(child, "content")); } contentDictionary.Add("blocks", contentModelDataList); } var group = contentType.PropertyGroups.FirstOrDefault(x => x.Alias == propertyGroupAlias); var groupProperties = group?.PropertyTypes.Select(x => x.Alias); foreach (var property in content.Properties.Where(x => groupProperties.Contains(x.Alias))) { var converter = _converters.FirstOrDefault(x => x.EditorAlias.Equals(property.PropertyType.PropertyEditorAlias)); if (converter is not null) { var propertyValue = property.GetValue(); if (propertyValue is null) { contentDictionary.Add(property.Alias, null); continue; } propertyValue = converter.Convert(propertyValue, options?.ToDictionary(x => x.Key, x => x.Value)); contentDictionary.Add(property.Alias, propertyValue); } else { contentDictionary.Add( property.Alias, $"No converter implemented for editor: {property.PropertyType.PropertyEditorAlias}"); } } contentModel.Content = contentDictionary; return(contentModel); } catch (Exception e) { _logger.LogError(e, "An exception occured when resolving content, see the inner exception for details"); throw; } }
public ContentModel ResolveContent(IPublishedElement content, Dictionary <string, object> options = null) { try { if (content == null) { throw new ArgumentNullException(nameof(content)); } var contentModel = new ContentModel { System = new SystemModel { Id = content.Key, ContentType = content.ContentType.Alias, Type = content.ContentType.ItemType.ToString() } }; var dict = new Dictionary <string, object>(); if (content is IPublishedContent publishedContent) { contentModel.System.CreatedAt = publishedContent.CreateDate; contentModel.System.EditedAt = publishedContent.UpdateDate; contentModel.System.Locale = _variationContextAccessor.VariationContext.Culture; contentModel.System.Name = publishedContent.Name; contentModel.System.UrlSegment = publishedContent.UrlSegment; if (options != null && options.ContainsKey("addUrl") && bool.TryParse(options["addUrl"].ToString(), out bool addUrl) && addUrl) { contentModel.System.Url = publishedContent.Url(mode: UrlMode.Absolute); } } foreach (IPublishedProperty property in content.Properties) { IConverter converter = _converters.FirstOrDefault(x => x.EditorAlias.Equals(property.PropertyType.EditorAlias)); if (converter != null) { object prop = property.Value(); if (prop == null) { continue; } prop = converter.Convert(prop, options?.ToDictionary(x => x.Key, x => x.Value)); dict.Add(property.Alias, prop); } else { dict.Add( property.Alias, $"No converter implemented for editor: {property.PropertyType.EditorAlias}"); } } contentModel.Fields = dict; return(contentModel); } catch (Exception e) { _logger.Error <ContentResolver>(e); throw; } }
public static async Task StartBuildAsync( EnvDTE.Project project, string projectPath, string configName, Dictionary <string, string> properties, IEnumerable <string> targets, LoggerVerbosity verbosity) { if (project == null) { throw new ArgumentException("Project cannot be null."); } if (configName == null) { throw new ArgumentException("Configuration name cannot be null."); } RequestTimer.Restart(); var tracker = QtProjectTracker.Get(project, projectPath); await tracker.Initialized; if (QtVsToolsPackage.Instance.Options.BuildDebugInformation) { Messages.Print(string.Format( "{0:HH:mm:ss.FFF} QtProjectBuild({1}): Request [{2}] {3}", DateTime.Now, Thread.CurrentThread.ManagedThreadId, configName, tracker.UnconfiguredProject.FullPath)); } var knownConfigs = await tracker.UnconfiguredProject.Services .ProjectConfigurationsService.GetKnownProjectConfigurationsAsync(); ConfiguredProject configuredProject = null; foreach (var config in knownConfigs) { var configProject = await tracker.UnconfiguredProject .LoadConfiguredProjectAsync(config); if (configProject.ProjectConfiguration.Name == configName) { configuredProject = configProject; break; } } if (configuredProject == null) { throw new ArgumentException(string.Format("Unknown configuration '{0}'.", configName)); } BuildQueue.Enqueue(new QtProjectBuild() { Project = project, VcProject = tracker.VcProject, UnconfiguredProject = tracker.UnconfiguredProject, ConfiguredProject = configuredProject, Properties = properties?.ToDictionary(x => x.Key, x => x.Value), Targets = targets?.ToList(), LoggerVerbosity = verbosity }); StaticThreadSafeInit(() => BuildDispatcher, () => BuildDispatcher = Task.Run(BuildDispatcherLoopAsync)) .Forget(); }
private ValidationResult(string errorMessage, Dictionary <string, List <string> > result) : this(errorMessage, result?.ToDictionary(x => x.Key, x => (IReadOnlyList <string>)x.Value)) { }
public void PrepareRender() { stateCounters = stateCounters?.ToDictionary(i => i.Key, _ => 0); }
/// <summary> /// This extension method will create a new clone of the provided dictionary. /// </summary> /// <typeparam name="TK">Key type.</typeparam> /// <typeparam name="TV">Value type.</typeparam> /// <param name="dict">The dictionary to clone.</param> /// <returns>A new dictionary instance cloned from the provided instance.</returns> public static Dictionary <TK, TV> Clone <TK, TV>(this Dictionary <TK, TV> dict) => dict?.ToDictionary( pair => pair.Key, pair => pair.Value );
public bool Subscribe(string listId, MailAddress email, Dictionary <string, string> mergeFields, string apiKey) { var apiKeyParts = apiKey.Split('-'); if (apiKeyParts.Length != 2) { Log.Warning("The MailChimp API key is invalid; it should contain the MailChimp data center (e.g. 6292043b52144da2a5ccba0ed8dd9016-us15)"); return(false); } var emailAddress = email.Address; var key = apiKeyParts.First(); var dc = apiKeyParts.Last(); var hash = GetMd5Hash(emailAddress.ToLowerInvariant()); var uri = new Uri($"https://{dc}.api.mailchimp.com/3.0/lists/{listId}/members/{hash}"); var client = new WebClient { Encoding = Encoding.UTF8 }; // set JSON content type client.Headers[HttpRequestHeader.ContentType] = "application/json"; // basic auth, base64 encode of username:password var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"-:{key}")); client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}"; try { var data = Serialize(new SubscriptionData { email_address = emailAddress, status = "subscribed", merge_fields = mergeFields?.ToDictionary(kvp => kvp.Key.ToUpperInvariant(), kvp => kvp.Value) ?? new Dictionary <string, string>() }); var response = client.UploadString(uri, "PUT", data); var result = Deserialize <SubscriptionData>(response); return("subscribed".Equals(result.status, StringComparison.OrdinalIgnoreCase) && emailAddress.Equals(result.email_address, StringComparison.OrdinalIgnoreCase)); } catch (WebException wex) { var responseStream = wex.Response?.GetResponseStream(); if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { var response = reader.ReadToEnd(); Log.Error(wex, $"An error occurred while trying to subscribe the email: {emailAddress}. Error details: {response}", null); } } return(false); } catch (Exception ex) { Log.Error(ex, $"An error occurred while trying to subscribe the email: {emailAddress}."); return(false); } }
// protected void LoadDefaultGame() // { // // Boot the game // } public virtual bool Load(string path, RunnerMode newMode = RunnerMode.Playing, Dictionary <string, string> metaData = null) { try { if (newMode == RunnerMode.Loading) { nextPathToLoad = path; // Save a copy of the meta data nextMetaData = metaData?.ToDictionary(entry => entry.Key, entry => entry.Value); nextMode = RunnerMode.Playing; // Create new meta data for the pre-loader metaData = new Dictionary <string, string> { { "nextMode", nextMode.ToString() }, { "showDiskAnimation", "false" } }; // Look to see if the game's meta data changes the disk animation flag if (nextMetaData != null && nextMetaData.ContainsKey("showDiskAnimation")) { metaData["showDiskAnimation"] = nextMetaData["showDiskAnimation"]; } // TODO this was where the eject animation flag was set // Get the default path to the load tool from the bios path = bios.ReadBiosData("LoadTool", "/PixelVisionOS/Tools/LoadTool/"); // Change the mode to loading newMode = RunnerMode.Loading; } // Create a new meta data dictionary if one doesn't exist yet if (metaData == null) { metaData = new Dictionary <string, string>(); } // Spit path and convert to a list var splitPath = path.Split('/').ToList(); var gameName = ""; var rootPath = "/"; var total = splitPath.Count - 1; // Loop through each item in the path and get the game name and root path for (var i = 1; i < total; i++) { if (i < total - 1) { rootPath += splitPath[i] + "/"; } else { gameName = splitPath[i]; } } // Console.WriteLine("Load "+ gameName + " in " + rootPath); // Add the game's name and root path to the meta data if (metaData.ContainsKey("GameName")) { metaData["GameName"] = gameName; } else { metaData.Add("GameName", gameName); } // Change the root path for the game's meta data if (metaData.ContainsKey("RootPath")) { metaData["RootPath"] = rootPath; } else { metaData.Add("RootPath", rootPath); } // Update the runner mode mode = newMode; // When playing a game, save it to history and the meta data so it can be reloaded correctly if (mode == RunnerMode.Playing) { lastMode = mode; var metaDataCopy = metaData.ToDictionary(entry => entry.Key, entry => entry.Value); if (loadHistory.Count > 0) { // Console.WriteLine("History " + loadHistory.Last().Key + " " + path); // Only add the history if the last item is not the same // Loop through the history and see if the path already exists for (int i = loadHistory.Count - 1; i >= 0; i--) { if (loadHistory[i].Key == path) { loadHistory.RemoveAt(i); } } if (loadHistory.Last().Key != path) { loadHistory.Add(new KeyValuePair <string, Dictionary <string, string> >(path, metaDataCopy)); } } else { loadHistory.Add(new KeyValuePair <string, Dictionary <string, string> >(path, metaDataCopy)); } } // Create a new tmpEngine ConfigureEngine(metaData); // Path the full path to the engine's name tmpEngine.name = path; bool success; // Have the workspace run the game from the current path var files = workspaceService.LoadGame(path); if (files != null) { // Read and Run the disk ProcessFiles(tmpEngine, files, displayProgress); success = true; } else { DisplayError(ErrorCode.LoadError, new Dictionary <string, string> { { "@{path}", path } }); success = false; } // TODO need to remove old load disk animation? // if (metaDataCopy.ContainsKey("showDiskAnimation")) // { // metaData["showDiskAnimation"] = "false"; // } // If the game is unable to run, display an error // if (success == false) // Create new FileSystemPath return(success); // return base.Load(path, newMode, metaData); } catch (Exception e) { // Console.WriteLine("Load Error:\n"+e.Message); DisplayError(ErrorCode.Exception, new Dictionary <string, string> { { "@{error}", e is ScriptRuntimeException error ? error.DecoratedMessage : e.Message } }, e);
public ContentModelData ResolveContent(IPublishedElement content, string propertyGroupAlias, Dictionary <string, object>?options = null) { try { if (content is null) { return(new ContentModelData()); } var contentType = _contentTypeService.Get(content.ContentType.Alias); var contentModel = new ContentModelData { Item = new ContentModelItemData { Id = content.Key, ContentType = content.ContentType.Alias, Type = content.ContentType.ItemType.ToString(), } }; var contentDictionary = new Dictionary <string, object>(); if (content is IPublishedContent publishedContent) { contentModel.Item.CreatedAt = publishedContent.CreateDate; contentModel.Item.EditedAt = publishedContent.UpdateDate; contentModel.Item.Locale = _variationContextAccessor.VariationContext.Culture; contentModel.Item.Name = publishedContent.Name; contentModel.Item.UrlSegment = publishedContent.UrlSegment; if (options is not null && options.ContainsKey("addUrl") && bool.TryParse(options["addUrl"].ToString(), out var addUrl) && addUrl) { contentModel.Item.Url = publishedContent.Url(mode: UrlMode.Absolute); } // Add blocks to content if applicable (loops through all nested content) List <ContentModelData> contentModelDataList = new(); if (publishedContent.Children is not null && publishedContent.Children.Any()) { foreach (var child in publishedContent.Children.Where(x => x.ContentType.Alias is not GeneralWebPage.ModelTypeAlias)) { contentModelDataList.Add(ResolveContent(child, "content")); } contentDictionary.Add("blocks", contentModelDataList); } } var group = contentType.PropertyGroups.FirstOrDefault(x => x.Alias == propertyGroupAlias); var groupProperties = group?.PropertyTypes.Select(x => x.Alias); if (groupProperties is not null) { foreach (var property in content.Properties.Where(x => groupProperties.Contains(x.Alias))) { var converter = _converters.FirstOrDefault(x => x.EditorAlias.Equals(property.PropertyType.EditorAlias)); if (converter is not null) { var propertyValue = property.Value(_publishedValueFallback); if (propertyValue is null) { contentDictionary.Add(property.Alias, null); continue; } propertyValue = converter.Convert(propertyValue, options?.ToDictionary(x => x.Key, x => x.Value)); if (propertyValue is not null) { contentDictionary.Add(property.Alias, propertyValue); } } else { contentDictionary.Add( property.Alias, $"No converter implemented for editor: {property.PropertyType.EditorAlias}"); } } } contentModel.Content = contentDictionary; return(contentModel); } catch (Exception e) { _logger.LogError(e, "An exception occured when resolving content, see the inner exception for details"); throw; } }