public string NullConditionalOperator(Dictionary <int, string> d, int index) { string result = string.Empty; // Think fluent functional programming int?countNull = d?.Count(); // if d is null returns null, else call Count method if (countNull == null) { result += "countNull is null, "; } else { result += $"countNull value {countNull}, "; } int count = d?.Count() ?? 0; // if d is null ?? returns 0, else call Count method result += $"count value {count}, "; if (count == 0) { return(result); } // ALWAYS convert to Empty String even it is null // if d is null returns empty string, if d[index] is null returns empty string, else returns d[index] value string string valEmptyString = d?[index] ?? ""; if (valEmptyString == null) { result += "valEmptyString is null. SHOULD NEVER REACH HERE, "; } else { result += $"valEmptyString value {valEmptyString}, "; } // Null OR Empty String // if d is null returns null, if d[index] is null returns null, else returns d[index] value string string valNull = d?[index]; if (valNull == null) { result += "valNull is null, "; } else { result += $"valNull value {valNull}, "; } return(result); }
/*** * Bully class constructor */ public Bully(Dictionary<int, String> candidateMachines) { machines = candidateMachines; n = candidateMachines.Count(); positionValue = new int[candidateMachines.Count()]; for (int i = 0; i < candidateMachines.Count(); i++) { positionValue[i] = candidateMachines.Keys.ElementAt(i); } Console.WriteLine(classNameLog + "New instance of bully generator with machines " + machines); Console.WriteLine(classNameLog + "Key values array" + positionValue); myIp = CSharpRpcServer.getMyIpAddress(); }
private static void ProblemA() { var addressCount = int.Parse(Console.ReadLine()); var addresses = new Dictionary<string, List<string>>(); for (int i = 0; i < addressCount; i++) { var email = Console.ReadLine(); var canonicalEmail = GetCanonicalEmail(email); if (addresses.ContainsKey(canonicalEmail)) addresses[canonicalEmail].Add(email); else addresses.Add(canonicalEmail, new List<string> { email }); } Console.WriteLine(addresses.Count()); foreach (var a in addresses) { Console.Write(a.Value.Count); Console.Write(' '); foreach (var item in a.Value) { Console.Write(item + ' '); } Console.WriteLine(); } }
public void AggregatesDataIntoDictionary() { var lastReductionTime = new DateTime(2011, 11, 11, 5, 30, 0, 0); var reduceLevel = new ReduceLevel { Resolution = 5000 }; var sourceAggregationList = new List<MonitorRecord<double>> { new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 0, 500), 5, 5), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 0), 25, 4), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 500), 7, 8), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 40, 0), 3, 3) }; var destination = new Dictionary<DateTime, IList<MonitorRecord<double>>>(); var aggregater = new RecordReduceAggregate(); var result = aggregater.Aggregate(lastReductionTime, reduceLevel, sourceAggregationList, destination); Assert.Equal(2, destination.Count()); var firstItem = destination.First(); Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 2, 500), firstItem.Key); Assert.Equal(3, firstItem.Value.Count); var lastItem = destination.Last(); Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 42, 500), lastItem.Key); Assert.Equal(1, lastItem.Value.Count); }
public void Test_Analyze() { var httpClientMock = new Mock<IHttpClient>(); httpClientMock.Setup(it => it.DownloadString(It.IsAny<string>())) .Returns<string>((url) => { return "script"; }); var siteFileProviderMock = new Mock<ISiteFileProvider>(); Dictionary<string, string> styles = new Dictionary<string, string>(); siteFileProviderMock.Setup(it => it.AddFile(It.IsAny<Site>(), It.IsAny<string>(), It.IsAny<string>())) .Callback<Site, string, string>((site1, path, content) => { styles.Add(path, content); }); var scriptAnalyzer = new ScriptAnalyzer(httpClientMock.Object, siteFileProviderMock.Object); var pageHtml = @"<html> <head> <script src=""/script1.js"" type=""text/javascript""></script> <script src=""/script2.js"" type=""text/javascript""></script> </head> <body> </body> </html>"; SiteDownloadContext siteDownloadContext = new SiteDownloadContext(null, new DownloadOptions() { SiteName = "Test_Analyze", Url = "localhost", Pages = 20, Deep = 1 }, null, null); PageDownloadContext pageDownloadContext = new PageDownloadContext(siteDownloadContext, new PageLevel("http://localhost", 1), pageHtml); scriptAnalyzer.Analyze(pageDownloadContext); Assert.AreEqual(2, styles.Count()); Assert.AreEqual("script", styles["\\Scripts\\script1.js"]);
private static void CharHistogram(string str) { Dictionary<char,int> dict=new Dictionary<char,int>(); foreach (var item in str) { if (dict.ContainsKey(item)) { dict[item] += 1; } else { dict.Add(item, 1); } } int counter = 0; Console.Write("{ "); foreach (var ch in dict) { if (counter==dict.Count()-1) { Console.Write("'" + ch.Key + "'" + ": " + ch.Value + " }"); } else { Console.Write("'" + ch.Key + "'" + ": " + ch.Value + ", "); } counter++; } }
public override void Effect(Pawn target) { base.Effect(target); IEnumerable <BodyPartRecord> recs = target.health.hediffSet.GetNotMissingParts(); Dictionary <BodyPartRecord, HediffDef> bodyPartRecords = new Dictionary <BodyPartRecord, HediffDef>(); if (recs.FirstOrDefault(x => (x.def == BodyPartDefOf.LeftHand)) is BodyPartRecord leftHand) { bodyPartRecords.Add(leftHand, VampDefOf.ROMV_FeralClaw); } if (recs.FirstOrDefault(x => (x.def == BodyPartDefOf.RightHand)) is BodyPartRecord rightHand) { bodyPartRecords.Add(rightHand, VampDefOf.ROMV_FeralClaw); } if ((bodyPartRecords?.Count() ?? 0) > 0) { foreach (KeyValuePair <BodyPartRecord, HediffDef> transformableParts in bodyPartRecords) { Hediff transformedHediff = HediffMaker.MakeHediff(transformableParts.Value, target, transformableParts.Key); transformedHediff.Severity = 1.0f; target.health.AddHediff(transformedHediff, transformableParts.Key, null); } } }
/// <summary> /// 用户向消息总线注册 /// </summary> public void Register() { //向共享内存中写入数据,进行注册 int pid = Process.GetCurrentProcess().Id; string address = ".\\Private$\\myQueue" + pid; MyLocker.Lock("sm"); try { processDic = (Dictionary<int, string>)sm.Data; } catch (Exception ex) { processDic = new Dictionary<int, string>(); } if (!processDic.ContainsKey(pid)) { processDic.Add(pid, address); sm.Data = processDic; } processDic = (Dictionary<int, string>)sm.Data; localV = sm.Version; MyLocker.Unlock("sm"); Console.WriteLine("客户端数量:" + processDic.Count()); ReceiveNow(); }
private GeoBoundingBoxFilter RetrieveBox(string fieldName, Dictionary<string, object> boxDict) { // maybe are are dealing with the vertices if (boxDict.Count() == 4) return GetBoxFromVertices(fieldName, boxDict); CoordinatePoint topLeft; CoordinatePoint bottomRight; if (boxDict.ContainsKey(_TOP_LEFT)) { topLeft = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_TOP_LEFT)); bottomRight = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_BOTTOM_RIGHT)); } else if (boxDict.ContainsKey(_TOP_RIGHT)) { CoordinatePoint topRight = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_TOP_RIGHT)); CoordinatePoint bottomLeft = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_BOTTOM_LEFT)); topLeft = new CoordinatePoint(topRight.Latitude, bottomLeft.Longitude); bottomRight = new CoordinatePoint(bottomLeft.Latitude, topRight.Longitude); } else { throw new Exception("No bounding box formed by current properties."); } return new GeoBoundingBoxFilter(fieldName, topLeft, bottomRight); }
private void HeaderInfo() { this.Output.AppendLine(Messages.WavesSeparator); if (this.IsLogged) { this.Output.AppendLine(string.Format(Messages.UserWelcomeMessage, this.CurrentUser.Username)); } else { this.Output.AppendLine(string.Format(Messages.GuestWelcomeMessage)); } var allQuestions = this.Questions; var hotQuestions = allQuestions.Sum(question => question.Answers.OfType<BestAnswer>().Count()); var allAnswers = this.Answers; var userAnswers = new Dictionary<string, int>(); foreach (var answer in allAnswers) { var author = answer.Author.Username; if (!userAnswers.ContainsKey(author)) { userAnswers.Add(author, 0); } userAnswers[author]++; } var activeUsers = userAnswers.Count(user => user.Value >= 3); this.Output.AppendLine(string.Format(Messages.GeneralHeaderMessage, hotQuestions, activeUsers)); this.Output.AppendLine(Messages.WavesSeparator); }
/// <summary> /// Constructeur paramétré /// </summary> /// <param name="journees">Liste des journées de la mission</param> public GestionCarte(Dictionary<int, Journee> journees) { InitializeComponent(); this.journees = journees; lieuxADessiner = new List<Lieu>(); TreeNode t = new TreeNode("Tout afficher"); activitesExterieures.Nodes.Add(t); activitesExterieures.SelectedNode = t; for (int i = 1; i <= journees.Count(); ++i) { if (journees[i].isJourneeExterieure()) { TreeNode tn = new TreeNode("Journée " + i); activitesExterieures.Nodes.Add(tn); foreach (Activite a in journees[i].getActivites()) if (a.isActiviteExterieure()) { TreeNode tnn = new TreeNode(a.getNom() + " - " + a.getHeureDebut().getHeures() + "h -> " + a.getHeureFin().getHeures() + "h"); tnn.Tag = a; tn.Nodes.Add(tnn); lieuxADessiner.Add(a.getLieu()); } } } this.Refresh(); }
private static int BruteForce() { //read Pythagorean Triplets on wikipedia var map = new Dictionary<int, int>(); var sqrt = Math.Sqrt(750000); for (var m = 2; m < sqrt; m++) { for (var n = 1; n < m; n++) { if ((m + n)%2 > 0 && MathUtils.Gcd(m, n) == 1) { var a = m*m - n*n; var b = 2*m*n; var c = m*m + n*n; var d = a + b + c; while (d <= 1500000) { if (!map.ContainsKey(d)) { map.Add(d, 0); } map[d]++; d += a + b + c; } } } } return map.Count(x => x.Value == 1); }
public static string AddQueryString( string url, string key, string value) { string result = url; string[] t = url.Split('?'); string path = t[0]; string[] querystring = new string[]{}; if(t.Length > 1) querystring = t[1].Split('&'); Dictionary<string, string> queryParams = new Dictionary<string,string>(); foreach( string q in querystring ){ if( q != string.Empty ) queryParams.Add( q.Split('=')[0], q.Split('=')[1]); } if( queryParams.ContainsKey(key) ) queryParams[key] = value; else queryParams.Add( key, value); result = path; if( queryParams.Count() > 0) { result += "?"; foreach( string k in queryParams.Keys ) result += k + "=" + queryParams[k] + "&"; if (result.EndsWith("&")) result = result.TrimEnd('&'); } return result; }
public void getFrameVisitFromLevel(List<Visit> listVisit, out HelperFrame.GroupType groupType, out Dictionary<string, List<Visit>> visitByDate) { this.visits = listVisit; groupType = HelperFrame.GroupType.DAY; visitByDate = HelperDate.getVisitsByDate(listVisit, "dd MMM"); if (!isBlend(visitByDate.Count())) { groupType = HelperFrame.GroupType.WEEK; visitByDate = HelperDate.getVisitsByWeek(listVisit); if (!isBlend(visitByDate.Count())) { groupType = HelperFrame.GroupType.MONTH; visitByDate = HelperDate.getVisitsByDate(listVisit, "MMM yyyy"); } } }
//constructors; public Filler(DMSImage Source) : base(new Size(Source.Width, Source.Height), Source, Color.Gray) { m_pixelindex = new Dictionary<int, int>(); m_pixels = new List<PixelInfo>(); m_resolution = START_RESOLUTION; m_rand = new Random(); double delta = 0; int iter = 0; while (m_pixels.Count < MIN_PIXELS || delta > DELTA_THRESHOLD && iter < MAX_ITERS) { if (iter == MAX_ITERS || delta < DELTA_THRESHOLD) { iter = 0; m_resolution >>= 1; if (m_resolution == 0) break; Console.Write("\n" + m_resolution); //bring on new pixels if necessary for (int u = 0; u < Source.Width; u += m_resolution) { for (int v = 0; v < Source.Height; v += m_resolution) { if (GetPixelHelper(u, v) == null) { PixelInfo newpixel = new PixelInfo(u, v, new Point3D()); newpixel.SetNeighbors(m_Source, m_resolution); SetAvgColour(newpixel); m_pixels.Add(newpixel); m_pixelindex.Add(v * Source.Width + u, m_pixels.Count() - 1); } } } } else { iter++; } Console.Write('.'); //do the averaging! delta = 0.0; if (m_pixels.Count() == 0) continue; for (int i = 0; i < 10000; i++) { int idx = m_rand.Next(m_pixelindex.Count()); idx = m_pixelindex.Keys.ToArray()[idx]; int u = idx % Source.Width; int v = idx / Source.Width; int pixelidx = m_pixelindex[idx]; delta += SetAvgColour(m_pixels[pixelidx]); } } Console.WriteLine(); }
public bool isDrawActive(UserInfo[] userInfos, Skeleton[] skeletons) { Dictionary<int, double> userDistanceList = new Dictionary<int, double>(); foreach (var userInfo in userInfos) { int userID = userInfo.SkeletonTrackingId; if (userID == 0) { continue; } foreach (var skel in skeletons) { double skeletonPosition; if (skel.TrackingId == userID) { skeletonPosition = skel.Position.Z; userDistanceList[userID] = skeletonPosition; } else { continue; } } } if (userDistanceList.Count() == 0) return false; // get id of the closest user double smallest = 100000.0; int UserIdOfClosest = 0; foreach (KeyValuePair<int, double> entry in userDistanceList) { if (entry.Value < smallest) { smallest = entry.Value; UserIdOfClosest = entry.Key; } } if (UserIdOfClosest == 0) { return false; } // check if the closest users action is triggered foreach (var userInfo in userInfos){ if (userInfo.SkeletonTrackingId == UserIdOfClosest) { return modesList.ElementAt(currentModeId).isInteractionActive(userInfo.HandPointers); } else { continue; } } return false; }
internal static double Mean(Dictionary<DateTime, double> returns) { double S = 0; foreach(KeyValuePair<DateTime, double> kvp in returns) { S += kvp.Value; } return S/returns.Count(); }
static void Main(string[] args) { Dictionary<string, string> languagesDictionary = new Dictionary<string, string>(); languagesDictionary.Add("C#", "The best programming language in the world."); Console.WriteLine("This is a dictionary of computer programming languages. To search for a language by it's name press N or to search by description enter D"); Console.WriteLine("Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit."); char userInput = Convert.ToChar(Console.ReadLine().ToLower()); do { switch (userInput) { case 'n': Console.WriteLine("Please enter the name of the language you are searching for."); string searchName = Console.ReadLine(); if (languagesDictionary.ContainsKey(searchName) == true) { Console.WriteLine(searchName + " is in the dictionary."); } else { Console.WriteLine(searchName + " could not be found."); } break; case 'd': Console.WriteLine("Please enter a description of the language you are searching for."); string searchDescription = Console.ReadLine(); if (languagesDictionary.ContainsValue(searchDescription) == true) { Console.WriteLine(searchDescription + " is in the dictionary."); } else { Console.WriteLine(searchDescription + " could not be found."); } break; case 'c': int dictionarySize = languagesDictionary.Count(); Console.WriteLine("There are " + dictionarySize + " languages in the dictionary"); break; default: break; } Console.WriteLine("To search for a language by it's name press N or to search by description enter D. Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit."); userInput = Convert.ToChar(Console.ReadLine().ToLower()); } while (userInput != 'x'); Console.WriteLine("Your session has now ended."); }
public void Dictionary() { /* Dictionary<string, int> people = new Dictionary<string, int>(); people.Add("Emmy", 4); people.Add("Abby", 10); people.Add("Cathy", 45); people.Add("Laffy", 13); people.Add("Daffy", 60); */ //or Dictionary<string, int> people = new Dictionary<string, int>() { { "Emmy", 4}, { "Abby", 10 }, { "Cathy", 45}, { "Laffy", 13}, { "Daffy", 60 }, }; //two ways of checking if a key exists if(people.ContainsKey("Abby")) { int value = people["Abby"]; Console.WriteLine(value); } int value2; if (people.TryGetValue("Laffy", out value2)) { Console.WriteLine(value2); } //print out all keys and values foreach (KeyValuePair<string, int> pair in people) { Console.WriteLine("Key: " + pair.Key + " Value: " + pair.Value); } //or foreach(string key in people.Keys) { Console.WriteLine("Key: " + key); } foreach(int value in people.Values) { Console.WriteLine("Value: " + value); } //get dictionary size Console.WriteLine(people.Count); //or Console.WriteLine(people.Count()); }
/** * Join parameters map into string, usually query string * * @param queryParams Map to join * @param isUri Indicates that value parameters must be uri-encoded * @return Result query string, like k=v&k1=v1 */ public static String joinParams(Dictionary<String, Object> queryParams, bool isUri) { var parameters = new List<string>(queryParams.Count()); parameters.AddRange( queryParams.Select( entry => String.Format("{0}={1}", entry.Key, isUri ? HttpUtility.UrlEncode(Convert.ToString(entry.Value)) : Convert.ToString(entry.Value)))); return join(parameters, "&"); }
public void DownloadLookUp_ValidJson(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string,IDictionary<string,int>> packages = downloadLookup.Load(); Assert.True(packages != null & packages.Count() == 2); IDictionary<string,int> versions = new Dictionary<string,int>(); Assert.True(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 2); Assert.True(versions.Values.ToArray()[0] == 406 && versions.Values.ToArray()[1] == 137); }
static void Main(string[] args) { Console.WriteLine("loading options..."); options = LoadOptions("options.csv"); mmmOptions = LoadOptions("mmm_candidates.csv"); Console.WriteLine("loading voters..."); var lines = File.ReadAllLines("voters.csv").Skip(1).Select(line => line.Split(';')).ToList(); Console.WriteLine("parsing voters..."); deactivated = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[3].Contains("Deactivated")); voters = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[1]); //id+phone => datetime Console.WriteLine("voters: {0}", voters.Count); Console.WriteLine("decrypting..."); var decrypted = new Blowfish(File.ReadAllText("key.txt")).decryptString(File.ReadAllText("protocol.csv")); File.WriteAllText("decrypted.csv", decrypted); Console.WriteLine("filtering..."); var voteLines = decrypted.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(line => line.Split(';')); var votes = voteLines .Select( parts => new { voter = parts[0] + parts[1], //id + phone candidates = parts[2].Split(',').ToArray() }).ToList(); Console.WriteLine("deactivated count: " + deactivated.Count(kv => kv.Value)); // не 0 Console.WriteLine("Votes by deactivated: " + votes.Count(v => deactivated[v.voter])); //0 Console.WriteLine("Voters with more than 45 votes: " + votes.Count(v => v.candidates.Count() > 45)); //0 Console.WriteLine("Voters with duplicated votes: " + votes.Count(v => v.candidates.Distinct().Count() != v.candidates.Count())); //0 Console.WriteLine("Voters with more than 45 UNIQUE votes: " + votes.Count(v => v.candidates.Distinct().Count() > 45)); //0 Console.WriteLine("Banned MMMs: " + votes.Count(v => IsMmm(v.voter, v.candidates))); var results = votes .Where(v => !IsMmm(v.voter, v.candidates) && !deactivated[v.voter]) .SelectMany(v => v.candidates.Distinct()) .GroupBy(cand => cand) .ToDictionary(g => g.Key, g => g.Count()); Console.WriteLine("results:"); foreach (var res in results.OrderByDescending(kv => kv.Value)) { Console.WriteLine(res.Value + "\t" + options[res.Key]); } Console.WriteLine("Elliminate ALL MMM:"); Console.WriteLine("Banned ALL MMMs: " + votes.Count(v => IsMmmAll(v.voter, v.candidates))); Console.WriteLine("results:"); var results2 = votes .Where(v => !IsMmmAll(v.voter, v.candidates) && !deactivated[v.voter]) .SelectMany(v => v.candidates.Distinct()) .GroupBy(cand => cand) .ToDictionary(g => g.Key, g => g.Count()); foreach (var res in results2.OrderByDescending(kv => kv.Value)) { Console.WriteLine(res.Value + "\t" + options[res.Key]); } }
public string Execute(Dictionary <string, string> dynamicRuleExceptions, string text) { DynamicRuleExceptions = dynamicRuleExceptions; if (Exceptions?.Count() > 0 || DynamicRuleExceptions?.Count() > 0) { text = ReplaceExceptions(text); } return(ReplaceMany(text)); }
internal static double WeightedSum(Dictionary<DateTime, double> ret1, Dictionary<DateTime, double> ret2, double lambda) { if (ret1.Count() != ret2.Count()) throw new ArgumentException("dictionnaire de taille différentes."); double S = 0; int i = 0; foreach(KeyValuePair<DateTime, double> kvp in ret1) { S += Math.Pow(lambda, i)*ret1[kvp.Key]*ret2[kvp.Key]; i+=1; } return S; }
public IEnumerable <Award> GetAll() { using (StreamReader fileJson = new StreamReader(_path)) { var stringJson = fileJson.ReadToEnd(); //yield ??77? FakeDaoAward = JsonConvert.DeserializeObject <Dictionary <int, Award> >(stringJson); _id = FakeDaoAward?.Count() ?? 0; return(FakeDaoAward?.Select(x => x.Value)); } }
public void DownloadLookUp_NoExceptionThrownWithDuplicateKeys(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string, IDictionary<string, int>> packages = downloadLookup.Load(); // Dict should have only one entry when there are duplicate entries. Assert.True(packages != null & packages.Count() == 1); IDictionary<string, int> versions = new Dictionary<string, int>(); Assert.True(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 2); // When duplicate entries are present,the first one should be taken and the consecutive ones should be ignored. Assert.True(versions.Values.ToArray()[0] == 406 && versions.Values.ToArray()[1] == 137); }
public ImportResult Import() { if (String.IsNullOrEmpty(_importFileName)) return ImportResult.ImportFileMissing; if (String.IsNullOrEmpty(_outputFileName)) return ImportResult.OutputFileMissing; if (_importFileName.Substring(_importFileName.Length - 4, 4) != ".csv") return ImportResult.BadInputFileType; string[] allRows = File.ReadAllLines(_importFileName); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var configSectionGroup = config.GetSectionGroup("transformationRules") as TransformationRuleGroup; if (configSectionGroup != null) { _transformationRules = new List<TransformationRule>(); if (configSectionGroup.InitialsTransformation != null) _transformationRules.Add(configSectionGroup.InitialsTransformation); if (configSectionGroup.BirthDateTransformation != null) _transformationRules.Add(configSectionGroup.BirthDateTransformation); } var transformedRows = TransformRows(allRows, _transformationRules); SourceHeaders = GetSourceHeaders(transformedRows); ColumnsToSkip = GetColumnsToSkip(SourceHeaders); var columnCount = SourceHeaders.Count(); if (columnCount == 0) return ImportResult.BadFormat; var rows = GetRows(transformedRows); if (rows.Count(c => c.Count() != columnCount) > 0) return ImportResult.BadFormat; var encryptedRows = EncryptRows(rows); try { var writer = new StreamWriter(_outputFileName); writer.WriteLine(string.Join(columnSeparator.ToString(), SourceHeaders.Select(c => c.Value))); encryptedRows.ForEach(writer.WriteLine); writer.Flush(); writer.Close(); } catch (IOException e) { return ImportResult.WriteAccessDenied; } return ImportResult.Success; }
internal static Dictionary <string, string> UpgradeVirtualGroupNamesV1(Dictionary <string, string> _oldVirtualGroupNames) { Dictionary <string, string> _outfitVirtualGroupInfo = new Dictionary <string, string>(); if (_oldVirtualGroupNames?.Count() > 0) { foreach (KeyValuePair <string, string> _group in _oldVirtualGroupNames) { _outfitVirtualGroupInfo[_group.Key] = _group.Value; } } return(_outfitVirtualGroupInfo); }
public void DownloadLookUp_InvalidEntriesIgnored(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string, IDictionary<string, int>> packages = downloadLookup.Load(); // Out of two entries one is invalid. So dict count should be 1. Assert.True(packages != null & packages.Count() == 1); IDictionary<string, int> versions = new Dictionary<string, int>(); Assert.False(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(packages.TryGetValue("Assman.Core".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 1); // When duplicate entries are present,the first one should be taken and the consecutive ones should be ignored. Assert.True(versions.Values.ToArray()[0] == 138 && versions.Keys.ToArray()[0] == "2.0.7"); }
static void Main(string[] args) { Customer cust1 = new Customer() { ID = 1, Name = "Sowmya", Gender = "Female" }; Customer cust2 = new Customer() { ID = 2, Name = "Mukund", Gender = "Male" }; Customer cust3 = new Customer() { ID = 3, Name = "Vishnu", Gender = "Male" }; Dictionary<int, Customer> dictioncustomers = new Dictionary<int, Customer>(); dictioncustomers.Add(cust1.ID, cust1); dictioncustomers.Add(cust2.ID, cust2); dictioncustomers.Add(cust3.ID, cust3); Customer customer1 = dictioncustomers[1]; Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", customer1.ID, customer1.Name, customer1.Gender); foreach (KeyValuePair<int, Customer> custkeyvaluepair in dictioncustomers) { Console.WriteLine("key is {0}", custkeyvaluepair.Key); Customer cust = custkeyvaluepair.Value; Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", cust.ID, cust.Name, cust.Gender); Console.WriteLine("_____________________________________________________________________"); } foreach(int key in dictioncustomers.Keys) { Console.WriteLine(key); } foreach (Customer custy in dictioncustomers.Values) { Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", custy.ID, custy.Name, custy.Gender); } if (dictioncustomers.ContainsKey(5)) { Customer cust5 = dictioncustomers[5]; } Console.WriteLine("total items={0} ", dictioncustomers.Count(kvp => kvp.Value.ID > 0)); // dictioncustomers.Remove(119); to remove item with key 119 //dictioncustomers.clear(); to remove all items. Customer[] custs = new Customer[3]; custs[0] = cust1; custs[1] = cust2; custs[2] = cust3; Dictionary<int, Customer> customers = custs.ToDictionary(cust => cust.ID, cust => cust); foreach (KeyValuePair<int, Customer> kvp in customers) { Console.WriteLine("key is {0}", kvp.Key); Customer custys = kvp.Value; Console.WriteLine("id is {0}, Name = {1}", custys.ID, custys.Name); } }
/// <summary> /// 对接视频接口 /// </summary> /// <param name="method">方法方式</param> /// <param name="canonicalURI">baseurl + url</param> /// <param name="requestParas">请求参数</param> /// <returns></returns> public static string HttpRequest(HttpMethod method, string canonicalURI, Dictionary <string, string> requestParas = null) { var requestUrl = AppSetting.GetSection("ZDingTalk:VideoBaseUrl") + canonicalURI; //域名配置地址 try { var message = new HttpRequestMessage { Method = method, }; if (method == HttpMethod.Post) { var paras = new Dictionary <string, string>(); if (requestParas?.Count() > 0) { foreach (var dic in requestParas) { paras.Add(dic.Key, Uri.UnescapeDataString(dic.Value)); } message.Content = new FormUrlEncodedContent(paras); message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); } } else if (method == HttpMethod.Get) { requestUrl += $"?{DicionartyToUrlParameters(requestParas)}"; } message.RequestUri = new Uri(requestUrl); using (var client = new System.Net.Http.HttpClient()) { var request = client.SendAsync(message); var reponseContent = request.Result.Content.ReadAsStringAsync(); if (!request.Result.IsSuccessStatusCode) { throw new Exception(reponseContent.Result); } return(reponseContent.Result); } } catch (Exception ex) { //记录日志 throw; } }
/// <summary> /// 删除集合数据,并且删除本地缓存 /// </summary> /// <returns>删除结果</returns> public bool Flush () { if (globalDictionary?.Count () > 0) { cacheLock.EnterWriteLock (); globalDictionary.Clear (); try { return Utility.SaveCache (globalDictionary, CacheName, FileMode.Create); } catch (System.Exception ex) { throw ex; } finally { cacheLock.ExitWriteLock (); } } return false; }
static void Main(string[] args) { Dictionary<char, int> alphabet = new Dictionary<char, int>(); string key = Console.ReadLine(); foreach (char letter in key) { if (!alphabet.ContainsKey(letter)) { alphabet.Add(letter, 0); } alphabet[letter]++; } int oddNumber = alphabet.Count(pair => pair.Value % 2 == 1); Console.WriteLine(oddNumber > 1 ? "NO" : "YES"); }
internal static Dictionary <string, VirtualGroupInfo> UpgradeVirtualGroupNamesV2(Dictionary <string, string> _oldVirtualGroupNames) { Dictionary <string, VirtualGroupInfo> _outfitVirtualGroupInfo = new Dictionary <string, VirtualGroupInfo>(); if (_oldVirtualGroupNames?.Count() > 0) { foreach (KeyValuePair <string, string> _group in _oldVirtualGroupNames) { if (_group.Key.StartsWith("custom_")) { _outfitVirtualGroupInfo[_group.Key] = new VirtualGroupInfo(_group.Key, int.Parse(_group.Key.Replace("custom_", "")) + 9, _group.Value); } } } return(_outfitVirtualGroupInfo); }
public int countRareNotes3(int[] notes) { var counters = new Dictionary<int, int>(); foreach (var note in notes) { if (counters.ContainsKey(note)) { counters[note]++; } else { counters[note] = 1; } } return counters.Count(x => x.Value == 1); }
private void DrawHeader() { StringBuilder sb = new StringBuilder(); sb.AppendLine("~~~~~~~~~~~~~~~~~~~~"); sb.AppendLine(!base.IsLogged ? Messages.GuestWelcomeMessage : string.Format(Messages.UserWelcomeMessage, this.CurrentUser.Username)); int hotQuestionCount = base.Questions .Count(q => q.Answers .Any(a => a.GetType() == typeof (BestAnswer)) ); int activeUsersCount = 0; var userActivity = new Dictionary<IUser, int>(); base.Questions .ToList() .ForEach(q => { q.Answers .ToList() .ForEach(a => { var answerAuthor = a.Author; if (!userActivity.ContainsKey(answerAuthor)) userActivity.Add(answerAuthor, 0); userActivity[answerAuthor]++; }); }); activeUsersCount = userActivity .Count(g => g.Value >= 3); sb.AppendLine(string.Format(Messages.GeneralHeaderMessage, hotQuestionCount, activeUsersCount)); sb.AppendLine("~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine(sb.ToString().Trim()); }
public override void WorldComponentTick() { base.WorldComponentTick(); if (Find.TickManager.TicksGame % 100 == 0 && !isTeleporting) { isTeleporting = true; if (pawnsToTeleport != null && pawnsToTeleport?.Count() > 0) { foreach (var teleportPawn in pawnsToTeleport) { teleportPawn.Key.DeSpawn(); GenPlace.TryPlaceThing(teleportPawn.Key, teleportPawn.Value.Cell, teleportPawn.Value.Map, ThingPlaceMode.Near); AccessTools.Method(typeof(FogGrid), "FloodUnfogAdjacent").Invoke(teleportPawn.Value.Map.fogGrid, new object[] { teleportPawn.Key.PositionHeld }); } } pawnsToTeleport.Clear(); isTeleporting = false; } }
/// <summary> /// Determine whether this member is a full or partial match /// (or no match) for the set of words that is passed in /// </summary> /// <param name="line">a set of words that is part of a scenario</param> /// <returns></returns> public NameMatch GetMatch(string line) { var words = _scenarioLineParser.ExtractWordsFromScenarioLine(line); // can't match if not enough words to fill us up if (words.Count < _wordFilters.Count) return null; var paramValues = new Dictionary<string, object>(); var wordIndex = 0; // check each word for a match for (int i = 0; i < _wordFilters.Count; i++) { var wordMatch = _wordFilters[i].GetMatch(words.Skip(wordIndex).ToArray()); if (!wordMatch.IsMatch) return null; // if this is a parameter, add to our hash so we can resolve the (string) value later var paramFilter = _wordFilters[i] as ParameterMatchWordFilter; if (paramFilter != null) paramValues.Add(paramFilter.ParameterName, wordMatch.Value); wordIndex += wordMatch.WordCount; } var match = BuildNameMatch(words, paramValues); if (match != null) { DebugTrace.Trace("Method name match", "Method = " + _methodInfo.DeclaringType.Name + "." +_methodInfo.Name); if (paramValues.Count() > 0) { var paramValueString = string.Join(",", match.ParamValues.Select(kvp => kvp.Key + ":" + kvp.Value). ToArray()); DebugTrace.Trace("Method name match", "Params= " + paramValueString); } } return match; }
public static string ParametersToString(Dictionary<string, string> parameters) { string output = String.Empty; if(parameters != null && parameters.Count>0) { output += "?"; int i = 0; foreach(var parameter in parameters) { output += parameter.Key + "=" + parameter.Value; output += (i != parameters.Count() - 1) ? "&" : ""; i++; } } return output; }
private FontTexture generateTexture(string text) { var filename = text.Length == 1 ? $"{(int)text[0]:x4}.png" : $"_{textureCache.Count(l => l.Key.Length > 1):x3}.png"; var bitmapPath = Path.Combine(mapsetDirectory, Directory, filename); System.IO.Directory.CreateDirectory(Path.GetDirectoryName(bitmapPath)); var fontPath = Path.Combine(projectDirectory, description.FontPath); if (!File.Exists(fontPath)) { fontPath = description.FontPath; } float offsetX = 0, offsetY = 0; int baseWidth, baseHeight, width, height; using (var graphics = Graphics.FromHwnd(IntPtr.Zero)) using (var stringFormat = new StringFormat(StringFormat.GenericTypographic)) using (var textBrush = new SolidBrush(Color.FromArgb(description.Color.ToArgb()))) using (var fontCollection = new PrivateFontCollection()) { graphics.TextRenderingHint = TextRenderingHint.AntiAlias; stringFormat.Alignment = StringAlignment.Center; stringFormat.FormatFlags = StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoClip; FontFamily fontFamily = null; if (File.Exists(fontPath)) { fontCollection.AddFontFile(fontPath); fontFamily = fontCollection.Families[0]; } var dpiScale = 96f / graphics.DpiY; var fontStyle = description.FontStyle; using (var font = fontFamily != null ? new Font(fontFamily, description.FontSize * dpiScale, fontStyle) : new Font(fontPath, description.FontSize * dpiScale, fontStyle)) { var measuredSize = graphics.MeasureString(text, font, 0, stringFormat); baseWidth = (int)Math.Ceiling(measuredSize.Width); baseHeight = (int)Math.Ceiling(measuredSize.Height); var effectsWidth = 0f; var effectsHeight = 0f; foreach (var effect in effects) { var effectSize = effect.Measure(); effectsWidth = Math.Max(effectsWidth, effectSize.X); effectsHeight = Math.Max(effectsHeight, effectSize.Y); } width = (int)Math.Ceiling(baseWidth + effectsWidth + description.Padding.X * 2); height = (int)Math.Ceiling(baseHeight + effectsHeight + description.Padding.Y * 2); var paddingX = description.Padding.X + effectsWidth * 0.5f; var paddingY = description.Padding.Y + effectsHeight * 0.5f; var textX = paddingX + measuredSize.Width * 0.5f; var textY = paddingY; offsetX = -paddingX; offsetY = -paddingY; if (text.Length == 1 && char.IsWhiteSpace(text[0]) || width == 0 || height == 0) { return(new FontTexture(null, offsetX, offsetY, baseWidth, baseHeight, width, height)); } using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) { using (var textGraphics = Graphics.FromImage(bitmap)) { textGraphics.TextRenderingHint = graphics.TextRenderingHint; textGraphics.SmoothingMode = SmoothingMode.HighQuality; textGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; if (description.Debug) { var r = new Random(textureCache.Count); textGraphics.Clear(Color.FromArgb(r.Next(100, 255), r.Next(100, 255), r.Next(100, 255))); } foreach (var effect in effects) { if (!effect.Overlay) { effect.Draw(bitmap, textGraphics, font, stringFormat, text, textX, textY); } } if (!description.EffectsOnly) { textGraphics.DrawString(text, font, textBrush, textX, textY, stringFormat); } foreach (var effect in effects) { if (effect.Overlay) { effect.Draw(bitmap, textGraphics, font, stringFormat, text, textX, textY); } } if (description.Debug) { using (var pen = new Pen(Color.FromArgb(255, 0, 0))) { textGraphics.DrawLine(pen, textX, textY, textX, textY + baseHeight); textGraphics.DrawLine(pen, textX - baseWidth * 0.5f, textY, textX + baseWidth * 0.5f, textY); } } } var bounds = description.TrimTransparency ? BitmapHelper.FindTransparencyBounds(bitmap) : null; if (bounds != null && bounds != new Rectangle(0, 0, bitmap.Width, bitmap.Height)) { var trimBounds = bounds.Value; using (var trimmedBitmap = new Bitmap(trimBounds.Width, trimBounds.Height)) { offsetX += trimBounds.Left; offsetY += trimBounds.Top; width = trimmedBitmap.Width; height = trimmedBitmap.Height; using (var trimGraphics = Graphics.FromImage(trimmedBitmap)) trimGraphics.DrawImage(bitmap, 0, 0, trimBounds, GraphicsUnit.Pixel); BrewLib.Util.Misc.WithRetries(() => trimmedBitmap.Save(bitmapPath, ImageFormat.Png)); } } else { BrewLib.Util.Misc.WithRetries(() => bitmap.Save(bitmapPath, ImageFormat.Png)); } } } } return(new FontTexture(Path.Combine(Directory, filename), offsetX, offsetY, baseWidth, baseHeight, width, height)); }
/// <summary> /// 选择最优参数对。用前choicePeriod个交易日的数据计算出最优参数对,作为之后serviceLife个交易日的交易参数 /// </summary> /// <param name="result"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="choicePeriod"></param> /// <param name="serviceLife"></param> /// <returns></returns> private Dictionary <DateTime, FourParameterPairs> chooseParameters(Dictionary <FourParameterPairs, SortedDictionary <DateTime, double> > result, DateTime startDate, DateTime endDate, int choicePeriod, int serviceLife) { DateTime start = startDate; DateTime end = DateUtils.NextTradeDay(start, choicePeriod - 1); DateTime paraStart = DateUtils.NextTradeDay(start, choicePeriod); DateTime paraEnd = DateUtils.NextTradeDay(start, choicePeriod + serviceLife - 1); //如果choicePeriod的数值,超过了回测周期的长度。做一些特殊处理。 if (end > endDate) { end = endDate; paraStart = start; paraEnd = end; } ///最高分。因为参数对计算得分可能会出现负数,所以这里初始默认值不能为0。 ///否则会出现循环所有参数对结束之后,最优参数对bestPara依然没有复制的情况。 double marks = -1000000; //用来记录(在choicePeriod时间段中)得分最高的参数对 FourParameterPairs bestPara = new FourParameterPairs(); //记录每个交易日的最佳参数对(Dictionary类型) Dictionary <DateTime, FourParameterPairs> paras = new Dictionary <DateTime, FourParameterPairs>(); //记录每个交易日使用的参数对(List类型),用于输出到CSV文件 List <ParameterPairsWithScore> parasWithScore = new List <ParameterPairsWithScore>(); #region debug专用 //debug专用:存贮所有参数组合在规定start, end期间的得分... Dictionary <FourParameterPairs, double> scoreWithParameterPair = new Dictionary <FourParameterPairs, double>(); #endregion while (end <= endDate) { //循环所有的参数组合,选出(在choicePeriod时间段中)得分最高的参数对 foreach (var item in result) { var mark0 = getMarks(result, item.Key, start, end); #region debug专用 //debug专用:存贮debug信息... if (mark0 > 0.1) { scoreWithParameterPair.Add(item.Key, mark0); } #endregion if (mark0 > marks) { marks = mark0; bestPara = item.Key; } } if (paras.Count() == 0) { List <DateTime> dates0 = DateUtils.GetTradeDays(start, end); foreach (var item in dates0) { paras.Add(item, bestPara); parasWithScore.Add(new ParameterPairsWithScore { tradeday = item, frequency = bestPara.frequency, numbers = bestPara.numbers, lossPercent = bestPara.lossPercent, ERRatio = bestPara.ERRatio, Score = marks }); } } //将选出的(choicePeriod时间段中)最优参数对,作为最优解保存到( choicePeriod + serviceLife时间段) List <DateTime> dates = DateUtils.GetTradeDays(paraStart, paraEnd); foreach (var item in dates) { paras.Add(item, bestPara); parasWithScore.Add(new ParameterPairsWithScore { tradeday = item, frequency = bestPara.frequency, numbers = bestPara.numbers, lossPercent = bestPara.lossPercent, ERRatio = bestPara.ERRatio, Score = marks }); } //计算日期往后顺延serviceLife时间段,重置相关数据 start = DateUtils.NextTradeDay(start, serviceLife); end = DateUtils.NextTradeDay(end, serviceLife); paraStart = DateUtils.NextTradeDay(paraStart, serviceLife); paraEnd = DateUtils.NextTradeDay(paraEnd, serviceLife); marks = -1000000; bestPara = new FourParameterPairs(); if (end >= endDate) { break; } #region debug专用 scoreWithParameterPair = new Dictionary <FourParameterPairs, double>(); #endregion } //每个交易日使用的策略,写入CSV文件 //List<ParameterPairs> tradeDaysWithBestParas = convertType(paras); string recordName = underlying.Replace(".", "_") + "_" + startDate.ToShortDateString().Replace("/", "_") + "_to_" + endDate.ToShortDateString().Replace("/", "_"); RecordUtil.recordToCsv(data: parasWithScore, type: "tradeDaysWithBestParas", tag: GetType().FullName, parameters: recordName, performance: ""); return(paras); }
public static void Descomprimir(IFormFile archivo) { if (File.Exists($"Datos\\{archivo.FileName}")) { File.Delete($"Datos\\{archivo.FileName}"); } using (var reader = new BinaryReader(archivo.OpenReadStream())) { using (var streamWriter = new FileStream($"Datos\\{archivo.FileName}", FileMode.OpenOrCreate)) { using (var writer = new BinaryWriter(streamWriter)) { var DiccionarioLetras = new Dictionary <int, string>(); var bufferLength = 10000; var bytebuffer = new byte[bufferLength]; bytebuffer = reader.ReadBytes(8); var CantidadDiccionario = Convert.ToInt32(Encoding.UTF8.GetString(bytebuffer)); for (int i = 0; i < CantidadDiccionario; i++) { bytebuffer = reader.ReadBytes(1); var Letra = Convert.ToChar(bytebuffer[0]).ToString(); DiccionarioLetras.Add(DiccionarioLetras.Count() + 1, Letra); } bytebuffer = reader.ReadBytes(1); var cantidadBits = Convert.ToInt32(bytebuffer[0]); var auxActual = string.Empty; var auxPrevio = string.Empty; var aux = string.Empty; var first = true; var bufferEscritura = new List <byte>(); while (reader.BaseStream.Position != reader.BaseStream.Length) { bytebuffer = reader.ReadBytes(bufferLength); foreach (var item in bytebuffer) { aux += Convert.ToString(item, 2).PadLeft(8, '0'); while (aux.Length >= cantidadBits) { var nuevoNum = Convert.ToInt32(aux.Substring(0, cantidadBits), 2); if (nuevoNum != 0) { if (first) { first = false; auxPrevio = DiccionarioLetras[nuevoNum]; bufferEscritura.Add(Convert.ToByte(Convert.ToChar(auxPrevio))); } else { if (nuevoNum > DiccionarioLetras.Count) { auxActual = auxPrevio + auxPrevio.First(); DiccionarioLetras.Add(DiccionarioLetras.Count + 1, auxActual); } else { auxActual = DiccionarioLetras[nuevoNum]; DiccionarioLetras.Add(DiccionarioLetras.Count + 1, $"{auxPrevio}{auxActual.First()}"); } foreach (var letra in auxActual) { bufferEscritura.Add(Convert.ToByte(letra)); } auxPrevio = auxActual; } } aux = aux.Substring(cantidadBits); } } } writer.Write(bufferEscritura.ToArray()); } } } }
public EffectsModifiedUndoAction(Dictionary <Element, EffectModelCandidate> changedElements, string labelName = "properties") { _changedElements = changedElements; _labelName = labelName; _count = _changedElements.Count(); }
/// <summary> /// 通用请求方法 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="method"></param> /// <param name="canonicalURI"></param> /// <param name="requestParas"></param> /// <returns></returns> private static T DingGovRequest <T>(HttpMethod method, string canonicalURI, Dictionary <string, string> requestParas) { var domain = Dingdomainname; var accessKey = Appkey; var secretKey = Appsecret; var timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"); var nonce = T_ConvertDateTimeToInt(DateTime.Now) + "1234"; var requestUrl = domain + canonicalURI; try { var bytesToSign = $"{method}\n{timestamp}\n{nonce}\n{canonicalURI}"; if (requestParas?.Count() > 0) { //参数参与签名 bytesToSign += '\n' + DicionartyToUrlParameters(requestParas); } var message = new HttpRequestMessage { Method = method, }; #region 请求头 //message.Headers.Add("X-Hmac-Auth-IP", "1.1.1.1"); //message.Headers.Add("X-Hmac-Auth-MAC", "MAC"); message.Headers.Add("X-Hmac-Auth-Timestamp", timestamp); message.Headers.Add("X-Hmac-Auth-Version", "1.0"); message.Headers.Add("X-Hmac-Auth-Nonce", nonce); message.Headers.Add("apiKey", accessKey); message.Headers.Add("X-Hmac-Auth-Signature", T_GetSignature(bytesToSign, secretKey)); #endregion if (method == HttpMethod.Post) { var paras = new Dictionary <string, string>(new RepeatDictionaryComparer()); if (requestParas?.Count() > 0) { foreach (var dic in requestParas) { if (canonicalURI == "/message/workNotification" && dic.Key == "msg") { paras.Add(dic.Key, dic.Value); } else { paras.Add(dic.Key, Uri.UnescapeDataString(dic.Value)); } } message.Content = new FormUrlEncodedContent(paras); message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); } } else if (method == HttpMethod.Get) { requestUrl += $"?{DicionartyToUrlParameters(requestParas)}"; } message.RequestUri = new Uri(requestUrl); using (var client = new HttpClient()) { var request = client.SendAsync(message); var reponseContent = request.Result.Content.ReadAsStringAsync(); //记录日志 if (!request.Result.IsSuccessStatusCode) { throw new Exception(reponseContent.Result); } return(JsonConvert.DeserializeObject <T>(reponseContent.Result)); } } catch (Exception ex) { //记录日志 return((T) default);
static object Solve() { var s = Console.ReadLine(); var n = s.Length; var d = new Dictionary <char, Queue <int> >(); var lastIndexes = new Dictionary <char, int>(); for (char c = 'a'; c <= 'z'; c++) { d[c] = new Queue <int>(); lastIndexes[c] = max; } for (int i = 0; i < n; i++) { d[s[i]].Enqueue(i); lastIndexes[s[i]] = i; } var length = d.Count(p => p.Value.Any()); var r = new char[length]; for (int i = 0; i < length; i++) { for (char c = 'z'; c >= 'a'; c--) { if (lastIndexes[c] == max) { continue; } if (IsNext(c)) { r[i] = c; var index = d[c].Dequeue(); d[c].Clear(); lastIndexes[c] = max; for (char c2 = 'a'; c2 <= 'z'; c2++) { if (lastIndexes[c2] == max) { continue; } var q = d[c2]; while (q.Peek() < index) { q.Dequeue(); } } break; } } } return(new string(r)); bool IsNext(char c) { var index = d[c].Peek(); for (c--; c >= 'a'; c--) { if (lastIndexes[c] < index) { return(false); } } return(true); } }
public async Task <Dictionary <string, PKMember> > CreateMembersBulk(PKSystem system, Dictionary <string, string> names) { using (var conn = await _conn.Obtain()) using (var tx = conn.BeginTransaction()) { var results = new Dictionary <string, PKMember>(); foreach (var name in names) { string hid; do { hid = await conn.QuerySingleOrDefaultAsync <string>("SELECT @Hid WHERE NOT EXISTS (SELECT id FROM members WHERE hid = @Hid LIMIT 1)", new { Hid = Utils.GenerateHid() }); } while (hid == null); var member = await conn.QuerySingleAsync <PKMember>("INSERT INTO members (hid, system, name) VALUES (@Hid, @SystemId, @Name) RETURNING *", new { Hid = hid, SystemID = system.Id, Name = name.Value }); results.Add(name.Key, member); } tx.Commit(); _logger.Information("Created {MemberCount} members for system {SystemID}", names.Count(), system.Hid); return(results); } }
bool IsFullUserCount() { return(MaxUserCount <= UserMap.Count()); }
public static async void postPoCPosted() { string cpuReturn = returnMonitorListAsString(cpuList); string ramReturn = returnMonitorListAsString(ramList); string harddiskReturn = returnMonitorListAsString(harddiskList); string threadReturn = returnMonitorListAsString(threadList); string handleReturn = returnMonitorListAsString(handleList); List <string> killedProcesses = ActionTaker.getKilledProcesses(); string changedFilesReturn = ""; string deletedFilesReturn = ""; string newFilesReturn = ""; string filemonChangesReturn = ""; string killedProcessesReturn = ""; for (int i = 0; i < changedKeyList.Count - 1; i++) { changedFilesReturn += changedKeyList[i]; changedFilesReturn += "?"; } foreach (string s in hashedFilesAtStartKeys) { deletedFilesReturn += s; deletedFilesReturn += "?"; } foreach (string s in hashedFilesAtEndKeys) { newFilesReturn += s; newFilesReturn += "?"; } foreach (var item in fileMonChanges) { filemonChangesReturn += item.Value + ":" + item.Key.ToString("dd/MM/yyyy HH:mm:ss.fff"); filemonChangesReturn += "?"; } foreach (string s in killedProcesses) { killedProcessesReturn += s; killedProcessesReturn += "?"; } var options = new { RansomwareName = NAMEONTEST, MonitorStatus = "1", MonitorCount = amountOfLoops.ToString(), CountChangedFiles = changedKeyList.Count().ToString(), CountDeletedFiles = hashedFilesAtStartKeys.Count().ToString(), CountNewFiles = hashedFilesAtEndKeys.Count().ToString(), CountFilemonObservations = fileMonChanges.Count().ToString(), CPU = cpuReturn, RAM = ramReturn, HDD = harddiskReturn, ThreadCount = threadReturn, HandleCount = handleReturn, ListChangedFiles = changedFilesReturn, ListDeletedFiles = deletedFilesReturn, ListNewFiles = newFilesReturn, ListFilemonObservations = filemonChangesReturn, NameOfShutdownRansomware = killedProcessesReturn, Detected = FileMon.getFirstDetected().ToString("dd/MM/yyyy HH:mm:ss.fff"), Shutdown = ActionTaker.getFirstKilledTime().ToString("dd/MM/yyyy HH:mm:ss.fff") }; var stringPayload = JsonConvert.SerializeObject(options); var content = new StringContent(stringPayload, Encoding.UTF8, "application/json"); var response = client.PostAsync("http://192.168.8.102/v1/index.php/posthp1posted", content).Result; var result = await response.Content.ReadAsByteArrayAsync(); }
/// <summary> /// 读取奖项 /// </summary> private void GetPrizeCategories() { var ws = _wb.Worksheets.FirstOrDefault(); if (ws != null) { var firstRow = ws.FirstRowUsed(); firstRow = firstRow.RowBelow(); firstRow = firstRow.RowBelow(); firstRow = firstRow.RowBelow(); var categoryRow = firstRow.RowUsed(); int maxColNo = categoryRow.CellCount(); _lastCategoryColNo = maxColNo; int currentCol = 4; string category = ""; //int perCategoryCols = 1; _dictionaryCategory = new Dictionary <int, string>(); while (currentCol <= maxColNo) { if (categoryRow.Cell(currentCol).IsEmpty()) { if (currentCol <= _lastProjectColNo) { _dictionaryCategory.Add(currentCol, ""); } else { _dictionaryPrizeClassify.Add(currentCol, _dictionaryPrizeClassify[_lastClassifyColNo]); _lastClassifyColNo++; _dictionaryProject.Add(currentCol, _dictionaryProject[_lastProjectColNo]); _lastProjectColNo++; _dictionaryCategory.Add(currentCol, ""); } currentCol++; } else { string temp = categoryRow.Cell(currentCol).GetString(); temp = temp.Replace(" ", ""); if (temp.Contains("小计")) { _dictionaryCategory.Add(currentCol, ""); currentCol++; } else { category = temp; _dictionaryCategory.Add(currentCol, category); if (currentCol > _lastProjectColNo) { _dictionaryPrizeClassify.Add(currentCol, _dictionaryPrizeClassify[_lastClassifyColNo]); _lastClassifyColNo++; _dictionaryProject.Add(currentCol, _dictionaryProject[_lastProjectColNo]); _lastProjectColNo++; } //perCategoryCols = 1; currentCol++; } } } int lastCol = _dictionaryPrizeClassify.Count() > _dictionaryProject.Count() ? 3 + _dictionaryPrizeClassify.Count() : 3 + _dictionaryProject.Count(); if (maxColNo < lastCol) { maxColNo++; while (maxColNo <= lastCol) { _dictionaryCategory.Add(maxColNo, ""); maxColNo++; } _lastCategoryColNo = lastCol; } } }
public static int NumberOfUsersInChannel(string channelName) { return(ChannelDictionary.Count(x => x.Value == channelName)); }
public static string[] GetDictionaryPath(LogicObjects.TrackerInstance Instance) { var Currentversion = Instance.LogicVersion; //Get the dictionary int smallestDicEntry = 0; int largestDicEntry = 0; Dictionary <int, string> dictionaries = new Dictionary <int, string>();//< Int (Version),String (Path to the that dictionary)> var dic = Instance.GameCode + "DICTIONARY"; string[] files = Directory.GetFiles(@"Recources\Dictionaries").Where(x => x.Contains(dic)).ToArray(); foreach (var i in files) { var entry = i.Replace("Recources\\Dictionaries\\" + dic + "V", ""); entry = entry.Replace(".csv", ""); int version = 0; try { version = Int32.Parse(entry); } catch { continue; } dictionaries.Add(version, i); if (version > largestDicEntry) { largestDicEntry = version; } if (smallestDicEntry == 0) { smallestDicEntry = largestDicEntry; } if (version < smallestDicEntry) { smallestDicEntry = version; } } //Get the entrance pair list int smallestPairEntry = 0; int largestPairEntry = 0; Dictionary <int, string> Pairs = new Dictionary <int, string>();//< Int (Version),String (Path to the that dictionary)> dic = Instance.GameCode + "ENTRANCEPAIRS"; files = Directory.GetFiles(@"Recources\Other Files").Where(x => x.Contains(dic)).ToArray(); foreach (var i in files) { var entry = i.Replace("Recources\\Other Files\\" + dic + "V", ""); entry = entry.Replace(".csv", ""); int version = 0; try { version = Int32.Parse(entry); } catch { continue; } Pairs.Add(version, i); if (version > largestPairEntry) { largestPairEntry = version; } if (smallestPairEntry == 0) { smallestPairEntry = largestPairEntry; } if (version < smallestPairEntry) { smallestPairEntry = version; } } string[] currentdictionary = new string[2]; var index = 0; if (dictionaries.Count() == 0) { currentdictionary[0] = ""; } else { if (dictionaries.ContainsKey(Currentversion)) { index = Currentversion; } else //If we are using a logic version that doesn't have a dictionary, use the dictioary with the closest version { index = dictionaries.Keys.Aggregate((x, y) => Math.Abs(x - Currentversion) < Math.Abs(y - Currentversion) ? x : y); } currentdictionary[0] = dictionaries[index]; } Console.WriteLine(currentdictionary[0]); if (Pairs.Count() == 0) { currentdictionary[1] = ""; } else { if (Pairs.ContainsKey(Currentversion)) { index = Currentversion; } else //If we are using a logic version that doesn't have a Pair List, use the pair List with the closest version { index = Pairs.Keys.Aggregate((x, y) => Math.Abs(x - Currentversion) < Math.Abs(y - Currentversion) ? x : y); } currentdictionary[1] = Pairs[index]; } Console.WriteLine(currentdictionary[1]); return(currentdictionary); }
// Public Function count() As Integer // count = Points_.Count //End Function public int count() { return(Points_.Count()); }
/// <summary> /// 政务钉请求 /// </summary> /// <param name="method"></param> /// <param name="canonicalURI"></param> /// <param name="requestParas"></param> /// <returns></returns> public static string DingGovRequest(Method method, string canonicalURI, Dictionary <string, string> requestParas = null) { var timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"); var nonce = ConvertDateTimeToInt(DateTime.Now) + "1234"; var requestUrl = AppSetting.GetSection("ZDingTalk:DingUrl").ToString(); //域名配置地址 var client = new RestClient(requestUrl); try { var request = new RestRequest(canonicalURI, method); var bytesToSign = $"{method}\n{timestamp}\n{nonce}\n{canonicalURI}"; if (requestParas?.Count() > 0) { requestParas = requestParas.OrderBy(m => m.Key).ToDictionary(m => m.Key, p => p.Value); //参数参与签名 bytesToSign += '\n' + DicionartyToUrlParameters(requestParas); } #region 请求头 Dictionary <string, string> dict = new Dictionary <string, string>() { // {"X-Hmac-Auth-IP","1.1.1.1"}, // {"X-Hmac-Auth-MAC","MAC"}, { "X-Hmac-Auth-Timestamp", timestamp }, { "X-Hmac-Auth-Version", "1.0" }, { "X-Hmac-Auth-Nonce", nonce }, { "apiKey", AppSetting.GetSection("ZDingTalk:AppKey").ToString() }, { "Content-Type", "application/json" }, { "X-Hmac-Auth-Signature", GetSignature(bytesToSign, AppSetting.GetSection("ZDingTalk:AppSecret").ToString()) }, }; client.AddDefaultHeaders(dict); #endregion if (method == Method.POST) { var paras = new Dictionary <string, string>(); if (requestParas?.Count() > 0) { foreach (var dic in requestParas) { //paras.Add(dic.Key, Uri.UnescapeDataString(dic.Value)); request.AddParameter(dic.Key, Uri.UnescapeDataString(dic.Value)); } } } else if (method == Method.GET) { requestUrl += $"?{DicionartyToUrlParameters(requestParas)}"; } var response = client.Execute(request); if (!response.IsSuccessful) { throw new Exception(response.Content); } return(response.Content); } catch (Exception ex) { //记录日志 throw; } }
/// <summary> /// Updates the available vehicle category list. /// </summary> public void UpdateMenuAvailableCategories() { savedVehicles = GetSavedVehicles(); svMenuItems = new Dictionary <MenuItem, KeyValuePair <string, VehicleInfo> >(); for (int i = 1; i < GetMenu().Size - 1; i++) { if (savedVehicles.Any(a => GetVehicleClassFromName(a.Value.model) == i - 1 && IsModelInCdimage(a.Value.model))) { GetMenu().GetMenuItems()[i].RightIcon = MenuItem.Icon.NONE; GetMenu().GetMenuItems()[i].Label = "→→→"; GetMenu().GetMenuItems()[i].Enabled = true; GetMenu().GetMenuItems()[i].Description = $"All saved vehicles from the {GetMenu().GetMenuItems()[i].Text} category."; } else { GetMenu().GetMenuItems()[i].Label = ""; GetMenu().GetMenuItems()[i].RightIcon = MenuItem.Icon.LOCK; GetMenu().GetMenuItems()[i].Enabled = false; GetMenu().GetMenuItems()[i].Description = $"You do not have any saved vehicles that belong to the {GetMenu().GetMenuItems()[i].Text} category."; } } // Check if the items count will be changed. If there are less cars than there were before, one probably got deleted // so in that case we need to refresh the index of that menu just to be safe. If not, keep the index where it is for improved // usability of the menu. foreach (Menu m in subMenus) { int size = m.Size; int vclass = subMenus.IndexOf(m); int count = savedVehicles.Count(a => GetVehicleClassFromName(a.Value.model) == vclass); if (count < size) { m.RefreshIndex(); } } foreach (Menu m in subMenus) { // Clear items but don't reset the index because we can guarantee that the index won't be out of bounds. // this is the case because of the loop above where we reset the index if the items count changes. m.ClearMenuItems(true); } // Always clear this index because it's useless anyway and it's safer. unavailableVehiclesMenu.ClearMenuItems(); foreach (var sv in savedVehicles) { if (IsModelInCdimage(sv.Value.model)) { int vclass = GetVehicleClassFromName(sv.Value.model); Menu menu = subMenus[vclass]; MenuItem savedVehicleBtn = new MenuItem(sv.Key.Substring(4), $"Manage this saved vehicle."); savedVehicleBtn.Label = $"({sv.Value.name}) →→→"; menu.AddMenuItem(savedVehicleBtn); svMenuItems.Add(savedVehicleBtn, sv); } else { MenuItem missingVehItem = new MenuItem(sv.Key.Substring(4), "This model could not be found in the game files. Most likely because this is an addon vehicle and it's currently not streamed by the server."); missingVehItem.Label = "(" + sv.Value.name + ")"; missingVehItem.Enabled = false; missingVehItem.LeftIcon = MenuItem.Icon.LOCK; unavailableVehiclesMenu.AddMenuItem(missingVehItem); } } foreach (Menu m in subMenus) { m.SortMenuItems((MenuItem A, MenuItem B) => { return(A.Text.ToLower().CompareTo(B.Text.ToLower())); }); } }
/// <summary> /// How many dead characters there are. /// </summary> /// <returns>>=0</returns> public int DeadCharacters() => _characters?.Count(m => m.Value.Available && m.Value.IsDead) ?? 0;
public MarksAddedRemovedUndoAction(TimedSequenceEditorForm form, Dictionary <TimeSpan, MarkCollection> markCollections) { _form = form; _markCollections = markCollections; _count = _markCollections.Count(); }
public static void Comprimir(string nombre) { Directory.CreateDirectory("temp"); ArbolB <ProductData> .IniciarArbol(nombre, null, null); using (var streamReader = new FileStream($"Datos\\{nombre}.txt", FileMode.Open)) { using (var reader = new BinaryReader(streamReader)) { using (var streamWriter = new FileStream($"temp\\{nombre}.txt", FileMode.OpenOrCreate)) { using (var writer = new BinaryWriter(streamWriter)) { var DiccionarioLetras = new Dictionary <string, string>(); var bufferLength = 10000; var bytebuffer = new byte[bufferLength]; var stringLetra = string.Empty; while (reader.BaseStream.Position != reader.BaseStream.Length) { bytebuffer = reader.ReadBytes(bufferLength); for (int i = 0; i < bytebuffer.Count(); i++) { stringLetra = Convert.ToString(Convert.ToChar(bytebuffer[i])); if (!DiccionarioLetras.ContainsKey(stringLetra)) { var stringnum = Convert.ToString(DiccionarioLetras.Count() + 1, 2); DiccionarioLetras.Add(stringLetra, stringnum); stringLetra = string.Empty; } } } writer.Write(Encoding.UTF8.GetBytes(Convert.ToString(DiccionarioLetras.Count).PadLeft(8, '0').ToCharArray())); foreach (var fila in DiccionarioLetras) { writer.Write(Convert.ToByte(Convert.ToChar(fila.Key[0]))); } reader.BaseStream.Position = 0; stringLetra = string.Empty; var anterior = string.Empty; var ListaCaracteres = new List <string>(); while (reader.BaseStream.Position != reader.BaseStream.Length) { bytebuffer = reader.ReadBytes(bufferLength); for (int i = 0; i < bytebuffer.Count(); i++) { stringLetra += Convert.ToString(Convert.ToChar(bytebuffer[i])); if (!DiccionarioLetras.ContainsKey(stringLetra)) { var stringnum = Convert.ToString(DiccionarioLetras.Count() + 1, 2); DiccionarioLetras.Add(stringLetra, stringnum); ListaCaracteres.Add(DiccionarioLetras[anterior]); anterior = string.Empty; anterior += stringLetra.Last(); stringLetra = anterior; } else { anterior = stringLetra; } } } ListaCaracteres.Add(DiccionarioLetras[stringLetra]); var cantMaxBits = Math.Log2((float)DiccionarioLetras.Count); cantMaxBits = cantMaxBits % 1 >= 0.5 ? Convert.ToInt32(cantMaxBits) : Convert.ToInt32(cantMaxBits) + 1; writer.Write(Convert.ToByte(cantMaxBits)); for (int i = 0; i < ListaCaracteres.Count; i++) { ListaCaracteres[i] = ListaCaracteres[i].PadLeft(Convert.ToInt32(cantMaxBits), '0'); } var bufferEscritura = new List <byte>(); var aux = string.Empty; foreach (var item in ListaCaracteres) { aux += item; if (aux.Length >= 8) { var max = aux.Length / 8; for (int i = 0; i < max; i++) { bufferEscritura.Add(Convert.ToByte(Convert.ToInt32(aux.Substring(0, 8), 2))); aux = aux.Substring(8); } } } if (aux.Length != 0) { bufferEscritura.Add(Convert.ToByte(Convert.ToInt32(aux.PadRight(8, '0'), 2))); } writer.Write(bufferEscritura.ToArray()); } } } } }
void TransferContextsFlowEdges() { var initializeContexts = m_SourceControllers.OfType <VFXContextController>().Where(t => t.model.contextType == VFXContextType.Init || t.model.contextType == VFXContextType.Spawner || t.model.contextType == VFXContextType.Subgraph).ToArray(); var outputSpawners = new Dictionary <VFXContextController, List <VFXFlowAnchorController> >(); var outputEvents = new Dictionary <string, List <VFXFlowAnchorController> >(); foreach (var initializeContext in initializeContexts) { for (int i = 0; i < initializeContext.flowInputAnchors.Count; ++i) { if (initializeContext.flowInputAnchors[i].connections.Count() > 0) { var outputContext = initializeContext.flowInputAnchors[i].connections.First().output.context; //output context must be linked through is it is linked with a spawner if (!m_SourceControllers.Contains(outputContext)) { if (outputContext.model.contextType == VFXContextType.Spawner /*|| * ((outputContext.model is VFXBasicEvent) && * (new string[] { VisualEffectAsset.PlayEventName, VisualEffectAsset.StopEventName }.Contains((outputContext.model as VFXBasicEvent).eventName) || * sourceController.model.isSubgraph && (outputContext.model as VFXBasicEvent).eventName == VFXSubgraphContext.triggerEventName))*/) { List <VFXFlowAnchorController> inputs = null; if (!outputSpawners.TryGetValue(outputContext, out inputs)) { inputs = new List <VFXFlowAnchorController>(); outputSpawners.Add(outputContext, inputs); } inputs.Add(initializeContext.flowInputAnchors[i]); } else if (outputContext.model is VFXBasicEvent) { List <VFXFlowAnchorController> inputs = null; var eventName = (outputContext.model as VFXBasicEvent).eventName; if (!outputEvents.TryGetValue(eventName, out inputs)) { inputs = new List <VFXFlowAnchorController>(); outputEvents.Add(eventName, inputs); } inputs.Add(initializeContext.flowInputAnchors[i]); } } } } } { if (outputSpawners.Count() > 1) { Debug.LogWarning("More than one spawner is linked to the content if the new subgraph, some links we not be kept"); } } { //link named events as if foreach (var kv in outputEvents) { CreateAndLinkEvent(m_SourceControllers, m_TargetController, m_TargetControllers, kv.Value, kv.Key); } } }
/// <summary> /// Returns the number of worked grounds in a determined range from the player. /// </summary> public int CountTerrainsInRange(float range) { return(WorkedGrounds.Count(o => o.Value.Distance(UtilityClass.Player.Position) <= range)); }
protected override object SolvePart1() { var state = "A"; var tape = new Dictionary <int, int>(); var a = 12317297; var pos = 0; var statePos = 0; for (var i = 0; i < a; i++) { if (!tape.ContainsKey(pos)) { tape.Add(pos, 0); } if (state[statePos] == 'A') { if (tape[pos] == 0) { tape[pos] = 1; pos++; state = "B"; } else { tape[pos] = 0; pos--; state = "D"; } } else if (state[statePos] == 'B') { if (tape[pos] == 0) { tape[pos] = 1; pos++; state = "C"; } else { tape[pos] = 0; pos++; state = "F"; } } else if (state[statePos] == 'C') { if (tape[pos] == 0) { tape[pos] = 1; pos--; state = "C"; } else { tape[pos] = 1; pos--; state = "A"; } } else if (state[statePos] == 'D') { if (tape[pos] == 0) { tape[pos] = 0; pos--; state = "E"; } else { tape[pos] = 1; pos++; state = "A"; } } else if (state[statePos] == 'E') { if (tape[pos] == 0) { tape[pos] = 1; pos--; state = "A"; } else { tape[pos] = 0; pos++; state = "B"; } } else if (state[statePos] == 'F') { if (tape[pos] == 0) { tape[pos] = 0; pos++; state = "C"; } else { tape[pos] = 0; pos++; state = "E"; } } } return(tape.Count(i => i.Value == 1)); }