public MultiFormatOneDReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList)hints[DecodeHintType.POSSIBLE_FORMATS]; bool useCode39CheckDigit = hints != null && hints[DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT] != null; readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { readers.Add(new Code39Reader(useCode39CheckDigit)); } if (possibleFormats.Contains(BarcodeFormat.CODE_128)) { readers.Add(new Code128Reader()); } if (possibleFormats.Contains(BarcodeFormat.ITF)) { readers.Add(new ITFReader()); } } if ((readers.Count == 0)) { readers.Add(new MultiFormatUPCEANReader(hints)); readers.Add(new Code39Reader()); readers.Add(new Code128Reader()); readers.Add(new ITFReader()); } }
/// <summary> /// 过滤出有权限的病区 /// </summary> /// <param name="p_objArea">病区对象</param> /// <param name="p_ilUsableAreaID">有权访问的病区ID集合</param> /// <returns>有权访问的病区对象集合</returns> public System.Collections.IList GetUsableAreaObject(clsBIHArea[] p_objArea, System.Collections.IList p_ilUsableAreaID) { System.Collections.IList ilRes = new System.Collections.ArrayList(); if (p_objArea == null || p_objArea.Length <= 0) { return(ilRes); } //全部的可访问的病区对象 for (int i1 = 0; i1 < p_objArea.Length; i1++) { if (p_objArea[i1] == null) { continue; } if (p_ilUsableAreaID.Contains(p_objArea[i1].m_strAreaID.Trim())) { if (!(ilRes.Contains(p_objArea[i1]))) { ilRes.Contains(ilRes); } } } return(ilRes); }
public bool bAdiciona(string strNome, double dValor) { dValor = System.Math.Round(dValor, 4); if (dValor == 0) { return(false); } if (m_arlNomes.Contains(strNome)) { return(false); } double dSaldoAtual = dSaldo(); dSaldoAtual = System.Math.Round(dSaldoAtual, 2); if (dValor > dSaldoAtual) { return(false); } m_arlNomes.Add(strNome); m_arlValores.Add(dValor); m_arlPorcentagemExata.Add(null); vCalculaPorcentagemExata(m_arlPorcentagemExata.Count - 1); m_arlPorcentagem.Add(null); vCalculaPorcentagem(); return(true); }
public MultiFormatOneDReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList) hints[DecodeHintType.POSSIBLE_FORMATS]; readers = new System.Collections.ArrayList(); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { readers.Add(new Code39Reader()); } if (possibleFormats.Contains(BarcodeFormat.CODE_128)) { readers.Add(new Code128Reader()); } if (possibleFormats.Contains(BarcodeFormat.ITF)) { readers.Add(new ITFReader()); } } if (readers.Count==0) { readers.Contains(new MultiFormatUPCEANReader(hints)); readers.Contains(new Code39Reader()); readers.Contains(new Code128Reader()); // TODO: Add ITFReader once it is validated as production ready, and tested for performance. //readers.addElement(new ITFReader()); } }
public void Add(BusinessObject mbusinessobject) { if (!objectlist.Contains(mbusinessobject)) { objectlist.Add(mbusinessobject); } }
private bool bDespachantesExclui(ref System.Collections.ArrayList arlDespachantes, bool bSilent) { if (!bSilent) { if (mdlMensagens.clsMensagens.ShowInformation("Siscobras", "Deseja mesmo excluir este(s) despachante(s) ?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) { return(false); } } // Despachantes for (int i = m_typdatSetDespachantes.tbDespachantes.Rows.Count - 1; i >= 0; i--) { mdlDataBaseAccess.Tabelas.XsdTbDespachantes.tbDespachantesRow dtrwDespachante = (mdlDataBaseAccess.Tabelas.XsdTbDespachantes.tbDespachantesRow)m_typdatSetDespachantes.tbDespachantes.Rows[i]; if (dtrwDespachante.RowState != System.Data.DataRowState.Deleted) { if (arlDespachantes.Contains(dtrwDespachante.nIdDespachante)) { dtrwDespachante.Delete(); } } } // Contatos for (int i = m_typDatSetDespachantesContatos.tbDespachantesContatos.Rows.Count - 1; i >= 0; i--) { mdlDataBaseAccess.Tabelas.XsdTbDespachantesContatos.tbDespachantesContatosRow dtrwContato = (mdlDataBaseAccess.Tabelas.XsdTbDespachantesContatos.tbDespachantesContatosRow)m_typDatSetDespachantesContatos.tbDespachantesContatos.Rows[i]; if ((dtrwContato.RowState != System.Data.DataRowState.Deleted) && (arlDespachantes.Contains(dtrwContato.nIdDespachante))) { dtrwContato.Delete(); } } return(true); }
public bool Reload(XmlConfigSync mode) { string fileName = BuildName(false, true); if (fileName == null) { return(false); } //- First save changes if asked for lock (typeof(XmlConfig)) { XmlConfigFile cfgFile = (XmlConfigFile)mXmlDocs [fileName]; if (XmlDoc != null && ((mbXmlModifieds.Contains(XmlDoc) == true && mode != XmlConfigSync.Discard) || mode != XmlConfigSync.ForceSave ) ) { XmlDoc.Save(fileName); mbXmlModifieds.Remove(XmlDoc); return(true); } //- Reload Xml document mbXmlModifieds.Remove(XmlDoc); //- Reload the document cfgFile.Reload(fileName); return(true); } }
public MultiFormatUPCEANReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null?null:(System.Collections.ArrayList)hints[DecodeHintType.POSSIBLE_FORMATS]; readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13)) { readers.Add(new EAN13Reader()); } else if (possibleFormats.Contains(BarcodeFormat.UPC_A)) { readers.Add(new UPCAReader()); } if (possibleFormats.Contains(BarcodeFormat.EAN_8)) { readers.Add(new EAN8Reader()); } if (possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new UPCEReader()); } } if ((readers.Count == 0)) { readers.Add(new EAN13Reader()); // UPC-A is covered by EAN-13 readers.Add(new EAN8Reader()); readers.Add(new UPCEReader()); } }
public void AtualizaStatusMatriculaMoodle(MatriculaOferta pMatriculaOferta, enumStatusMatricula statusMatriculaAnterior) { pMatriculaOferta.Oferta = new BMOferta().ObterPorId(pMatriculaOferta.Oferta.ID); if (pMatriculaOferta != null && pMatriculaOferta.Oferta != null) { // Status que provocam suspensão no moodle System.Collections.ArrayList failStatus = new System.Collections.ArrayList(); failStatus.Add(3); failStatus.Add(4); failStatus.Add(5); failStatus.Add(10); // Se for uma matricula em uma oferta de uma solução educacional do SEBRAE, e tiver indo de um status válido para um de suspensão if (pMatriculaOferta.Oferta.CodigoMoodle != null && pMatriculaOferta.Oferta.SolucaoEducacional.Fornecedor.ID.Equals((int)enumFornecedor.MoodleSebrae)) { Moodle.BMInscricao bmInscricao = new Moodle.BMInscricao(); // Indo de um status de não suspensão para um de suspensão if (failStatus.Contains((int)pMatriculaOferta.StatusMatricula) && !failStatus.Contains((int)statusMatriculaAnterior)) { bmInscricao.alterarInscricao(pMatriculaOferta.Oferta.CodigoMoodle.Value, pMatriculaOferta.Usuario.CPF, 1); // Indo de um status de suspensão para Inscrito } else if (!failStatus.Contains((int)pMatriculaOferta.StatusMatricula) && enumStatusMatricula.Inscrito.Equals(pMatriculaOferta.StatusMatricula)) { bmInscricao.alterarInscricao(pMatriculaOferta.Oferta.CodigoMoodle.Value, pMatriculaOferta.Usuario.CPF, 0); } } } }
public MultiFormatOneDReader(System.Collections.Hashtable hints) { System.Collections.ArrayList possibleFormats = hints == null ? null : (System.Collections.ArrayList)hints[DecodeHintType.POSSIBLE_FORMATS]; readers = new System.Collections.ArrayList(); if (possibleFormats != null) { if (possibleFormats.Contains(BarcodeFormat.EAN_13) || possibleFormats.Contains(BarcodeFormat.UPC_A) || possibleFormats.Contains(BarcodeFormat.EAN_8) || possibleFormats.Contains(BarcodeFormat.UPC_E)) { readers.Add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.Contains(BarcodeFormat.CODE_39)) { readers.Add(new Code39Reader()); } if (possibleFormats.Contains(BarcodeFormat.CODE_128)) { readers.Add(new Code128Reader()); } if (possibleFormats.Contains(BarcodeFormat.ITF)) { readers.Add(new ITFReader()); } } if (readers.Count == 0) { readers.Contains(new MultiFormatUPCEANReader(hints)); readers.Contains(new Code39Reader()); readers.Contains(new Code128Reader()); // TODO: Add ITFReader once it is validated as production ready, and tested for performance. //readers.addElement(new ITFReader()); } }
/// <summary> /// Adds a new license to the list of licenses to be searched for. /// </summary> /// <param name="license">The number of the license to search for.</param> public void AddLicense(int license) { if (!_licenses.Contains(license)) { _licenses.Add(license); } }
public virtual void parseElement(System.Xml.XmlNode oldEl, System.Xml.XmlNode newEl) { System.Xml.XmlNamedNodeMap nl = (System.Xml.XmlAttributeCollection)oldEl.Attributes; if (nl != null) { for (int i = 0; i < nl.Count; i++) { if (((System.Xml.XmlAttributeCollection)newEl.Attributes).GetNamedItem(nl.Item(i).Name) == null) { //System.out.println(nl.item(i).getNodeName()+" attribute not present, adding the attribute"); //UPGRADE_TODO: Method 'org.w3c.dom.Element.setAttribute' was converted to 'System.Xml.XmlElement.SetAttribute' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_orgw3cdomElementsetAttribute_javalangString_javalangString'" ((System.Xml.XmlElement)newEl).SetAttribute(nl.Item(i).Name, nl.Item(i).Value); } } } //UPGRADE_TODO: Method 'org.w3c.dom.Node.getChildNodes' was converted to 'System.Xml.XmlNode.ChildNodes' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" System.Xml.XmlNodeList oldNodes = oldEl.ChildNodes; //UPGRADE_TODO: Method 'org.w3c.dom.Node.getChildNodes' was converted to 'System.Xml.XmlNode.ChildNodes' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" System.Xml.XmlNodeList newNodes = newEl.ChildNodes; int i2 = 0; int j = 0; while (oldNodes.Item(i2) != null) { if (newNodes.Item(j) == null) { //System.out.println(oldNodes.item(i)+" not present, adding the whole element"); if (!ignoreList.Contains(oldNodes.Item(i2).Name)) { System.Xml.XmlNode n = newEl.OwnerDocument.ImportNode(oldNodes.Item(i2), true); newEl.AppendChild(n); } i2++; j++; } else { if ((System.Object)oldNodes.Item(i2).Name != (System.Object)newNodes.Item(j).Name) { if (!ignoreList.Contains(oldNodes.Item(i2).Name)) { //System.out.println(oldNodes.item(i)+" not present, adding the whole element"); System.Xml.XmlNode n = newEl.OwnerDocument.ImportNode(oldNodes.Item(i2), true); newEl.AppendChild(n); } i2++; } else { parseElement(oldNodes.Item(i2), newNodes.Item(j)); i2++; j++; } } } }
public void ImplementsComparerDefault_NonGeneric() { var set = new System.Collections.ArrayList() { JackAbrams, CaseyJohnson, AbeAbrams }; Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName })); Assert.False(set.Contains(WilliamAbrams)); }
public bool Convert(FilterRequest req) { if (valid_extensions.Contains(System.IO.Path.GetExtension(req.Current.LocalPath).ToLower())) { return(false); } if (!valid_extensions.Contains(".jpg") && !valid_extensions.Contains(".jpeg")) { throw new System.NotImplementedException("can only save jpeg :("); } return((new JpegFilter()).Convert(req)); }
public Form1() { InitializeComponent(); Random random = new Random(); int rand; while (arrayRand.Count < 6) { rand = random.Next(1, 49); if (!arrayRand.Contains(rand)) { arrayRand.Add(rand); } } arrayRand.Sort(); }
/// <summary> /// Removes a file path from the recent files list. /// </summary> /// <param name="fileName"> /// Path of the file. /// </param> public static void RemoveFromRecentFiles(string fileName) { if (recentFilesList.Contains(fileName)) { recentFilesList.Remove(fileName); } }
private bool bTerminaisExclui(ref System.Collections.ArrayList arlTerminais, bool bSilent) { if (!bSilent) { if (mdlMensagens.clsMensagens.ShowInformation("Siscobras", "Deseja mesmo excluir este(s) terminais(s) ?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) { return(false); } } // Terminais for (int i = m_typDatSetTerminais.tbTerminais.Rows.Count - 1; i >= 0; i--) { mdlDataBaseAccess.Tabelas.XsdTbTerminais.tbTerminaisRow dtrwTerminal = (mdlDataBaseAccess.Tabelas.XsdTbTerminais.tbTerminaisRow)m_typDatSetTerminais.tbTerminais.Rows[i]; if (dtrwTerminal.RowState != System.Data.DataRowState.Deleted) { if (arlTerminais.Contains(dtrwTerminal.nIdTerminal)) { dtrwTerminal.Delete(); } } } // TODO: Apagar Contatos return(true); }
public static System.Collections.ArrayList getArgs(System.String text) { System.Collections.ArrayList args = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); int i = text.IndexOf("${"); while (i != - 1) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" int j = text.IndexOf("}", i); if (j == - 1) { System.Console.Error.WriteLine("Warning: unterminated ${...} arg"); break; } System.String arg = text.Substring(i + 2, (j) - (i + 2)); if (!args.Contains(arg)) { args.Add(arg); } //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = text.IndexOf("${", j + 1); } return args; }
private void QuestionAnswer_Load(object sender, EventArgs e) { string username = LogInForm.username_s; QuestionCounter = 0; CurrentNumberOfQuestions = 0; lstNumbers = new System.Collections.ArrayList(); Random rndNumber = new Random(); int number = rndNumber.Next(1, 7); lstNumbers.Add(number); int count = 0; do { number = rndNumber.Next(1, 7); if (!lstNumbers.Contains(number)) { lstNumbers.Add(number); } count++; } while (count <= 100); btnCheckAnswer_Click(sender, e); con.Close(); }
/// <param name="entry">the record associated with the msg to retransmit. It /// contains the list of receivers that haven't yet ack reception /// </param> internal void _retransmit(Entry entry) { Address sender; bool received; lock (entry) { for (System.Collections.IEnumerator e = entry.senders.Keys.GetEnumerator(); e.MoveNext();) { sender = (Address)e.Current; received = ((System.Boolean)entry.senders[sender]); if (!received) { if (suspects.Contains(sender)) { NCacheLog.Warn("AckMcastSenderWindow", "removing " + sender + " from retransmit list as it is in the suspect list"); remove(sender); continue; } NCacheLog.Warn("AckMcastSenderWindow", "--> retransmitting msg #" + entry.seqno + " to " + sender); cmd.retransmit(entry.seqno, entry.msg.copy(), sender); } } } }
public void Optimize(Directory directory) { string[] files = directory.List(); System.Collections.ArrayList segment_names = new System.Collections.ArrayList(); foreach (SegmentInfo si in this) { segment_names.Add(si.name); } foreach (string file in files) { string basename = System.IO.Path.GetFileNameWithoutExtension(file); if (segment_names.Contains(basename)) { continue; } // Allowed files deletable, segments, segments.gen, segments_N if (basename == IndexFileNames.DELETABLE || basename.StartsWith(IndexFileNames.SEGMENTS)) { continue; } Console.WriteLine("WARNING! Deleting stale data {0}", file); try { directory.DeleteFile(file); } catch { /* Could be already deleted. */ } } }
public virtual void registerStateObserver(FormElementStateListener qsl) { if (!observers.Contains(qsl)) { observers.Add(qsl); } }
/// <summary> Checks a group's children against a list of allowed structures for the group /// (ie those mentioned in the profile with usage other than X). Returns /// a list of exceptions representing structures that appear in the message /// but are not supposed to. /// </summary> private NuGenHL7Exception[] checkForExtraStructures(Group group, System.Collections.ArrayList allowedStructures) { System.Collections.ArrayList exList = new System.Collections.ArrayList(); System.String[] childNames = group.Names; for (int i = 0; i < childNames.Length; i++) { if (!allowedStructures.Contains(childNames[i])) { try { Structure[] reps = group.getAll(childNames[i]); for (int j = 0; j < reps.Length; j++) { if (hasContent(reps[j])) { NuGenHL7Exception e = new NuGenXElementPresentException("The structure " + childNames[i] + " appears in the message but not in the profile"); exList.Add(e); } } } catch (NuGenHL7Exception he) { throw new NuGenProfileException("Problem checking profile", he); } } } return(toArray(exList)); }
/// <summary> Checks a segment against a list of allowed fields /// (ie those mentioned in the profile with usage other than X). Returns /// a list of exceptions representing field that appear /// but are not supposed to. /// </summary> /// <param name="allowedFields">an array of Integers containing field #s of allowed fields /// </param> private NuGenHL7Exception[] checkForExtraFields(Segment segment, System.Collections.ArrayList allowedFields) { System.Collections.ArrayList exList = new System.Collections.ArrayList(); for (int i = 1; i <= segment.numFields(); i++) { if (!allowedFields.Contains((System.Int32)i)) { try { Genetibase.NuGenHL7.model.Type[] reps = segment.getField(i); for (int j = 0; j < reps.Length; j++) { if (hasContent(reps[j])) { NuGenHL7Exception e = new NuGenXElementPresentException("Field " + i + " in " + segment.getName() + " appears in the message but not in the profile"); exList.Add(e); } } } catch (NuGenHL7Exception he) { throw new NuGenProfileException("Problem testing against profile", he); } } } return(this.toArray(exList)); }
private bool bNaviosExcluir(int nIdArmador, ref System.Collections.ArrayList arlNavios, bool bSilent) { if (!bSilent) { if (mdlMensagens.clsMensagens.ShowInformation("Siscobras", "Deseja mesmo excluir este(s) navio(s) ?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) { return(false); } } // Navios for (int i = m_typDatSetArmadoresNavios.tbArmadoresNavios.Rows.Count - 1; i >= 0; i--) { mdlDataBaseAccess.Tabelas.XsdTbArmadoresNavios.tbArmadoresNaviosRow dtrwNavio = (mdlDataBaseAccess.Tabelas.XsdTbArmadoresNavios.tbArmadoresNaviosRow)m_typDatSetArmadoresNavios.tbArmadoresNavios.Rows[i]; if (dtrwNavio.RowState != System.Data.DataRowState.Deleted) { if (dtrwNavio.nIdArmador == nIdArmador) { if (arlNavios.Contains(dtrwNavio.nIdNavio)) { dtrwNavio.Delete(); } } } } return(true); }
// Eliminamos un Sink en tiempo de ejecucion public void DeleteSink(Interface.IEventosRefri pSink) { if (listaSinks.Contains(pSink)) { listaSinks.Remove(pSink); } }
public void Optimize(Directory directory) { string[] files = directory.List(); System.Collections.ArrayList segment_names = new System.Collections.ArrayList(); foreach (SegmentInfo si in this) { segment_names.Add(si.name); } foreach (string file in files) { string basename = System.IO.Path.GetFileNameWithoutExtension(file); if (segment_names.Contains(basename)) { continue; } if (basename == IndexFileNames.DELETABLE || basename == IndexFileNames.SEGMENTS) { continue; } Console.WriteLine("WARNING! Deleting stale data {0}", file); directory.DeleteFile(file); } }
/* * /// <summary> * /// 添加键值,若遇到已有key则覆盖 * /// </summary> * /// <param name="dc">Dictionary</param> * /// <param name="yourKey">Key</param> * /// <param name="yourValue">Value</param> * public static void myAdd(this Dictionary<string, ICaseExecutionDevice> dc, string yourKey, ICaseExecutionDevice yourValue) * { * if (dc.ContainsKey(yourKey)) * { * dc[yourKey] = yourValue; * } * else * { * dc.Add(yourKey, yourValue); * } * } * */ /* * /// <summary> * /// 添加键值,若遇到已有key则覆盖 * /// </summary> * /// <param name="dc">Dictionary</param> * /// <param name="yourKey">Key</param> * /// <param name="yourValue">Value</param> * public static void myAdd(this Dictionary<string, IRunTimeStaticData> dc, string yourKey, IRunTimeStaticData yourValue) * { * if (dc.ContainsKey(yourKey)) * { * dc[yourKey] = yourValue; * } * else * { * dc.Add(yourKey, yourValue); * } * } * */ /// <summary> /// 添加键值,若遇到已有则不添加 /// </summary> /// <param name="myArratList">ArratList</param> /// <param name="yourIp">IPAddress</param> public static void myAdd(this System.Collections.ArrayList myArratList, System.Net.IPAddress yourIp) { if (!myArratList.Contains(yourIp)) { myArratList.Add(yourIp); } }
/// <summary> /// Add given remote recorder to list of recorder info /// </summary> /// <param name="remoteRecorderInfo">remote recorder info list</param> /// <param name="rr">remote recorder to add to list</param> /// <param name="duplicates">duplicates found</param> private static void recorderAdd(Dictionary <string, Guid> remoteRecorderInfo, RemoteRecorder rr, System.Collections.ArrayList duplicates) { // Check for recorder status and only store recorders that are connected if (rr.State == RemoteRecorderState.Previewing) { string rrName = rr.Name; // Check for duplicates before storing if (duplicates.Contains(rr.Name)) { rrName += " (" + rr.Id + ")"; } else if (remoteRecorderInfo.ContainsKey(rr.Name)) { Guid tempID = remoteRecorderInfo[rr.Name]; string tempName = rr.Name + " (" + tempID + ")"; remoteRecorderInfo.Remove(rr.Name); remoteRecorderInfo.Add(tempName, tempID); duplicates.Add(rr.Name); rrName += " (" + rr.Id + ")"; } remoteRecorderInfo.Add(rr.Name, rr.Id); } }
/// <summary> Get the paths starting from an atom of specified length. /// <p/> /// This method returns a set of paths. Each path is a <code>List</code> of atoms that /// make up the path (ie they are sequentially connected). /// /// </summary> /// <param name="atomContainer">The molecule to consider /// </param> /// <param name="start"> The starting atom /// </param> /// <param name="length"> The length of paths to look for /// </param> /// <returns> A <code>List</code> containing the paths found /// </returns> public static System.Collections.IList getPathsOfLength(IAtomContainer atomContainer, IAtom start, int length) { System.Collections.ArrayList curPath = new System.Collections.ArrayList(); System.Collections.ArrayList paths = new System.Collections.ArrayList(); curPath.Add(start); paths.Add(curPath); for (int i = 0; i < length; i++) { System.Collections.ArrayList tmpList = new System.Collections.ArrayList(); for (int j = 0; j < paths.Count; j++) { curPath = (System.Collections.ArrayList)paths[j]; IAtom lastVertex = (IAtom)curPath[curPath.Count - 1]; System.Collections.IList neighbors = atomContainer.getConnectedAtomsVector(lastVertex); for (int k = 0; k < neighbors.Count; k++) { System.Collections.ArrayList newPath = new System.Collections.ArrayList(curPath); if (newPath.Contains(neighbors[k])) { continue; } newPath.Add(neighbors[k]); tmpList.Add(newPath); } } paths.Clear(); paths.AddRange(tmpList); } return(paths); }
/// <summary> /// Retains the elements in the target collection that are contained in the specified collection /// </summary> /// <param name="target">Collection where the elements will be removed.</param> /// <param name="c">Elements to be retained in the target collection.</param> /// <returns>true</returns> public static bool RetainAll(System.Collections.ICollection target, System.Collections.ICollection c) { System.Collections.IEnumerator e = new System.Collections.ArrayList(target).GetEnumerator(); System.Collections.ArrayList al = new System.Collections.ArrayList(c); //Reflection. Invoke "retainAll" method for proprietary classes or "Remove" for each element in the collection System.Reflection.MethodInfo method; try { method = c.GetType().GetMethod("retainAll"); if (method != null) { method.Invoke(target, new Object[] { c }); } else { method = c.GetType().GetMethod("Remove"); while (e.MoveNext() == true) { if (al.Contains(e.Current) == false) { method.Invoke(target, new Object[] { e.Current }); } } } } catch (Exception ex) { throw ex; } return(true); }
public Config() { InitializeComponent(); BindFrequency(); BindPixelFormat(); cbxAutoRun.Checked = IsSubValueExist(); // ControlCollection cols = new ControlCollection(this); GetChildControl(this); System.Collections.ArrayList excludedControls = new System.Collections.ArrayList(); excludedControls.Add(cbxAutoRun); foreach (object o in array) { Control c = (Control)o; if (excludedControls.Contains(c)) { continue; } if (c.GetType().Equals(typeof(TextBox))) { c.TextChanged +=new EventHandler(SaveControlValue); string propValue=(string) Properties.Settings.Default[c.Name.TrimStart("tbx".ToCharArray())]; if (c.Name.ToLower().IndexOf("password") >= 0) { if (!string.IsNullOrEmpty(propValue)) { PHComponents.SCCrypto scc = new PHComponents.SCCrypto(); propValue = scc.Decrypting(propValue); } } c.Text = propValue; } if (c.GetType().Equals(typeof(CheckBox))) { ((CheckBox)c).CheckedChanged += new EventHandler(SaveControlValue); ((CheckBox)c).Checked=Convert.ToBoolean(Properties.Settings.Default[c.Name.TrimStart("cbx".ToCharArray())]); } } }
[Test] public void RowFilter() { //note: this test does not check all the possible row filter expression. this is done in DataTable.Select method. // this test also check DataView.Count property DataRowView[] drvResult = null; System.Collections.ArrayList al = new System.Collections.ArrayList(); //create the source datatable DataTable dt = DataProvider.CreateChildDataTable(); //create the dataview for the table DataView dv = new DataView(dt); //------------------------------------------------------------- //Get excpected result al.Clear(); foreach (DataRow dr in dt.Rows ) { if ((int)dr["ChildId"] == 1) { al.Add(dr); } } // RowFilter = 'ChildId=1', check count dv.RowFilter = "ChildId=1"; Assert.AreEqual(al.Count , dv.Count , "DV70"); // RowFilter = 'ChildId=1', check rows drvResult = new DataRowView[dv.Count]; dv.CopyTo(drvResult,0); //check that the filterd rows exists bool Succeed = true; for (int i=0; i<drvResult.Length ; i++) { Succeed = al.Contains(drvResult[i].Row); if (!Succeed) break; } Assert.AreEqual(true, Succeed , "DV71"); //------------------------------------------------------------- //------------------------------------------------------------- //Get excpected result al.Clear(); foreach (DataRow dr in dt.Rows ) if ((int)dr["ChildId"] == 1 && dr["String1"].ToString() == "1-String1" ) al.Add(dr); // RowFilter - ChildId=1 and String1='1-String1' dv.RowFilter = "ChildId=1 and String1='1-String1'"; Assert.AreEqual(al.Count , dv.Count , "DV72"); // RowFilter = ChildId=1 and String1='1-String1', check rows drvResult = new DataRowView[dv.Count]; dv.CopyTo(drvResult,0); //check that the filterd rows exists Succeed = true; for (int i=0; i<drvResult.Length ; i++) { Succeed = al.Contains(drvResult[i].Row); if (!Succeed) break; } Assert.AreEqual(true, Succeed , "DV73"); //------------------------------------------------------------- //EvaluateException // RowFilter - check EvaluateException try { dv.RowFilter = "Col=1"; Assert.Fail("DV74: RowFilter Failed to throw EvaluateException"); } catch (EvaluateException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Assert.Fail("DV75: RowFilter. Wrong exception type. Got:" + exc); } //SyntaxErrorException 1 // RowFilter - check SyntaxErrorException 1 try { dv.RowFilter = "sum('something')"; Assert.Fail("DV76: RowFilter Failed to throw SyntaxErrorException"); } catch (SyntaxErrorException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Assert.Fail("DV77: RowFilter. Wrong exception type. Got:" + exc); } //SyntaxErrorException 2 // RowFilter - check SyntaxErrorException 2 try { dv.RowFilter = "HH**!"; Assert.Fail("DV78: RowFilter Failed to throw SyntaxErrorException"); } catch (SyntaxErrorException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Assert.Fail("DV79: RowFilter. Wrong exception type. Got:" + exc); } }
private System.Collections.ArrayList MakeRand(int intLower, int intUpper, int intNum) { System.Collections.ArrayList arrayRand = new System.Collections.ArrayList(); Random random = new Random((int)DateTime.Now.Ticks); int intRnd; while (arrayRand.Count < intNum) { intRnd = random.Next(intLower, intUpper + 1); if (!arrayRand.Contains(intRnd)) { arrayRand.Add(intRnd); } } return arrayRand; }
public void Optimize(Directory directory) { string[] files = directory.List(); System.Collections.ArrayList segment_names = new System.Collections.ArrayList(); foreach (SegmentInfo si in this) segment_names.Add (si.name); foreach (string file in files) { string basename = System.IO.Path.GetFileNameWithoutExtension (file); if (segment_names.Contains (basename)) continue; if (basename == IndexFileNames.DELETABLE || basename == IndexFileNames.SEGMENTS) continue; Console.WriteLine ("WARNING! Deleting stale data {0}", file); directory.DeleteFile (file); } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Images(); // Load the source PDF file Document doc = new Document(dataDir+ "ImageInformation.pdf"); // Define the default resolution for image int defaultResolution = 72; System.Collections.Stack graphicsState = new System.Collections.Stack(); // Define array list object which will hold image names System.Collections.ArrayList imageNames = new System.Collections.ArrayList(doc.Pages[1].Resources.Images.Names); // Insert an object to stack graphicsState.Push(new System.Drawing.Drawing2D.Matrix(1, 0, 0, 1, 0, 0)); // Get all the operators on first page of document foreach (Operator op in doc.Pages[1].Contents) { // Use GSave/GRestore operators to revert the transformations back to previously set Operator.GSave opSaveState = op as Operator.GSave; Operator.GRestore opRestoreState = op as Operator.GRestore; // Instantiate ConcatenateMatrix object as it defines current transformation matrix. Operator.ConcatenateMatrix opCtm = op as Operator.ConcatenateMatrix; // Create Do operator which draws objects from resources. It draws Form objects and Image objects Operator.Do opDo = op as Operator.Do; if (opSaveState != null) { // Save previous state and push current state to the top of the stack graphicsState.Push(((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Clone()); } else if (opRestoreState != null) { // Throw away current state and restore previous one graphicsState.Pop(); } else if (opCtm != null) { System.Drawing.Drawing2D.Matrix cm = new System.Drawing.Drawing2D.Matrix( (float)opCtm.Matrix.A, (float)opCtm.Matrix.B, (float)opCtm.Matrix.C, (float)opCtm.Matrix.D, (float)opCtm.Matrix.E, (float)opCtm.Matrix.F); // Multiply current matrix with the state matrix ((System.Drawing.Drawing2D.Matrix)graphicsState.Peek()).Multiply(cm); continue; } else if (opDo != null) { // In case this is an image drawing operator if (imageNames.Contains(opDo.Name)) { System.Drawing.Drawing2D.Matrix lastCTM = (System.Drawing.Drawing2D.Matrix)graphicsState.Peek(); // Create XImage object to hold images of first pdf page XImage image = doc.Pages[1].Resources.Images[opDo.Name]; // Get image dimensions double scaledWidth = Math.Sqrt(Math.Pow(lastCTM.Elements[0], 2) + Math.Pow(lastCTM.Elements[1], 2)); double scaledHeight = Math.Sqrt(Math.Pow(lastCTM.Elements[2], 2) + Math.Pow(lastCTM.Elements[3], 2)); // Get Height and Width information of image double originalWidth = image.Width; double originalHeight = image.Height; // Compute resolution based on above information double resHorizontal = originalWidth * defaultResolution / scaledWidth; double resVertical = originalHeight * defaultResolution / scaledHeight; // Display Dimension and Resolution information of each image Console.Out.WriteLine( string.Format(dataDir + "image {0} ({1:.##}:{2:.##}): res {3:.##} x {4:.##}", opDo.Name, scaledWidth, scaledHeight, resHorizontal, resVertical)); } } } }
public TaskSearchReturnValue MemberTaskSearch(Guid logonId, CollectionRequest collectionRequest, TaskSearchCriteria criteria) { TaskSearchReturnValue returnValue = new TaskSearchReturnValue(); try { // Get the logged on user from the current logons and add their // ApplicationSettings the list of concurrent sessions. Host.LoadLoggedOnUser(logonId); try { Functions.RestrictRekoopIntegrationUser(UserInformation.Instance.DbUid); switch (UserInformation.Instance.UserType) { case DataConstants.UserType.Staff: // Can do everything break; case DataConstants.UserType.Client: case DataConstants.UserType.ThirdParty: throw new Exception("Access denied"); default: throw new Exception("Access denied"); } // Create a data list creator for a list of matters DataListCreator<Task> dataListCreator = new DataListCreator<Task>(); // Declare an inline event (annonymous delegate) to read the // dataset if it is required dataListCreator.ReadDataSet += delegate(object Sender, ReadDataSetEventArgs e) { DiaryMemberSearchItem diaryMembers = this.GetDiaryMemberDetails(criteria.MemberID); string UsersChosenMemberID = criteria.MemberID; DateTime usersDiaryDate = DateTime.Today; bool ShowCancelled = false; string memberIds; string[] usersChosenMemberIDs = new string[] { }; DateTime taskFromDate = usersDiaryDate; DateTime taskToDate = usersDiaryDate; TimeSpan timeSpan = taskToDate - taskFromDate; int taskNoOfDays = (timeSpan.Days + 1); int taskBookingID = 0; int statusID = 0; string occurrencePriority = string.Empty; int dateFilter = 0; int incItems = 1; int progress = 0; DiaryViewDts dvDiary = new DiaryViewDts(); if (criteria.StartDate != DataConstants.BlankDate) { taskFromDate = Convert.ToDateTime(criteria.StartDate); } if (!diaryMembers.IsGroup) { UsersChosenMemberID = diaryMembers.MemberID; dvDiary = SrvBookingEntryLookup.GetAllTasksForMember(UsersChosenMemberID, taskFromDate, ShowCancelled, taskNoOfDays, taskBookingID, statusID, occurrencePriority, dateFilter, incItems, progress); } else { usersChosenMemberIDs = this.ResolveGroupMembers(int.Parse(diaryMembers.MemberID)); memberIds = string.Join(",", usersChosenMemberIDs); dvDiary = SrvBookingEntryLookup.GetAllTasksForMember(memberIds, taskFromDate, ShowCancelled, taskNoOfDays, taskBookingID, statusID, occurrencePriority, dateFilter, incItems, progress); } // Add New Column Editable dvDiary.DiaryEntries.Columns.Add("isEdit"); // Add New Column Matters dvDiary.DiaryEntries.Columns.Add("OccurrenceMatter"); // Add New Column IsLimitation dvDiary.DiaryEntries.Columns.Add("IsLimitationTask", typeof(Boolean)); // Add New Column NewRecordedDueDate for filtering dvDiary.DiaryEntries.Columns.Add("NewRecordedDueDate", typeof(DateTime)); System.Collections.ArrayList listIds = new System.Collections.ArrayList(); foreach (DiaryViewDts.DiaryEntriesRow row in dvDiary.DiaryEntries.Rows) { row["isEdit"] = this.IsOccurrenceViewableBy(row.OccurrenceID); row["IsLimitationTask"] = this.IsALimitationTask(Convert.ToInt32(row.BookingTypeID)); if (!listIds.Contains(row.BookingID)) { listIds.Add(row.BookingID); } if (row["RecordedDueDate"].ToString() != "") { row["NewRecordedDueDate"] = Convert.ToDateTime(row["RecordedDueDate"]); } } StringBuilder ids = new StringBuilder(); foreach (int bookingId in listIds) { ids.Append(bookingId.ToString()); ids.Append(","); } DiaryViewMattersDts matterDts = new DiaryViewMattersDts(); if (ids.Length > 0) { ids.Length--; matterDts = SrvBookingEntryLookup.GetMattersForBookings(ids.ToString()); } foreach (DiaryViewDts.DiaryEntriesRow row in dvDiary.DiaryEntries.Rows) { DiaryViewMattersDts.BookingMatterRow[] matterRows; matterRows = (DiaryViewMattersDts.BookingMatterRow[])matterDts.BookingMatter.Select(string.Format("BookingID = {0}", row.BookingID)); StringBuilder sb = new StringBuilder(); foreach (DiaryViewMattersDts.BookingMatterRow matterRow in matterRows) { sb.AppendFormat("{0}$({1}-{2}) {3}~", matterRow.ProjectID, matterRow.MatterRef.Substring(0, 6), matterRow.MatterRef.Substring(6, 4), matterRow.matDescription); } if (sb.Length > 0) { string matters = sb.ToString().Substring(0, sb.Length - 1); row["OccurrenceMatter"] = matters; } } DataView dvDiaryView = new DataView(dvDiary.Tables[0]); string filter = string.Empty; switch (criteria.Status) { case "Outstanding": filter += " (OccStatusDesc <> 'Completed') and "; break; case "Completed": filter += " (OccStatusDesc = 'Completed') and "; break; } bool isStartDate = false; if (criteria.StartDate != DataConstants.BlankDate) { filter += " ((NewRecordedDueDate >= #" + Convert.ToDateTime(criteria.StartDate).ToString("yyyy-MM-dd") + "#) "; isStartDate = true; } if (criteria.ToDate != DataConstants.BlankDate) { if (isStartDate) { filter += " and "; } filter += "(NewRecordedDueDate <= #" + Convert.ToDateTime(criteria.ToDate).ToString("yyyy-MM-dd") + "#)"; if (isStartDate) { filter += ") "; } filter += " and "; } else { filter += ") and "; } if (!string.IsNullOrEmpty(filter)) { filter = filter.Trim().Substring(0, filter.Trim().Length - 3); } dvDiaryView.RowFilter = filter; DataSet dsFiltered = new DataSet(); dsFiltered.Tables.Add(dvDiaryView.ToTable()); e.DataSet = dsFiltered; if (criteria.OrderBy != string.Empty) { DataTable dt = Functions.SortDataTable(e.DataSet.Tables[0], criteria.OrderBy); e.DataSet.Tables.Remove("DiaryEntries"); e.DataSet.Tables.Add(dt); } }; returnValue.Tasks = dataListCreator.Create(logonId, "TaskSearch", // Tell it the query criteria used so if the cache is accessed // again it knows if it is the same query criteria.ToString(), collectionRequest, // Import mappings to map the dataset row fields to the data // list entity properties new ImportMapping[] { new ImportMapping("Id", "OccurrenceID"), new ImportMapping("RecordedDueDate", "RecordedDueDate"), new ImportMapping("Subject", "OccSpecificText"), new ImportMapping("StatusDesc", "OccStatusDesc"), new ImportMapping("Progress", "OccProgress"), new ImportMapping("Notes", "OccurrenceNoteText"), new ImportMapping("Matters", "OccurrenceMatter"), new ImportMapping("IsEditable", "isEdit"), new ImportMapping("IsLimitationTask", "IsLimitationTask") // More fields are required here but the service layer query may not be // providing them. This is enough for a test. } ); } finally { // Remove the logged on user's ApplicationSettings from the // list of concurrent sessions Host.UnloadLoggedOnUser(); } } catch (System.Data.SqlClient.SqlException) { returnValue.Success = false; returnValue.Message = Functions.SQLErrorMessage; } catch (Exception ex) { returnValue.Success = false; returnValue.Message = ex.Message; } return returnValue; }
public void Optimize(Directory directory) { string[] files = directory.List(); System.Collections.ArrayList segment_names = new System.Collections.ArrayList(); foreach (SegmentInfo si in this) segment_names.Add (si.name); foreach (string file in files) { string basename = System.IO.Path.GetFileNameWithoutExtension (file); if (segment_names.Contains (basename)) continue; // Allowed files deletable, segments, segments.gen, segments_N if (basename == IndexFileNames.DELETABLE || basename.StartsWith (IndexFileNames.SEGMENTS)) continue; Console.WriteLine ("WARNING! Deleting stale data {0}", file); try { directory.DeleteFile (file); } catch { /* Could be already deleted. */ } } }
/// <summary> /// Retains the elements in the target collection that are contained in the specified collection /// </summary> /// <param gridTemplateName="target">Collection where the elements will be removed.</param> /// <param gridTemplateName="c">Elements to be retained in the target collection.</param> /// <returns>true</returns> public static bool RetainAll(System.Collections.ICollection target, System.Collections.ICollection c) { System.Collections.IEnumerator e = new System.Collections.ArrayList(target).GetEnumerator(); System.Collections.ArrayList al = new System.Collections.ArrayList(c); //Reflection. Invoke "retainAll" method for proprietary classes or "Remove" for each element in the collection System.Reflection.MethodInfo method; try { method = c.GetType().GetMethod("retainAll"); if (method != null) method.Invoke(target, new System.Object[] {c}); else { method = c.GetType().GetMethod("Remove"); while (e.MoveNext() == true) { if (al.Contains(e.Current) == false) method.Invoke(target, new System.Object[] {e.Current}); } } } catch (System.Exception ex) { throw ex; } return true; }
/// <summary> /// ��������ɾ���ظ����� /// tc 08-11-18 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string[] RepaceSpilthItem(string[] str) { System.Collections.ArrayList list = new System.Collections.ArrayList(); string tempStr = ""; foreach (string s in str) { tempStr = s.ToLower(); if (list.Contains(tempStr)) continue; list.Add(tempStr); } return (string[])list.ToArray(typeof(string)); }
public System.Collections.ArrayList queEtapasEnRevaluo() { TimeSpan ts = TimeSpan.FromSeconds(2); DateTime inicio = DateTime.Now; byte auxEtapa = 255; System.Collections.ArrayList etapas = new System.Collections.ArrayList(); while (((TimeSpan)(DateTime.Now - inicio)).CompareTo(ts) < 0) { auxEtapa = etapaEnCalculo; if (auxEtapa != 255) { if (!etapas.Contains(auxEtapa)) { etapas.Add(auxEtapa); } } } return etapas; }
public void SessionFeedLocationsTest() { PackageManager target = new PackageManager(); System.Collections.ArrayList expected, actual; string[] var = {"c:\\"}; expected = new System.Collections.ArrayList(); IEnumerable<string> tmp = target.SessionFeedLocations; IEnumerator<string> stepper = tmp.GetEnumerator(); stepper.MoveNext(); //init to first item while (stepper.Current != null) { expected.Add(stepper.Current); stepper.MoveNext(); } expected.Add(var[0].ToLower()); // The following line generates downstream tasks, and must be waited on to pass the test. target.SessionFeedLocations = var; // Adding this did not cause the test to run successfully. // Tasklet.WaitforCurrentChildTasks(); actual = new System.Collections.ArrayList(); tmp = target.SessionFeedLocations; stepper = tmp.GetEnumerator(); stepper.MoveNext(); //init to first item while (stepper.Current != null) { actual.Add(stepper.Current); stepper.MoveNext(); } Assert.IsNotNull(actual, "Received NULL session feed list after assignment."); foreach (object t in expected) if (!actual.Contains(t)) { string Estring = ""; for (int j = 0; j < expected.Count; j++) Estring += (string)expected[j] + "\n"; string Astring = ""; for (int j = 0; j < actual.Count; j++) Astring += (string)actual[j] + "\n"; Assert.Fail("Added feed location does not match expectation.\tMay be caused by incompleted child tasks."); } Assert.IsTrue(true, "Retrieved and altered Session feed locations successfully."); }
/// <summary> Get the paths starting from an atom of specified length. /// <p/> /// This method returns a set of paths. Each path is a <code>List</code> of atoms that /// make up the path (ie they are sequentially connected). /// /// </summary> /// <param name="atomContainer">The molecule to consider /// </param> /// <param name="start"> The starting atom /// </param> /// <param name="length"> The length of paths to look for /// </param> /// <returns> A <code>List</code> containing the paths found /// </returns> public static System.Collections.IList getPathsOfLength(IAtomContainer atomContainer, IAtom start, int length) { System.Collections.ArrayList curPath = new System.Collections.ArrayList(); System.Collections.ArrayList paths = new System.Collections.ArrayList(); curPath.Add(start); paths.Add(curPath); for (int i = 0; i < length; i++) { System.Collections.ArrayList tmpList = new System.Collections.ArrayList(); for (int j = 0; j < paths.Count; j++) { curPath = (System.Collections.ArrayList)paths[j]; IAtom lastVertex = (IAtom)curPath[curPath.Count - 1]; System.Collections.IList neighbors = atomContainer.getConnectedAtomsVector(lastVertex); for (int k = 0; k < neighbors.Count; k++) { System.Collections.ArrayList newPath = new System.Collections.ArrayList(curPath); if (newPath.Contains(neighbors[k])) continue; newPath.Add(neighbors[k]); tmpList.Add(newPath); } } paths.Clear(); paths.AddRange(tmpList); } return (paths); }
/// <summary> /// Constrói dados do grupo. /// Percorre tabela de dados do relatório, filtrando e distinguindo os dados pela coluna do grupo. /// </summary> /// <param name="p_table">Tabela de dados do relatório.</param> /// <param name="p_parentgroupcolumn">Coluna do grupo pai.</param> public void Build(System.Data.DataTable p_table, string p_parentgroupcolumn) { System.Collections.ArrayList v_allcolumns_temp; string[] v_allcolumns; int k; // alocando lista de colunas v_allcolumns_temp = new System.Collections.ArrayList(); // adicionando coluna do grupo pai if (p_parentgroupcolumn != null && p_parentgroupcolumn != "") v_allcolumns_temp.Add(p_parentgroupcolumn); // adicionando coluna do grupo v_allcolumns_temp.Add(this.v_column); // adicionando todas as colunas do cabeçalho do grupo for (k = 0; k < this.v_headerfields.Count; k++) { if (! v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column) && ((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column != "") v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column); } // adicionando todas as colunas do rodapé do grupo for (k = 0; k < this.v_footerfields.Count; k++) { if (! v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column) && ((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column != "") v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column); } // alocando vetor de string v_allcolumns = new string[v_allcolumns_temp.Count]; // copiando nomes de colunas para o vetor de string for (k = 0; k < v_allcolumns_temp.Count; k++) v_allcolumns [k] = (string) v_allcolumns_temp[k]; // filtrando dados distintos pela lista de colunas, e armazenando em tabela if (p_parentgroupcolumn != null && p_parentgroupcolumn != "") p_table.DefaultView.Sort = p_parentgroupcolumn + ", " + this.v_column; else p_table.DefaultView.Sort = this.v_column; this.v_table = p_table.DefaultView.ToTable(true, v_allcolumns); }
/// <summary> /// 合并字符串数组,例如:"1,2,3,"和"2,3,5,"生成"1,2,3,5," /// </summary> /// <param name="s1"></param> /// <param name="s2"></param> /// <returns></returns> public static string UnionStr(string s1, string s2) { string[] strs1, strs2; strs1 = s1.Split(','); strs2 = s2.Split(','); System.Collections.ArrayList sc = new System.Collections.ArrayList(); sc.AddRange(strs1); foreach (string s in strs2) { if (s != string.Empty && !sc.Contains(s)) { sc.Add(s); } } string lastStr = ","; foreach (string s in sc) { lastStr += s + ","; } return lastStr; }
/// <summary> /// Constrói dados do grupo. /// Percorre tabela de dados do relatório, filtrando e distinguindo os dados pela coluna do grupo. /// Também calcula os valores de cada grupo, totalizando-os. /// </summary> /// <param name="p_table">Tabela de dados do relatório.</param> /// <param name="p_parentgroupcolumn">Coluna do grupo pai.</param> public void BuildCalculate(System.Data.DataTable p_table, string p_parentgroupcolumn) { System.Collections.ArrayList v_allcolumns_temp; string[] v_allcolumns; int i, j, k; // PASSO 1: PEGANDO COLUNAS E DADOS DO GRUPO // alocando lista de colunas v_allcolumns_temp = new System.Collections.ArrayList(); // adicionando coluna do grupo pai if (p_parentgroupcolumn != null && p_parentgroupcolumn != "") v_allcolumns_temp.Add(p_parentgroupcolumn); // adicionando coluna do grupo v_allcolumns_temp.Add(this.v_column); // adicionando todas as colunas do cabeçalho do grupo (exceto as colunas de valor) for (k = 0; k < this.v_headerfields.Count; k++) { if (((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column != "" && !((Spartacus.Reporting.Field)this.v_headerfields [k]).v_groupedvalue && !v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column)) v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column); } // adicionando todas as colunas do rodapé do grupo (exceto as colunas de valor) for (k = 0; k < this.v_footerfields.Count; k++) { if (((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column != "" && !((Spartacus.Reporting.Field)this.v_footerfields [k]).v_groupedvalue && !v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column)) v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column); } // alocando vetor de string v_allcolumns = new string[v_allcolumns_temp.Count]; // copiando nomes de colunas para o vetor de string for (k = 0; k < v_allcolumns_temp.Count; k++) v_allcolumns [k] = (string)v_allcolumns_temp [k]; // filtrando dados distintos pela lista de colunas, e armazenando em tabela if (p_parentgroupcolumn != null && p_parentgroupcolumn != "") p_table.DefaultView.Sort = p_parentgroupcolumn + ", " + this.v_column; else p_table.DefaultView.Sort = this.v_column; this.v_table = p_table.DefaultView.ToTable(true, v_allcolumns); // PASSO 2: PREENCHENDO VALORES // limpando array temporario v_allcolumns_temp.Clear(); // adicionando todas as colunas do cabeçalho do grupo (somente as colunas de valor) for (k = 0; k < this.v_headerfields.Count; k++) { if (((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column != "" && ((Spartacus.Reporting.Field)this.v_headerfields [k]).v_groupedvalue && ! v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column)) v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_headerfields [k]).v_column); } // adicionando todas as colunas do rodapé do grupo (somente as colunas de valor) for (k = 0; k < this.v_footerfields.Count; k++) { if (((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column != "" && ((Spartacus.Reporting.Field)this.v_footerfields [k]).v_groupedvalue && ! v_allcolumns_temp.Contains(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column)) v_allcolumns_temp.Add(((Spartacus.Reporting.Field)this.v_footerfields [k]).v_column); } // criando colunas de valor na tabela do grupo for (k = 0; k < v_allcolumns_temp.Count; k++) this.v_table.Columns.Add((string)v_allcolumns_temp [k]); // preenchendo valores sumarizados for (i = 0; i < this.v_table.Rows.Count; i++) { for (j = 0; j < v_allcolumns_temp.Count; j++) this.v_table.Rows [i] [(string)v_allcolumns_temp [j]] = p_table.Compute("Sum(" + ((string)v_allcolumns_temp [j]) + ")", this.v_column + " = '" + this.v_table.Rows [i] [this.v_column].ToString() + "'").ToString(); } }
private void FillContract() { const string METHOD_NAME = "FillContract"; try { lstGtContract.Items.Clear(); string contractList = Common.UILib.GetListText(lstGtContract, ","); string[] list = contractList.Split(new char[] { ',' }); System.Collections.ArrayList contractIDs = new System.Collections.ArrayList(list); string cropYear = ((HarvestReportTemplate)Master).CropYear; int shid = ((HarvestReportTemplate)Master).SHID; using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) { using (SqlDataReader dr = WSCReportsExec.ContractsByPayeeNumber(conn, Convert.ToInt32(cropYear), shid)) { while (dr.Read()) { string contractNo = dr.GetInt32(dr.GetOrdinal("cnt_contract_no")).ToString(); System.Web.UI.WebControls.ListItem item = new ListItem(contractNo, contractNo); lstGtContract.Items.Add(item); if (contractIDs.Contains(contractNo)) { lstGtContract.Items[lstGtContract.Items.Count - 1].Selected = true; } } } } } catch (Exception ex) { Common.CException wex = new Common.CException(MOD_NAME + METHOD_NAME, ex); throw (wex); } }
public int Process() { string SourceTableName = "vContactSalesCurrent"; //'Dim culture = New System.Globalization.CultureInfo("en-US", True) 'default culture int TotalRecords = 0; //'Total record count int i = 0; //'current record index DataSet ds = new DataSet(SourceTableName); //Remove old holdings records (> 90 days) try { string deleteSql = "Delete From " + this.TableOwner + "." + "ImportHold Where RepProcessed = 1 And DealerProcessed = 1"; deleteSql += " And Convert(date, SubString(BatchName, 0, 9)) < Convert(date, DateAdd(day, -90, GetDate()))"; deleteSql += " And Convert(date, SubString(BatchName, 0, 9)) Not In (Select Convert(date, ArchiveDate) From " + this.TableOwner + "." + "ArchiveCalendar)"; DataAccess.OLEDB_ExecuteNonQuery(OLEDBConnection.ConnectionString, deleteSql, 15000); } catch (Exception de) { //don't want an error here to interrupt Trace.TraceInformation("ERROR Removing Previous Holdings Batch - " + ClassName + ": " + "Record: " + i + " - " + de.Message); EventLog.WriteEntry(Application.ProductName, "ERROR Removing Previous Holdings Batch - " + ClassName + ": " + "Record: " + i + " - " + de.Message, EventLogEntryType.Error); } //Check to see if there are any records to process. exit if not. string countSQL = "select Count(*) FROM " + this.TableOwner + "." + "[vImportHoldings] AS h"; //countSQL += " INNER JOIN " + this.TableOwner + "." + "[FUND] AS f ON h.FundCode = f.FundCode"; countSQL += " Where (IsNull(h.RepProcessed, 0) = 0)"; int recordCount = DataAccess.OLEDB_ExecuteScalar<int>(OLEDBConnection.ConnectionString, countSQL); if (recordCount <= 0) { Trace.TraceInformation("Process - " + ClassName + ": Complete " + recordCount + " processed"); EventLog.WriteEntry(Application.ProductName, "Process - " + ClassName + ": Complete " + recordCount + " processed", EventLogEntryType.Information); return recordCount; } //'sql query //string sql = "Select h.BatchName, h.DealerCode, h.RepCode, h.FundCode, f.FundName"; //sql += ", Max(Convert(BigInt, h.NAVLastReported) * 0.0000000001) As Price"; //sql += ", Sum(Convert(BigInt, h.MarketValue) * 0.01) As MarketValue"; //sql += ", Count(Distinct h.AccountNumber) As NumOfAccounts"; //sql += ", (Select Sum(Convert(BigInt, h3.MarketValue) * 0.01)"; //sql += " FROM " + this.TableOwner + "." + "ImportHold h3"; //sql += " Inner Join " + this.TableOwner + "." + "Fund f3 On h3.FundCode = f3.FundCode"; //sql += " Where h3.BatchName = h.BatchName"; //sql += " AND h3.DealerCode = h.DealerCode AND h3.RepCode = h.RepCode"; //sql += ") As TotalMarketValue"; //sql += " FROM " + this.TableOwner + "." + "ImportHold h"; //sql += " Inner Join " + this.TableOwner + "." + "Fund f On h.FundCode = f.FundCode"; //sql += " Group By h.BatchName, h.DealerCode, h.RepCode, h.FundCode, f.FundName, h.RepProcessed"; //sql += " Having h.BatchName = (Select Max(h4.BatchName) From " + this.TableOwner + "." + "ImportHold h4)"; //sql += " AND Not (h.RepCode is null Or h.RepCode = '')"; //sql += " And (h.RepProcessed <> 1 Or h.RepProcessed Is Null)"; //sql += " Order By h.RepCode, h.FundCode"; string sql = "SELECT [BatchName], [DealerCode], [RepCode], [FundCode], [FundName], [Price]"; sql += ", [MarketValue], [NumOfAccounts], [TotalMarketValue], [TotalNumOfAccounts]"; sql += ", [YTDGrossSales], [YTDRedemptions], [YTDNetSales]"; sql += ", [TotalYTDGrossSales], [TotalYTDRedemptions], [TotalYTDNetSales]"; sql += " FROM " + this.TableOwner + "." + "[vContactSalesCurrent]"; try { //'Open the Dataset DataAccess.OLEDB_FillDataset(ref ds, OLEDBConnection.ConnectionString, sql, SourceTableName, 15000); //'Get the totals TotalRecords = ds.Tables[SourceTableName].Rows.Count; i = 1; //'Initialiize batch values //'Me.BatchId = Me.GetNextID("BatchId", "LicenseTransactionTable", Me.DestinationNativeConnection) this.BatchDate = DateTime.Now; //list the batches to archive System.Collections.ArrayList ArchiveList = new System.Collections.ArrayList(); try { //list the batches in the results var distinctbatches = (from DataRow dRow in ds.Tables[SourceTableName].Rows select dRow["BatchName"]).Distinct(); foreach (string batch in distinctbatches) { //read the date part of the batch string batchDate = batch.Substring(0, 8); //If the date is found in the archive calendar, then archive the batch string sqlremove = "Select Count(*) From " + this.TableOwner + "." + "ArchiveCalendar Where CONVERT(date, ArchiveDate) = ?"; int archive = DataAccess.OLEDB_ExecuteScalar<int>(OLEDBConnection.ConnectionString, sqlremove, 15000 , new OleDbParameter("BatchName", batchDate)); if (archive > 0) { //Archive date matches, archive this batch ArchiveList.Add(batchDate); //If there are records to process, remove the existing history to avoid duplicates if (TotalRecords > 0) { Target.SLXContactFundSales.RemoveHistory(batch, SaleslogixConnection.ConnectionString, this.TableOwner); } } } } catch (Exception de) { //don't want an error here to interrupt Trace.TraceInformation("ERROR Listing Archives - " + ClassName + ": " + "Record: " + i + " - " + de.Message); EventLog.WriteEntry(Application.ProductName, "ERROR Listing Archives - " + ClassName + ": " + "Record: " + i + " - " + de.Message, EventLogEntryType.Error); } //existing records will be removed before adding new ones. if (TotalRecords > 0) { //new records found, clear old ones Target.SLXContactFundSales.Truncate(SaleslogixConnection.ConnectionString, this.TableOwner); } //'for each record foreach (DataRow row in ds.Tables[SourceTableName].Rows) { //Insert the contact records try { //Load object with row data Target.SLXContactFundSales cfs = new Target.SLXContactFundSales(this); //check for an existing contact List<string> contactIdList = cfs.FindContactsByRepCode( DataAccess.ReplaceNull<String>(row["DealerCode"]) , DataAccess.ReplaceNull<String>(row["RepCode"])); //Handle sharing rep codes foreach (string contactId in contactIdList) { cfs.ContactId = contactId; cfs.Owner = "SYST00000001"; cfs.DealerCode = DataAccess.ReplaceNull<String>(row["DealerCode"]); cfs.RepCode = DataAccess.ReplaceNull<String>(row["RepCode"]); cfs.Fund = DataAccess.ReplaceNull<String>(row["FundName"]); cfs.FundCode = DataAccess.ReplaceNull<String>(row["FundCode"]); cfs.FundPrice = DataAccess.ReplaceNull<double>(row["Price"]); cfs.Holdings = DataAccess.ReplaceNull<double>(row["MarketValue"]); cfs.NumberOfAccounts = DataAccess.ReplaceNull<int>(row["NumOfAccounts"]); cfs.TotalHoldings = DataAccess.ReplaceNull<double>(row["TotalMarketValue"]); string batchName = DataAccess.ReplaceNull<String>(row["BatchName"]); //cfs.RecordSource = DataAccess.ReplaceNull<String>(row["RecordSource"]); //string sql2 = "Select Count(Distinct h2.AccountNumber) AS TotalnumOfAccounts"; //sql2 += " FROM " + this.TableOwner + "." + "ImportHold h2"; //sql2 += " Inner Join " + this.TableOwner + "." + "Fund f2 On h2.FundCode = f2.FundCode"; //sql2 += " Where h2.BatchName = ?"; //sql2 += " AND h2.DealerCode = ? AND h2.RepCode = ?"; //int? totalnumofaccount = DataAccess.OLEDB_ExecuteScalar<int?>(OLEDBConnection.ConnectionString // , sql2, 180 // , new OleDbParameter ("BatchName", batchName) // , new OleDbParameter ("DealerCode", cfs.DealerCode) // , new OleDbParameter ("RepCode", cfs.RepCode)); //cfs.TotalNumberOfAccounts = Convert.ToInt32(totalnumofaccount); cfs.TotalNumberOfAccounts = DataAccess.ReplaceNull<int>(row["TotalNumOfAccounts"]); //cfs.YTDGrossSales = cfs.CalculateYTDGrossSales(cfs.FundCode, cfs.DealerCode, cfs.RepCode); cfs.YTDGrossSales = DataAccess.ReplaceNull<double>(row["YTDGrossSales"]); cfs.YTDRedemptions = DataAccess.ReplaceNull<double>(row["YTDRedemptions"]); //cfs.YTDNetSales = cfs.CalculateYTDNetSales(cfs.FundCode, cfs.DealerCode, cfs.RepCode); cfs.YTDNetSales = DataAccess.ReplaceNull<double>(row["YTDNetSales"]); //cfs.TotalYTDGrossSales = cfs.CalculateTotalYTDGrossSales(cfs.DealerCode, cfs.RepCode); cfs.TotalYTDGrossSales = DataAccess.ReplaceNull<double>(row["TotalYTDGrossSales"]); cfs.TotalYTDRedemptions = DataAccess.ReplaceNull<double>(row["TotalYTDRedemptions"]); //cfs.TotalYTDNetSales = cfs.CalculateTotalYTDNetSales(cfs.DealerCode, cfs.RepCode); cfs.TotalYTDNetSales = DataAccess.ReplaceNull<double>(row["TotalYTDNetSales"]); if (!String.IsNullOrEmpty(contactId)) { //Contact found, insert record string contactFundSalesId = cfs.Insert(); //check if this batch should be archived //Only archive transaction records, not holdings records if (ArchiveList.Contains(batchName.Substring(0, 8)) ) { //& cfs.RecordSource == "Transaction") { //Archive date matches, archive this batch cfs.InsertHistory(batchName); } } } Trace.TraceInformation("Process - " + ClassName + ": Contact Record: (" + i + " of " + TotalRecords + ")"); } catch (Exception ex) { Trace.TraceInformation("ERROR Process - " + ClassName + ": " + "Contact Record: " + i + " - " + ex.Message); EventLog.WriteEntry(Application.ProductName, "ERROR Process - " + ClassName + ": " + "Record: " + i + " - " + ex.Message, EventLogEntryType.Error); ErrorLog.Add("ERROR Process - " + ClassName + ": " + "Contact Record: " + i + " - " + ex.Message); //'Move to the next record - record failure will not stop processing of subsequent records } //Move to the next record i += 1; } // Next //Mark the data as processed var distinctRows = (from DataRow dRow in ds.Tables[SourceTableName].Rows select dRow["BatchName"]).Distinct(); foreach (string batch in distinctRows) { string sqlprocess = "Update " + this.TableOwner + "." + "ImportHold Set RepProcessed = 1 Where BatchName = ?"; DataAccess.OLEDB_ExecuteNonQuery(OLEDBConnection.ConnectionString, sqlprocess, 15000 , new OleDbParameter("BatchName", batch)); } i--; Trace.TraceInformation("Process - " + ClassName + ": Complete " + i + " of " + TotalRecords + " processed"); EventLog.WriteEntry(Application.ProductName, "Process - " + ClassName + ": Complete " + i + " of " + TotalRecords + " processed", EventLogEntryType.Information); return TotalRecords; } catch (Exception ex1) { // Trace.TraceInformation("ERROR Process - " & ClassName & ":" & ex1.Message) // My.Application.Log.WriteException(ex1, TraceEventType.Error, vbCrLf & "ERROR Process - " & ClassName) Trace.TraceInformation("ERROR Process - " + ClassName + ": " + "Contact Record: " + i + " - " + ex1.Message); EventLog.WriteEntry(Application.ProductName, "ERROR Process - " + ClassName + ": " + "Contact Record: " + i + " - " + ex1.Message, EventLogEntryType.Error); ErrorLog.Add("ERROR Process - " + ClassName + ": " + "Contact Record: " + i + " - " + ex1.Message); return i; } }
/// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns>Returns <see langword="true" /> if the task successfully /// executed; otherwise, <see langword="false" />. /// </returns> public override bool Execute() { bool success = true; this.resultItems = new ITaskItem[items.Length]; for (int i = 0; i < resultItems.Length; i++) { ITaskItem newItem = new TaskItem(items[i]); this.items[i].CopyMetadataTo(newItem); //Need to set this so it is not reset newItem.SetMetadata("RecursiveDir", items[i].GetMetadata("RecursiveDir")); if (String.IsNullOrEmpty(this.metadataName)) { IDictionary<string, string> metadataBag = ParseMetadata(this.metadata); foreach (string metadataName in metadataBag.Keys) { newItem.SetMetadata(metadataName, metadataBag[metadataName]); } } else { System.Collections.ArrayList names = new System.Collections.ArrayList(newItem.MetadataNames); string value = String.Empty; if (names.Contains(this.metadataName)) { value = String.Format(CultureInfo.InvariantCulture, "{0};{1}", newItem.GetMetadata(this.metadataName), String.Join(";", this.metadata)); } else { value = String.Join(";", this.metadata); } newItem.SetMetadata(this.metadataName, value); } this.resultItems[i] = newItem; } return success; }
/// <summary> Populates the given group object with data from the given group element, ignoring /// any unrecognized nodes. /// </summary> private void parse(Genetibase.NuGenHL7.model.Group groupObject, System.Xml.XmlElement groupElement) { System.String[] childNames = groupObject.Names; System.String messageName = groupObject.Message.getName(); System.Xml.XmlNodeList allChildNodes = groupElement.ChildNodes; System.Collections.ArrayList unparsedElementList = new System.Collections.ArrayList(); for (int i = 0; i < allChildNodes.Count; i++) { System.Xml.XmlNode node = allChildNodes.Item(i); System.String name = node.Name; if (System.Convert.ToInt16(node.NodeType) == (short) System.Xml.XmlNodeType.Element && !unparsedElementList.Contains(name)) { unparsedElementList.Add(name); } } //we're not too fussy about order here (all occurances get parsed as repetitions) ... for (int i = 0; i < childNames.Length; i++) { SupportClass.ICollectionSupport.Remove(unparsedElementList, childNames[i]); parseReps(groupElement, groupObject, messageName, childNames[i], childNames[i]); } for (int i = 0; i < unparsedElementList.Count; i++) { System.String segName = (System.String) unparsedElementList[i]; System.String segIndexName = groupObject.addNonstandardSegment(segName); parseReps(groupElement, groupObject, messageName, segName, segIndexName); } }
/// <summary> /// Generates a Summary Table Outlining the Provider Charges and Revenues /// Illustrating Unearned Income /// use MinDate and MaxDate to flag all dates /// </summary> public static DataTable GenerateSummaryTable(int Guarantor,DateTime dtFrom, DateTime dtTo) { DataTable rValReturnTable = null; DataTable dtProviderBalance = Db.GetTableOld(ProviderRevenueByGuarantor(Guarantor,dtFrom,dtTo)); DataTable dtProvAbbr = Db.GetTableOld("SELECT ProvNum, Abbr FROM Provider"); if (dtProviderBalance != null && dtProviderBalance.Rows.Count != 0) { // Get Provider Abbreviations System.Collections.Hashtable htAllProvs = new System.Collections.Hashtable(); for (int i = 0; i < dtProvAbbr.Rows.Count; i++) if (!htAllProvs.ContainsKey(dtProvAbbr.Rows[i][0].ToString())) htAllProvs[dtProvAbbr.Rows[i][0].ToString()] = dtProvAbbr.Rows[i][1].ToString(); if (!htAllProvs.ContainsKey("0")) htAllProvs["0"] = "Unearned"; // First establish a list of providers System.Collections.ArrayList alProvs = new System.Collections.ArrayList(); for (int i = 0; i < dtProviderBalance.Rows.Count; i++) if (!alProvs.Contains(dtProviderBalance.Rows[i][0].ToString())) alProvs.Add(dtProviderBalance.Rows[i][0].ToString()); // Fill and Create DataTable DataTable dtBalancesTable = new DataTable(); dtBalancesTable.Columns.Add(new DataColumn("Provider", typeof(string))); dtBalancesTable.Columns.Add(new DataColumn("Charges", typeof(string))); dtBalancesTable.Columns.Add(new DataColumn("Adjustments", typeof(string))); dtBalancesTable.Columns.Add(new DataColumn("Revenue", typeof(string))); dtBalancesTable.Columns.Add(new DataColumn("Balance", typeof(string))); DataRow drWorkingRow = null; int ColumnIndex = -1; try { System.Collections.Hashtable htAllProvs_Indexes = new System.Collections.Hashtable(); for (int i = 0; i < alProvs.Count; i++) // For Each Provider add a Row in the Balances Table { dtBalancesTable.Rows.Add(dtBalancesTable.NewRow()); dtBalancesTable.Rows[i][0] = alProvs[i].ToString(); } for (int i = 0; i < dtProviderBalance.Rows.Count; i++) { drWorkingRow = dtBalancesTable.Rows[alProvs.IndexOf(dtProviderBalance.Rows[i][0].ToString())]; drWorkingRow[0] = htAllProvs[dtProviderBalance.Rows[i][0].ToString()].ToString(); // the abbreviation // Which Column of the Row to add the number to? Find the column // stated in the query's column 2 string ColumnName_FromQuery = dtProviderBalance.Rows[i][2].ToString(); ColumnIndex = dtBalancesTable.Columns.IndexOf(ColumnName_FromQuery); if (ColumnIndex > 0) drWorkingRow[ColumnIndex] = dtProviderBalance.Rows[i][1].ToString(); // note is not cast as number so numeric specifies cannot apply //ToString("F2"); else drWorkingRow[4] = "ERROR!"; ColumnIndex = -1; } decimal[] Totals = new decimal[4]; // Fill in Null and Empty Entries for (int j = 0; j < dtBalancesTable.Rows.Count; j++) for (int k = 1; k < dtBalancesTable.Columns.Count; k++) { if (dtBalancesTable.Rows[j][k] == null || dtBalancesTable.Rows[j][k].ToString().Trim() == "") dtBalancesTable.Rows[j][k] = "0.00"; if (k == dtBalancesTable.Columns.Count - 1) { decimal Balance = decimal.Parse(dtBalancesTable.Rows[j][1].ToString()) + decimal.Parse(dtBalancesTable.Rows[j][2].ToString()) + decimal.Parse(dtBalancesTable.Rows[j][3].ToString()); dtBalancesTable.Rows[j][4] = Balance.ToString("F2"); } // Add to the Totals to be placed at the bottom of the Table Totals[k - 1] += decimal.Parse(dtBalancesTable.Rows[j][k].ToString()); // Format the Numbers Better dtBalancesTable.Rows[j][k] = decimal.Parse(dtBalancesTable.Rows[j][k].ToString()).ToString("F2"); } DataRow TotalRow = dtBalancesTable.NewRow(); TotalRow[0] = "Totals-->"; for (int i = 1; i < dtBalancesTable.Columns.Count; i++) TotalRow[i] = Totals[i - 1].ToString("F2"); dtBalancesTable.Rows.Add(TotalRow); } catch { } rValReturnTable = dtBalancesTable; // Set this first becuase SummaryTable_as_Strings() will check for _SummaryTable != null // _SummaryTableHeader = SummaryTable_as_Strings(); } return rValReturnTable; }
/// <summary> /// Returns all the selected rows index /// </summary> /// <returns></returns> public virtual int[] GetRowsIndex() { System.Collections.ArrayList indexList = new System.Collections.ArrayList(); RangeCollection ranges = GetRanges(); for (int iRange = 0; iRange < ranges.Count; iRange++) { for (int r = ranges[iRange].Start.Row; r <= ranges[iRange].End.Row; r++) { if (indexList.Contains(r) == false) indexList.Add(r); } } int[] ret = new int[indexList.Count]; indexList.CopyTo(ret, 0); return ret; }
/// <summary> /// Seperates a dataset into clusters or groups with similar characteristics /// </summary> /// <param name="clusterCount">The number of clusters or groups to form</param> /// <param name="data">An array containing data that will be clustered</param> /// <returns>A collection of clusters of data</returns> public static ClusterCollection ClusterDataSet(int clusterCount, IList<IDataList> data) { //bool stableClusterFormation = false; int clusterNumber = 0; int rowCount = data.Count; int fieldCount = data[0].Data.Length; int stableClustersCount = 0; int iterationCount = 0; double[] dataPoint; Random random = new Random(); Cluster cluster = null; ClusterCollection clusters = new ClusterCollection(); System.Collections.ArrayList clusterNumbers = new System.Collections.ArrayList(clusterCount); while (clusterNumbers.Count < clusterCount) { clusterNumber = random.Next(0, rowCount - 1); if (!clusterNumbers.Contains(clusterNumber)) { cluster = new Cluster(); clusterNumbers.Add(clusterNumber); cluster.Add(data[clusterNumber]); clusters.Add(cluster); } } while (stableClustersCount != clusters.Count) { stableClustersCount = 0; ClusterCollection newClusters = KMeans.ClusterDataSet(clusters, data); for (int clusterIndex = 0; clusterIndex < clusters.Count; clusterIndex++) { if ((KMeans.EuclideanDistance(newClusters[clusterIndex].ClusterMean, clusters[clusterIndex].ClusterMean)) == 0) { stableClustersCount++; } } iterationCount++; clusters = newClusters; } return clusters; }
//Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { //note: this test does not check all the possible row filter expression. this is done in DataTable.Select method. // this test also check DataView.Count property Exception exp = null; DataRowView[] drvResult = null; System.Collections.ArrayList al = new System.Collections.ArrayList(); //create the source datatable DataTable dt = GHTUtils.DataProvider.CreateChildDataTable(); //create the dataview for the table DataView dv = new DataView(dt); //------------------------------------------------------------- //Get excpected result al.Clear(); foreach (DataRow dr in dt.Rows ) { if ((int)dr["ChildId"] == 1) { al.Add(dr); } } try { BeginCase("RowFilter = 'ChildId=1', check count"); dv.RowFilter = "ChildId=1"; Compare(dv.Count ,al.Count ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("RowFilter = 'ChildId=1', check rows"); drvResult = new DataRowView[dv.Count]; dv.CopyTo(drvResult,0); //check that the filterd rows exists bool Succeed = true; for (int i=0; i<drvResult.Length ; i++) { Succeed = al.Contains(drvResult[i].Row); if (!Succeed) break; } Compare(Succeed ,true); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //------------------------------------------------------------- //------------------------------------------------------------- //Get excpected result al.Clear(); foreach (DataRow dr in dt.Rows ) if ((int)dr["ChildId"] == 1 && dr["String1"].ToString() == "1-String1" ) al.Add(dr); try { BeginCase("RowFilter - ChildId=1 and String1='1-String1'"); dv.RowFilter = "ChildId=1 and String1='1-String1'"; Compare(dv.Count ,al.Count ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} try { BeginCase("RowFilter = ChildId=1 and String1='1-String1', check rows"); drvResult = new DataRowView[dv.Count]; dv.CopyTo(drvResult,0); //check that the filterd rows exists bool Succeed = true; for (int i=0; i<drvResult.Length ; i++) { Succeed = al.Contains(drvResult[i].Row); if (!Succeed) break; } Compare(Succeed ,true); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //------------------------------------------------------------- //EvaluateException try { BeginCase("RowFilter - check EvaluateException"); try { dv.RowFilter = "Col=1"; } catch (EvaluateException ex) { exp=ex; } Compare(exp.GetType().FullName ,typeof(EvaluateException).FullName); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //SyntaxErrorException 1 try { BeginCase("RowFilter - check SyntaxErrorException 1"); try { dv.RowFilter = "sum('something')"; } catch (SyntaxErrorException ex) { exp=ex; } Compare(exp.GetType().FullName ,typeof(SyntaxErrorException).FullName); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //SyntaxErrorException 2 try { BeginCase("RowFilter - check SyntaxErrorException 2"); try { dv.RowFilter = "HH**!"; } catch (SyntaxErrorException ex) { exp=ex; } Compare(exp.GetType().FullName ,typeof(SyntaxErrorException).FullName); exp=null; } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} }
/// <summary> Populates the given group object with data from the given group element, ignoring /// any unrecognized nodes. /// </summary> private void parse(ca.uhn.hl7v2.model.Group groupObject, System.Xml.XmlElement groupElement) { System.String[] childNames = groupObject.Names; System.String messageName = groupObject.Message.getStructureName(); //UPGRADE_TODO: Method 'org.w3c.dom.Node.getChildNodes' was converted to 'System.Xml.XmlNode.ChildNodes' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" System.Xml.XmlNodeList allChildNodes = groupElement.ChildNodes; System.Collections.ArrayList unparsedElementList = new System.Collections.ArrayList(); for (int i = 0; i < allChildNodes.Count; i++) { System.Xml.XmlNode node = allChildNodes.Item(i); System.String name = node.Name; if (System.Convert.ToInt16(node.NodeType) == (short) System.Xml.XmlNodeType.Element && !unparsedElementList.Contains(name)) { unparsedElementList.Add(name); } } //we're not too fussy about order here (all occurances get parsed as repetitions) ... for (int i = 0; i < childNames.Length; i++) { SupportClass.ICollectionSupport.Remove(unparsedElementList, childNames[i]); parseReps(groupElement, groupObject, messageName, childNames[i], childNames[i]); } for (int i = 0; i < unparsedElementList.Count; i++) { System.String segName = (System.String) unparsedElementList[i]; System.String segIndexName = groupObject.addNonstandardSegment(segName); parseReps(groupElement, groupObject, messageName, segName, segIndexName); } }
/* Standard A* */ public bool Astar_start(AstarNode startNode, AstarNode targetNode) { System.Collections.ArrayList closedlist = new System.Collections.ArrayList(); System.Collections.ArrayList openlist = new System.Collections.ArrayList(); closedlist.Clear(); openlist.Clear(); startNode.fvalue = calcFvalue(startNode); //this sets g and h openlist.Add(startNode); while (openlist.Count > 0) { Globals.debugPath = pathNodes; AstarNode xNode; openlist.Sort(); xNode = ((AstarNode)openlist[0]); if (xNode == targetNode) { pathNodes.Add(xNode); return true; } openlist.Remove(xNode); closedlist.Add(xNode); pathNodes.Add(xNode); findAdjacentNodes(xNode); foreach (AstarNode yNode in xNode.adjacentNodes) { if (closedlist.Contains(yNode)) continue; int tempGScore; bool isBetter = false; //todo add diagonals. tempGScore = xNode.gvalue + HorizontalCost; yNode.fvalue = calcFvalue(yNode); if (openlist.Contains(yNode)) { openlist.Add(yNode); isBetter = true; } else if (tempGScore < yNode.gvalue) isBetter = true; else isBetter = false; if (isBetter) { yNode.gvalue = tempGScore; yNode.hvalue = calcHvalue(yNode); yNode.fvalue = yNode.gvalue + yNode.hvalue; } } } return false; }
private void MapSubclasses(System.Collections.ArrayList subclasses, System.Collections.Specialized.StringCollection extendedClassesNames, System.Collections.ArrayList mappedClassesNames, System.Xml.XmlTextWriter writer) { System.Collections.ArrayList mappedSubclassesNames = new System.Collections.ArrayList(); // Map each subclass after the class it extends while(subclasses.Count > 0) for(int i=subclasses.Count-1; i>=0; i--) { System.Type type = subclasses[i] as System.Type; string extendedClassName = extendedClassesNames[i]; if(extendedClassName==null) throw new MappingException("You must specify the Extends attribute of the Subclass: " + type.FullName); if( ! mappedClassesNames.Contains(extendedClassName) && ! mappedSubclassesNames.Contains(extendedClassName) ) { bool extendedClassFoundButNotMappedYet = false; // Make sure that the extended class is mapped (in this assembly) foreach(System.Type subclass in subclasses) { if( HbmWriterHelper.GetNameWithAssembly(subclass) == extendedClassName ) { if(subclass==type) throw new MappingException("The Subclass " + type.FullName + " extends itself."); else { extendedClassFoundButNotMappedYet = true; break; } } } if (extendedClassFoundButNotMappedYet) continue; // Map this one later // Else unknown extended class: // Assume it is mapped somewhere else and map this subclass } if( IsSubclass(type, typeof(SubclassAttribute)) ) HbmWriter.WriteSubclass(writer, type); else if( IsSubclass(type, typeof(JoinedSubclassAttribute)) ) HbmWriter.WriteJoinedSubclass(writer, type); else if( IsSubclass(type, typeof(UnionSubclassAttribute)) ) HbmWriter.WriteUnionSubclass(writer, type); // Note: Do not add to mappedClassesNames because it is for x-subclasses (and a x-subclasses shouldn't extend another x-subclasses) mappedSubclassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type)); subclasses.RemoveAt(i); extendedClassesNames.RemoveAt(i); } }
public void Run() { System.Collections.ArrayList tradeScrollList = new System.Collections.ArrayList(); for (int ip = 0; ip < Globals.iprp_spells2da.RowCount; ip++) { //DebugWindow.PrintDebugMessage("Looking at iprp_spells.2da row: " + ip); string tdaSpellId = Globals.iprp_spells2da["SpellIndex"][ip]; string tdaCasterLevel = Globals.iprp_spells2da["CasterLvl"][ip]; string icon = Globals.iprp_spells2da["Icon"][ip]; bool formatOK = true; int spellId = -1; int casterLevel = -1; try { spellId = Convert.ToInt32(tdaSpellId); casterLevel = Convert.ToInt32(tdaCasterLevel); DebugWindow.PrintDebugMessage("Creating consumables for spell id " + spellId + ", caster level " + casterLevel + " and scroll icon " + icon + "."); } catch { DebugWindow.PrintDebugMessage("2da format error for iprp_spells.2da line " + ip + ", spell id " + tdaSpellId + ", caster level " + tdaCasterLevel + "."); formatOK = false; } if (formatOK && !ipHash.Contains(tdaSpellId.ToString() + "_" + tdaCasterLevel.ToString())) { NWN2Toolset.NWN2.Rules.CNWSpell spell = Globals.spells.GetSpell(spellId); ipHash.Add(tdaSpellId.ToString() + "_" + tdaCasterLevel.ToString()); if (spell != null && spell.IsValid() == 1) { int targets = spell.GetSpellTargetType(); int wizardLevel = spell.GetSpellWizardLevel(); int clericLevel = spell.GetSpellClericLevel(); int druidLevel = spell.GetSpellDruidLevel(); int rangerLevel = spell.GetSpellRangerLevel(); int paladinLevel = spell.GetSpellPaladinLevel(); int bardLevel = spell.GetSpellBardLevel(); // Find the lowest spell level. int lowestSpellLevel = wizardLevel; if (lowestSpellLevel > clericLevel) lowestSpellLevel = clericLevel; if (lowestSpellLevel > druidLevel) lowestSpellLevel = druidLevel; float costLevel = lowestSpellLevel; if (lowestSpellLevel == 0) costLevel = 0.5F; if ((lowestSpellLevel < 255)) { if ((targets & 2) != 0 && lowestSpellLevel <= 3 && spell.GetSpellHostile() != 1 && !nonpotion(spellId)) { // Can target a creature, ie can be a potion. Potion potion = new Potion(ip, spellId, lowestSpellLevel, casterLevel, spell); Globals.AddBlueprint(potion.blueprint); potionStore.addToPotionItems(potion.blueprint); } if (lowestSpellLevel <= 4) { // Can be a wand. Wand wand = new Wand(ip, spellId, lowestSpellLevel, casterLevel, spell); addClassRestrictions(wand.blueprint, bardLevel, clericLevel, druidLevel, paladinLevel, rangerLevel, wizardLevel); Globals.AddBlueprint(wand.blueprint); wandStore.addToPotionItems(wand.blueprint); } int lowestDivineLevel = clericLevel; if (druidLevel < clericLevel) { lowestDivineLevel = druidLevel; } if (lowestDivineLevel == 255) { lowestDivineLevel = rangerLevel; if (lowestDivineLevel > paladinLevel) lowestDivineLevel = paladinLevel; } if (lowestDivineLevel < 255) { // Can be a divine scroll. Scroll scroll = new DivineScroll(ip, spellId, lowestSpellLevel, casterLevel, spell, icon); addClassRestrictions(scroll.blueprint, 255, clericLevel, druidLevel, paladinLevel, rangerLevel, 255); Globals.AddBlueprint(scroll.blueprint); scrollStore.addToPotionItems(scroll.blueprint); } int lowestArcaneLevel = wizardLevel; if (wizardLevel == 255) { lowestArcaneLevel = bardLevel; } if (wizardLevel < 255 && !tradeScrollList.Contains(spellId)) { // Can be a trade scroll. TradeScroll tradescroll = new TradeScroll(spellId, lowestSpellLevel, spell); Globals.AddBlueprint(tradescroll.blueprint); tradeScrollList.Add(spellId); } if (lowestArcaneLevel < 255) { // Can be an arcane scroll. Scroll scroll = new ArcaneScroll(ip, spellId, lowestSpellLevel, casterLevel, spell, icon); addClassRestrictions(scroll.blueprint, bardLevel, 255, 255, 255, 255, wizardLevel); Globals.AddBlueprint(scroll.blueprint); scrollStore.addToPotionItems(scroll.blueprint); } } } } } DebugWindow.PrintDebugMessage("Items in blueprint collection: " + Globals.items.Count); NotfyIconsNotFoundFor("Potions", Potion.iconsMissing); NotfyIconsNotFoundFor("Wand", Wand.iconsMissing); NotfyIconsNotFoundFor("Scroll", Scroll.iconsMissing); ipHash = new HashSet<String>(); }
static void Main(string[] args) { System.Collections.ArrayList M = new System.Collections.ArrayList(); string s = System.Console.ReadLine(); int N = int.Parse(s); char c; Int64 L; int x; for(int i=0;i<N;i++) { s = System.Console.ReadLine(); c = s[0]; L = Int64.Parse(s.Substring(2)); M.Sort(); switch (c) { case 'I': if (!M.Contains(L)) { M.Insert(0, L); } break; case 'D': x = Array.BinarySearch(M.ToArray(), L); if(x < 0) { System.Console.WriteLine("BRAK"); } else { System.Console.WriteLine("OK"); M.Remove(L); } break; case 'U': x = Array.BinarySearch(M.ToArray(), L); if (x >= 0) { System.Console.WriteLine(M[x]); } else if (~x < 0) { System.Console.WriteLine("BRAK"); } else if ((~x) >= M.ToArray().Length) { System.Console.WriteLine("BRAK"); } else { System.Console.WriteLine(M[~x].ToString()); } break; case 'L': x = Array.BinarySearch(M.ToArray(), L); if (x >= 0) { System.Console.WriteLine(M[x]); } else if (~x <= 0) { System.Console.WriteLine("BRAK"); } else if ((~x) > M.ToArray().Length) { System.Console.WriteLine("BRAK"); } else { System.Console.WriteLine(M[~x-1].ToString()); } break; } } }
/// <summary> /// 绑定行业类别(大类) /// </summary> private void Load_JobFeildKinds() { zlzw.BLL.GeneralBasicSettingBLL generalBasicSettingBLL = new zlzw.BLL.GeneralBasicSettingBLL(); DataTable dt = generalBasicSettingBLL.GetList("SettingCategory='IndustrySector'").Tables[0]; System.Collections.ArrayList arrList = new System.Collections.ArrayList(); string strTemp=""; for (int nCount = 0; nCount < dt.Rows.Count; nCount++) { strTemp = dt.Rows[nCount]["DisPlayName"].ToString(); if (!arrList.Contains(strTemp)) { arrList.Add(strTemp); } } //drpJobFeildKinds.DataTextField = "DisPlayName"; //drpJobFeildKinds.DataValueField = "SettingID"; //drpJobFeildKinds.DataSource = arrList; //drpJobFeildKinds.DataBind(); //Load_JobFeildKinds01(drpJobFeildKinds.SelectedValue); }