public void BringToFront(int index) { WorldWind.NewWidgets.IWidget currentWidget = m_ChildWidgets[index] as WorldWind.NewWidgets.IWidget; if (currentWidget != null) { m_ChildWidgets.RemoveAt(index); m_ChildWidgets.Insert(0, currentWidget); } }
public void BringToFront(int index) { jhuapl.util.IWidget currentWidget = m_ChildWidgets[index] as jhuapl.util.IWidget; if (currentWidget != null) { m_ChildWidgets.RemoveAt(index); m_ChildWidgets.Insert(0, currentWidget); } }
public void Delete(int position) { try { servers.RemoveAt(position); } catch (System.Exception e) { string temp = e.Message; } }
public bool finalCraftCheck() { if (!hasUncraftable && instances.Count > 0) { instances.RemoveAt(instances.Count - 1); } if (instances.Count > 0) { return(true); } return(false); }
public void Delete(string nick) { for (int i = 0; i < users.Count; i++) { info = (serverUserInfo)users[i]; if (info.nick.ToString() == nick.ToLower()) { users.RemoveAt(i); break; } } }
/// <summary> /// 内部方法 /// </summary> /// <param name="strURL"></param> /// <returns></returns> public static string CombineUrl(string strURL) { int index = strURL.IndexOf("//"); string strPrefix = null; if (index > 0) { strPrefix = strURL.Substring(0, index + 2); } if (index >= 0) { strURL = strURL.Substring(index + 2); } string[] strItems = strURL.Split("/\\".ToCharArray()); System.Collections.ArrayList myItems = new System.Collections.ArrayList(); foreach (string strItem in strItems) { if (strItem.Trim().Length != 0) { myItems.Add(strItem); } } for (int iCount = 0; iCount < myItems.Count; iCount++) { if ("..".Equals(myItems[iCount])) { if (iCount > 0) { myItems.RemoveAt(iCount); myItems.RemoveAt(iCount - 1); iCount -= 2; } } } //for System.Text.StringBuilder myStr = new System.Text.StringBuilder(); foreach (string strItem in myItems) { if (myStr.Length > 0) { myStr.Append("/"); } myStr.Append(strItem); } if (strPrefix != null) { myStr.Insert(0, strPrefix); } return(myStr.ToString()); }
private void button2_Click(object sender, EventArgs e) { int idx = fontlist.SelectedIndex; mFonts.RemoveAt(idx); fontlist.Items.RemoveAt(idx); if (idx >= fontlist.Items.Count) { --idx; } if (idx >= 0) { fontlist.SelectedIndex = idx; } }
// Remove the root Scorer from subScorers and re-establish it as a heap private void HeapRemoveRoot() { int size = subScorers.Count; if (size == 1) { subScorers.RemoveAt(0); } else { subScorers[0] = subScorers[size - 1]; subScorers.RemoveAt(size - 1); HeapAdjust(0); } }
/// <seealso cref="CrossComponentIterator.provideNextVertex()"> /// </seealso> protected internal override System.Object provideNextVertex() { System.Object tempObject; tempObject = m_queue[0]; m_queue.RemoveAt(0); return(tempObject); }
/// <summary> /// Removes the element at the top of the stack and returns it. /// </summary> /// <param name="stack">The stack where the element at the top will be returned and removed.</param> /// <returns>The element at the top of the stack.</returns> public static System.Object Pop(System.Collections.ArrayList stack) { System.Object obj = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); return(obj); }
public void Stop() { keepRunning = false; // Begin closing all running processes for (int i = runningProcesses.Count - 1; i > -1; i--) { ((AgentProcess)runningProcesses[i]).StopAsync(); } if (RunningProcesses > 0) { // Give each process until its Runtime > StopProcessTimeout to end while (runningProcesses.Count > 0) { AgentProcess[] pa = RunningProcessesArray; for (int i = 0; i < pa.Length; i++) { if (pa[i].Runtime > StopProcessTimeout) { pa[i].Stop(); } } System.Threading.Thread.Sleep(100); } // Remove any stuck processes from the runningProcesses collection for (int i = runningProcesses.Count - 1; i > -1; i--) { ((AgentProcess)runningProcesses[i]).Dispose(); runningProcesses.RemoveAt(i); } } }
public static void RemovePlaza(System.Windows.Forms.Button b) { int i = botonesDiseño.IndexOf(b); plazas.RemoveAt(i); botonesDiseño.RemoveAt(i); }
public void RemoveSurfaceImage(string imageResource) { try { lock (m_SurfaceImages.SyncRoot) { for (int i = 0; i < m_SurfaceImages.Count; i++) { SurfaceImage current = m_SurfaceImages[i] as SurfaceImage; if (current != null && current.ImageFilePath == imageResource) { m_SurfaceImages.RemoveAt(i); break; } } m_SurfaceImages.Sort(); } LastChange = System.DateTime.Now; } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { Log.DebugWrite(ex); } }
private void listViewResultats_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { try { if (listViewResultatsSelection != -1) { LesRapports.RemoveAt(listViewResultatsSelection); } if (listViewResultatsSelection >= LesRapports.Count) { listViewResultatsSelection = -1; toolStripMenuItemCopierLesCoordonnees.Enabled = false; } } catch (Exception) { listViewResultatsSelection = -1; toolStripMenuItemCopierLesCoordonnees.Enabled = false; } listViewResultats.VirtualListSize = LesRapports.Count; } if (e.KeyCode == Keys.Enter) { MetAJourLaVueDuRapport(); } }
private static Bamboo.Query.Query.OrderByClause GetOrderBy(System.Collections.ArrayList tokens, string from) { System.Collections.ArrayList orderByExpressions = new System.Collections.ArrayList(tokens.Count); foreach (string token in tokens) { if (token.Equals("DESC")) { int index = orderByExpressions.Count - 1; Bamboo.Query.Query.OrderByExpression orderByExpression = (Bamboo.Query.Query.OrderByExpression)orderByExpressions[index]; orderByExpressions.RemoveAt(index); orderByExpressions.Add(new Bamboo.Query.Query.OrderByExpression(orderByExpression.Column, false)); } else if (token.Equals(",")) { } else { orderByExpressions.Add(new Bamboo.Query.Query.OrderByExpression(CreateColumn(token, from))); } } if (orderByExpressions.Count == 0) { return(null); } else { return(new Bamboo.Query.Query.OrderByClause(orderByExpressions)); } }
/// <summary>Delete an HDU from the HDU list.</summary> /// <param name="n"> The index of the HDU to be deleted. /// If n is 0 and there is more than one HDU present, then /// the next HDU will be converted from an image to /// primary HDU if possible. If not a dummy header HDU /// will then be inserted.</param> public virtual void DeleteHDU(int n) { int size = NumberOfHDUs; if (n < 0 || n >= size) { throw new FitsException("Attempt to delete non-existent HDU:" + n); } try { hduList.RemoveAt(n); if (n == 0 && size > 1) { BasicHDU newFirst = (BasicHDU)hduList[0]; if (newFirst.CanBePrimary) { newFirst.PrimaryHDU = true; } else { InsertHDU(BasicHDU.DummyHDU, 0); } } } catch (Exception) { throw new FitsException("Internal Error: hduList Vector Inconsitency"); } }
/// <summary> /// Sorts the card by their suit /// </summary> /// <param name="pile"></param> /// <returns></returns> public static Pile SortBySuit(Pile pile) { System.Collections.ArrayList newHand = new System.Collections.ArrayList(); System.Collections.ArrayList CardPile = (System.Collections.ArrayList)pile.CardPile; while (CardPile.Count > 0) { int pos = 0; // Position of minimal card. SpadesCard minSpadescard = (SpadesCard)CardPile[0]; // Minimal card. int mincard = (int)minSpadescard.CardIndex; for (int i = 1; i < CardPile.Count; i++) { SpadesCard nextSpadescard = (SpadesCard)CardPile[i]; int nextcard = nextSpadescard.CardIndex; if (Card.SuitFromCardIndex(nextcard) < Card.SuitFromCardIndex(mincard) || (Card.SuitFromCardIndex(nextcard) == Card.SuitFromCardIndex(mincard) && Card.RankFromCardIndex(nextcard) < Card.RankFromCardIndex(mincard)) ) { pos = i; mincard = nextcard; minSpadescard = nextSpadescard; } } CardPile.RemoveAt(pos); newHand.Add(minSpadescard); } CardPile = newHand; pile.CardPile = CardPile; return(pile); }
void System.Collections.IList.RemoveAt(int Index) { try { Buffer.RemoveAt(Index); } catch (System.Exception Excpt) { Err.Add(Excpt); } }
public static void AddRecentFile(string fileName) { if (recentFiles.Count == 4) { recentFiles.RemoveAt(3); } recentFiles.Insert(0, fileName); }
public static void AddRecentProject(string projectName) { if (recentProjects.Count == 4) { recentProjects.RemoveAt(3); } recentProjects.Insert(0, projectName); }
public T Remove(int index) { var removed = Get(index); _internalArray.RemoveAt(index); return(removed); }
/// <summary> /// Adds a project file path to the recent projects list. /// </summary> /// <param name="projectName"> /// Path of the project file. /// </param> public static void AddToRecentProjects(string projectName) { for (int index = 0; index < recentProjectsList.Count; index++) { if (projectName.ToLower() == ((string)recentProjectsList[index]).ToLower()) { recentProjectsList.RemoveAt(index); recentProjectsList.Insert(0, projectName); return; } } if (recentProjectsList.Count >= 4) { recentProjectsList.RemoveAt(3); } recentProjectsList.Insert(0, projectName); }
//remove children from [start,end) and replace with node n public virtual void condense(ASTNode node, int start, int end) { for (int i = end - 1; i >= start; i--) { content.RemoveAt(i); } content.Insert(start, node); }
public void DeleteCurrentItemSelected() { if (this.SelectedItem != null) { m_arlObjects.RemoveAt(this.SelectedIndex); this.Items.RemoveAt(this.SelectedIndex); this.Text = ""; } }
public static void ProceedOneXML_File(String url) { XmlTextReader reader = new XmlTextReader(url); String[] delim = new String[2]; string last = "last"; delim[0] = "coll\\"; delim[1] = ".xml"; String[] s = url.Split(delim, System.StringSplitOptions.None); Int32.TryParse(s[s.Length - 2], out _currentDocument.number); bool tof = true; while (tof) { try { tof = reader.Read(); if (reader.NodeType == XmlNodeType.Element && !(reader.NodeType == XmlNodeType.EndElement)) { int k = 1; last = reader.Name; if (balises.ContainsKey(last)) { balises[last]++; } else { balises.Add(last, 1); } k = balises[last]; last += "[" + k + "]"; al.Add(last); } if (reader.NodeType == XmlNodeType.EndElement) { last = (al[al.Count - 1]).ToString(); string nom_balise = reader.Name; if (last.Contains(nom_balise)) { al.RemoveAt(al.Count - 1); } } if (reader.NodeType == XmlNodeType.Text) { ProceedOneLineXML(reader.Value); } } catch (Exception e) { } } reader.Close(); }
/// <summary>Increments the enumeration to the next element. True if one exists. </summary> //@Override public override bool Next() { // if a current term exists, the actual enum is initialized: // try change to next term, if no such term exists, fall-through if (currentTerm != null) { System.Diagnostics.Debug.Assert(actualEnum != null); if (actualEnum.Next()) { currentTerm = actualEnum.Term(); if (TermCompare(currentTerm)) { return(true); } } } // if all above fails, we go forward to the next enum, // if one is available currentTerm = null; if (rangeBounds.Count < 2) { return(false); } // close the current enum and read next bounds if (actualEnum != null) { actualEnum.Close(); actualEnum = null; } System.Object tempObject; tempObject = rangeBounds[0]; rangeBounds.RemoveAt(0); System.String lowerBound = (System.String)tempObject; System.Object tempObject2; tempObject2 = rangeBounds[0]; rangeBounds.RemoveAt(0); this.currentUpperBound = ((System.String)tempObject2); // this call recursively uses next(), if no valid term in // next enum found. // if this behavior is changed/modified in the superclass, // this enum will not work anymore! SetEnum(reader.Terms(new Term(Enclosing_Instance.field, lowerBound))); return(currentTerm != null); }
public void shuffle() { Random r = new Random(); int randomIndex = 0; for (int i = 0; i < 10; i++) { System.Collections.ArrayList ar = new System.Collections.ArrayList(); while (Cards.Count > 0) { randomIndex = r.Next(0, Cards.Count); //Choose a random object in the list ar.Add(Cards[randomIndex]); //add it to the new, random list Cards.RemoveAt(randomIndex); //remove to avoid duplicates } Cards.Clear(); Cards = null; Cards = ar; } }
public virtual void EhView_StyleRemove(int[] selindices) { for (int i = selindices.Length - 1; i >= 0; --i) { _tempdoc.RemoveAt(selindices[i]); } UpdateStyleList(new int[0]); OnCollectionChangeCommit(); }
internal virtual Term GetDeleteTerm() { lock (toDeleteTerms.SyncRoot) { System.Object tempObject; tempObject = toDeleteTerms[0]; toDeleteTerms.RemoveAt(0); return((Term)tempObject); } }
//remove a value; return index of item just removed if it was present, -1 if it was not public virtual int remove(int n) { int i = indexOf(n, true); if (i != -1) { v.RemoveAt(i); } return(i); }
void BFolderClick(object sender,System.EventArgs e) { if(PatchInProgress) { MessageBox.Show("Can only patch one file at a time.","Error"); return; } if(OpenFolder.ShowDialog()==DialogResult.OK) { ArrayList files=new ArrayList(Directory.GetFiles(OpenFolder.SelectedPath)); for(int i=0;i<files.Count;i++) { if(Array.IndexOf(ExecutableExtensions,Path.GetExtension((string)files[i]))==-1) { files.RemoveAt(i--); } } new PatchDialog((string[])files.ToArray(typeof(string))); } }
//Create a Set command for the identifier on top of the stack //NOTE: unlike GET, the last value on the SET stack is assumed to be the new value private void RecordStack(Type ExpectedDataType) { string total = ""; //Add the dot notation System.Collections.ArrayList thiscommand = new System.Collections.ArrayList(); foreach (string i in stack) { thiscommand.Add(i); thiscommand.Add("."); } //some string fixup thiscommand.Reverse(); thiscommand.RemoveAt(thiscommand.Count - 2); string value = (string)thiscommand[thiscommand.Count - 1]; thiscommand.RemoveAt(thiscommand.Count - 1); foreach (string i in thiscommand) { total += i; } //Total is not the name of the identifier //value is the value total = total.Substring(1); // add cmi. to all data model identifiers total = "cmi." + total; ScormSet ss = new ScormSet(total, value, ExpectedDataType); //set this on the serilization list //NOTE: we could just call the wrapper here directly wrapper.Set(ss); }
public bool BenergyTest(ArrayList index1, ArrayList index2) { int i,j; int count = 0; string te = ArraytoString(index1); if (string.Compare(ArraytoString(index1), ArraytoString(index2)) == 0) { return false; } if (index1.Count >= index2.Count) { for (i = 0; i < index1.Count; i++) { for (j = 0; j < index2.Count; j++) { if ((index1[i].ToString() == "+") || (index1[i].ToString() == "-") || (index1[i].ToString() == "[")) { index1.RemoveAt(i); } if (String.Compare(index1[i].ToString() ,index2[j].ToString()) == 0) { index1.RemoveAt(i); index2.RemoveAt(j); } else { count++; } } } if (index1.Count == 0) { return false; } } else { for (i = 0; i < index2.Count; i++) { for (j = 0; j < index1.Count; j++) { if ((index2[i].ToString() == "+") || (index2[i].ToString() == "-") || (index2[i].ToString() == "[")) { index2.RemoveAt(i); } if (String.Compare(index2[i].ToString(), index1[j].ToString())==0) { index2.RemoveAt(i); index1.RemoveAt(j); } else { count++; } } } if (index2.Count == 0) { return false; } } return true; }
protected override Object CreateObject(NonterminalToken token) { string name; int bytes, inx, value; CmdItem cmdItem; TestValue testval; try { switch (token.Rule.Id) { case (int)RuleConstants.RULE_TESTGROUPEXPRESS_TESTEQ: CanTest = false; break; case (int)RuleConstants.RULE_VERSION_VERSIONEQ_FLOAT: this.version = token.Tokens[1].UserObject.ToString(); break; case (int)RuleConstants.RULE_TESTGROUPEXPRESS_TESTEQ2: CanTest = true; break; case (int)RuleConstants.RULE_TESTEXPRESS_ATCMD: tmpTestExpress.Add(tmpTestValues); tmpTestValues = new System.Collections.ArrayList(10); break; case (int)RuleConstants.RULE_TESTREPEATITEMS_LBRACE_RBRACE: testval = (TestValue)token.Tokens[0].UserObject; inx = tmpTestValues.IndexOf(testval); for (int i = inx + 1; i < tmpTestValues.Count; i++) testval.subValues.Add(tmpTestValues[i]); for (int i = tmpTestValues.Count - 1; i > inx; i--) tmpTestValues.RemoveAt(i); break; case (int)RuleConstants.RULE_TESTSELECTVALUE_NUMBER: return token.Tokens[0].ToString(); case (int)RuleConstants.RULE_TESTSELECTVALUES: return token.Tokens[0].UserObject; case (int)RuleConstants.RULE_TESTSELECTITEM_IDENTIFIER_LPARAN_RPARAN: name = token.Tokens[0].UserObject.ToString(); value = Convert.ToInt32(token.Tokens[2].UserObject.ToString()); tmpTestValues.Add(testval = new TestValue(name, value)); return testval; case (int)RuleConstants.RULE_TESTITEM2: return token.Tokens[0].UserObject; case (int)RuleConstants.RULE_RANGEITEM_IDENTIFIER_LPARAN_RPARAN: NonterminalToken ntok; name = token.Tokens[getTokenInx(token, "Identifier")].UserObject.ToString(); ntok = findToken(token, "Bytes"); bytes = Convert.ToInt32(ntok.Tokens[0].UserObject.ToString()); ntok = findToken(token, "LValue"); int lval = Convert.ToInt32(ntok.Tokens[0].UserObject.ToString()); ntok = findToken(token, "HValue"); int hval = Convert.ToInt32(ntok.Tokens[0].UserObject.ToString()); TmpCmdItems.Add(cmdItem = new CmdItem(name, bytes, lval, hval)); return cmdItem; case (int)RuleConstants.RULE_SELECTITEM_IDENTIFIER_LPARAN_RPARAN: SelectValue[] selectvalues; name = token.Tokens[0].UserObject.ToString(); bytes = Convert.ToInt32(findToken(token, "Bytes").Tokens[0].UserObject.ToString()); selectvalues = new SelectValue[TmpSelectValues.Count]; for (int i = 0; i < TmpSelectValues.Count; i++) { selectvalues[i] = (SelectValue)TmpSelectValues[i]; } TmpCmdItems.Add(cmdItem = new CmdItem(name, bytes, selectvalues)); TmpSelectValues.Clear(); return cmdItem; case (int)RuleConstants.RULE_SELECTVALUE_NUMBER: SelectValue sVal = new SelectValue(); sVal.value = Convert.ToInt32(token.Tokens[0].UserObject.ToString()); sVal.valueName = findToken(token, "ValueDescription").Tokens[0].UserObject.ToString(); TmpSelectValues.Add(sVal); break; case (int)RuleConstants.RULE_EXPRESSITEM: return token.Tokens[0].UserObject; case (int)RuleConstants.RULE_REPEATEXPRESS_LBRACE_RBRACE: inx = TmpCmdItems.IndexOf(token.Tokens[0].UserObject); for (int i = inx + 1; i < TmpCmdItems.Count; i++) ((CmdItem)TmpCmdItems[inx]).AddSubItems((CmdItem)TmpCmdItems[i]);//reduce repeat item for (int i = TmpCmdItems.Count - 1; i > inx; i--) TmpCmdItems.RemoveAt(i); return TmpCmdItems[inx]; case (int)RuleConstants.RULE_SENDEXPRESS_SENDEQ: //send express tmpSendExpress.Clear(); break; case (int)RuleConstants.RULE_SENDEXPRESS_SENDEQ2: //sendexpress tmpSendExpress = (System.Collections.ArrayList)TmpCmdItems.Clone(); TmpCmdItems.Clear(); break; case (int)RuleConstants.RULE_RETURNEXPRESS_RETURNEQ: tmpReturnExpress.Clear(); break; case (int)RuleConstants.RULE_RETURNEXPRESS_RETURNEQ2: tmpReturnExpress = (System.Collections.ArrayList)TmpCmdItems.Clone(); TmpCmdItems.Clear(); break; case (int)RuleConstants.RULE_DEVICETYPE_DEVICETYPEEQ_IDENTIFIER: this.DeviceType = token.Tokens[1].UserObject.ToString(); break; case (int)RuleConstants.RULE_IP_IPEQ_IP: ip = token.Tokens[1].UserObject.ToString(); break; case (int)RuleConstants.RULE_PORT_PORTEQ_NUMBER: port = int.Parse(token.Tokens[1].UserObject.ToString()); break; case (int)RuleConstants.RULE_DEVICEID_DEVICEIDEQ_DEVICEID: deviceId = Convert.ToInt32(token.Tokens[1].ToString(), 16); break; case (int)RuleConstants.RULE_CMD_CMDEQ_CMD: //Cmd cmd; //if(token.Tokens[2].UserObject==null) // cmd=new Cmd(Convert.ToByte(token.Tokens[1].UserObject.ToString(),16)); //else //cmd=new Cmd(Convert.ToByte(token.Tokens[1].UserObject.ToString(),16), // Convert.ToByte(token.Tokens[2].UserObject.ToString(),16)); // return cmd; break; case (int)RuleConstants.RULE_COMMAND: //CmdClass cls; //CmdType type; //string desc; //string func_name; //byte cmdcode; Cmd cmd = new Cmd(this); // inx = getTokenInx(token, "Description"); for (int i = 0; i < token.Tokens.Length; i++) { NonterminalToken ttok; ttok = (NonterminalToken)token.Tokens[i]; if (token.Rule.Rhs[i].Name == "Description") { cmd.description = ((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString().Trim(new char[] { '\"' }); } else if (token.Rule.Rhs[i].Name == "FuncName") { cmd.cmdName = ((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString().Trim(new char[] { '\"' }); } else if (token.Rule.Rhs[i].Name == "CmdClass") { switch (((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString()[0]) { case 'A': cmd.cmdClass = CmdClass.A; break; case 'B': cmd.cmdClass = CmdClass.B; break; case 'C': cmd.cmdClass = CmdClass.C; break; case 'D': cmd.cmdClass = CmdClass.D; break; } } else if (token.Rule.Rhs[i].Name == "CmdType") { if (((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString() == "Set") cmd.cmdType = CmdType.CmdSet; else if (((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString() == "Query") cmd.cmdType = CmdType.CmdQuery; else if (((NonterminalToken)token.Tokens[i]).Tokens[1].UserObject.ToString() == "Report") cmd.cmdType = CmdType.CmdReport; else cmd.cmdType = CmdType.CmdUnkonwn; } else if (token.Rule.Rhs[i].Name == "Cmd") { cmd.cmd = Convert.ToByte(ttok.Tokens[1].UserObject.ToString(), 16); //cmd if (((NonterminalToken)ttok.Tokens[2]).Tokens.Length > 0) cmd.subCmd = Convert.ToByte(((NonterminalToken)ttok.Tokens[2]).Tokens[0].UserObject.ToString(), 16); //subCmd } } //for cmd.SendCmdItems = (System.Collections.ArrayList)tmpSendExpress.Clone(); cmd.ReturnCmdItems = (System.Collections.ArrayList)tmpReturnExpress.Clone(); cmd.TestGroupValues = tmpTestExpress; cmd.CanTest = CanTest; tmpReturnExpress.Clear(); tmpSendExpress.Clear(); tmpTestValues.Clear(); tmpTestExpress = new System.Collections.ArrayList(5); //try //{ if (cmd.cmdType != CmdType.CmdReport) cmd.CheckTestValue(); cmd.GenerateCmdDataSet(); //} //catch (Exception ex) //{ // Console.WriteLine(ex.StackTrace); //} this.AddCmd(cmd); break; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); throw ex; } return null; }
private void createMinimumCycleBasis() { org._3pq.jgrapht.Graph subgraph = new Subgraph(graph, null, null); CSGraphT.SupportClass.SetSupport remainingEdges = new CSGraphT.SupportClass.HashSetSupport(graph.edgeSet()); //UPGRADE_TODO: Class 'java.util.HashSet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashSet'" CSGraphT.SupportClass.SetSupport selectedEdges = new CSGraphT.SupportClass.HashSetSupport(); while (!(remainingEdges.Count == 0)) { //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" Edge edge = (Edge)remainingEdges.GetEnumerator().Current; subgraph.removeEdge(edge); // Compute a shortest cycle through edge System.Collections.IList path = BFSShortestPath.findPathBetween(subgraph, edge.Source, edge.Target); path.Add(edge); SimpleCycle cycle = new SimpleCycle(graph, path); subgraph.addEdge(edge); selectedEdges.Add(edge); cycles_Renamed_Field.Insert(0, cycle); edgeList.Insert(0, edge); SupportClass.ICollectionSupport.RemoveAll(remainingEdges, path); } subgraph.removeAllEdges(selectedEdges); // The cycles just created are already minimal, so we can start minimizing at startIndex int startIndex = cycles_Renamed_Field.Count; // Now we perform a breadth first traversal and build a fundamental tree base // ("Kirchhoff base") of the remaining subgraph System.Object currentVertex = graph.vertexSet()[0]; // We build a spanning tree as a directed graph to easily find the parent of a // vertex in the tree. This means however that we have to create new Edge objects // for the tree and can't just use the Edge objects of the graph, since the // the edge in the graph might have a wrong or no direction. DirectedGraph spanningTree = new SimpleDirectedGraph(); //UPGRADE_TODO: Class 'java.util.HashSet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashSet'" CSGraphT.SupportClass.SetSupport visitedEdges = new CSGraphT.SupportClass.HashSetSupport(); // FIFO for the BFS //UPGRADE_TODO: Class 'java.util.LinkedList' was converted to 'System.Collections.ArrayList' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilLinkedList'" System.Collections.ArrayList vertexQueue = new System.Collections.ArrayList(); // currentVertex is the root of the spanning tree spanningTree.addVertex(currentVertex); vertexQueue.Insert(vertexQueue.Count, currentVertex); // We need to remember the tree edges so we can add them at once to the // index list for the incidence matrix System.Collections.IList treeEdges = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); while (!(vertexQueue.Count == 0)) { System.Object tempObject; tempObject = vertexQueue[0]; vertexQueue.RemoveAt(0); currentVertex = tempObject; System.Collections.IEnumerator edges = subgraph.edgesOf(currentVertex).GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" while (edges.MoveNext()) { // find a neighbour vertex of the current vertex //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" Edge edge = (Edge)edges.Current; if (!visitedEdges.Contains(edge)) { // mark edge as visited visitedEdges.Add(edge); System.Object nextVertex = edge.oppositeVertex(currentVertex); if (!spanningTree.containsVertex(nextVertex)) { // tree edge treeEdges.Add(edge); spanningTree.addVertex(nextVertex); // create a new (directed) Edge object (as explained above) spanningTree.addEdge(currentVertex, nextVertex); // add the next vertex to the BFS-FIFO vertexQueue.Insert(vertexQueue.Count, nextVertex); } else { // non-tree edge // This edge defines a cycle together with the edges of the spanning tree // along the path to the root of the tree. We create a new cycle containing // these edges (not the tree edges, but the corresponding edges in the graph) System.Collections.IList edgesOfCycle = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // follow the path to the root of the tree System.Object vertex = currentVertex; // get parent of vertex System.Collections.IList incomingEdgesOfVertex = spanningTree.incomingEdgesOf(vertex); System.Object parent = (incomingEdgesOfVertex.Count == 0) ? null : ((Edge)incomingEdgesOfVertex[0]).oppositeVertex(vertex); while (parent != null) { // add the corresponding edge to the cycle edgesOfCycle.Add(subgraph.getEdge(vertex, parent)); // go up the tree vertex = parent; // get parent of vertex incomingEdgesOfVertex = spanningTree.incomingEdgesOf(vertex); parent = (incomingEdgesOfVertex.Count == 0) ? null : ((Edge)incomingEdgesOfVertex[0]).oppositeVertex(vertex); } // do the same thing for nextVertex vertex = nextVertex; // get parent of vertex incomingEdgesOfVertex = spanningTree.incomingEdgesOf(vertex); parent = (incomingEdgesOfVertex.Count == 0) ? null : ((Edge)incomingEdgesOfVertex[0]).oppositeVertex(vertex); while (parent != null) { edgesOfCycle.Add(subgraph.getEdge(vertex, parent)); vertex = parent; // get parent of vertex incomingEdgesOfVertex = spanningTree.incomingEdgesOf(vertex); parent = (incomingEdgesOfVertex.Count == 0) ? null : ((Edge)incomingEdgesOfVertex[0]).oppositeVertex(vertex); } // finally, add the non-tree edge to the cycle edgesOfCycle.Add(edge); // add the edge to the index list for the incidence matrix edgeList.Add(edge); SimpleCycle newCycle = new SimpleCycle(graph, edgesOfCycle); cycles_Renamed_Field.Add(newCycle); } } } } // Add all the tree edges to the index list for the incidence matrix SupportClass.ICollectionSupport.AddAll(edgeList, treeEdges); edgeIndexMap = createEdgeIndexMap(edgeList); // Now the index list is ordered: first the non-tree edges, then the tree edge. // Moreover, since the cycles and the corresponding non-tree edge have been added // to their lists in the same order, the incidence matrix is in upper triangular form. // Now we can minimize the cycles created from the tree base minimize(startIndex); }
/// <summary> Returns a list of atoms in the shortest path between two atoms. /// /// This method uses the Djikstra algorithm to find all the atoms in the shortest /// path between the two specified atoms. The start and end atoms are also included /// in the path returned /// /// </summary> /// <param name="atomContainer">The molecule to search in /// </param> /// <param name="start">The starting atom /// </param> /// <param name="end">The ending atom /// </param> /// <returns> A <code>List</code> containing the atoms in the shortest path between <code>start</code> and /// <code>end</code> inclusive /// </returns> public static System.Collections.IList getShortestPath(IAtomContainer atomContainer, IAtom start, IAtom end) { int natom = atomContainer.AtomCount; int endNumber = atomContainer.getAtomNumber(end); int startNumber = atomContainer.getAtomNumber(start); int[] d = new int[natom]; int[] previous = new int[natom]; for (int i = 0; i < natom; i++) { d[i] = 99999999; previous[i] = -1; } d[atomContainer.getAtomNumber(start)] = 0; System.Collections.ArrayList S = new System.Collections.ArrayList(); System.Collections.ArrayList Q = new System.Collections.ArrayList(); for (int i = 0; i < natom; i++) Q.Add((System.Int32)i); while (true) { if (Q.Count == 0) break; // extract min int u = 999999; int index = 0; for (int i = 0; i < Q.Count; i++) { int tmp = ((System.Int32)Q[i]); if (d[tmp] < u) { u = d[tmp]; index = i; } } Q.RemoveAt(index); S.Add(atomContainer.getAtomAt(u)); if (u == endNumber) break; // relaxation IAtom[] connected = atomContainer.getConnectedAtoms(atomContainer.getAtomAt(u)); for (int i = 0; i < connected.Length; i++) { int anum = atomContainer.getAtomNumber(connected[i]); if (d[anum] > d[u] + 1) { // all edges have equals weights d[anum] = d[u] + 1; previous[anum] = u; } } } System.Collections.ArrayList tmp2 = new System.Collections.ArrayList(); int u2 = endNumber; while (true) { tmp2.Insert(0, atomContainer.getAtomAt(u2)); u2 = previous[u2]; if (u2 == startNumber) { tmp2.Insert(0, atomContainer.getAtomAt(u2)); break; } } return tmp2; }
/// <summary> /// 计算其他独立义原描述式的相似度 /// </summary> /// <param name="line1"></param> /// <param name="line2"></param> /// <returns></returns> private double calSim2(string line1, string line2) { if (line1 == "" && line2 == "") { return 1d; } if (line1 == "" || line2 == "") { return 0d; } string[] sems1 = this.splitSemanetes(line1); System.Collections.ArrayList array_sems1 = new System.Collections.ArrayList(); for (int i = 0; i < sems1.Length; i++) { array_sems1.Add(sems1[i]); } string[] sems2 = this.splitSemanetes(line2); System.Collections.ArrayList array_sems2 = new System.Collections.ArrayList(); for (int j = 0; j < sems2.Length; j++) { array_sems2.Add(sems2[j]); } Stack<double> stk_max_sim = new Stack<double>(); int len1 = array_sems1.Count; int len2 = array_sems2.Count; while (len1 != 0 && len2 != 0) { int m = -1, n = -1; double max_sim = 0d; for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { double simil = calSimBase((string)array_sems1[i], (string)array_sems2[j]); if (simil > max_sim) { m = i; n = j; max_sim = simil; } } } if (max_sim == 0d) { break; } stk_max_sim.Push(max_sim); if (m != -1) { array_sems1.RemoveAt(m); } if (n != -1) { array_sems2.RemoveAt(n); } len1 = array_sems1.Count; len2 = array_sems2.Count; } //把整体相似度还原为部分相似度的加权平均,这里权值取一样,即计算算术平均 if (stk_max_sim.Count == 0) { return 0d; } double sum = 0.0; int count = stk_max_sim.Count; while (stk_max_sim.Count > 0) { sum += stk_max_sim.Pop(); } return sum / count; }
/// <summary> /// 计算符号义原描述式的相似度 /// </summary> /// <param name="line1"></param> /// <param name="line2"></param> /// <returns></returns> private double calSim4(string line1, string line2) { if (line1 == "" && line2 == "") { return 1d; } if (line1 == "" || line2 == "") { return 0d; } string[] sems1 = splitSemanetes(line1); System.Collections.ArrayList array_sems1 = new System.Collections.ArrayList(); for (int i = 0; i < sems1.Length; i++) { array_sems1.Add(sems1[i]); } string[] sems2 = splitSemanetes(line2); System.Collections.ArrayList array_sems2 = new System.Collections.ArrayList(); for (int j = 0; j < sems2.Length; j++) { array_sems2.Add(sems2[j]); } Stack<double> stk_sim = new Stack<double>(); int len1 = array_sems1.Count; int len2 = array_sems2.Count; while (len1 != 0 && len2 != 0) { char sym1 = ((string)array_sems1[len1 - 1])[0]; for (int j = 0; j < len2; j++) { char sym2 = ((string)array_sems2[j])[0]; if (sym1 == sym2) { string base1 = ((string)array_sems1[len1 - 1]).Substring(1); string base2 = ((string)array_sems2[j]).Substring(1); double ss = calSimBase(base1, base2); stk_sim.Push(ss); array_sems2.RemoveAt(j); break; } } array_sems1.RemoveAt(len1 - 1); len1 = array_sems1.Count; len2 = array_sems2.Count; } if (stk_sim.Count == 0) { return 0d; } double sum = 0d; int count = stk_sim.Count; while (stk_sim.Count > 0) { sum += stk_sim.Pop(); } return sum / count; }
void tbBlacklistLeave(object sender,System.EventArgs e) { ArrayList lines=new ArrayList(tbBlacklist.Lines); for(int i=0;i<lines.Count;i++) { string s=(string)lines[i]; if(s.Length!=8) { lines.RemoveAt(i--); } else { for(int a=0;a<8;a++) { if(Array.IndexOf(Hex2,s[a])==-1) { lines.RemoveAt(i--); break; } } } } tbBlacklist.Lines=(string[])lines.ToArray(typeof(string)); }
public System.Collections.ArrayList GeneratePath(Point start, Point dest) { System.Collections.ArrayList my_path = new System.Collections.ArrayList(); Point intersect = new Point(); int index = 0; if (FindIntersect(start, dest, ref intersect, ref index)) { my_path.Add(intersect); //need to trace the left and right paths double left_dist = 0; double right_dist = 0; System.Collections.ArrayList left_path = new System.Collections.ArrayList(); System.Collections.ArrayList right_path = new System.Collections.ArrayList(); Point t1 = new Point(); Point t2 = new Point(); Point tp = new Point(); int ti = 0; //generate left path t1 = (Point)PointList[index]; left_path.Add(t1); left_dist += Get_Dist(intersect, t1); while (FindIntersect(t1, dest, ref tp, ref ti)) { t2.X = t1.X; t2.Y = t1.Y; t2.Z = t1.Z; index = Get_Left_Point(index); t1 = (Point)PointList[index]; left_path.Add(t1); left_dist += Get_Dist(t1, t2); } left_dist += Get_Dist(t1, dest); left_path.Add(dest); //generate right path index = Get_Right_Point(index); t1 = (Point)PointList[index]; right_path.Add(t1); right_dist += Get_Dist(intersect, t1); while (FindIntersect(t1, dest, ref tp, ref ti)) { t2.X = t1.X; t2.Y = t1.Y; t2.Z = t1.Z; index = Get_Right_Point(index); t1 = (Point)PointList[index]; right_path.Add(t1); right_dist += Get_Dist(t1, t2); } right_dist += Get_Dist(t1, dest); right_path.Add(dest); if (left_dist > right_dist) { //use our right path for (int i = 0; i < right_path.Count; i++) { my_path.Add(right_path[i]); } } else { //use our left path for (int i = 0; i < left_path.Count; i++) { my_path.Add(left_path[i]); } } //clean up our pathing bool cleaned = false; do { for (int i = 0; i < my_path.Count - 2; i++) { if (!FindIntersect((Point)my_path[i], (Point)my_path[i + 2], ref tp, ref ti)) { my_path.RemoveAt(i + 1); cleaned = true; break; } } } while (cleaned); } else { //no intersection... //straight shot to the destination my_path.Add(dest); } return my_path; }
public void Update(GameTime gameTime) { if (es.EditMode) { if (es.EditType == EditorType.EntityMode) { if (Mouse.GetState().LeftButton == ButtonState.Pressed) { if (draggedEntity != null) { draggedEntity.getAs<Position>().EntityPosition = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - MouseOffset; draggedEntity.getAs<Position>().EntityPosition -= new Vector2(draggedEntity.getAs<Position>().EntityPosition.X % (int)es.GridType, draggedEntity.getAs<Position>().EntityPosition.Y % (int)es.GridType); //draggedEntity.getAs<Position>().EntityPosition = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - MouseOffset; } else { draggedEntity = TestForTargetedDrawable(Mouse.GetState().X, Mouse.GetState().Y); if (draggedEntity != null) { MouseOffset = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - draggedEntity.getAs<Position>().EntityPosition; } } selectedEntity = TestForTargetedDrawable(Mouse.GetState().X, Mouse.GetState().Y); } else { draggedEntity = null; } } else if (es.EditType == EditorType.WallMode) { if (Keyboard.GetState().IsKeyDown(Keys.Add)) { System.Threading.Thread.Sleep(100); if (selectedEntity == null) { selectedEntity = new Entity(es.CreateEntityID()); } Wall entWall = selectedEntity.getAs<Wall>(); if (entWall == null) { entWall = new Wall(); es.RegisterComponent(selectedEntity, entWall); } System.Collections.ArrayList wallPoints = new System.Collections.ArrayList(); if (entWall.WallPoints != null) { wallPoints.AddRange(entWall.WallPoints); } if (wallPoints.Count == 0) { wallPoints.Add(new Vector2(0, 0)); } Vector2 lastPoint = (Vector2)wallPoints[wallPoints.Count - 1]; wallPoints.Add(new Vector2(lastPoint.X + 30, lastPoint.Y + 30)); entWall.WallPoints = (Vector2[])wallPoints.ToArray(typeof(Vector2)); } if (Keyboard.GetState().IsKeyDown(Keys.Subtract)) { if (selectedEntity != null) { Wall entWall = selectedEntity.getAs<Wall>(); if (entWall != null) { if (entWall.WallPoints != null) { System.Collections.ArrayList wallPoints = new System.Collections.ArrayList(); wallPoints.AddRange(entWall.WallPoints); for (int i = 0; i < wallPoints.Count; i++) { if (selectedVertex == i) { wallPoints.RemoveAt(i); break; } } entWall.WallPoints = (Vector2[])wallPoints.ToArray(typeof(Vector2)); } } } } if (Mouse.GetState().LeftButton == ButtonState.Pressed) { if (selectedEntity != null) { Wall entWall = selectedEntity.getAs<Wall>(); if (entWall != null) { if (draggedVertex != -1) { entWall.WallPoints[draggedVertex] = RenderingSystem.camera.RealCoordsFromScreen(Mouse.GetState().X, Mouse.GetState().Y) - selectedEntity.getAs<Position>().EntityPosition; } else { for (int i = 0; i < entWall.WallPoints.Length; i++)// (Vector2 wallPoint in entWall.WallPoints) { Vector2 rectPos = RenderingSystem.camera.ScreenCoordsFromWorldPosition(entWall.WallPoints[i] + selectedEntity.getAs<Position>().EntityPosition); Rectangle entRect = new Rectangle((int)(rectPos.X - 15), (int)(rectPos.Y - 15), 30, 30); if (entRect.Contains(Mouse.GetState().X, Mouse.GetState().Y)) { draggedVertex = i; } } } for (int i = 0; i < entWall.WallPoints.Length; i++)// (Vector2 wallPoint in entWall.WallPoints) { Vector2 rectPos = RenderingSystem.camera.ScreenCoordsFromWorldPosition(entWall.WallPoints[i] + selectedEntity.getAs<Position>().EntityPosition); Rectangle entRect = new Rectangle((int)(rectPos.X - 15), (int)(rectPos.Y - 15), 30, 30); if (entRect.Contains(Mouse.GetState().X, Mouse.GetState().Y)) { selectedVertex = i; } } } } } else { draggedVertex = -1; } } } }
private System.IO.Stream generateData() { int numGuests = 16; int numSeats = 16; int minHobbies = 2; int maxHobbies = 3; System.String LINE_SEPARATOR = System.Environment.NewLine; System.IO.StringWriter writer = new System.IO.StringWriter(); int maxMale = numGuests / 2; int maxFemale = numGuests / 2; int maleCount = 0; int femaleCount = 0; // init hobbies System.Collections.IList hobbyList = new System.Collections.ArrayList(); for (int i = 1; i <= maxHobbies; i++) { hobbyList.Add("h" + i); } System.Random rnd = new System.Random(); for (int i = 1; i <= numGuests; i++) { //UPGRADE_ISSUE: Method 'java.util.Random.nextBoolean' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilRandomnextBoolean'" char sex = (rnd.Next(2) == 0)?'m':'f'; if (sex == 'm' && maleCount == maxMale) { sex = 'f'; } if (sex == 'f' && femaleCount == maxFemale) { sex = 'm'; } if (sex == 'm') { maleCount++; } if (sex == 'f') { femaleCount++; } System.Collections.IList guestHobbies = new System.Collections.ArrayList(hobbyList); int numHobbies = minHobbies + rnd.Next(maxHobbies - minHobbies + 1); for (int j = 0; j < numHobbies; j++) { int hobbyIndex = rnd.Next(guestHobbies.Count); System.String hobby = (System.String) guestHobbies[hobbyIndex]; writer.Write("(guest (name n" + i + ") (sex " + sex + ") (hobby " + hobby + "))" + LINE_SEPARATOR); guestHobbies.RemoveAt(hobbyIndex); } } writer.Write("(last_seat (seat " + numSeats + "))" + LINE_SEPARATOR); writer.Write(LINE_SEPARATOR); writer.Write("(context (state start))" + LINE_SEPARATOR); return new System.IO.MemoryStream(new UnicodeEncoding().GetBytes(writer.GetStringBuilder().ToString())); //(writer.GetStringBuilder().ToString()).ToCharArray() }
bool RetrieveDhcpMessage(UdpSocket socket, DhcpMessageType[] messageTypes, UInt32 transactionID, UInt64 clientHardwareAddress, out UInt32 assignedIPAddress, out DhcpOption[] options, Int64 timeoutInMachineTicks) { byte[] dhcpFrameBuffer = new byte[DHCP_FRAME_BUFFER_LENGTH]; while (timeoutInMachineTicks > Microsoft.SPOT.Hardware.Utility.GetMachineTime().Ticks) { Int32 bytesReceived = socket.Receive(dhcpFrameBuffer, 0, dhcpFrameBuffer.Length, 0, timeoutInMachineTicks); if (bytesReceived == 0) // timeout break; /* parse our DHCP frame */ // validate the operation if ((BootpOperation)dhcpFrameBuffer[0] != BootpOperation.BOOTREPLY) continue; /* filter out this BOOTP/DHCP frame */ /* verify magic cookie {99, 130, 83, 99} is the first 4-byte entry, as per RFC 1497 */ if ((dhcpFrameBuffer[236] != 99) || (dhcpFrameBuffer[237] != 130) || (dhcpFrameBuffer[238] != 83) || (dhcpFrameBuffer[239] != 99)) continue; /* filter out this BOOTP non-DHCP frame */ // verify that the transaction ID matches UInt32 verifyTransactionID = ( (UInt32)(dhcpFrameBuffer[4] << 24) + (UInt32)(dhcpFrameBuffer[5] << 16) + (UInt32)(dhcpFrameBuffer[6] << 8) + (UInt32)(dhcpFrameBuffer[7]) ); if (transactionID != verifyTransactionID) continue; /* filter out this DHCP frame */ // verify the the physical hardware type matches if (dhcpFrameBuffer[1] != (byte)HARDWARE_TYPE_ETHERNET) continue; /* filter out this DHCP frame */ if (dhcpFrameBuffer[2] != (byte)HARDWARE_ADDRESS_SIZE) continue; /* filter out this DHCP frame */ // verify that the physical address matches UInt64 verifyClientHardwareAddress = ( ((UInt64)(dhcpFrameBuffer[28]) << 40) + ((UInt64)(dhcpFrameBuffer[29]) << 32) + ((UInt64)(dhcpFrameBuffer[30]) << 24) + ((UInt64)(dhcpFrameBuffer[31]) << 16) + ((UInt64)(dhcpFrameBuffer[32]) << 8) + (UInt64)(dhcpFrameBuffer[33]) ); if (clientHardwareAddress != verifyClientHardwareAddress) continue; /* filter out this DHCP frame */ // retrieve allocated ip address /* yiaddr (ip address, populated by server */ assignedIPAddress = ( (UInt32)(dhcpFrameBuffer[16] << 24) + (UInt32)(dhcpFrameBuffer[17] << 16) + (UInt32)(dhcpFrameBuffer[18] << 8) + (UInt32)(dhcpFrameBuffer[19]) ); // retrieve options System.Collections.ArrayList optionsArrayList = new System.Collections.ArrayList(); bool optionOverloadReceived = false; DhcpOptionsBlockRange[] optionsBlocks = new DhcpOptionsBlockRange[] { new DhcpOptionsBlockRange(240, DHCP_FRAME_BUFFER_LENGTH - 240 - 1), }; int optionsBlocksIndex = 0; DhcpMessageType verifyMessageType = 0; while (optionsBlocksIndex < optionsBlocks.Length) { Int32 index = optionsBlocks[optionsBlocksIndex].BeginOffset; bool endOpcodeReceived = false; while (!endOpcodeReceived && index <= optionsBlocks[optionsBlocksIndex].EndOffset) { DhcpOptionCode optionCode = (DhcpOptionCode)dhcpFrameBuffer[index]; switch ((DhcpOptionCode)optionCode) { case DhcpOptionCode.Pad: { index++; } break; case DhcpOptionCode.End: { index++; endOpcodeReceived = true; } break; case DhcpOptionCode.OptionOverload: { if (optionsBlocksIndex == 0) { index++; if (dhcpFrameBuffer[index] != 1) break; index++; byte value = dhcpFrameBuffer[index]; index++; int numBlocks = 1 + (((value & 0x01) == 0x01) ? 1 : 0) + (((value & 0x02) == 0x02) ? 1 : 0); optionsBlocks = new DhcpOptionsBlockRange[numBlocks]; int iOptionBlock = 0; optionsBlocks[iOptionBlock++] = new DhcpOptionsBlockRange(240, DHCP_FRAME_BUFFER_LENGTH - 240 - 1); if ((value & 0x01) == 0x01) { /* use file field for extended options */ optionsBlocks[iOptionBlock++] = new DhcpOptionsBlockRange(108, 235); } if ((value & 0x02) == 0x02) { /* use sname field for extended options */ optionsBlocks[iOptionBlock++] = new DhcpOptionsBlockRange(44, 107); } } } break; default: { index++; byte[] value = new byte[Math.Min(dhcpFrameBuffer[index], DHCP_FRAME_BUFFER_LENGTH - index)]; index++; Array.Copy(dhcpFrameBuffer, index, value, 0, value.Length); index += value.Length; // if the option already exists, append to it bool foundOption = false; for (int iExistingOption = 0; iExistingOption < optionsArrayList.Count; iExistingOption++) { if (((DhcpOption)optionsArrayList[iExistingOption]).Code == optionCode) { byte[] newValue = new byte[((DhcpOption)optionsArrayList[iExistingOption]).Value.Length + value.Length]; Array.Copy(((DhcpOption)optionsArrayList[iExistingOption]).Value, 0, newValue, 0, ((DhcpOption)optionsArrayList[iExistingOption]).Value.Length); Array.Copy(value, 0, newValue, ((DhcpOption)optionsArrayList[iExistingOption]).Value.Length, value.Length); optionsArrayList.RemoveAt(iExistingOption); optionsArrayList.Add(new DhcpOption(optionCode, newValue)); foundOption = true; break; } } if (!foundOption) { optionsArrayList.Add(new DhcpOption(optionCode, value)); } if (optionCode == DhcpOptionCode.DhcpMessageType) { verifyMessageType = (DhcpMessageType)value[0]; } } break; } } optionsBlocksIndex++; } options = (DhcpOption[])optionsArrayList.ToArray(typeof(DhcpOption)); // verify that the DHCP message type matches bool messageTypeMatches = false; for (int iMessageType = 0; iMessageType < messageTypes.Length; iMessageType++) { if (messageTypes[iMessageType] == verifyMessageType) { messageTypeMatches = true; break; } } if (messageTypeMatches) return true; /* message matches the messageTypes filter, with a valid frame; return all data to the caller */ } // if we did not receive a message before timeout, return false. // set default return values assignedIPAddress = 0; options = null; return false; }