public void SelectProperty(string name, Button openPopupWithThis) { var parentWindow = Web.PortalDriver.Title; Wait.Until(d => openPopupWithThis.Exists); openPopupWithThis.AsyncClick(); Thread.Sleep(2000); PopUpWindow.SwitchTo(Title); // Switch to the frame within this popup dialog Web.PortalDriver.SwitchTo() .Frame(Web.PortalDriver.FindElement(By.Id("ifrmAttributeTable"))); Wait.Until(d => new Container(By.Id("spanAttributeName")).Exists); var parsedName = name.Split('.'); var path = new String[parsedName.Length - 1]; Array.Copy(parsedName, path, parsedName.Length - 1); var propertyName = parsedName.Last(); foreach (var expander in path.Select(attr => new Button(By.XPath(String.Format("//*[@id='spanAttributeName' and text()='{0}']/../../td[1]/a", attr))))) { expander.Click(); } var property = new Container(By.XPath(String.Format("//*[@id='spanAttributeName' and text()='{0}']", propertyName))); property.Click(); // Switch back out of frame PopUpWindow.SwitchTo(Title); OkButton.Click(); PopUpWindow.SwitchTo(parentWindow); }
/// <summary> /// Valida a Chave de Acesso de um documento fiscal. /// </summary> /// <param name="chaveAcesso">Chave de Acesso</param> /// <returns>verdadeiro caso a Chave de Acesso seja valida, false caso contrário.</returns> public static Boolean IsChaveAcessoValida(String chaveAcesso) { if (String.IsNullOrWhiteSpace(chaveAcesso) || chaveAcesso.Length != 44) { return false; } if (!Regex.IsMatch(chaveAcesso, @"^\d{44}$")) { return false; } int[] digitos = chaveAcesso.Select(x => int.Parse(x.ToString())).ToArray(); int soma = 0, dv, m; for (int i = digitos.Length - 2; i >= 0; ) { for (int p = 2; p <= 9 && i >= 0; p++, i--) { soma += digitos[i] * p; } } m = (soma % 11); dv = m <= 1 ? 0 : dv = 11 - m; return dv == digitos.Last(); }
public bool Matches(String str) { var chars = str.Distinct().Select(x => x.ToString()).ToList(); Dictionary<string, Boolean> mapping = new Dictionary<string, bool>(); mapping.Add(chars[0], true); mapping.Add(chars[1], false); var match = str.Select(x => mapping[x.ToString()]).Zip(BooleanPattern, (x, y) => x == y).All(x => x==true); if (match) return true; mapping.Clear(); mapping.Add(chars[0], false); mapping.Add(chars[1], true); match = str.Select(x => mapping[x.ToString()]).Zip(BooleanPattern, (x, y) => x == y).All(x => x == true); return match; }
public JsonResult GetQualifiedValues(String part, String locale, String[] keys) { if (!_context.DebugMode) throw new Exception("Unauthorized: DebugMode not on."); var values = keys == null ? Enumerable.Empty<FlattenedQualifiedValue>() : keys.Select(key => new FlattenedQualifiedValue(_context.Repository.GetQualified(new Qualifier.Unique(Part.Parse(part), new Locale(locale), key)))); return Json(new { Success = true, Values = values }, JsonRequestBehavior.AllowGet); }
internal static string TransformSpecialCase(IRow theRow, short redLightDiviser, short numberOfLightsOn) { var lightsOn = new String('\0', numberOfLightsOn); lightsOn = String.Join("", lightsOn.Select((light, index) => CheckIfIsTimeToUseRed(index, redLightDiviser) ? BerlinClockConstants.RedLight : BerlinClockConstants.YellowLight)); return AppendLightsOffAndLineBreak(theRow.NumberOfLights, lightsOn, theRow.HasLineBreak); }
public uint ComputeCrcHash(String input) { Byte[] bytes = input.Select(c => (byte) c).ToArray(); uint crc = bytes.Aggregate(0xffffffff, (current, b) => (current >> 8) ^ CrcTable[(current ^ b) & 0xff]); crc = crc ^ 0xffffffff; return crc; }
public static String reconstructMessage(String s, int k) { var r = s.GroupBy(x => x) .Select(x => new KeyValuePair<int, char>(x.Count(), x.First())) .Aggregate( new { pr = new KeyValuePair<int, char>(0, '0'), alphabet = "abcdefghijklmnopqrstuvwxyz" }, (seed, x) => { if (s.Count() - x.Key == k) return new { pr = x, alphabet = String.Join("", seed.alphabet.Except(new String(x.Value, 1))) }; return new { pr = seed.pr, alphabet = String.Join("", seed.alphabet.Except(new String(x.Value, 1))) }; }); if (r.pr.Key != 0) return String.Join("", s.Select(x => new String(r.pr.Value, 1))); return String.Join("", s.Select(x => new String(r.alphabet.First(), 1)));; }
static void Main(string[] args) { while (true) { // sleeps 10 milliseconds not to eat out cpu time Thread.Sleep(10); String action = Console.ReadLine().Trim(); switch (action) { case "ready?": Console.WriteLine("ready!"); Console.Out.Flush(); break; case "generate code": // makes a list of 25 dots, converts one of them in a sharp, splits the string in // 5 tokens of 5 characters each List<char> row = new String('.', 25).ToCharArray().ToList(); row[new Random().Next(24)] = '#'; List<string> rows = new List<string>(); for (int i = 0; i < 5; i++) rows.Add(string.Join("", row.Select(c => c.ToString()) .Skip(i*5) .Take(5) .ToArray())); foreach (string s in rows) { Console.WriteLine(s); Console.Out.Flush(); } break; case "find code": List<string> code = new List<string>(); for (int i = 0; i < 5; i++) code.Add(Console.ReadLine()); for (int y = 0; y < 5; y++) { int x = code[y].IndexOf('#'); if (x != -1) { Console.WriteLine("{0} {1}", x, y); Console.Out.Flush(); } } break; case "bye!": Console.WriteLine("bye!"); Console.Out.Flush(); System.Environment.Exit(0); break; } } }
static String[] set_x(String[] board, Char c) { bool changed = false; return board .Select(xs => String.Join("", xs.Select(x => { if (changed == false && x == '?') { changed = true; return c; } return x; })) ) .ToArray(); }
public void SelectProperty(string name) { // Switch to the frame within this popup dialog Web.PortalDriver.SwitchTo() .Frame(Web.PortalDriver.FindElement(By.Id("ifrmAttributeTable"))); Wait.Until(d => new Container(By.Id("spanAttributeName")).Exists); var parsedName = name.Split('.'); var path = new String[parsedName.Length - 1]; Array.Copy(parsedName, path, parsedName.Length - 1); //var propertyName = parsedName.Last(); foreach (var expander in path.Select(attr => new Button(By.XPath(String.Format("//*[@id='spanAttributeName' and text()='{0}']/../../td[1]/a", attr))))) { expander.Click(); } var property = new Container(By.XPath(String.Format("//*[@id='spanQualifiedAttributeDisplayName' and text()='{0}']/../span", name))); property.Click(); Web.PortalDriver.SwitchTo().DefaultContent(); }
[OutputCache(CacheProfile = "NoCacheProfile")] // TODO: Can't we just vary cache by parameter, when does it crawl ? public ActionResult _SearchResults(String searchTerm, String[] sources, String[] refiners, Int32 iDisplayLength = 10, Int32 iDisplayStart = 0) { Dictionary<String, String> srcs = null; if (sources != null && sources.Length > 0) { srcs = sources.Select(src => src.Split(':')).ToDictionary(defs => defs[0], defs => defs[1]); } Dictionary<String, String> refs = null; if (refiners != null && refiners.Length > 0) { var rs = refiners.Select(r => new Tuple<String, String>(r.Split(new Char[] { ':' })[0], r.Split(new Char[] { ':' })[1])) .GroupBy(r => r.Item1); refs = rs.ToDictionary(g => g.Key, g => g.Select(t => t.Item2).Aggregate((a, b) => a + "," + b)); } var searchContent = _businessModule.GetSearchResults(searchTerm, srcs, refs, iDisplayStart, iDisplayLength); return PartialView(searchContent); }
public void Map(String typeName, String[] queueName) { _typeNames.Add(typeName); _typeNamesMap.Add(typeName, queueName.Select(name => new QueueName(name)).ToArray()); }
/// <summary> /// Entry point - pass "verbose" as a command-line /// argument to initialize Embree in verbose mode. /// </summary> public static int Main(String[] args) { try { var verbose = (args.Select(s => s.ToLower()).Contains("verbose")); if (verbose) args.Select(s => s != "verbose"); // Clean up arglist ParseCommandLineArguments(args); // For selecting ray packet sizes if (verbose) { Console.WriteLine("Embree.NET Benchmark [VERBOSE]"); Console.WriteLine("=============================="); RTC.Register("verbose=999"); // max verbosity? } else { Console.WriteLine("Embree.NET Benchmark"); Console.WriteLine("===================="); } Console.WriteLine(""); // this is for debugging Console.WriteLine("[+] " + Bits + "-bit mode."); // Note this is similar to the original Embree benchmark program Console.WriteLine("[+] Performance indicators are per-thread."); { // Benchmark parameters int w = 1024, h = 1024; Console.WriteLine("[+] Benchmarking intersection queries."); foreach (var item in Benchmarks.Intersections(SceneFlags.Static, Flags, 501, w, h)) Measure(item.Item2, item.Item3, (s) => Console.WriteLine(" {0} = {1}", item.Item1.PadRight(35), s)); Console.WriteLine("[+] Benchmarking occlusion queries."); foreach (var item in Benchmarks.Occlusions(SceneFlags.Static, Flags, 501, w, h)) Measure(item.Item2, item.Item3, (s) => Console.WriteLine(" {0} = {1}", item.Item1.PadRight(35), s)); } /*{ Console.WriteLine("[+] Benchmarking geometry manipulations."); foreach (var item in Benchmarks.Geometries(SceneFlags.Static, Flags)) Measure(item.Item2, item.Item3, (s) => Console.WriteLine(" {0} = {1}", item.Item1.PadRight(35), s)); }*/ if (verbose) RTC.Unregister(); return EXIT_SUCCESS; } catch (Exception e) { var msg = e is AggregateException ? e.InnerException.Message : e.Message; Console.WriteLine(String.Format("[!] Error: {0}.", msg)); Console.WriteLine("\n========= STACK TRACE =========\n"); Console.WriteLine(e.StackTrace); return EXIT_FAILURE; } }
// Luhn Check methods (http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.23) private static bool luhnCheck(String cardNumber) { return luhnCheck(cardNumber.Select(c => c - '0').ToArray()); }
static bool remained(String[] board) { return board.Select(xs => xs.Select(x => x == '?').Aggregate((x, y) => x || y)) .Aggregate((x, y) => x || y); }
public static IDictionary<String, String> GetArguments(String[] args, String baseFile) { Dictionary<String, String> arguments = new Dictionary<String, String>(); if (!baseFile.IsNullOrEmpty() && new FileInfo(Assembly.GetCallingAssembly().Location).Directory.File(baseFile).Exists) { args = File.ReadAllLines("MetaTweet.args") .Where(l => !(l.StartsWith("#") || String.IsNullOrEmpty(l))) .Concat(args) .ToArray(); } foreach (Match match in args .Select(s => Regex.Match(s, "(-(?<key>[a-zA-Z0-9_]*)(=(?<value>(\"[^\"]*\")|('[^']*')|(.*)))?)*")) .Where(m => m.Success) ) { arguments[match.Groups["key"].Value] = match.Groups["value"].Success ? match.Groups["value"].Value : "true"; } return arguments; }
// Methods /// <summary> /// Creates a target <see cref="T:DataRecord"/> object that can be tested. /// </summary> /// <param name="columnNames">The column names.</param> /// <param name="values">The values.</param> /// <returns>The <see cref="T:DataRecord"/> created.</returns> private static DataRecord CreateDataRecord(String[] columnNames, Object[] values) { Debug.Assert(columnNames != null); Debug.Assert(columnNames.Length != 0); Debug.Assert(columnNames.All(columnName => columnName != null)); Debug.Assert(values != null); Debug.Assert(values.Length != 0); Debug.Assert(columnNames.Length == values.Length); using (DataTable dataTable = new DataTable()) { DataColumn[] dataColumns = columnNames .Select((columnName, i) => new DataColumn(columnName, values[i] != null ? values[i].GetType() : typeof(String))) .ToArray(); dataTable.Columns.AddRange(dataColumns); dataTable.Rows.Add(values); return dataTable.CreateDataReader().ReadAll().First(); } }
static bool check(String[] board) { return board.Select(xs => xs.GroupAdjacent(x => x).Count() == xs.Count()) .Aggregate((x, y) => x && y); }
private static IEnumerable<String> FilterDuplicateFormulae(String[] formulae) { var titles = formulae.Select(f => f.Substring(0, f.IndexOf("="))).ToArray(); for(var i = 0; i < formulae.Length; ++i) { var original = titles.Take(i).IndexOf(titles[i]); if (original == -1) { yield return formulae[i]; } else { Trace.WriteLine(String.Format("Ignoring '{0}': it has the same title as '{1}'", formulae[i], formulae[original])); } } Trace.WriteLine(String.Empty); }
public Pattern(String letter, String strPattern) { Letter = letter; StringPattern = strPattern; BooleanPattern = strPattern.Select(y => y == '*').ToList(); }
private String ConvertCharsToHexRepresentation(String text) { return String.Join("", text.Select(c => "\\u" + ((int)c).ToString("x4"))); }
public static void AddStringArrayAsDataSource(this ComboBox comboBox, String[] list) { comboBox.DataSource = list.Select(p => new {Name = p, Value = p}).ToList(); comboBox.ValueMember = "Value"; }
public static string ToUnderScore(this System.String str) => string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
// Methods /// <summary> /// Creates a target <see cref="T:IDataReader"/> object that can be tested. /// </summary> /// <param name="columnNames">The column names.</param> /// <param name="values">The values.</param> /// <returns>The <see cref="T:IDataReader"/> created.</returns> private static IDataReader CreateDataRecord(String[] columnNames, params IEnumerable<Object>[] values) { Debug.Assert(columnNames != null); Debug.Assert(columnNames.Length != 0); Debug.Assert(columnNames.All(columnName => columnName != null)); using (DataTable dataTable = new DataTable()) { DataColumn[] dataColumns = columnNames .Select((columnName, i) => new DataColumn(columnName, (values != null && values.Length > 0 && values[0].ElementAt(i) != null) ? values[0].ElementAt(i).GetType() : typeof(String))) .ToArray(); dataTable.Columns.AddRange(dataColumns); if (values != null && values.Length > 0) { foreach (Object[] rowValues in values) { dataTable.Rows.Add(rowValues); } } return dataTable.CreateDataReader(); } }
public TransCipher(String s) { Key = s.Select(ch => ch).Distinct().Count(); }
private void CheckAllLinesForSameWidth(String[] lines) { /* Assume the first line's width is correct. Even if it's not correct, errors will be thrown for all of the other lines. */ var widthOfFirstLine = this.GetWidthOfLine(lines[0]); var badLineWidths = lines .Select((line, index) => new { LineNumber = index + 1, Width = this.GetWidthOfLine(line) }) .Where(line => line.Width != widthOfFirstLine) .Select(line => String.Format(" Line {0} has {1} cells.", line.LineNumber, line.Width)); if (badLineWidths.Any()) throw new Exception(String.Format("Based on the width of the first line of the puzzle ({0}), the following lines have the wrong number of cells:{1}{2}", widthOfFirstLine, Environment.NewLine, String.Join(Environment.NewLine, badLineWidths))); }
private PitchType[] GetPitches(String pitches) { return pitches.Select(p => GetPitchType(p)).ToArray(); }
private void AfficherBlocHoraire(List<object> oTagInfo, String prof, Cours cours, BlocHoraire bloc) { Debug.Assert(bloc.EstAffecte); //On conserve seuelement les lettres majuscules pour identitfier le prof. prof = String.Concat(prof.Select(c => char.IsUpper(c) ? c.ToString() : String.Empty)); //On enlève les 0 et les lettres du numéro du groupe. string groupe = "Gr " + Regex.Match(cours.NoGroupe.Replace("0", ""), @"\d+").Value; //On conserve seulement une partie du numéro du cours String numero = cours.Numero.Remove(0, 4).Remove(3, 3); TableLayoutPanelCellPosition pos = CalculerPosition(bloc); // Affichage du Label System.Windows.Forms.Label lblCours = new System.Windows.Forms.Label(); lblCours.Text = numero + "\n" + prof + "\n" + groupe; lblCours.Anchor = AnchorStyles.Left; lblCours.Margin = new Padding(0); lblCours.AutoSize = false; lblCours.BackColor = GetCouleurFromNumCours(numero); lblCours.Width = tableLayoutPanel1.GetColumnWidths()[pos.Column]; lblCours.Height = tableLayoutPanel1.GetRowHeights()[pos.Row] * bloc.NbHeures; lblCours.ContextMenuStrip = this.contextMenuStrip1; lblCours.MouseDown += new System.Windows.Forms.MouseEventHandler(this.coursLabel_MouseDown); lblCours.AllowDrop = true; lblCours.Tag = oTagInfo; this.tableLayoutPanel1.Controls.Add(lblCours, pos.Column, pos.Row); this.tableLayoutPanel1.SetRowSpan(lblCours, bloc.NbHeures); }
private String HashString(String input) { return new SoapHexBinary(MD5.Create().ComputeHash(input.Select(Convert.ToByte).ToArray())).ToString().ToLower(); }
private static string Convert(String str, Encoding enc) { var b = str.Select(c => (byte)c).ToArray(); return enc.GetString(b); }
public static IList GetList(String csvLink, Boolean hasColumnNames, String groupBy, String filterBy, String filterValue, Boolean excatFilterMatch, String[] columnNamesToInclude) { ListImpl list = new ListImpl(); //WebClient client = new WebClient(); String content = ""; content = GetContent(csvLink.Replace("dl=0", "dl=1")); int iStart = content.IndexOf("//dl-web.dropbox.com/"); if (iStart > 0) { int iEnd = content.IndexOf("\"", iStart); if (iEnd > 0) { csvLink = content.Substring(iStart, iEnd - iStart); content = GetContent(csvLink); } } if( columnNamesToInclude != null ) columnNamesToInclude = columnNamesToInclude.Select(x => x.ToLower()).ToArray(); var lines = content.Split('\r'); //var lines = System.IO.File.ReadAllLines(fileName, System.Text.Encoding.UTF7); List<int> colsWithContent = new List<int>(); List<IRow> rows = new List<IRow>(); for (int i = 0; i < lines.Count(); i++) { var row = lines[i].Split(';'); IRow newRow = new RowImpl(); for (int iCol = 0; iCol < row.Length; iCol++) { String colValue = row[iCol]; // ColumnNames if (i == 0 && hasColumnNames && (columnNamesToInclude == null || columnNamesToInclude.Contains(colValue.ToLower()))) { if (!String.IsNullOrEmpty(colValue)) { if (!String.IsNullOrEmpty(colValue)) { colsWithContent.Add(iCol); } list.ColumnNames.Add(new ColumnNameImpl { Name = colValue }); } } else if (i > 0 || !hasColumnNames) { if (!hasColumnNames || colsWithContent.Contains(iCol)) { int realCol = colsWithContent.IndexOf(iCol); if (hasColumnNames && String.IsNullOrEmpty(list.ColumnNames[realCol].Type)) list.ColumnNames[realCol].Type = GetType(colValue); var newVal = new ValueImpl { Value = colValue }; Boolean addRow = true; DateTime tTemp; if (list.ColumnNames[realCol].Type == "DateTime") { if (!DateTime.TryParse(colValue, out tTemp)) tTemp = DateTime.MinValue; newVal.Value = tTemp; } if (newVal.Value is String) newVal.Value = newVal.Value.ToString().Replace("\n", ""); if (addRow) newRow.Values.Add(newVal); } } } if (!hasColumnNames || (newRow.Values.Count == list.ColumnNames.Count && newRow.Values.Any(y => !String.IsNullOrEmpty(y.Value as String)) && (i > 0 || !hasColumnNames))) rows.Add(newRow); } ListEntryImpl listEntry = null; if (!String.IsNullOrEmpty(filterBy)) { int index = list.ColumnNames.Select(x => x.Name.ToLower()).ToList().IndexOf(filterBy.ToLower()); if (index > -1) { if (excatFilterMatch) rows = rows.Where(x => (x.Values[index].Value ?? "").ToString() == filterValue).ToList(); else rows = rows.Where(x => (x.Values[index].Value ?? "").ToString().ToLower().Contains(filterValue.ToLower())).ToList(); } } if (!String.IsNullOrEmpty(groupBy)) { int index = list.ColumnNames.Select(x => x.Name).ToList().IndexOf(groupBy); if (index > -1) { var grouping = rows.GroupBy(x => x.Values[index].Value.ToString()).OrderBy(x => x.Key); rows = new List<IRow>(); foreach (var group in grouping) { listEntry = new ListEntryImpl { Title = group.Key.Replace("\n", ""), Parent = list, Rows = group.ToList() }; list.Add(listEntry); } } } if (list.Count() == 0 && rows.Count > 0) { listEntry = new ListEntryImpl { Parent = list, Rows = rows }; list.Add(listEntry); } list.CsvLink = csvLink; return list; }