protected override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var newTypeDeclaration = (TypeDeclarationSyntax)base.VisitClassDeclaration(node); if (_fields.Count > 0 || _methods.Count > 0) { var members = new List<MemberDeclarationSyntax>(newTypeDeclaration.Members); members.InsertRange(0, _methods); members.InsertRange(0, _fields); return ((ClassDeclarationSyntax)newTypeDeclaration).Update( newTypeDeclaration.Attributes, newTypeDeclaration.Modifiers, newTypeDeclaration.Keyword, newTypeDeclaration.Identifier, newTypeDeclaration.TypeParameterListOpt, newTypeDeclaration.BaseListOpt, newTypeDeclaration.ConstraintClauses, newTypeDeclaration.OpenBraceToken, Syntax.List(members.AsEnumerable()), newTypeDeclaration.CloseBraceToken, newTypeDeclaration.SemicolonTokenOpt); } return newTypeDeclaration; }
public List<string> GetAllArt() { List<string> paths = new List<string>(); paths.InsertRange(0, GetPlaylistArt()); paths.InsertRange(paths.Count - 1, GetAlbumArt()); return paths; }
private byte[] ToByteArray() { List<byte> messageBytes = new List<byte>(); foreach (STUNAttributeTLV attribute in this.Attributes) { messageBytes.InsertRange(messageBytes.Count, attribute.Bytes); MessageHeader.Length += attribute.Length; } messageBytes.InsertRange(0, MessageHeader.Bytes); return messageBytes.ToArray(); }
/// <summary> /// Gets the bytes matching the expected Kafka structure. /// </summary> /// <returns>The byte array of the request.</returns> public override byte[] GetBytes() { List<byte> encodedMessageSet = new List<byte>(); encodedMessageSet.AddRange(GetInternalBytes()); byte[] requestBytes = BitWorks.GetBytesReversed(Convert.ToInt16((int)RequestType.Produce)); encodedMessageSet.InsertRange(0, requestBytes); encodedMessageSet.InsertRange(0, BitWorks.GetBytesReversed(encodedMessageSet.Count)); return encodedMessageSet.ToArray(); }
/// <summary> /// Returns Artifacts files'information list from a given folder respecting include and exclude pattern /// </summary> /// <param name="directoryPath"></param> /// <param name="includePatterns"></param> /// <param name="excludePatterns"></param> public static IList<FileInfo> GetMatchingArtifactsFrom(string directoryPath, string includePatterns, string excludePatterns) { var fileInfos = new List<FileInfo>(); if (Directory.Exists((directoryPath))) { var includeFiles = new List<string>(); if (!string.IsNullOrEmpty(includePatterns)) { foreach (var includePattern in includePatterns.Split(',')) { if (includePattern.Contains(@"\") || includePattern.Contains(@"/")) { var regex = WildcardToRegex(includePattern); includeFiles.InsertRange(0, Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories) .Where(x => Regex.IsMatch(x, regex))); ; } else { includeFiles.InsertRange(0, Directory.GetFiles(directoryPath, includePattern, SearchOption.AllDirectories)); } } } var exludeFiles= new List<string>(); if (!string.IsNullOrEmpty(excludePatterns)) { foreach (var excludePattern in excludePatterns.Split(',')) { if (excludePattern.Contains(@"/") || excludePattern.Contains(@"\")) { var regex = WildcardToRegex(excludePattern); exludeFiles.InsertRange(0, Directory.GetFiles(directoryPath, "*", SearchOption.AllDirectories) .Where(x => Regex.IsMatch(x, regex))); } else { exludeFiles.InsertRange(0, Directory.GetFiles(directoryPath, excludePattern, SearchOption.AllDirectories)); } } } fileInfos = includeFiles.Except(exludeFiles) .Select(x=> new FileInfo(x)).ToList(); } return fileInfos; }
public static byte[] CombineFiles(FileEx[] data) { List<byte> result = new List<byte>(); // Generating the header int pos = 0; string toAdd = ""; foreach(var file in data) { int future = pos + file.data.Length; toAdd += string.Format("[|{0}|{1}|{2}|]", file.name, pos, file.data.Length); pos = future; } result.AddRange(GetBytes(toAdd)); //Adding the header's size result.InsertRange(0, BitConverter.GetBytes(result.Count)); //Adding the file data foreach(var file in data) { result.AddRange(file.data); } return result.ToArray(); }
// Method to retrieve all directories, recursively, within a store. public static List<String> GetAllDirectories(string pattern, IsolatedStorageFile storeFile) { // Get the root of the search string. string root = Path.GetDirectoryName(pattern); if (root != "") { root += "/"; } // Retrieve directories. List<String> directoryList = new List<String>(storeFile.GetDirectoryNames(pattern)); // Retrieve subdirectories of matches. for (int i = 0, max = directoryList.Count; i < max; i++) { string directory = directoryList[i] + "/"; List<String> more = GetAllDirectories(root + directory + "*", storeFile); // For each subdirectory found, add in the base path. for (int j = 0; j < more.Count; j++) { more[j] = directory + more[j]; } // Insert the subdirectories into the list and // update the counter and upper bound. directoryList.InsertRange(i + 1, more); i += more.Count; max += more.Count; } return directoryList; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Insert the collection to the beginning of the list"); try { string[] strArray = { "apple", "dog", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); string[] insert = { "Hello", "World" }; listObject.InsertRange(0, insert); if (listObject.Count != 8) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,Count is: " + listObject.Count); retVal = false; } if ((listObject[0] != "Hello") || (listObject[1] != "World")) { TestLibrary.TestFramework.LogError("004", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); retVal = false; } return retVal; }
private void SortGlobalSections(List<Line> lines) { var begin = lines .Where(line => line.Content.Trim().StartsWith("GlobalSection(", StringComparison.OrdinalIgnoreCase)) .ToList(); var sections = begin.Select(line => new { Begin = line, Entries = lines.Skip(line.Index + 1) .TakeWhile(x => !x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase)) .OrderBy(x => x.Content) .ToList(), End = lines.Skip(line.Index + 1) .First(x => x.Content.Trim().Equals("EndGlobalSection", StringComparison.OrdinalIgnoreCase)) }).ToList(); foreach (var section in sections) { lines.RemoveRange(section.Begin.Index + 1, section.Entries.Count); lines.InsertRange(section.Begin.Index + 1, section.Entries); } ResetIndexes(lines); }
/// <summary> /// Gets the bytes matching the expected Kafka structure. /// </summary> /// <returns>The byte array of the request.</returns> public override byte[] GetBytes() { List<byte> messagePack = new List<byte>(); foreach (Message message in Messages) { byte[] messageBytes = message.GetBytes(); messagePack.AddRange(BitWorks.GetBytesReversed(messageBytes.Length)); messagePack.AddRange(messageBytes); } byte[] requestBytes = BitWorks.GetBytesReversed(Convert.ToInt16((int)RequestType.Produce)); byte[] topicLengthBytes = BitWorks.GetBytesReversed(Convert.ToInt16(Topic.Length)); byte[] topicBytes = Encoding.UTF8.GetBytes(Topic); byte[] partitionBytes = BitWorks.GetBytesReversed(Partition); byte[] messagePackLengthBytes = BitWorks.GetBytesReversed(messagePack.Count); byte[] messagePackBytes = messagePack.ToArray(); List<byte> encodedMessageSet = new List<byte>(); encodedMessageSet.AddRange(requestBytes); encodedMessageSet.AddRange(topicLengthBytes); encodedMessageSet.AddRange(topicBytes); encodedMessageSet.AddRange(partitionBytes); encodedMessageSet.AddRange(messagePackLengthBytes); encodedMessageSet.AddRange(messagePackBytes); encodedMessageSet.InsertRange(0, BitWorks.GetBytesReversed(encodedMessageSet.Count)); return encodedMessageSet.ToArray(); }
public byte[] Write(ScenarioFile file) { var scenarioData = new List<byte>(); scenarioData.AddRange(Encoding.ASCII.GetBytes("SCENARIO\r\n")); scenarioData.AddRange(BitConverter.GetBytes(Version)); scenarioData.AddRange(BitConverter.GetBytes(file.ContentFiles.Count)); file.ContentFiles[0] = CreateAreaSubFile(file.ZoneData); var ndfBinWriter = new NdfbinWriter(); file.ContentFiles[1] = ndfBinWriter.Write(file.NdfBinary, false); foreach (var contentFile in file.ContentFiles) { scenarioData.AddRange(BitConverter.GetBytes(contentFile.Length)); scenarioData.AddRange(contentFile); } byte[] hash = MD5.Create().ComputeHash(scenarioData.ToArray()); scenarioData.InsertRange(10, hash.Concat(new byte[] { 0x00, 0x00 })); return scenarioData.ToArray(); }
private void Save_Button_Click(object sender, EventArgs e) { if (!IsCheckValidate()) { return; } List <Customer> saveData = this.CustommersData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (this.CustomersDeleteData != null) { saveData?.InsertRange(0, this.CustomersDeleteData); } if (saveData?.Count > 0) { CustomerController controller = new CustomerController(); if (controller.SaveCustommers(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); CustomersDeleteData = new List <Customer>(); this.LoadGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
private void UserSave_Button_Click(object sender, EventArgs e) { if (!IsCheckValidateUser()) { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000039); return; } List <Users> saveData = this.MasterData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (MasterDataDelete != null && MasterDataDelete.Count > 0) { saveData?.InsertRange(0, MasterDataDelete); } if (saveData?.Count > 0) { UserController controller = new UserController(); if (controller.SaveUser(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); MasterDataDelete = new List <Users>(); this.LoadGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
public override byte[] GetBytes() { var bytes = new List<byte>(base.GetBytes()); uint messageLength = (uint)bytes.Count; bytes.InsertRange(0, messageLength.GetBytes()); return bytes.ToArray(); }
public void Test(int arg) { ArrayList items = new ArrayList(); items.Add(1); items.AddRange(1, 2, 3); items.Clear(); bool b1 = items.Contains(2); items.Insert(0, 1); items.InsertRange(1, 0, 5); items.RemoveAt(4); items.RemoveRange(4, 3); items.Remove(1); object[] newItems = items.GetRange(5, 2); object[] newItems2 = items.GetRange(5, arg); List<int> numbers = new List<int>(); numbers.Add(1); numbers.AddRange(1, 2, 3); numbers.Clear(); bool b2 = numbers.Contains(4); numbers.Insert(1, 10); numbers.InsertRange(2, 10, 3); numbers.RemoveAt(4); numbers.RemoveRange(4, 2); int[] newNumbers = items.GetRange(5, 2); int[] newNumbers2 = items.GetRange(5, arg); string[] words = new string[5]; words[0] = "hello"; words[1] = "world"; bool b3 = words.Contains("hi"); string[] newWords = words.GetRange(5, 2); string[] newWords2 = words.GetRange(5, arg); }
private void AccountGroup_Save_Button_Click(object sender, EventArgs e) { if (!IsAccountGroupCheckValidate()) { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000039); return; } List <AccountGroup> saveData = this.AccountGroupData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (AccountGroupDeleteData != null && AccountGroupDeleteData.Count > 0) { saveData?.InsertRange(0, AccountGroupDeleteData); } if (saveData?.Count > 0) { AccountsController controller = new AccountsController(); if (controller.SaveAccountGroup(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); AccountGroupDeleteData = new List <AccountGroup>(); this.LoadAccountGroupGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
private void Items_Save_Button_Click(object sender, EventArgs e) { if (!IsValidateItemData(out string message)) { MessageBoxHelper.ShowErrorMessage(message); return; } List <Items> saveData = this.ItemsData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (ItemsDeleteData != null && ItemsDeleteData.Count > 0) { saveData?.InsertRange(0, ItemsDeleteData); } if (saveData?.Count > 0) { ItemsController controller = new ItemsController(); if (controller.SaveItems(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); ItemsDeleteData = new List <Items>(); this.LoadItemsGridView(); ReloadData.ItemUpdate(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
public List<AphidExpression> ExpandControlFlowExpressions(List<AphidExpression> ast) { var ast2 = new List<AphidExpression>(ast); var ifs = ast .Select(x => new { Expression = x, Expanded = ExpandControlFlowExpressions(x), }) .Where(x => x.Expanded != null) .ToArray(); foreach (var expandedIf in ifs) { var i = ast2.IndexOf(expandedIf.Expression); ast2.RemoveAt(i); ast2.InsertRange(i, expandedIf.Expanded); } if (AnyControlFlowExpressions(ast2)) { return ExpandControlFlowExpressions(ast2); } else { //foreach (var n in ast.OfType<IParentNode>()) //{ // ExpandControlFlowExpressions(n.GetChildren().ToList()); //} return ast2; } }
/// <summary> /// Downloads tweets since the most recent tweet in the list /// The list is assumed to be in descending chronological order, so the most recent is first /// Twitter restrict how far back tweets can be retrieved - we get as many as possible /// Only original tweets and RTs are included - not replies /// </summary> /// <param name="username">A Twitter username whose tweets are to be downloaded</param> /// <param name="tweets">Previously downloaded tweets for this user, most recent first</param> /// <returns>A list of tweets</returns> public static int DownloadNewTweets(string username, List<Tweet> tweets) { string sinceId = tweets.First().Id; List<Tweet> newTweets = DownloadTweets(username, sinceId, null); tweets.InsertRange(0, newTweets); return newTweets.Count; }
public static void Main(string[] args) { Dictionary<string,int> dict=new Dictionary<string,int>(); dict.Add("one",1); dict.Add("two",2); dict.Add("three",3); dict.Add("four",4); dict.Remove("one"); Console.WriteLine(dict.ContainsKey("dsaf")); Console.WriteLine("Key Value Pairs after Dictionary related operations:"); foreach (var pair in dict) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } dict.Clear (); List<string> strList = new List<string> (); strList.Add ("one"); strList.Add ("two"); strList.Add ("three"); strList.Add ("four"); strList.Add ("five"); strList.Insert (3, "great"); string[] newList = new string[3]{ "ten", "eleven", "twelve" }; strList.AddRange (newList); strList.InsertRange (3, newList); Console.WriteLine ("Output after all list related operations i.e. add, insert, addrange, insertrange,remove"); foreach (var i in strList) Console.WriteLine (i); }
public static PropertyInfo[] GetPublicProperties(this Type type) { if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); var newPropertyInfos = typeProperties.Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } return type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance); }
private void ItemUnit_Save_Button_Click(object sender, EventArgs e) { var group = this.ItemUnitData .GroupBy(o => o.ItemUnitID) .Where(g => g.Count() > 1) .Select(o => o.Key).ToList(); if (group.Count > 0) { MessageBoxHelper.ShowErrorMessage($"Mã ĐVT đã tồn tại!\r\n{string.Join(", ", group)}"); return; } List <ItemUnit> saveData = this.ItemUnitData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (ItemUnitDeleteData != null && ItemUnitDeleteData.Count > 0) { saveData?.InsertRange(0, ItemUnitDeleteData); } if (saveData?.Count > 0) { ItemsController controller = new ItemsController(); if (controller.SaveItemUnit(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); ItemUnitDeleteData = new List <ItemUnit>(); this.LoadItemUnitGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
static void Main(string[] args) { List<string> words = new List<string>(); // New string-typed list words.Add("melon"); words.Add("avocado"); words.AddRange(new[] { "banana", "plum" }); words.Insert(0, "lemon"); // Insert at start words.InsertRange(0, new[] { "peach", "nashi" }); // Insert at start words.Remove("melon"); words.RemoveAt(3); // Remove the 4th element words.RemoveRange(0, 2); // Remove first 2 elements words.RemoveAll(s => s.StartsWith("n"));// Remove all strings starting in 'n' Console.WriteLine(words[0]); // first word Console.WriteLine(words[words.Count - 1]); // last word foreach (string s in words) Console.WriteLine(s); // all words List<string> subset = words.GetRange(1, 2); // 2nd->3rd words string[] wordsArray = words.ToArray(); // Creates a new typed array string[] existing = new string[1000];// Copy first two elements to the end of an existing array words.CopyTo(0, existing, 998, 2); List<string> upperCastWords = words.ConvertAll(s => s.ToUpper()); List<int> lengths = words.ConvertAll(s => s.Length); ArrayList al = new ArrayList(); al.Add("hello"); string first = (string)al[0]; string[] strArr = (string[])al.ToArray(typeof(string)); List<string> list = al.Cast<string>().ToList(); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = { 0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14 }; List<int> listObject = new List<int>(iArray); int[] insert = { 4, 5, 6, 7 }; listObject.InsertRange(4, insert); for (int i = 0; i < 15; i++) { if (listObject[i] != i) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,listObject is: " + listObject[i]); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void Send(string name, string content) { // Sends text EV3Packet in this format: // bbbbmmmmttssllaaaLLLLppp // bbbb = bytes in the message, little endian // mmmm = message counter // tt = 0×81 // ss = 0x9E // ll = mailbox name length INCLUDING the \0 terminator // aaa… = mailbox name, should be terminated with a \0 // LLLL = payload length INCLUDING the , little endian // ppp… = payload, should be terminated with the \0 List<byte> MessageHeaderList = new List<byte>(); MessageHeaderList.AddRange(new byte[] { 0x00, 0x01, 0x81, 0x9E }); // mmmmm + tt + ss List<byte> by = BitConverter.GetBytes((Int16)(name.Length + 1)).Reverse().ToList(); by.RemoveAt(0); MessageHeaderList.AddRange(by.ToArray()); // ll MessageHeaderList.AddRange(Encoding.ASCII.GetBytes(name)); // aaa… MessageHeaderList.AddRange(new byte[] { 0x00 }); // \0 MessageHeaderList.AddRange(BitConverter.GetBytes((Int16)(content.Length + 1))); // LLLL MessageHeaderList.AddRange(Encoding.ASCII.GetBytes(content)); // ppp… MessageHeaderList.AddRange(new byte[] { 0x00 }); // \0 MessageHeaderList.InsertRange(0, BitConverter.GetBytes((Int16)(MessageHeaderList.Count))); // bbbb EV3ComPort.Write(MessageHeaderList.ToArray(), 0, MessageHeaderList.ToArray().Length); }
public void BindSelected() { var selectedList = Position.GetPositionList() .Where(p => this.SelectedList.Contains(p.Id)) .ToList(); var fullNameList = new List<string>(); foreach (Position postion in selectedList) { if (postion == null) continue; List<string> buffer = new List<string>(); buffer.Insert(0, postion.Name); var org = postion.GetOrganization(); if (org != null) { buffer.Insert(0, org.Name); var parentOrgList = org.DeepParentList; if (parentOrgList != null) { buffer.InsertRange(0, parentOrgList.Select(o2 => o2.Name)); } } fullNameList.Add(string.Join("/", buffer.ToArray())); } this.selectedDataList.DataSource = fullNameList; this.selectedDataList.DataBind(); this.PageEngine.UpdateControlRender(this.selectedDataListArea); }
public static void Main () { List<int> array = new List<int> { 1, 2, 3 }; List<int> array2 = new List<int> { 4, 5, 6 }; array.InsertRange(1, array2); foreach (var member in array) Console.WriteLine(member); }
private void Save_Button_Click(object sender, EventArgs e) { VoucherCover selected = VoucherCover_LookupEdit.GetSelectedDataRow().CastTo <VoucherCover>(); if (selected == null) { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000032); } List <VoucherCoverDetail> saveData = this.VoucherCoverDetailData .Where(o => (o.SEQ ?? 0) > 0 && (o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update)).ToList(); if (VoucherCoverDetailDeleteData != null && VoucherCoverDetailDeleteData.Count > 0) { saveData?.InsertRange(0, VoucherCoverDetailDeleteData); } if (saveData?.Count > 0) { using (VoucherCoverController controller = new VoucherCoverController()) { if (controller.SaveVoucherCoverDetail(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); VoucherCoverDetailDeleteData = new List <VoucherCoverDetail>(); this.LoadGridData(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } } }
void DetermineFields() { var currentType = _typeToProcess; _fields = currentType.GetFields(TestRunManager.FieldsToRetrieve).ToList(); while ((currentType = currentType.BaseType) != null) _fields.InsertRange(0, currentType.GetFields(TestRunManager.FieldsToRetrieve)); }
private void BindComboBoxToDrives() { List<string> sysDriveList = new List<string>(); sysDriveList.InsertRange(0, System.IO.Directory.GetLogicalDrives()); BindingSource drvSource = new BindingSource(); drvSource.DataSource = sysDriveList; cmbDriveSelect.DataSource = drvSource; }
private static void ExecuteRollRightCommand(string[] commandArgs, List<string> collection) { int numberOfRolls = int.Parse(commandArgs[1]) % collection.Count; var elementsToMove = collection.Skip(collection.Count - numberOfRolls).Take(numberOfRolls).ToArray(); collection.InsertRange(0, elementsToMove); collection.RemoveRange(collection.Count - numberOfRolls, numberOfRolls); }
private static List<avm.ComponentInstance> RecursivelyGetAllComponentInstances(avm.Design dm_root) { List<avm.ComponentInstance> lci_rtn = new List<avm.ComponentInstance>(); foreach (Compound c in dm_root.RootContainer.Container1.Where(c => c is Compound)) { lci_rtn.InsertRange(0, RecursivelyGetAllComponentInstances(c)); } return lci_rtn; }
private static void processDirectory(string inputFilename, string outputPath, int cellWidth, int cellHeight) { string[] pngFilenames = Directory.GetFiles(inputFilename, "*.png"); string[] bmpFilenames = Directory.GetFiles(inputFilename, "*.bmp"); string[] tgaFilenames = Directory.GetFiles(inputFilename, "*.tga"); List<string> allFilenames = new List<string>(); allFilenames.InsertRange(0, tgaFilenames); allFilenames.InsertRange(0, bmpFilenames); allFilenames.InsertRange(0, pngFilenames); // now process all files foreach (string filename in allFilenames) { processFile(filename, outputPath, cellWidth, cellHeight); } }
public static MemberInfo[] GetProperties(Type type) { var flags = BindingFlags.Public | BindingFlags.Instance; if (type.IsInterface) { var propertyInfos = new List<PropertyInfo>(); var considered = new List<Type>(); var queue = new Queue<Type>(); considered.Add(type); queue.Enqueue(type); while (queue.Count > 0) { var subType = queue.Dequeue(); foreach (var subInterface in subType.GetInterfaces()) { if (considered.Contains(subInterface)) continue; considered.Add(subInterface); queue.Enqueue(subInterface); } var typeProperties = subType.GetProperties(flags) .Where(o => !o.HasAttribute<HideInInspector>()) .Where(o => !o.Module.Name.Contains("UnityEngine")) .OrderBy(o => o.Name); var newPropertyInfos = typeProperties .Where(x => !propertyInfos.Contains(x)); propertyInfos.InsertRange(0, newPropertyInfos); } return propertyInfos.ToArray(); } else { var propertyInfos = new List<MemberInfo>(); var props = type.GetProperties(flags).Where(o => !o.HasAttribute<HideInInspector>() && !o.Module.Name.Contains("UnityEngine")).OrderBy(o => o.Name); foreach (var prop in props) { if (prop.IsSpecialName) continue; propertyInfos.Add(prop); } var fields = type.GetFields(flags).Where(o => !o.HasAttribute<HideInInspector>() && !o.Module.Name.Contains("UnityEngine")).OrderBy(o => o.Name); foreach (var prop in fields) { propertyInfos.Add(prop); } return propertyInfos.ToArray(); } }
public static void Test(Assert assert) { assert.Expect(10); List<string> magic1 = new List<string>(); magic1.Insert(magic1.Count, "first"); magic1.Insert(magic1.Count, "second"); assert.Equal(magic1[0], "first", "magic1[0]"); assert.Equal(magic1[1], "second", "magic1[1]"); List<string> magic2 = new List<string>(); magic2.InsertRange(magic2.Count, new[] { "first", "second" }); magic2.InsertRange(magic2.Count, new[] { "third", "fourth" }); assert.Equal(magic2[0], "first", "magic1[0]"); assert.Equal(magic2[1], "second", "magic1[1]"); assert.Equal(magic2[2], "third", "magic1[2]"); assert.Equal(magic2[3], "fourth", "magic1[3]"); assert.Throws(() => { List<string> magic = new List<string>(); magic.Insert(1, "first"); }, "Insert at length + 1"); assert.Throws(() => { List<string> magic = new List<string>(); magic.Insert(-1, "first"); }, "Insert at -1"); assert.Throws(() => { List<string> magic = new List<string>(); magic.InsertRange(1, new[] { "first", "second" }); }, "InsertRange at length + 1"); assert.Throws(() => { List<string> magic = new List<string>(); magic.InsertRange(-1, new[] { "first", "second" }); }, "InsertRange at -1"); }
private static List<avm.ComponentInstance> RecursivelyGetAllComponentInstances(Compound c_root) { List<avm.ComponentInstance> lci_rtn = new List<avm.ComponentInstance>(); if (c_root.ComponentInstance != null) { lci_rtn.InsertRange(0, c_root.ComponentInstance); } if (c_root.Container1 != null) { foreach (Compound c in c_root.Container1.Where(c => c is Compound)) { lci_rtn.InsertRange(0, RecursivelyGetAllComponentInstances(c)); } } return lci_rtn; }
private void Save_Button_Click(object sender, EventArgs e) { if (!IsCheckValidate()) { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000039); return; } List <Customer> saveData = this.CustommersData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (this.CustomersDeleteData != null) { saveData?.InsertRange(0, this.CustomersDeleteData); } if (saveData?.Count > 0) { CustomerController controller = new CustomerController(); if (controller.SaveCustommers(saveData, out string customerID)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); CustomersDeleteData = new List <Customer>(); this.LoadGridView(); ReloadData.CustomerUpdate(); // Chọn KH sau khi lưu thành công if (!string.IsNullOrEmpty(customerID)) { Customer_GridView.SetFocusRowByValue("CustomerID", customerID); SelectedRow = Customer_GridView.GetFocusedRow().CastTo <Customer>(); } } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
private void AccountDetail_Save_Button_Click(object sender, EventArgs e) { List <AccountDetail> saveData = this.AccountDetailData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (AccountDetailDeleteData != null && AccountDetailDeleteData.Count > 0) { saveData?.InsertRange(0, AccountDetailDeleteData); } if (saveData?.Count > 0) { AccountsController controller = new AccountsController(); if (controller.SaveAccountDetail(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); this.LoadAccountDetailGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
private void UserRoleSave_Button_Click(object sender, EventArgs e) { List <UserCompany> saveData = this.DetailData.Where(o => o.Status == ModifyMode.Insert || o.Status == ModifyMode.Update).ToList(); if (DetailDataDelete != null && DetailDataDelete.Count > 0) { saveData?.InsertRange(0, DetailDataDelete); } if (saveData?.Count > 0) { UserController controller = new UserController(); if (controller.SaveUserRoleCompany(saveData)) { MessageBoxHelper.ShowInfoMessage(BSMessage.BSM000001); DetailDataDelete = new List <UserCompany>(); this.LoadDetailGridView(); } else { MessageBoxHelper.ShowErrorMessage(BSMessage.BSM000002); } } }
public override SyntaxNode VisitTryStatement(TryStatementSyntax node) { _trysInStack++; try { var newNode = (TryStatementSyntax)base.VisitTryStatement(node); if (_tryConcurrent) { var variableName = "__try" + _trysInStack; _tryVariables.Add(variableName); //we can only split on expressions directly on the try level //i.e. no try { if () { EXPRESSION }} if (_trysInStack > 1 && !(newNode.Parent.Parent is TryStatementSyntax)) { Debug.Assert(false); //td: error return(newNode); } var statements = new List <StatementSyntax>(newNode.Block.Statements); var newStatements = new List <StatementSyntax>(); var currentIndex = 0; while (currentIndex < statements.Count) { var oldIndex = currentIndex; for (int i = oldIndex; i < statements.Count; i++, currentIndex++) { var statement = statements[i]; if (statement is YieldStatementSyntax) { newStatements.Add(newNode .WithBlock(CSharp.Block( statements .Skip(oldIndex) .Take(currentIndex - oldIndex - 1)))); //variable and return yield //td: assert newStatements.Add(statements[currentIndex - 1]); newStatements.Add(statements[currentIndex++]); break; } //must make variables available to later code, unless it precedes a yield var yieldNext = statements.Count > i + 1 && statements[i + 1] is YieldStatementSyntax; if (statement is LocalDeclarationStatementSyntax && !yieldNext) { var decl = statement as LocalDeclarationStatementSyntax; var varType = decl.Declaration.Type; if (varType == null || varType.Kind() == SyntaxKind.TypeVarKeyword) { varType = Roslyn.SymbolTypeSyntax(_model, decl .Declaration .Variables[0] .Initializer .Value); } Debug.Assert(varType != null, "Untyped local variable on try fix"); var assignmentStatements = new List <StatementSyntax>(); newStatements.Add(decl .WithDeclaration(decl.Declaration .WithType(varType) .WithVariables(CSharp.SeparatedList( decl .Declaration .Variables .Select(v => { assignmentStatements.Add(CSharp.ExpressionStatement( CSharp.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, CSharp.IdentifierName(v.Identifier), v.Initializer.Value))); return(v.WithInitializer(v .Initializer .WithValue(Templates .DefaultValue .Get <ExpressionSyntax>(varType)))); }))))); //once moved the variables "up" scope //we must keep the assignments Debug.Assert(assignmentStatements.Any()); statements.RemoveAt(i); statements.InsertRange(i, assignmentStatements); } } } Debug.Assert(newStatements.Any()); return(LinkTryStatements(newStatements, variableName)); } return(newNode); } finally { _trysInStack--; } }
public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new List <int>(); var actual = ImmutableList <int> .Empty; int seed = (int)DateTime.Now.Ticks; Debug.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int value = random.Next(); Debug.WriteLine("Adding \"{0}\" to the list.", value); expected.Add(value); actual = actual.Add(value); VerifyBalanced(actual); break; case Operation.AddRange: int inputLength = random.Next(100); int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray(); Debug.WriteLine("Adding {0} elements to the list.", inputLength); expected.AddRange(values); actual = actual.AddRange(values); VerifyBalanced(actual); break; case Operation.Insert: int position = random.Next(expected.Count + 1); value = random.Next(); Debug.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position); expected.Insert(position, value); actual = actual.Insert(position, value); VerifyBalanced(actual); break; case Operation.InsertRange: inputLength = random.Next(100); values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray(); position = random.Next(expected.Count + 1); Debug.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position); expected.InsertRange(position, values); actual = actual.InsertRange(position, values); VerifyBalanced(actual); break; case Operation.RemoveAt: if (expected.Count > 0) { position = random.Next(expected.Count); Debug.WriteLine("Removing element at position {0} from the list.", position); expected.RemoveAt(position); actual = actual.RemoveAt(position); VerifyBalanced(actual); } break; case Operation.RemoveRange: position = random.Next(expected.Count); inputLength = random.Next(expected.Count - position); Debug.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position); expected.RemoveRange(position, inputLength); actual = actual.RemoveRange(position, inputLength); VerifyBalanced(actual); break; } Assert.Equal <int>(expected, actual); } }
/// <summary>Inserts the length of the packet's content at the start of the buffer.</summary> public void WriteLength() { buffer.InsertRange(0, BitConverter.GetBytes(buffer.Count)); // Insert the byte length of the packet at the very beginning }
public void AddRange(ClockValues b) { if (b != null && b.Count > 0) { if (list.Count == 0) { list.AddRange(b); } else { int acount = list.Count, bcount = b.Count; if (list[acount - 1].Clock < b[0].Clock) { list.AddRange(b); } else if (list[0].Clock > b[bcount - 1].Clock) { list.InsertRange(0, b); } else { IClockValue[] array = ArrayPool <IClockValue> .Shared.Rent(acount + bcount); Span <IClockValue> span = array.AsSpan(); int i = 0, j = 0, k = 0; while (i < acount && j < bcount) { if (list[i].Clock < b[j].Clock) { span[k++] = list[i++]; } else if (list[i].Clock == b[j].Clock) { i++; } else { span[k++] = b[j++]; } } while (i < acount) { span[k++] = list[i++]; } while (j < bcount) { span[k++] = b[j++]; } if (k > acount) { for (int l = 0; l < acount; l++) { list[l] = span[l]; } list.AddRange(array.Skip(acount).Take(k - acount)); }//将array的内容复制给list. ArrayPool <IClockValue> .Shared.Return(array); } } } }
public static IEnumerable <Mod> OrderMods(IEnumerable <Mod> mods) { if (ruleList.Count == 0) { ruleList = GetRules(); } foreach (var rule in ruleList) { foreach (var orderedMod in rule.Mod) { var mod = mods.FirstOrDefault(c => Path.GetFileName(c.FilePath).Contains(orderedMod)); if (mod == null) { continue; } if (Path.GetFileName(mod.FilePath).Contains(orderedMod)) { mod.OrderedAutomatically = true; removeModFromOtherList(mod, rule.Order); if (!rule.ModsOrdered.Any(q => q.UniqueIdentifier == mod.UniqueIdentifier)) { rule.ModsOrdered.Add(mod); } continue; } } } foreach (var item in mods.Where(c => !c.OrderedAutomatically)) { ruleList.FirstOrDefault(c => c.Order == 10).ModsOrdered.Add(item); Console.WriteLine(Path.GetFileName(item.FilePath)); } var ordered = new List <Mod>(); foreach (var rule in ruleList) { var index = rule.InitialRange; foreach (var mod in rule.ModsOrdered) { mod.Order = index; index++; } ordered.AddRange(rule.ModsOrdered.OrderBy(o => o.Order)); } var i = 0; foreach (var item in ordered.OrderBy(o => o.Order)) { item.Order = i; i++; } foreach (var rule in ruleList) { rule.ModsOrdered.Clear(); } var required = ordered.Where(c => c.AllDependencies.Any()).ToList(); foreach (var item in required) { var oldOrder = item.Order; var dependencies = ordered.Where(c => item.AllDependencies.Any(q => q.IndexOf(c.FileName, StringComparison.CurrentCultureIgnoreCase) >= 0) ); if (!dependencies.Any()) { continue; } if (oldOrder > dependencies.Max(c => c.Order)) { continue; } ordered.Remove(ordered.FirstOrDefault(c => c.UniqueIdentifier == item.UniqueIdentifier)); ordered.InsertRange( ordered.IndexOf(dependencies.OrderBy(c => c.Order).Last()) + 1 , new List <Mod> { item }); for (int ii = 0; ii < ordered.Count; ii++) { ordered.ElementAt(ii).Order = ii; } } return(ordered.OrderBy(o => ordered)); void removeModFromOtherList(Mod mod, int order) { foreach (var rule in ruleList.Where(c => c.Order < order)) { rule.ModsOrdered.Remove(mod); } } }
static void Main() { int[][] intervals = new int[3][]; intervals[0] = new int[2] { 1, 2 }; intervals[1] = new int[2] { 6, 10 }; intervals[2] = new int[2] { 11, 15 }; /* * intervals[0] = new int[2] { 1, 4 }; * intervals[1] = new int[2] { 7, 10 }; * intervals[2] = new int[2] { 3, 5 }; * * int[][] intervals = new int[5][]; * * intervals[0] = new int[2] { 1, 5 }; * intervals[1] = new int[2] { 10, 20 }; * intervals[2] = new int[2] { 1, 6 }; * intervals[3] = new int[2] { 16, 19 }; * intervals[4] = new int[2] { 5, 11 }; */ List <List <int> > fullIntervals = new List <List <int> >(); foreach (int[] interval in intervals) { List <int> fullInterval = Enumerable.Range(interval[0], (interval[1] - interval[0] + 1)).ToList <int>(); Console.WriteLine($"Full interval: {fullInterval[0]} - {fullInterval[fullInterval.Count - 1]}"); fullInterval.ForEach(Print); fullIntervals.Add(fullInterval); } while (true) { List <List <int> > rIntervals = CheckIntersection(fullIntervals); int fiCount = fullIntervals.Count; int riCount = rIntervals.Count; fullIntervals.Clear(); fullIntervals.InsertRange(0, rIntervals); if (fiCount == riCount) { break; } } Console.WriteLine("Print of final intervals"); int SumOfIntervals = 0; foreach (List <int> finalInterval in fullIntervals) { Console.WriteLine($"Final interval: {finalInterval[0]} - {finalInterval[finalInterval.Count - 1]}"); finalInterval.ForEach(Print); SumOfIntervals += finalInterval.Max() - finalInterval.Min(); } Console.WriteLine($"Sum of intervals: {SumOfIntervals}"); }
void InjectStub(ConfuserContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule) { var rt = context.Registry.GetService <IRuntimeService>(); RandomGenerator random = context.Registry.GetService <IRandomService>().GetRandomGenerator(Id); var comp = context.Registry.GetService <ICompressionService>(); var rtType = rt.GetRuntimeType(compCtx.CompatMode ? "Confuser.Runtime.CompressorCompat" : "Confuser.Runtime.Compressor"); IEnumerable <IDnlibDef> defs = InjectHelper.Inject(rtType, stubModule.GlobalType, stubModule); switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal)) { case Mode.Normal: compCtx.Deriver = new NormalDeriver(); break; case Mode.Dynamic: compCtx.Deriver = new DynamicDeriver(); break; default: throw new UnreachableException(); } compCtx.Deriver.Init(context, random); context.Logger.Debug("Encrypting modules..."); // Main MethodDef entryPoint = defs.OfType <MethodDef>().Single(method => method.Name == "Main"); stubModule.EntryPoint = entryPoint; if (compCtx.EntryPoint.HasAttribute("System.STAThreadAttribute")) { var attrType = stubModule.CorLibTypes.GetTypeRef("System", "STAThreadAttribute"); var ctorSig = MethodSig.CreateInstance(stubModule.CorLibTypes.Void); entryPoint.CustomAttributes.Add(new CustomAttribute( new MemberRefUser(stubModule, ".ctor", ctorSig, attrType))); } else if (compCtx.EntryPoint.HasAttribute("System.MTAThreadAttribute")) { var attrType = stubModule.CorLibTypes.GetTypeRef("System", "MTAThreadAttribute"); var ctorSig = MethodSig.CreateInstance(stubModule.CorLibTypes.Void); entryPoint.CustomAttributes.Add(new CustomAttribute( new MemberRefUser(stubModule, ".ctor", ctorSig, attrType))); } uint seed = random.NextUInt32(); compCtx.OriginModule = context.OutputModules[compCtx.ModuleIndex]; byte[] encryptedModule = compCtx.Encrypt(comp, compCtx.OriginModule, seed, progress => context.Logger.Progress((int)(progress * 10000), 10000)); context.Logger.EndProgress(); context.CheckCancellation(); compCtx.EncryptedModule = encryptedModule; MutationHelper.InjectKeys(entryPoint, new[] { 0, 1 }, new[] { encryptedModule.Length >> 2, (int)seed }); InjectData(stubModule, entryPoint, encryptedModule); // Decrypt MethodDef decrypter = defs.OfType <MethodDef>().Single(method => method.Name == "Decrypt"); decrypter.Body.SimplifyMacros(decrypter.Parameters); List <Instruction> instrs = decrypter.Body.Instructions.ToList(); for (int i = 0; i < instrs.Count; i++) { Instruction instr = instrs[i]; if (instr.OpCode == OpCodes.Call) { var method = (IMethod)instr.Operand; if (method.DeclaringType.Name == "Mutation" && method.Name == "Crypt") { Instruction ldDst = instrs[i - 2]; Instruction ldSrc = instrs[i - 1]; Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc); instrs.RemoveAt(i); instrs.RemoveAt(i - 1); instrs.RemoveAt(i - 2); instrs.InsertRange(i - 2, compCtx.Deriver.EmitDerivation(decrypter, context, (Local)ldDst.Operand, (Local)ldSrc.Operand)); } else if (method.DeclaringType.Name == "Lzma" && method.Name == "Decompress") { MethodDef decomp = comp.GetRuntimeDecompressor(stubModule, member => { }); instr.Operand = decomp; } } } decrypter.Body.Instructions.Clear(); foreach (Instruction instr in instrs) { decrypter.Body.Instructions.Add(instr); } // Pack modules PackModules(context, compCtx, stubModule, comp, random); }
static void Main(string[] args) { List <string> list = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList(); string input = Console.ReadLine(); while (input != "end") { string[] inputs = input.Split(' '); if (inputs[0] == "reverse") { bool parsedS = int.TryParse(inputs[2], out int start); bool parsedC = int.TryParse(inputs[4], out int count); if (!parsedS || !parsedC || count < 0 || count > list.Count - start || start < 0 || start >= list.Count) { Console.WriteLine("Invalid input parameters."); input = Console.ReadLine(); continue; } var rev = list.Skip(start).Take(count).Reverse().ToList(); list.RemoveRange(start, count); list.InsertRange(start, rev); } else if (inputs[0] == "sort") { bool parsedS = int.TryParse(inputs[2], out int start); bool parsedC = int.TryParse(inputs[4], out int count); if (!parsedS || !parsedC || count < 0 || count > list.Count - start || start < 0 || start >= list.Count) { Console.WriteLine("Invalid input parameters."); input = Console.ReadLine(); continue; } var sort = list.Skip(start).Take(count).OrderBy(x => x).ToList(); list.RemoveRange(start, count); list.InsertRange(start, sort); } else if (inputs[0] == "rollLeft") { bool parsed = int.TryParse(inputs[1], out int count); if (!parsed || count < 0) { Console.WriteLine("Invalid input parameters."); input = Console.ReadLine(); continue; } for (int i = 0; i < count % list.Count; i++) { var elem = list[0]; list.RemoveAt(0); list.Add(elem); } } else if (inputs[0] == "rollRight") { bool parsed = int.TryParse(inputs[1], out int count); if (!parsed || count < 0) { Console.WriteLine("Invalid input parameters."); input = Console.ReadLine(); continue; } for (int i = 0; i < count % list.Count; i++) { var elem = list[list.Count - 1]; list.RemoveAt(list.Count - 1); list.Insert(0, elem); } } input = Console.ReadLine(); } Console.WriteLine("[" + string.Join(", ", list) + "]"); }
public static IEnumerable <CodeInstruction> Transpiler_StatWorker_GetValueUnfinalized(IEnumerable <CodeInstruction> instructions, ILGenerator il) { List <CodeInstruction> instructionList = new List <CodeInstruction>(instructions); List <CodeInstruction> instructionInjectionList = new List <CodeInstruction>(); //Look for the Primary part. int desiredPosition = instructionList.FirstIndexOf(instruction => instruction.opcode == OpCodes.Ldfld && instruction.operand == typeof(Pawn).GetField("skills")); //Log.Message("#1: desiredPosition is at: " + desiredPosition); //Now after it is popped inject our own code. { //Pawn CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldloc_1; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { //Stat CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldarg_0; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { //Stat CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldfld; injectedInstruction.operand = typeof(StatWorker).GetField("stat", BindingFlags.NonPublic | BindingFlags.Instance); instructionInjectionList.Add(injectedInstruction); } { //Load: Inject our own function. CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Call; injectedInstruction.operand = typeof(HarmonyPatches).GetMethod(nameof(StatWorkerInjection_AddShieldValue)); instructionInjectionList.Add(injectedInstruction); } { //Load: Value being modifier CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldloc_0; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { //Add both together. CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Add; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { //Store: New value. CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Stloc_0; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } if (instructionInjectionList.Count > 0) { instructionList.InsertRange(desiredPosition - 1, instructionInjectionList); } return(instructionList); }
public static IEnumerable <CodeInstruction> Transpiler_StatWorker_GetExplanationUnfinalized(IEnumerable <CodeInstruction> instructions, ILGenerator il) { List <CodeInstruction> instructionList = new List <CodeInstruction>(instructions); List <CodeInstruction> instructionInjectionList = new List <CodeInstruction>(); //Look for the Primary part. int desiredPosition = instructionList.FirstIndexOf(instruction => instruction.opcode == OpCodes.Callvirt && instruction.operand == typeof(Pawn_EquipmentTracker).GetProperty("Primary").GetGetMethod()); //Log.Message("#1: desiredPosition is at: " + desiredPosition); //Now go forward two System.Text.StringBuilder::AppendLine() calls. MethodInfo appendLineMethod1 = typeof(StringBuilder).GetMethod("AppendLine", new Type[] { typeof(string) }); MethodInfo appendLineMethod2 = typeof(StringBuilder).GetMethod("AppendLine", new Type[] {}); int calls = 0; for (int i = desiredPosition; i < instructionList.Count; i++) { CodeInstruction cil = instructionList[i]; if (cil.opcode == OpCodes.Callvirt && (cil.operand == appendLineMethod1 || cil.operand == appendLineMethod2)) { calls++; } if (calls >= 2) { desiredPosition = i; break; } } desiredPosition -= 2; //Log.Message("#2: desiredPosition is at: " + desiredPosition); //Now after it is popped inject our own code. { CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldloc_0; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldloc_2; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldarg_0; injectedInstruction.operand = null; instructionInjectionList.Add(injectedInstruction); } { CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Ldfld; injectedInstruction.operand = typeof(StatWorker).GetField("stat", BindingFlags.NonPublic | BindingFlags.Instance); instructionInjectionList.Add(injectedInstruction); } { CodeInstruction injectedInstruction = new CodeInstruction(instructionList[desiredPosition]); injectedInstruction.opcode = OpCodes.Call; injectedInstruction.operand = typeof(HarmonyPatches).GetMethod(nameof(StatWorkerInjection_BuildShieldString)); instructionInjectionList.Add(injectedInstruction); } if (instructionInjectionList.Count > 0) { instructionList.InsertRange(desiredPosition + 1, instructionInjectionList); } return(instructionList); }
private InjectionMetadata BuildAutowiringMetadata(Type objectType) { var elements = new List <InjectionMetadata.InjectedElement>(); do { foreach (var autowiredType in autowiredPropertyTypes) { var currElements = new List <InjectionMetadata.InjectedElement>(); foreach ( var property in objectType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { var required = true; var attr = Attribute.GetCustomAttribute(property, autowiredType); if (attr is AutowiredAttribute) { required = ((AutowiredAttribute)attr).Required; } if (attr != null && property.DeclaringType == objectType) { currElements.Add(new AutowiredPropertyElement(property, required)); } } foreach ( var field in objectType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { var required = true; var attr = Attribute.GetCustomAttribute(field, autowiredType); if (attr is AutowiredAttribute) { required = ((AutowiredAttribute)attr).Required; } if (attr != null && field.DeclaringType == objectType) { currElements.Add(new AutowiredFieldElement(field, required)); } } foreach ( var method in objectType.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)) { var required = true; var attr = Attribute.GetCustomAttribute(method, autowiredType); if (attr is AutowiredAttribute) { required = ((AutowiredAttribute)attr).Required; } if (attr != null && method.DeclaringType == objectType) { if (method.IsStatic) { logger.Warn( m => m("Autowired annotation is not supported on static methods: " + method.Name)); continue; } if (method.IsGenericMethod) { logger.Warn( m => m("Autowired annotation is not supported on generic methods: " + method.Name)); continue; } currElements.Add(new AutowiredMethodElement(method, required)); } } elements.InsertRange(0, currElements); } objectType = objectType.BaseType; } while (objectType != null && objectType != typeof(Object)); return(new InjectionMetadata(objectType, elements)); }
static void Main(string[] args) { List <string> data = Console.ReadLine().Split().ToList(); string input = Console.ReadLine(); while (input != "3:1") { string[] commandElements = input.Split(); string command = commandElements[0]; if (command == "merge") { int startIndex = int.Parse(commandElements[1]); int endIndex = int.Parse(commandElements[2]); string concatData = string.Empty; if (startIndex < 0) { if (endIndex >= 0 && endIndex <= data.Count) { startIndex = 0; } } if (endIndex > data.Count - 1) { if (startIndex >= 0 && startIndex <= data.Count) { endIndex = data.Count - 1; } } if ((startIndex >= 0 && startIndex <= data.Count - 1) && (endIndex >= 0 && endIndex <= data.Count - 1)) { for (int i = startIndex; i <= endIndex; i++) { concatData += data[i]; } data.RemoveRange(startIndex, endIndex - startIndex + 1); data.Insert(startIndex, concatData); } } else if (command == "divide") { int index = int.Parse(commandElements[1]); int partitions = int.Parse(commandElements[2]); if (index >= 0 && index <= data.Count - 1) { string word = data[index]; List <string> dividedWord = new List <string>(); int stringLengthToAdd = word.Length / partitions; int startindex = 0; for (int i = 0; i < partitions; i++) { if (i == partitions - 1) { dividedWord.Add(word.Substring(startindex, word.Length - startindex)); } else { dividedWord.Add(word.Substring(startindex, stringLengthToAdd)); startindex += stringLengthToAdd; } } data.RemoveAt(index); data.InsertRange(index, dividedWord); } } input = Console.ReadLine(); } Console.WriteLine(string.Join(' ', data)); }
public void PrependPropertyName(string propertyName) { Common.EnsurePropertyNameIsValid(propertyName); _propertyNames ??= new List <string>(); _propertyNames.InsertRange(0, propertyName.Split(".")); }
static void Main(string[] args) { List <string> input = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); string conditionToStopTheLoop = string.Empty; while ((conditionToStopTheLoop = Console.ReadLine()) != "3:1") { List <string> command = conditionToStopTheLoop .Split(' ', StringSplitOptions.RemoveEmptyEntries) .ToList(); if (command[0] == "merge") { int startIndex = int.Parse(command[1]); int endIndex = int.Parse(command[2]); if (startIndex < 0) { startIndex = 0; } if (startIndex > input.Count - 1) { startIndex = input.Count - 1; } if (endIndex < 0) { endIndex = 0; } if (endIndex > input.Count - 1) { endIndex = input.Count - 1; } //Ivo Johny Tony Bony Mony //merge 0 3 //merge 3 4 //merge 0 3 //3:1 List <string> temp = new List <string>(); for (int i = startIndex; i <= endIndex; i++) { temp.Add(input[i]); } input[startIndex] = string.Join("", temp); for (int i = startIndex + 1; i <= endIndex; i++) { input.RemoveAt(startIndex + 1); } } else if (command[0] == "divide") { //abcd efgh ijkl mnop qrst uvwx yz //merge 4 10 //divide 4 5 //3:1 List <string> temp = new List <string>(); string wordToDivide = input[int.Parse(command[1])]; int partitions = int.Parse(command[2]); int length = wordToDivide.Length / int.Parse(command[2]); int lengthIfIsOdd = wordToDivide.Length % int.Parse(command[2]); for (int i = 0; i < partitions; i++) { if (i == partitions - 1) { length += lengthIfIsOdd; } temp.Add(wordToDivide.Substring(0, length)); wordToDivide = wordToDivide.Remove(0, length); } input.RemoveAt(int.Parse(command[1])); input.InsertRange(int.Parse(command[1]), temp); } } Console.WriteLine(string.Join(" ", input)); }
public void Construct() { meshFilter = GetComponent <MeshFilter>(); Mesh msh = new Mesh(); List <int> triangles = new List <int>(); List <Vector3> vert = new List <Vector3>(); float MinCoordY = 500.0f; //Recalculate coordinate with the city center for (int i = 0; i < building.points.Count; i++) { building.points[i] = new Vector3((building.points[i].x - cityCenter.x), building.points[i].y, (building.points[i].z - cityCenter.z)); //if () } //Down vertices for (int i = 0; i < building.points.Count; i++) { vert.Add(new Vector3(building.points[i].x, 150, building.points[i].z)); } //Up vertices for (int i = 0; i < building.points.Count; i++) { vert.Add(new Vector3(building.points[i].x, building.points[i].y, building.points[i].z)); } msh.vertices = vert.ToArray(); //Down face tesselation List <double> testBas = new List <double>(); int sizeBAs = 0; for (int i = 0; i < vert.Count / 2; i++) { testBas.Add(vert[sizeBAs].x); testBas.Add(vert[sizeBAs].z); sizeBAs++; } List <int> tessalationBas = EarcutNet.Earcut.Tessellate(testBas.ToArray(), new int[] { }); triangles.InsertRange(0, tessalationBas); //Up face tesselation List <double> UpFace = new List <double>(); int size = building.points.Count * 2; for (int i = 0; i < vert.Count / 2; i++) { UpFace.Add(vert[size - 1].x); UpFace.Add(vert[size - 1].z); size--; } List <int> tessalationHaut = EarcutNet.Earcut.Tessellate(UpFace.ToArray(), new int[] { }); for (int i = 0; i < tessalationHaut.Count; i++) { tessalationHaut[i] = tessalationHaut[i] + building.points.Count; //mise a niveau pour les indices car la tesselation n'a pas tout le tab sinon il ferait une seul face } //avec la face du haut et du bas triangles.InsertRange(triangles.Count, tessalationHaut); //Lateral face for (int i = 0; i < building.points.Count - 1; i++) { triangles.Add(i); triangles.Add(i + 1); triangles.Add(i + building.points.Count); triangles.Add(i + 1); triangles.Add(i + building.points.Count + 1); triangles.Add(i + building.points.Count); } //Last face - connect with the fist vertices and the last triangles.Add(building.points.Count - 1); triangles.Add(0); triangles.Add(vert.Count - 1); triangles.Add(0); triangles.Add(building.points.Count + 2); triangles.Add(vert.Count - 1); //Add data to the mesh msh.triangles = triangles.ToArray(); GetComponent <MeshRenderer>().material = mat; meshFilter.mesh = msh; }
static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.Cyan; //If the number of arguments is larger than 0 if (args.Length > 0) { //Get the file attributes for file or directory FileAttributes attr = File.GetAttributes(@args[0]); //Detect whether its a directory or file if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { isDir = true; } else { isDir = false; } string mainClass = args[0]; string name = Path.GetFileNameWithoutExtension(args[0]); bool hideConsole = false;//Whether or not the compiled .exe has a hidden console(for win forms etc) List <string> references = new List <string>(); List <string> classes = new List <string>(); string icon = ""; //If it is a directory, A.C.S.C will search the directory for a file named "base.cs", as that will be the main file to base the program off if (isDir) { AprilSpeak("I don't know what you think you are doing... But I don't work like that!"); } else //If it is just a file { foreach (string line in File.ReadAllLines(args[0])) { if (line.StartsWith("//")) { if (line.ToLower().Trim().StartsWith("//[reference]") || line.ToLower().Trim().StartsWith("//[ref]")) //If the line reads "[reference]", then we want to add that reference path to the .dll file to the compiler { references.Add(line.ToLower().Replace("//[reference]", "").Replace("//[ref]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } if (line.ToLower().Trim().StartsWith("//[class]")) //If the line reads "[class]", then we want to add that class path to the .cs file to the temp file we are going to compile { if (!line.ToLower().Replace("//[class]", "").Contains(":")) { classes.Add(Path.GetDirectoryName(args[0]) + "/" + line.ToLower().Replace("//[class]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } else { classes.Add(line.ToLower().Replace("//[class]", "").Replace(";", "").Trim()); } } if (line.ToLower().Trim().StartsWith("//[icon]")) //If the line reads "[class]", then we want to add that class path to the .cs file to the temp file we are going to compile { if (!line.ToLower().Replace("//[icon]", "").Contains(":")) { icon = Path.GetDirectoryName(args[0]) + "\\" + line.ToLower().Replace("//[icon]", "").Replace(";", "").Trim(); //classes.Add(Path.GetDirectoryName(args[0]) + "/" + line.ToLower().Replace("[icon]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } else { icon = line.ToLower().Replace("//[icon]", "").Replace(";", "").Trim(); } } if (line.ToLower().Trim().StartsWith("//[name]")) { name = line.ToLower().Replace("//[name]", "").Replace(";", "").Trim(); } /*if (line.ToLower().Trim().StartsWith("//[name]")) * { * name = line.ToLower().Replace("//[name]", "").Trim(); * }*/ if (line.ToLower().Trim().StartsWith("//[hidden]")) { hideConsole = true; } } else { if (line.ToLower().Trim().StartsWith("[reference]") || line.ToLower().Trim().StartsWith("[ref]")) //If the line reads "[reference]", then we want to add that reference path to the .dll file to the compiler { references.Add(line.ToLower().Replace("[reference]", "").Replace("[ref]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } if (line.ToLower().Trim().StartsWith("[class]")) //If the line reads "[class]", then we want to add that class path to the .cs file to the temp file we are going to compile { if (!line.ToLower().Replace("[class]", "").Contains(":")) { classes.Add(Path.GetDirectoryName(args[0]) + "/" + line.ToLower().Replace("[class]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } else { classes.Add(line.ToLower().Replace("[class]", "").Replace(";", "").Trim()); } } if (line.ToLower().Trim().StartsWith("[icon]")) //If the line reads "[class]", then we want to add that class path to the .cs file to the temp file we are going to compile { if (!line.ToLower().Replace("[icon]", "").Contains(":")) { icon = Path.GetDirectoryName(args[0]) + "\\" + line.ToLower().Replace("[icon]", "").Replace(";", "").Trim(); //classes.Add(Path.GetDirectoryName(args[0]) + "/" + line.ToLower().Replace("[icon]", "").Replace(";", "").Trim()); //This will add the reference to the compiler } else { icon = line.ToLower().Replace("[icon]", "").Replace(";", "").Trim(); } } if (line.ToLower().Trim().StartsWith("[name]")) { name = line.ToLower().Replace("[name]", "").Replace(";", "").Trim(); } /*if (line.ToLower().Trim().StartsWith("//[name]")) * { * name = line.ToLower().Replace("//[name]", "").Trim(); * }*/ if (line.ToLower().Trim().StartsWith("[hidden]")) { hideConsole = true; } } } string[] temp; //Now we want to create a temporary file, copy the main class file to it, and then copy the data from the included classes to it. if (!File.Exists(Path.GetDirectoryName(args[0]) + "/temp.tmp")) { StreamWriter sw = File.CreateText(Path.GetDirectoryName(args[0]) + "/temp.tmp"); sw.Close(); } else { File.Delete(Path.GetDirectoryName(args[0]) + "/temp.tmp"); StreamWriter sw = File.CreateText(Path.GetDirectoryName(args[0]) + "/temp.tmp"); sw.Close(); } List <string> resUsing = new List <string>(); //Reserved using commands List <string> tempList = new List <string>(); //List the temp file so we can add/remove any text needed for extras temp = File.ReadAllLines(args[0]); tempList.AddRange(temp); for (int k = 0; k < temp.Length - 1; k++) { //AprilSpeak(temp[k]); if (hideConsole) { //Add variables to hide window try { if ((temp[k - 1].Trim().ToLower().StartsWith("{") && temp[k - 2].Trim().ToLower().Contains("class ")) || (temp[k - 1].Trim().ToLower().EndsWith("{") && temp[k - 1].Trim().ToLower().Contains("class "))) { tempList.InsertRange(k, AddHiddenVariables()); //AprilSpeak("Added var to class line " + k); } } catch (Exception ex) { } try{ //Add code to Main() for hiding console window if ((temp[k - 1].Trim().ToLower().StartsWith("{") && temp[k - 2].Trim().Contains("void Main(")) || (temp[k - 1].Trim().ToLower().EndsWith("{") && temp[k - 1].Trim().Contains("void Main("))) { tempList.InsertRange(k + 7, HideConsole()); //AprilSpeak("Added var to Main line " + k); } } catch (Exception ex) { } //Console.ReadLine(); } } tempList.Add("//[reference]System.Runtime.InteropServices.dll"); temp = tempList.ToArray(); for (int j = 0; j < temp.Length - 1; j++) { if (temp[j].StartsWith("using")) { if (!resUsing.Contains(temp[j])) { resUsing.Add(temp[j]); } temp[j] = ""; } if (temp[j].ToLower().Trim().StartsWith("[reference]") || temp[j].ToLower().Trim().StartsWith("[icon]") || temp[j].ToLower().Trim().StartsWith("[class]") || temp[j].ToLower().Trim().StartsWith("[ref]") || temp[j].ToLower().Trim().StartsWith("[name]") || temp[j].ToLower().Trim().StartsWith("[hidden]")) { temp[j] = "//" + temp[j]; } } if (hideConsole) { if (!resUsing.Contains("using System.Runtime.InteropServices;")) { resUsing.Add("using System.Runtime.InteropServices;"); } } File.AppendAllLines(Path.GetDirectoryName(args[0]) + "/temp.tmp", temp); File.AppendAllText(Path.GetDirectoryName(args[0]) + "/temp.tmp", "\n\n"); if (classes.Count > 0) { for (int i = 0; i < classes.Count; i++) { temp = File.ReadAllLines(classes[i]); for (int j = 0; j < temp.Length - 1; j++) { if (temp[j].StartsWith("using")) { if (!resUsing.Contains(temp[j])) { resUsing.Add(temp[j]); } temp[j] = ""; } if (temp[j].ToLower().Trim().StartsWith("[reference]") || temp[j].ToLower().Trim().StartsWith("[icon]") || temp[j].ToLower().Trim().StartsWith("[class]") || temp[j].ToLower().Trim().StartsWith("[ref]") || temp[j].ToLower().Trim().StartsWith("[name]") || temp[j].ToLower().Trim().StartsWith("[hidden]")) { temp[j] = "//" + temp[j]; } } File.AppendAllLines(Path.GetDirectoryName(args[0]) + "/temp.tmp", temp); File.AppendAllText(Path.GetDirectoryName(args[0]) + "/temp.tmp", "\n\n"); } } if (resUsing.Count > 0) { PrependAllLines(Path.GetDirectoryName(args[0]) + "/temp.tmp", resUsing.ToArray()); } string sir = Path.GetDirectoryName(args[0]) + "\\temp.tmp"; //AprilSpeak(Path.GetDirectoryName(args[0]) + "/temp.cs"); //Console.ReadLine(); CompileFile(sir, Path.GetDirectoryName(args[0]) + "/" + name + ".exe", references.ToArray(), icon); AprilSpeak("I have successfully evaluated and compiled '" + name + ".exe' without any errors..."); Console.ReadLine(); try { //File.Delete(Path.GetDirectoryName(args[0]) + "/temp.tmp"); } catch (Exception ex) { AprilSpeak(ex.ToString()); } } } else { //If the compiler has been clicked on instead of dragged over AprilSpeak("Hello. I am the April Compiler module. I can compile special types of C Sharp files sources. I make the compiler smarter and more user friendly to use without Visual Studio!"); while (true) { Console.ForegroundColor = ConsoleColor.Green; string input = Console.ReadLine().ToLower().Trim(); //Interpret input and reply with output if (input == "help") { AprilSpeak("Well, if you have any source files, just drag them onto the Compiler(The executable you clicked on to bring me up!). My style is pretty much just the same Syntax as C Sharp, except you can call different commands from the beginning of the source file, making things easier! Here are a list of commands..."); AprilSpeak(""); AprilSpeak("'[reference]*DLL*' - This will add a dll/library file to the list of references. Example: [reference]System.dll"); AprilSpeak("'[class]*FILE*' - This will add a reference to a class file to add to the source. Example: [class]MyClass.cs"); AprilSpeak("'[name]*STRING*' - This will set the application executable name. Example: [name]My Application"); AprilSpeak("'[hidden]' - This will hide the console window for the executable. Good for making WinForm applications, or background tasks"); } else if (input.StartsWith("generate")) { using (StreamWriter sw = new StreamWriter("Source.cs")) { sw.WriteLine("/*"); sw.WriteLine(" * This is a source file created using ACSC."); sw.WriteLine(" * You can now build a project from here and compile it by dragging it"); sw.WriteLine(" * onto the ACSC application."); sw.WriteLine(" *"); sw.WriteLine(" * Date Of Creation: " + DateTime.Now.ToString("dd/MM/yyyy h:mm tt")); sw.WriteLine(" */"); sw.WriteLine("[Reference]System.dll"); sw.WriteLine("[Name]Source"); sw.WriteLine(""); sw.WriteLine("using System;"); sw.WriteLine(""); sw.WriteLine("namespace SourceFile {"); sw.WriteLine(" class Source {"); sw.WriteLine(""); sw.WriteLine(" static void Main() {"); sw.WriteLine(" Console.WriteLine(\"This is a source file created by April...\");"); sw.WriteLine(" Console.ReadLine();"); sw.WriteLine(" }"); sw.WriteLine(" }"); sw.WriteLine("}"); } AprilSpeak("File has been generated. I named it 'source.cs'. This will make a good base for you to work from."); Console.ReadLine(); return; } else if (input == "exit" || input == "quit") { AprilSpeak("Ok then. Goodbye!"); Console.ReadLine(); return; } } } }
/// <summary>Equivalent to the same method in <see cref="List{T}"/>.</summary> public void InsertRange(int index, IEnumerable <T> collection) { fill(index); _inner.InsertRange(index, collection); }
private async void HandleTcpListenerAsync() { TcpClient client = null; try { try { client = await _tcpListener.AcceptTcpClientAsync(); ClientConnectedEventArgs clientConnectedEventArgs = new ClientConnectedEventArgs(ProtocolType.Tcp, (IPEndPoint)client.Client.RemoteEndPoint); await ClientConnected.RaiseAsync(this, clientConnectedEventArgs); if (clientConnectedEventArgs.RefuseConnect) { return; } } finally { lock (_listenerLock) { _hasActiveTcpListener = false; } } StartTcpListenerTask(); using (NetworkStream stream = client.GetStream()) { while (true) { byte[] buffer = await ReadIntoBufferAsync(client, stream, 2); if (buffer == null) // client disconneted while reading or timeout { break; } int offset = 0; int length = DnsMessageBase.ParseUShort(buffer, ref offset); buffer = await ReadIntoBufferAsync(client, stream, length); if (buffer == null) // client disconneted while reading or timeout { throw new Exception("Client disconnted or timed out while sending data"); } DnsMessageBase query; byte[] tsigMac; try { query = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null); tsigMac = query.TSigOptions?.Mac; } catch (Exception e) { throw new Exception("Error parsing dns query", e); } DnsMessageBase response; try { response = await ProcessMessageAsync(query, ProtocolType.Tcp, (IPEndPoint)client.Client.RemoteEndPoint); } catch (Exception ex) { OnExceptionThrownAsync(ex); response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null); response.IsQuery = false; response.AdditionalRecords.Clear(); response.AuthorityRecords.Clear(); response.ReturnCode = ReturnCode.ServerFailure; } byte[] newTsigMac; length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac); if (length <= 65535) { await stream.WriteAsync(buffer, 0, length); } else { if ((response.Questions.Count == 0) || (response.Questions[0].RecordType != RecordType.Axfr)) { OnExceptionThrownAsync(new ArgumentException("The length of the serialized response is greater than 65,535 bytes")); response = DnsMessageBase.CreateByFlag(buffer, TsigKeySelector, null); response.IsQuery = false; response.AdditionalRecords.Clear(); response.AuthorityRecords.Clear(); response.ReturnCode = ReturnCode.ServerFailure; length = response.Encode(true, tsigMac, false, out buffer, out newTsigMac); await stream.WriteAsync(buffer, 0, length); } else { bool isSubSequentResponse = false; while (true) { List <DnsRecordBase> nextPacketRecords = new List <DnsRecordBase>(); while (length > 65535) { int lastIndex = Math.Min(500, response.AnswerRecords.Count / 2); int removeCount = response.AnswerRecords.Count - lastIndex; nextPacketRecords.InsertRange(0, response.AnswerRecords.GetRange(lastIndex, removeCount)); response.AnswerRecords.RemoveRange(lastIndex, removeCount); length = response.Encode(true, tsigMac, isSubSequentResponse, out buffer, out newTsigMac); } await stream.WriteAsync(buffer, 0, length); if (nextPacketRecords.Count == 0) { break; } isSubSequentResponse = true; tsigMac = newTsigMac; response.AnswerRecords = nextPacketRecords; length = response.Encode(true, tsigMac, true, out buffer, out newTsigMac); } } } // Since support for multiple tsig signed messages is not finished, just close connection after response to first signed query if (newTsigMac != null) { break; } } } } catch (Exception ex) { OnExceptionThrownAsync(ex); } finally { try { // ReSharper disable once ConstantConditionalAccessQualifier client?.Close(); } catch { // ignored } lock (_listenerLock) { _availableTcpListener++; } StartTcpListenerTask(); } }
/// <summary> /// Lists the stops along a route, in order. /// </summary> /// <param name="feed">The GTFS feed to use.</param> /// <param name="route">The ID of the route to get stops for.</param> /// <param name="direction"> /// The direction of trips to get. Must exactly match the direction /// provided in GTFS; <c>null</c> here does not match "any direction" /// in the data. /// </param> public static IEnumerable <Stop> GetStopOrder(GTFSFeed feed, string route, DirectionType?direction = null) { var routeStopTimes = from stopTimes in feed.StopTimes join trips in feed.Trips on stopTimes.TripId equals trips.Id where trips.RouteId == route && trips.Direction == direction select stopTimes; // If it's empty, return empty list. Though that shouldn't be possible in well-formed GTFS. if (routeStopTimes.Count() == 0) { return(Enumerable.Empty <Stop>()); } // First, we'll need a listing of every trip, how many stops it has, and how many of those we've already listed. var stopsOnTrips = from rstListingUngrouped in routeStopTimes group rstListingUngrouped by rstListingUngrouped.TripId into rstListingGrouped let stopCount = rstListingGrouped.Count() orderby stopCount descending select new { rstListingGrouped.First().TripId, Stops = stopCount, FoundStops = 0 }; List <string> outStops = new List <string>(); while (stopsOnTrips.Count() > 0) { // First take the first trip with "unlisted" stops string newTrip = stopsOnTrips.First().TripId; var newStops = (from rstListing in routeStopTimes where rstListing.TripId == newTrip orderby rstListing.StopSequence select rstListing.StopId).Distinct(); // Handling for first trip searched if (outStops.Count == 0) { outStops = newStops.Distinct().ToList(); } else { // Now merge the listings List <string> foundStops = new List <string>(outStops); List <string> addingStops = new List <string>(); string lastFoundStop = null; foreach (string stop in newStops) { int foundIndex = foundStops.IndexOf(stop); if (foundIndex != -1) { // Remove the found stop and all preceding stops from the found-stops list foundStops.RemoveRange(0, foundIndex + 1); // If there were unfound stops, add them to the output too if (addingStops.Count > 0) { int outIndex = outStops.IndexOf(stop); outStops.InsertRange(outIndex, addingStops); addingStops.Clear(); } // Also, set the last found stop to this one lastFoundStop = stop; } else { addingStops.Add(stop); } } // Add stray stops just after the last found stop if (lastFoundStop != null) { outStops.InsertRange(outStops.IndexOf(lastFoundStop) + 1, addingStops); } else { // Or on the end if the two segments are, somehow, not linked outStops.AddRange(addingStops); } // Make sure outStops only contains items once outStops = outStops.Distinct().ToList(); } // Now we need to update stopsOnTrips stopsOnTrips = from rstListingUngrouped in routeStopTimes group rstListingUngrouped by rstListingUngrouped.TripId into rstListingGrouped let stopCount = rstListingGrouped.Count() let foundStopCount = rstListingGrouped.Count(x => outStops.Contains(x.StopId)) where foundStopCount < stopCount orderby Math.Sign(stopCount) descending, stopCount - foundStopCount descending, stopCount select new { rstListingGrouped.First().TripId, Stops = rstListingGrouped.Count(), FoundStops = rstListingGrouped.Count(x => outStops.Contains(x.StopId)) }; } return (from stops in outStops join feedStops in feed.Stops on stops equals feedStops.Id select feedStops); }
//Removes the hamming bits from the supplied array //Returns the new array of bytes properly flipped and aligned\ //Removes trailing 0's from the block static byte[] RemoveHammingBits(byte[] toCorrect) { //First, copy the array into a list of bools, for easier individual bit handling List <bool> bitList = new List <bool>(); List <bool> resultBitList = new List <bool>(); for (int i = 0; i < toCorrect.Length; ++i) { for (int offset = 7; offset >= 0; --offset) { if ((toCorrect[i] & (1 << offset)) != 0) { bitList.Add(true); } else { bitList.Add(false); } } } //Loop while we still have unmodified bits List <bool> previous = new List <bool>(); while (bitList.Count > 0) { //Get the next 32 bits List <bool> tmpChunk = new List <bool>(); tmpChunk.AddRange(bitList.Take(32).ToList()); bitList.RemoveRange(0, 32); //Remove the hamming bits themselves tmpChunk.RemoveAt(31); tmpChunk.RemoveAt(30); tmpChunk.RemoveAt(28); tmpChunk.RemoveAt(24); tmpChunk.RemoveAt(16); tmpChunk.RemoveAt(0); //Prepend with any bits from the previous chunk tmpChunk.InsertRange(0, previous); previous.RemoveRange(0, previous.Count); //Flip the first 3 bytes, and add them to the finished list List <bool> tmpByte = tmpChunk.Take(8).ToList(); tmpChunk.RemoveRange(0, 8); tmpByte.Reverse(); resultBitList.AddRange(tmpByte); tmpByte = tmpChunk.Take(8).ToList(); tmpChunk.RemoveRange(0, 8); tmpByte.Reverse(); resultBitList.AddRange(tmpByte); tmpByte = tmpChunk.Take(8).ToList(); tmpChunk.RemoveRange(0, 8); tmpByte.Reverse(); resultBitList.AddRange(tmpByte); //If the last section is less than a byte, save it for the next chunk //Otherwise, flip and add it if (tmpChunk.Count < 8) { previous = tmpChunk.Take(tmpChunk.Count).ToList(); tmpChunk.RemoveRange(0, tmpChunk.Count); } else { tmpByte = tmpChunk.Take(8).ToList(); tmpChunk.RemoveRange(0, 8); tmpByte.Reverse(); resultBitList.AddRange(tmpByte); previous.RemoveRange(0, previous.Count); } } resultBitList.AddRange(previous); List <byte> corrected = new List <byte>(); //Add the inidividual bits to an array of bytes while (resultBitList.Count >= 8) { bool[] tmpByte = resultBitList.Take(8).ToArray(); resultBitList.RemoveRange(0, 8); byte insertedByte = 0; for (int i = 0; i < 8; ++i) { if (tmpByte[i]) { insertedByte += (byte)Math.Pow(2, 7 - i); } } corrected.Add(insertedByte); } return(corrected.ToArray()); }
public void Modify(string path, List <string> filterClasses) { // convert saveable collection to string var filterTemplateCollection = Properties.Settings.Default.FilterTemplate; var filterTemplateList = filterTemplateCollection.Cast <string>().ToList(); template = string.Join(Environment.NewLine, filterTemplateList); template += Environment.NewLine + "{0}"; // preventing edge case: empty Class in filter if (filterClasses.Count == 0) { template = ""; } // build class string string filterClassStr = "Class "; foreach (var filterClass in filterClasses) { filterClassStr += String.Format("\"{0}\" ", filterClass); } // read the specified filter text List <string> filterFileLines = new List <string>(System.IO.File.ReadAllLines(Properties.Settings.Default.FilterPath)); int lineStart = -1; int lineStop = -1; // search for 'start' and 'stop' stop tags for (int i = 0; i < filterFileLines.Count; i++) { string line = filterFileLines[i]; if (line == start) { lineStart = i; } else if (line == stop) { lineStop = i; } } // both start and stop tags exist if (lineStart != -1 && lineStop != -1) { // check if we have to write an update bool updateRequired = true; for (int i = lineStart; i < lineStop; i++) { var currLine = filterFileLines[i]; if (currLine.Contains(filterClassStr)) { updateRequired = false; } } if (updateRequired) { // delete existing lines for (int i = lineStop; i > lineStart - 1; i--) { filterFileLines.RemoveAt(i); } // write template between tags filterFileLines.InsertRange(lineStart, new List <string> { start, String.Format(template, filterClassStr), stop }); System.IO.File.WriteAllLines(path, filterFileLines); MessageBox.Show("Filter changed, pls refresh!", "Alert", MessageBoxButtons.OK); } } else { MessageBox.Show("Can't find start and stop tags. Please adjust your filter.", "Alert", MessageBoxButtons.OK); } }