/// <summary> /// A simple bubble sort for two arrays, limited to some region of the arrays. /// This is a regular bubble sort, nothing fancy. /// </summary> public static void SimpleSort(Array array, Array items, int startingIndex, int length, IComparer comparer) { bool finished = false; while (!finished) { bool swapped = false; for (int g = startingIndex; g < startingIndex + length - 1; g++) { Object first = array.GetValue(g); Object second = array.GetValue(g + 1); int comparison = comparer.Compare(first, second); if (comparison == 1) { Swap(g, g + 1, array, items); swapped = true; first = array.GetValue(g); second = array.GetValue(g + 1); } } if (!swapped) { finished = true; } } }
public static string CodeRepresentation(Array a) { StringBuilder ret = new StringBuilder(); ret.Append(a.GetType().FullName); ret.Append("("); switch (a.Rank) { case 1: { for (int i = 0; i < a.Length; i++) { if (i > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0)))); } } break; case 2: { int imax = a.GetLength(0); int jmax = a.GetLength(1); for (int i = 0; i < imax; i++) { ret.Append("\n"); for (int j = 0; j < jmax; j++) { if (j > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0), j + a.GetLowerBound(1)))); } } } break; default: ret.Append(" Multi-dimensional array "); break; } ret.Append(")"); return ret.ToString(); }
public static string GetValue(Array MyValues) { String ret = ""; ret=MyValues.GetValue(1, RowIndex) == null?"":MyValues.GetValue(1, RowIndex).ToString(); RowIndex++; return ret; }
/// <summary> /// Sort elements in an Array object, using the Order /// delegate to determine how items should be sorted. /// </summary> /// <param name="table">Array to be sorted</param> /// <param name="sortHandler">Delegate to manage /// sort order.</param> public void Sort(Array table, Order sortHandler) { if(sortHandler == null) throw new ArgumentNullException(); bool nothingSwapped = false; int pass = 1; while(nothingSwapped == false) { nothingSwapped = true; for(int index = 0; index < table.Length - pass; ++index) { // Use an Order delegate to determine the sort order. if(sortHandler(table.GetValue(index), table.GetValue(index + 1)) == false) { nothingSwapped = false; object temp = table.GetValue(index); table.SetValue(table.GetValue(index + 1), index); table.SetValue(temp, index + 1); } } ++pass; } }
public bool SendEmail(string name, string email, Array arrayFrontEnd, Array arrayBackEnd, Array arrayMobile) { bool criterion = false; bool sucess = true; string subject = string.Empty; string content = string.Empty; IDictionary<int, string> dictionary = new Dictionary<int, string>(); if (Convert.ToInt32(arrayFrontEnd.GetValue(0)) >= 7 || 10 <= Convert.ToInt32(arrayFrontEnd.GetValue(0)) && Convert.ToInt32(arrayFrontEnd.GetValue(1)) >= 7 || 10 <= Convert.ToInt32(arrayFrontEnd.GetValue(1)) && Convert.ToInt32(arrayFrontEnd.GetValue(2)) >= 7 || 10 <= Convert.ToInt32(arrayFrontEnd.GetValue(2))) { criterion = true; subject = string.Concat("Obrigado por se candidatar ", name); content = "Obrigado por se candidatar, assim que tivermos uma vaga disponível para programador Front-End entraremos em contato."; dictionary.Add(1, string.Concat(subject, "|", content)); } if (Convert.ToInt32(arrayBackEnd.GetValue(0)) >= 7 || 10 <= Convert.ToInt32(arrayBackEnd.GetValue(0)) && Convert.ToInt32(arrayBackEnd.GetValue(1)) >= 7 || 10 <= Convert.ToInt32(arrayBackEnd.GetValue(1))) { criterion = true; subject = string.Concat("Obrigado por se candidatar ", name); content = "Obrigado por se candidatar, assim que tivermos uma vaga disponível para programador Back-End entraremos em contato."; dictionary.Add(2, string.Concat(subject, "|", content)); } if (Convert.ToInt32(arrayMobile.GetValue(0)) >= 7 || 10 <= Convert.ToInt32(arrayMobile.GetValue(0)) && Convert.ToInt32(arrayMobile.GetValue(1)) >= 7 || 10 <= Convert.ToInt32(arrayMobile.GetValue(1))) { criterion = true; subject = string.Concat("Obrigado por se candidatar ", name); content = "Obrigado por se candidatar, assim que tivermos uma vaga disponível para programador Mobile entraremos em contato."; dictionary.Add(3, string.Concat(subject, "|", content)); } if (!criterion) { subject = string.Concat("Obrigado por se candidatar ", name); content = "Obrigado por se candidatar, assim que tivermos uma vaga disponível para programador entraremos em contato."; dictionary.Add(4, string.Concat(subject, "|", content)); } foreach (var item in dictionary) { List<string> stringList = new List<string>(item.Value.Split(new string[] { "|" }, StringSplitOptions.None)); sucess = SendEmailToClient(email, stringList[0], stringList[1]); if (!sucess) break; } if (!sucess) return false; else return true; }
public object ConnectData(int topicId, ref Array Strings, ref bool GetNewValues) { m_source[topicId] = Strings.GetValue(0).ToString(); m_bland[topicId] = Strings.GetValue(1).ToString(); m_field[topicId] = Strings.GetValue(2).ToString(); m_timer.Start(); return "Data not found."; }
public static void Shuffle(this Random rng, Array array) { int n = array.Length; while (n > 1) { int k = rng.Next (n--); object temp = array.GetValue (n); array.SetValue (array.GetValue (k), n); array.SetValue (temp, k); } }
public void AddToLog(Array lines, int i, Color textColor) { rtbLogText.SelectionColor = textColor; rtbLogText.AppendText(string.Format("{0}{1}", lines.GetValue(i) as string, Environment.NewLine)); fullRTFcode = rtbLogText.Rtf; if (textColor == Color.Red) subsetErrorRTFList.Add((string.Format("{0}{1}", lines.GetValue(i) as string, Environment.NewLine))); else if (textColor == Color.DarkCyan) subsetWarningRTFList.Add((string.Format("{0}{1}", lines.GetValue(i) as string, Environment.NewLine))); else if (textColor == ForeColor) subsetSubmittedRTFList.Add((string.Format("{0}{1}", lines.GetValue(i) as string, Environment.NewLine))); }
public static bool CompareObjects(Array obj1, Array obj2) { if (obj1 == null || obj2 == null) return false; string s; string y; for (int i = 0; i < obj1.Length; i++) { s = obj1.GetValue(i).ToString(); y = obj2.GetValue(i).ToString(); if (obj1.GetValue(i).ToString() != obj2.GetValue(i).ToString()) return false; } return true; }
public static void Equals(Array a, Array b, string message=null) { if(a.Length != b.Length) throw new AssertFailedException("A and B are not of equal length (" + a.Length + " != " + b.Length + ")"); for(int i=0;i<a.Length;i++) { var ai = a.GetValue(i); var bi = b.GetValue(i); if(ai is IComparable && bi is IComparable) { Equals((IComparable)ai, (IComparable)bi, message); } else if(ai != bi){ throw new AssertFailedException(String.IsNullOrEmpty(message) ? a.GetValue(i).ToString() + " != " + b.GetValue(i).ToString() : message); } } }
protected override void SortGenericArray(Array items, int left, int right) { int lo = left; int hi = right; if (lo >= hi) { return; } int mid = (lo + hi) / 2; // Partition the items into two lists and Sort them recursively SortGenericArray(items, lo, mid); SortGenericArray(items, mid + 1, hi); // Merge the two sorted lists int end_lo = mid; int start_hi = mid + 1; while ((lo <= end_lo) && (start_hi <= hi)) { if (this.comparer.Compare(items.GetValue(lo), items.GetValue(start_hi)) < 0) { lo++; } else { /* * items[lo] >= items[start_hi] * The next element comes from the second items, * move the items[start_hi] element into the next * position and shuffle all the other elements up. */ object T = items.GetValue(start_hi); for (int k = start_hi - 1; k >= lo; k--) { items.SetValue(items.GetValue(k), k + 1); } items.SetValue(T, lo); lo++; end_lo++; start_hi++; } } }
public static JavaObjectFactory Array(JniWrapper vm, Type dotNetType, Array prototype) { object innerPrototype = null; if (prototype != null && prototype.Length > 0) { innerPrototype = prototype.GetValue(0); } JavaObjectFactory innerFactory = GetJavaType(vm, dotNetType.GetElementType(), innerPrototype); ArrayType javaArrayType = new ArrayType(innerFactory.JavaType); return new JavaObjectFactory(o => { Array asArray = (Array)o; PrimitiveType asPrimitive = javaArrayType.MemberType as PrimitiveType; if (asPrimitive != null) { switch (asPrimitive.Kind) { case PrimitiveTypeKind.Boolean: return vm.NewBooleanArray((bool[])o); case PrimitiveTypeKind.Byte: return vm.NewByteArray((byte[])o); case PrimitiveTypeKind.Char: return vm.NewCharArray((char[])o); case PrimitiveTypeKind.Double: return vm.NewDoubleArray((double[])o); case PrimitiveTypeKind.Float: return vm.NewFloatArray((float[])o); case PrimitiveTypeKind.Int: return vm.NewIntArray((int[])o); case PrimitiveTypeKind.Long: return vm.NewLongArray((long[])o); case PrimitiveTypeKind.Short: return vm.NewShortArray((short[])o); default: throw new InvalidOperationException("Unknown primitive kind: " + asPrimitive.Kind); } } else { IntPtr[] elements = asArray.Cast<object>().Select(innerFactory._factory).Select(v => v.ToIntPtr()).ToArray(); return vm.NewArray(vm.FindClass(innerFactory.JavaType.JniClassName), elements); } }, javaArrayType); }
public string ioPrint(Array Formats, Array StorageTypes) { string msgString = ""; for (int iIndex = 0; iIndex < Formats.Length; iIndex++) { msgString = msgString + Formats.GetValue(iIndex); StorageTypeEnum lType; lType = (StorageTypeEnum)StorageTypes.GetValue(iIndex); switch(lType) { case StorageTypeEnum.kFileOrStreamStorage: msgString = msgString + "(File or Stream) "; break; case StorageTypeEnum.kFileStorage: msgString = msgString + "(File) "; break; case StorageTypeEnum.kStorageStorage: msgString = msgString + "(Storage) "; break; case StorageTypeEnum.kUnknownStorage: msgString = msgString + "(Unknown) "; break; default: msgString = msgString + "(Stream) "; break; } } return msgString; }
public static String GenerateName(Species species) { string result = ""; string[] split = new string[1] { "\r\n" }; char[] splitchar = new char[1] { ':' }; switch (species) { case Species.Human: srReader = new StreamReader("Data/HumanNames.txt"); break; default: return "TEST"; } NameCategories = srReader.ReadToEnd().Split(splitchar, System.StringSplitOptions.RemoveEmptyEntries); for (int i = 1; i <= NameCategories.Length - 1; i = i + 2) { SpecificNames = ((String)NameCategories.GetValue(i)).Split(split, System.StringSplitOptions.RemoveEmptyEntries); result = result + SpecificNames.GetValue(ran.Next(0, SpecificNames.Length - 1)); } result = result.Replace("%", string.Empty); return result; }
public static bool IsAssignableArrayFrom(this Array source, Array target) { if (source == null || target == null) { throw new ArgumentNullException("source"); } if (source == target) { return true; } if (source.Length != target.Length) { return false; } int i = 0; while (i < source.Length) { if (source.GetType().IsAssignableFrom(target.GetValue(i).GetType())) { return false; } i++; } return true; }
public dynamic ConnectData(int TopicID, ref Array Strings, ref bool GetNewValues) { var start = Convert.ToInt32(Strings.GetValue(0).ToString()); GetNewValues = true; _topics[TopicID] = new IncrementUpwards { CurrentValue = start }; return start; }
/// <summary> /// Returns hash code for an array that is generated based on the elements. /// </summary> /// <remarks> /// Hash code returned by this method is guaranteed to be the same for /// arrays with equal elements. /// </remarks> /// <param name="array"> /// Array to calculate hash code for. /// </param> /// <returns> /// A hash code for the specified array. /// </returns> public static int GetHashCode(Array array) { int hashCode = 0; if (array != null) { for (int i = 0; i < array.Length; i++) { object el = array.GetValue(i); if (el != null) { if (el is Array) { hashCode += 17 * GetHashCode(el as Array); } else { hashCode += 13 * el.GetHashCode(); } } } } return hashCode; }
public static void Encode(LittleEndianOutput out1, Array values) { for (int i = 0; i < values.Length; i++) { EncodeSingleValue(out1, values.GetValue(i)); } }
public static int GetArrayHashCode(Array arr) { int arrHash = arr.Length; for (int i = 0; i < arr.Length; ++i) { arrHash = arrHash ^ arr.GetValue(i).GetHashCode(); } return arrHash; }
void IMediaStatusSession.MediaStatusChange(Array tags, Array properties) { Sink.TraceInformation("Session.MediaStatusChange called"); for (int i = 0; i < tags.Length; i++) { MEDIASTATUSPROPERTYTAG tag = (MEDIASTATUSPROPERTYTAG)tags.GetValue(i); object value = properties.GetValue(i); Sink.TraceInformation("Tag {0}={1}", tag, value); string tagStr = tag.ToString(); if (tagStr.Equals("MSPROPTAG_MediaName")) { Sink.TraceInformation("Witing to key"); WriteToRegistry("Name", value.ToString()); } else if(tagStr.Equals("MSPROPTAG_TrackNumber")) { WriteToRegistry("Channel", value.ToString()); } } }
private void fillHeftArray(int spaceDimension, int histogramResolution, Array array, Array heftArray) { int cellNO = (int)Math.Pow(histogramResolution, spaceDimension); int[] outerIndicesArray = new int[spaceDimension]; int[] innerIndicesArray = new int[spaceDimension]; int[] windowIndicesArray = new int[spaceDimension]; for (int outerCellIdx = 0; outerCellIdx < cellNO; outerCellIdx++) { transformator.transformCellIdxToIndicesArray(histogramResolution, outerIndicesArray, outerCellIdx); for (int innerCellIdx = outerCellIdx; innerCellIdx < cellNO; innerCellIdx++) { transformator.transformCellIdxToIndicesArray(histogramResolution, innerIndicesArray, innerCellIdx); int[] heftArrayIndeces; int cellPoints; bool validHeftArrayIndeces = transformator.mergeIndicesArrays(spaceDimension, outerIndicesArray, innerIndicesArray, out heftArrayIndeces, out cellPoints); if (validHeftArrayIndeces) { int cellValue = 0; for (int windowIdx = outerCellIdx; windowIdx <= innerCellIdx; windowIdx++) { transformator.transformCellIdxToIndicesArray(histogramResolution, windowIndicesArray, windowIdx); bool validSummableArrayIndeces = transformator.validateIndicesArrays(spaceDimension, outerIndicesArray, innerIndicesArray, windowIndicesArray); if (validSummableArrayIndeces) { cellValue += (int)array.GetValue(windowIndicesArray); } } heftArray.SetValue(cellValue, heftArrayIndeces); } } } }
public object ConnectData(int topicId, ref Array strings, ref bool newValues) { var isin = strings.GetValue(0) as string; LoggingWindow.WriteLine("Connecting: {0} {1}", topicId, isin); lock (topics) { // create a listener for this topic var listener = new SpotListener(isin); listener.OnUpdate += (sender, args) => { try { if (callback != null) { callback.UpdateNotify(); } } catch (COMException comex) { LoggingWindow.WriteLine("Unable to notify Excel: {0}", comex.ToString()); } }; listener.Start(); topics.Add(topicId, listener); } return "WAIT"; }
public static bool ArrayDeepEquals(Array arr1, Array arr2) { if (arr1.Length!=arr2.Length || arr1.GetType()!=arr2.GetType()) return false; for (int i=0; i<arr1.Length; i++) { var v1 = arr1.GetValue(i); var v2 = arr2.GetValue(i); if (v1 is Array && v2 is Array) if (!ArrayDeepEquals((Array)v1, (Array)v2)) { return false; } else continue; if (v1==null && v2==null) continue; if (v1!=null) if (!v1.Equals(v2)) return false; if (v2 != null) if (!v2.Equals(v1)) return false; } return true; }
/// <summary> /// Initializes a new instance of the QTable with specified column names and data matrix. /// </summary> public QTable(string[] columns, Array data) { if (columns == null || columns.Length == 0) { throw new ArgumentException("Columns array cannot be null or 0-length"); } if (data == null || data.Length == 0) { throw new ArgumentException("Data matrix cannot be null or 0-length"); } if (columns.Length != data.Length) { throw new ArgumentException("Columns array and data matrix cannot have different length"); } if (data.Cast<object>().Any(col => !col.GetType().IsArray)) { throw new ArgumentException("Non array column found in data matrix"); } columnsMap = new ListDictionary(); for (int i = 0; i < columns.Length; i++) { columnsMap[columns[i]] = i; } this.columns = columns; this.data = data; RowsCount = ((Array)data.GetValue(0)).Length; }
public SArray(Array array) { Values = new ISItem[array.Length]; for (var i = 0; i < array.Length; i++) { Values[i] = SConvert.ToSettings(array.GetValue(i)); } }
/// <summary> /// Tests equality of two single-dimensional arrays by checking each element /// for equality. /// </summary> /// <param name="a">The first array to be checked.</param> /// <param name="b">The second array to be checked.</param> /// <returns>True if arrays are the same, false otherwise.</returns> public static bool AreEqual(Array a, Array b) { if (a == null && b == null) { return true; } if (a != null && b != null) { if (a.Length == b.Length) { for (var i = 0; i < a.Length; i++) { var elemA = a.GetValue(i); var elemB = b.GetValue(i); if (elemA is Array && elemB is Array) { if (!AreEqual(elemA as Array, elemB as Array)) { return false; } } else if (!Equals(elemA, elemB)) { return false; } } return true; } } return false; }
/// <summary> /// Modifies the specified array by applying the specified function to each element. /// </summary> /// <param name="a"></param> /// <param name="func">object delegate(object o){}</param> /// <returns></returns> public static void ForEach(Array a, ForEachFunction func) { long[] ix = new long[a.Rank]; //Init index for (int i = 0; i < ix.Length; i++) ix[i] = a.GetLowerBound(i); //Loop through all items for (long i = 0; i < a.LongLength; i++) { a.SetValue(func(a.GetValue(ix)), ix); //Increment ix, the index for (int j = 0; j < ix.Length; j++) { if (ix[j] < a.GetUpperBound(j)) { ix[j]++; break; //We're done incrementing. } else { //Ok, reset this one and increment the next. ix[j] = a.GetLowerBound(j); //If this is the last dimension, assert //that we are at the last element if (j == ix.Length - 1) { if (i < a.LongLength - 1) throw new Exception(); } continue; } } } return; }
//-------------------------------------------------------------------// /// <summary> /// Converts COM like 2dim array where one dimension is of length 1 to regular array. /// </summary> /// <param name="a">COM array</param> /// <returns>regular array</returns> public static object[] Com2DArray2Array(Array a) { if (a == null) return null; object[] converted = null; switch (a.Rank) { case 1: converted = new object[a.GetLength(0)]; for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { converted[i] = a.GetValue(i); } break; case 2: { var d1 = a.GetLength(0); var d2 = a.GetLength(1); var len = (d1 > d2) ? d1 : d2; converted = new object[len]; var dim = (d1 > d2) ? 0 : 1; for (var i = a.GetLowerBound(dim); i <= a.GetUpperBound(dim); i++) { converted[i - a.GetLowerBound(dim)] = a.GetValue((d1 == 1 ? a.GetLowerBound(0) : i), (d2 == 1 ? a.GetLowerBound(1) : i)); } } break; } return converted; }
public void OpenFiles(Array a) { string sError = ""; // process all files in array for (int i = 0; i < a.Length; i++) { string sFile = a.GetValue(i).ToString(); FileInfo info = new FileInfo(sFile); if (!info.Exists) { sError += "\nIncorrect file name: " + sFile; } else if (info.Name.ToLower().IndexOf(".srt") > -1) { tbSubtitle.Text = info.Name; ShowGuess(sFile); } else if (info.Name.ToLower().IndexOf(".mkv") > -1) { tbMovie.Text = info.Name; moviePath = info.FullName; } } if (sError.Length > 0) MessageBox.Show(this, sError, "Open File Error"); }
object Microsoft.Office.Interop.Excel.IRtdServer.ConnectData(int TopicID, ref Array Strings, ref bool GetNewValues) { object myRet = null; try { string myReqType = Strings.GetValue(0) as string; string myTopicID = Strings.GetValue(1) as string; string myHeaderName = Strings.GetValue(2) as string; string[] stringArray = null; switch (myReqType) { case "RESUB": // do a resubscribe m_RTDSupport.ReplaySubscriptions(); break; case "RESUBGW": // do a resubscribe for a gateway //KRTDSupport.KRTDSupport.Instance().ReSubscribeGW(myTopicID); break; case "NOP": // ignore the operation break; case "PX": // ignore the operation asStringArray(ref stringArray, Strings); m_RTDSupport.ConnectData(TopicID, stringArray); break; default: asStringArray(ref stringArray, Strings); m_RTDSupport.ConnectData(TopicID, stringArray); myRet = myTopicID; break; } // force excel to use the new value GetNewValues = true; } catch (Exception myE) { //KRTDSupport.KRTDSupport.Instance().Log.Error("Microsoft.Office.Interop.Excel.IRtdServer.ConnectData", myE); } return myRet; }
private bool ArrayCompare(System.Array a1, System.Array a2) { if (a1.Length != a2.Length) { return(false); } for (int i = 0; i < a1.Length; i++) { if (!a1.GetValue(i).Equals(a2.GetValue(i))) { return(false); } } return(true); }
public static bool TryFindEnum <T>(string str, out T value) { System.Array arr = System.Enum.GetValues(typeof(T)); for (int i = 0; i < arr.Length; i++) { T t = (T)arr.GetValue(i); if (t.ToString().ToLower().Contains(str.ToLower())) { value = t; return(true); } } value = default(T); return(false); }
public void testAsync() { System.Array array = fileArray; PackageAllVM.Instance.LoadingPanel = System.Windows.Visibility.Visible; string msg = ""; for (int i = 0; i < array.Length; i++) { msg = array.GetValue(i).ToString(); string inputPath = msg; string fileExt = System.IO.Path.GetExtension(msg); string outputPath = fileExt == "" ? msg : System.IO.Path.GetDirectoryName(msg); string path = PackageAllVM.Instance.OutPutPath; if (!String.IsNullOrEmpty(path)) { outputPath = path; if (!System.IO.Directory.Exists(path)) { try { System.IO.Directory.CreateDirectory(path); } catch { MessageBox.Show("创建文件夹失败, 请检查文件夹路径是否正确."); return; } } } if (PackageAllVM.Instance.AllPackageEncodeAll) { FileEncode.Instance.encodeLua(inputPath, outputPath); FileEncode.Instance.encodeImage(inputPath, outputPath); } else if (PackageAllVM.Instance.AllPackageEncodeLua) { FileEncode.Instance.encodeLua(inputPath, outputPath); } else if (PackageAllVM.Instance.AllPackageEncodeImage) { FileEncode.Instance.encodeImage(inputPath, outputPath); } } MessageBox.Show("完成加密!"); PackageAllVM.Instance.LoadingPanel = System.Windows.Visibility.Hidden; }
/// <summary> /// 读取指定Excel表中指定行中指定开始列与列数的数据 /// </summary> public String[] GetRowContent(int rowIndex, int columnIndex, int columnCount) { String[] retContent = null; Range objRange = dataSheet.get_Range(((Char)('A' + columnIndex - 1)).ToString() + rowIndex.ToString(), ((Char)('A' + columnCount + columnIndex - 2)).ToString() + rowIndex.ToString()); if (objRange != null) { System.Array values = (System.Array)objRange.Formula; retContent = new String[columnCount]; for (int index = 1; index <= columnCount; index++) { retContent[index - 1] = values.GetValue(1, index).ToString(); } } return(retContent); }
internal static string MakeConnectionString(object propnames, object propvalues) { ConnectionStringList connstrings = new ConnectionStringList(); string kvp = "{0}={1}"; System.Array propNameArray = (System.Array)propnames; System.Array propValuesArray = (System.Array)propvalues; for (int i = 0; i < propValuesArray.Length; i++) { connstrings.Add(string.Format(kvp, propNameArray.GetValue(i), propValuesArray.GetValue(i))); } return(string.Join(",", connstrings.ToArray())); }
/// <summary> /// Get a previously saved enum from settings. /// </summary> static public T GetEnum <T>(string name, T defaultValue) { string val = GetString(name, defaultValue.ToString()); string[] names = System.Enum.GetNames(typeof(T)); System.Array values = System.Enum.GetValues(typeof(T)); for (int i = 0; i < names.Length; ++i) { if (names[i] == val) { return((T)values.GetValue(i)); } } return(defaultValue); }
static private bool Equiv(System.Array a1, System.Array a2, int len, int off1, int off2) { bool result = true; for (int i = 0; i != len; ++i) { object v1 = a1.GetValue(i + off1); object v2 = a2.GetValue(i + off2); if (v1 != v2) { result = false; break; } } return(result); }
public static void BindTo(this Type enumType, ListControl ddl) { ddl.Items.Clear(); System.Array values = Enum.GetValues(enumType); string[] names = Enum.GetNames(enumType); for (int i = 0; i < names.Length; i++) { string name = names[i]; string resValue = name; if (resValue == null) { resValue = name; } ddl.Items.Add(new ListItem(resValue, ((int)values.GetValue(i)).ToString())); } }
/// <summary> /// Write a value to the specified tag /// </summary> /// <param name="tag">Name of tag to modify</param> /// <param name="value">Value to write to tag</param> public void writeTag(string tag, object value) { //find the group foreach (OPCAutomation.OPCGroup opcGroup in RSLinxOPCGroups) { //find the tag System.Array tagNames = getTagNames(RSLinxOPCGroups.IndexOf(opcGroup)); for (int i = 0; i < tagNames.Length; i++) { if (tagNames.GetValue(i).Equals(tag)) { opcGroup.OPCItems.Item(i).Write(value); } } } }
/// <summary> /// Binds the specified enum type. /// </summary> /// <param name="enumType">Type of the enum.</param> /// <param name="ddl">The DDL.</param> /// <param name="resourceType">Type of the resource.</param> /// <param name="initLabel">The init label.</param> public static void BindTo(this Type enumType, ListControl ddl, Type resourceType, string initLabel) { ddl.Items.Clear(); System.Array values = Enum.GetValues(enumType); string[] names = Enum.GetNames(enumType); System.Resources.ResourceManager rm = new System.Resources.ResourceManager(resourceType); for (int i = 0; i < names.Length; i++) { string name = names[i]; string text = rm.GetString("Enum_" + enumType.Name + "_" + name); ddl.Items.Add(new ListItem(text, ((int)values.GetValue(i)).ToString())); } ListItem li0 = new ListItem(initLabel, "0"); ddl.Items.Insert(0, li0); }
/// <summary> /// /// </summary> /// <param name="oldColName"></param> /// <param name="newColName"></param> /// <returns></returns> public void SetColumnName(string excelFilePath, ArrayList oldColName, ArrayList newColName) { Excel.Application myExcel = new Excel.Application(); try { if (oldColName == null || oldColName.Count == 0) { return; } //取得Excel文件中共有的sheet的数目 object oMissing = System.Reflection.Missing.Value; myExcel.Application.Workbooks.Open(excelFilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); Excel.Workbook myBook = myExcel.Workbooks[1]; Excel.Sheets sheets = myBook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); Excel.Range range = worksheet.get_Range("A1", "Z1"); System.Array myvalues = (System.Array)range.Cells.Value2; Excel._Workbook xBk; Excel._Worksheet xSt; xBk = myExcel.Workbooks[1]; xSt = (Excel._Worksheet)xBk.ActiveSheet; //Excel.Range delRange ; for (int i = 1; i <= myvalues.Length; i++) { int index = ISDelCol(myvalues.GetValue(1, i).ToString().Trim(), oldColName); if (index != -1) { xSt.Cells[1, i] = newColName[i].ToString().Trim(); } } myExcel.Application.Workbooks.Close(); System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel); } catch { Marshal.ReleaseComObject(myExcel); } }
//---------------------------------------------------------------------------- private void FormSelectTypeDevice_Load(object sender, EventArgs e) { List <String> deviceNames; this.comboBoxDeviceType.Items.Clear(); //deviceNames = Enum.GetNames(typeof(TYPE_NGK_DEVICE)); System.Array arr = Enum.GetValues(typeof(TYPE_NGK_DEVICE)); deviceNames = new List <string>(); for (int i = 0; i < arr.Length; i++) { switch ((UInt16)arr.GetValue(i)) { case (UInt16)TYPE_NGK_DEVICE.UNKNOWN_DEVICE: { //deviceNames.Add("Неизвестное устройство"); break; } case (UInt16)TYPE_NGK_DEVICE.BI_BATTERY_POWER: { deviceNames.Add("Устройство БИ(У)-01"); break; } case (UInt16)TYPE_NGK_DEVICE.BI_MAIN_POWERED: { deviceNames.Add("Устройство БИ(У)-00"); break; } default: { throw new Exception("Получен список устройств не поддерживаемых в данной версии ПО"); } } } this.comboBoxDeviceType.Items.AddRange(deviceNames.ToArray()); this.comboBoxDeviceType.SelectedIndex = 0; return; }
private void getRasterMatrix() { n = 0; List <double[]> inputMatrixLst = new List <double[]>(); IRaster2 rs2 = (IRaster2)InRaster; IRasterBandCollection rsbc = (IRasterBandCollection)rs2; IRasterProps rsp = (IRasterProps)rs2; System.Array nDataVlArr = (System.Array)rsp.NoDataValue; IRasterCursor rsCur = rs2.CreateCursorEx(null); IPixelBlock pb = null; System.Array[] pbArrs = new System.Array[rsbc.Count]; Random rand = new Random(); do { pb = rsCur.PixelBlock; for (int i = 0; i < pb.Planes; i++) { pbArrs[i] = (System.Array)pb.get_SafeArray(i); } for (int r = 0; r < pb.Height; r++) { for (int c = 0; c < pb.Width; c++) { if (rand.NextDouble() <= prop) { double[] vlBandArr = new double[rsbc.Count]; for (int p = 0; p < pb.Planes; p++) { System.Array pbArr = pbArrs[p]; double vl = System.Convert.ToDouble(pbArr.GetValue(c, r)); if (rasterUtil.isNullData(vl, nDataVlArr.GetValue(p))) { vl = 0; } vlBandArr[p] = vl; } inputMatrixLst.Add(vlBandArr); n++; } } } } while (rsCur.Next() == true); inputMatrix = inputMatrixLst.ToArray(); }
static public int GetValue__Int32__Int32(IntPtr l) { try { System.Array self = (System.Array)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); var ret = self.GetValue(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
private void ObjOPCGroup_AsyncReadComplete(int TransactionID, int NumItems, ref System.Array ClientHandles, ref System.Array ItemValues, ref System.Array Qualities, ref System.Array TimeStamps, ref System.Array Errors) { try { int index = 0; for (index = 1; index <= NumItems; index++) { List_Values[(int)ClientHandles.GetValue(index) - 1] = ItemValues.GetValue(index); // send to Tag Tags[List_TagName[(int)ClientHandles.GetValue(index) - 1]].TagValue = ItemValues.GetValue(index); //Array_Values(ClientHandles(index)) = index } if (DataArrivalEvent != null) { Evargs = new OPCDataUpdatedEventArgs(); for (int i = 0; i < List_Values.Count; i++) { if (!Tag.ValueEqual(Saved_List_Values[i], List_Values[i])) { // value update Saved_List_Values[i] = List_Values[i]; Evargs.AddUpdateTag(List_TagName[i], List_Values[i]); } } DataArrivalEvent(this, Evargs); } //if (ContinueReading) //{ // AsyncReadAllData(); // LOG.Info(string.Format("{0} read again.", SourceName)); //} } catch (Exception ex) { LOG.Error(string.Format("OPCDataSource异步读取出错:{0},", ex.Message)); //WarnLog("clsDeviceOPC.ObjOPCGroup_AsyncReadComplete() " + ex.Message); } }
public static int ArrayIndexer(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Array array = (System.Array)translator.FastGetCSObj(L, 1); if (array == null) { return(LuaAPI.luaL_error(L, "#1 parameter is not a array!")); } int i = LuaAPI.xlua_tointeger(L, 2); if (i >= array.Length) { return(LuaAPI.luaL_error(L, "index out of range! i =" + i + ", array.Length=" + array.Length)); } Type type = array.GetType(); if (tryPrimitiveArrayGet(type, L, array, i)) { return(1); } if (genTryArrayGetPtr != null) { try { if (genTryArrayGetPtr(type, L, translator, array, i)) { return(1); } } catch (Exception e) { return(LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace)); } } object ret = array.GetValue(i); translator.PushAny(L, ret); return(1); }
private void CompareArray(System.Array from, System.Array to) { if (!(from != null ^ to != null)) { if (from != null) { for (var i = 0; i < from.Length; i++) { Assert.AreEqual(from.GetValue(i), to.GetValue(i)); } } } else { throw new Exception(); } }
protected override bool OnLevelChange(int level) { // level goes from 0 to 10000 but the number of colors divides 10000 // so we need to do that hack that maps level 10000 to level 0 int animationLevel = level == _maxLevel ? 0 : level; // state int stateForLevel = (int)(animationLevel / _maxLevePerCircle); System.Array a = Enum.GetValues(typeof(ProgressStates)); _currentState = (ProgressStates)a.GetValue(stateForLevel); // colors ResetColor(_currentState); int levelForCircle = (int)(animationLevel % _maxLevePerCircle); bool halfPassed; if (!_goesBackward) { halfPassed = levelForCircle != (int)(animationLevel % (_maxLevePerCircle / 2)); } else { halfPassed = levelForCircle == (int)(animationLevel % (_maxLevePerCircle / 2)); levelForCircle = (int)(_maxLevePerCircle - levelForCircle); } if (!halfPassed) { _abovePaint.Color = _secondHalfPaint.Color; } else { _abovePaint.Color = _firstHalfPaint.Color; } // invalidate alpha (Paint#setAlpha is a shortcut for setColor(alpha part) // so alpha is affected by setColor()) SetAlpha(_alpha); // axis _axisValue = (int)(_controlPointMinimum + (_controlPointMaximum - _controlPointMinimum) * (levelForCircle / _maxLevePerCircle)); return(true); }
private bool method_0(string string_1) { if (this.object_0 == null) { return(true); } System.Array array = (System.Array) this.object_0; for (int i = 0; i < array.Length; i++) { string str = (string)array.GetValue(i); if (str == string_1) { return(true); } } return(false); }
public static Dictionary <int, int[]> getUniqueRegions(System.Array windowArr, int eC, int eR, int windowClms, int windowRows, int sc, int sr, float rsNoDataValue, int[,] circleWindow) { Dictionary <int, int[]> outDic = new Dictionary <int, int[]>(); int uniqueCnt = 1; int[,] windowArr2 = new int[windowClms, windowRows]; int noDataValue = 0; for (int c = sc; c < eC; c++) { int cSmall = c - sc; for (int r = sr; r < eR; r++) { int rSmall = r - sr; float cvd = System.Convert.ToSingle(windowArr.GetValue(c, r)); if (rasterUtil.isNullData(cvd, rsNoDataValue)) { } else { int circleVl = circleWindow[cSmall, rSmall]; if (circleVl == 0) { } else { int cv = System.Convert.ToInt32(cvd); int pv = windowArr2[cSmall, rSmall]; if (pv != noDataValue) { } else { int[] cntVls = { 1, 0 }; windowArr2[cSmall, rSmall] = uniqueCnt; outDic.Add(uniqueCnt, cntVls); getUniqueRegion(cv, uniqueCnt, c, r, cSmall, rSmall, windowArr, windowArr2, outDic, circleWindow); uniqueCnt++; } } } } } return(outDic); }
public virtual bool Fill(System.Array sourceArray) { try { this.ObjectName = ((string)(System.Convert.ChangeType(sourceArray.GetValue(0), typeof(string)))); this.ObjectType = ((string)(System.Convert.ChangeType(sourceArray.GetValue(1), typeof(string)))); this.FullPath = ((string)(System.Convert.ChangeType(sourceArray.GetValue(2), typeof(string)))); this.IsInDatabase = ((bool)(System.Convert.ChangeType(sourceArray.GetValue(3), typeof(bool)))); this.IsInFileSystem = ((bool)(System.Convert.ChangeType(sourceArray.GetValue(4), typeof(bool)))); this.FileName = ((string)(System.Convert.ChangeType(sourceArray.GetValue(5), typeof(string)))); this.SchemaOwner = ((string)(System.Convert.ChangeType(sourceArray.GetValue(6), typeof(string)))); return(true); } catch (System.Exception ex) { throw new System.ApplicationException("Error in the Auto-Generated: ObjectSyncData.Fill(System.Array) Method", ex); } }
/// <summary> /// /// </summary> /// <param name="excelFilePath"></param> /// <returns></returns> public bool DelSheetColumnData(string excelFilePath, System.Collections.ArrayList colName) { Excel.Application myExcel = new Excel.Application(); try { if (colName == null && colName.Count == 0) { return(true); } //取得Excel文件中共有的sheet的数目 object oMissing = System.Reflection.Missing.Value; myExcel.Application.Workbooks.Open(excelFilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); Excel.Workbook myBook = myExcel.Workbooks[1]; Excel.Sheets sheets = myBook.Worksheets; Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1); Excel.Range range = worksheet.get_Range("A1", "Z1"); System.Array myvalues = (System.Array)range.Cells.Value2; Excel.Range delRange; for (int i = 1; i <= myvalues.Length; i++) { if (ISDelCol(myvalues.GetValue(1, i).ToString().Trim(), colName) != -1) { delRange = worksheet.get_Range(i, i); delRange.Delete(i); } // if (values.GetValue(1, i) != null && values.GetValue(1,i).ToString().Trim() != "" ) // theArray.Add( values.GetValue( 1, i ).ToString().Trim() ); } myExcel.Application.Workbooks.Close(); Marshal.ReleaseComObject(myExcel); return(true); } catch { Marshal.ReleaseComObject(myExcel); return(false); } }
/// <summary> /// Ge the render color of the input layer rendering with discrete color ramp. /// </summary> /// <param name="layer">Input raster layer</param> /// <param name="value">Pixel value</param> /// <returns></returns> private static IColor GetRenderColor_DiscreteColor(ILayer layer, double value) { IRasterLayer rasterLayer = (IRasterLayer)layer; // Check whether the value is NoData value IRasterProps rasterProps = (IRasterProps)rasterLayer.Raster; System.Array noDataValue = (System.Array)rasterProps.NoDataValue; if ((rasterProps.NoDataValue != null) && (Convert.ToDouble(noDataValue.GetValue(0)) == value)) { return(null); } IRasterRendererColorRamp colorRamp = (IRasterRendererColorRamp)rasterLayer.Renderer; Random rnd = new Random(); return(colorRamp.ColorRamp.Color[rnd.Next(colorRamp.ColorRamp.Size)]); }
/// <summary> /// 获取IP地址 /// </summary> /// <returns></returns> public static string GetIpAddress() { try { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { System.Array ar = (System.Array)(mo.Properties["IpAddress"].Value); return(ar.GetValue(0).ToString()); } } } catch { } return(""); }
private static List <Contractor> ReadContractorData_MaterialyOgniotrwale() { List <Contractor> MO_ContractorList = new List <Contractor>(); for (int index = 2; index <= lastRow; index++) { System.Array MyValues = (System.Array)MySheet.get_Range("A" + index.ToString(), "L" + index.ToString()).Cells.Value; List <KeyWords> MO_KeyWords = SeparateKeyWords(MyValues.GetValue(1, 12).ToString()); Contractor ContracorData = new Contractor(); ContracorData.companyType = "Materiały Ogniotrwałe"; MO_ContractorList.Add(ValidateData(MyValues, ContracorData)); } MyApp.Quit(); return(MO_ContractorList); }
public void Initialize(Object inOwner) { owner = inOwner; enumType = typeof(T); System.Array enumVals = System.Enum.GetValues(enumType); int count = enumVals.Length; stateList = new List <BasicState>(count); for (int i = 0; i < count; ++i) { object enumValue = enumVals.GetValue(i); stateList.Add(new BasicState(i, enumValue, System.Enum.GetName(enumType, enumValue))); } previousState = stateList[0]; currentState = stateList[0]; timeInState = 0.0f; }
public RecognitionToken(int id, string name, string fregex, string hexColor, NormAbstract norm, ConormAbstract conorm) { this.Norm = norm; this.Conorm = conorm; Id = id; Name = name; RegexFuzzy = new RecognitionFuzzy(fregex, norm, conorm, 0.8); Unitary = (!String.IsNullOrEmpty(fregex)) && (fregex.Length == 1); if (string.IsNullOrWhiteSpace(hexColor)) { System.Array colorsArray = Enum.GetValues(typeof(KnownColor)); this.Color = Color.FromKnownColor((KnownColor)colorsArray.GetValue((id * 10) % colorsArray.Length)); } else { this.Color = System.Drawing.ColorTranslator.FromHtml(hexColor); } }
public static IEnumerable <TResult> Cast <TResult>(this IEnumerable source) { System.Array sourceArray = source as System.Array; if (sourceArray == null) { return(System.Linq.Enumerable.Cast <TResult>(source)); } TResult[] resultArray = new TResult[sourceArray.Length]; for (int i = 0; i < sourceArray.Length; i++) { resultArray[i] = (TResult)sourceArray.GetValue(i); } return(resultArray); }
public static object FitTypeForInternalUse(object o) { Core.DeReference(ref o); // leave a null unchanged if (o == null) { return(null); } // try to convert an integer type other than int to int if (o is uint || o is long || o is ulong || o is short || o is ushort || o is byte || o is sbyte || o is bool) { return(System.Convert.ToInt32(o)); } // try to convert a floating point type other than double to double else if (o is float || o is decimal) { return(System.Convert.ToDouble(o)); } // try to convert a string type other than string to string else if (o is char) { return(System.Convert.ToString(o)); } // try to convert an array type to Array else if (o.GetType().IsArray) { System.Array arr = (System.Array)o; ArrayList keys = new ArrayList(); ArrayList values = new ArrayList(); for (int i = 0; i < arr.GetLength(0); i++) { keys.Add(i); object value = arr.GetValue(i); // resursively fit type of current value values.Add(FitTypeForInternalUse(value)); } return(new Array(keys, values)); } // otherwise leave type unchanged else { return(o); } }
// This is called when a file is opened that contains real-time data // functions or when a user types in a new formula which contains // the RTD function. public object ConnectData( int TopicID, ref System.Array Strings, ref bool GetNewValues) { // Make sure the timer has been started. if (!timer.Enabled) { timer.Start(); } // Set GetNewValues to true to indicate that new values // will be acquired. GetNewValues = true; // The array of strings passed in will be the parameters // to the RTD function in the worksheet. In our example, we're // only expecting one string - and this will be the stock name. string stockName = (string)Strings.GetValue(0); // Check to see if the requested topic is already in our // collection. If not, create a new data item to represent // it, set its TopicID from the valued passed in by Excel, // and add the item to our collection. StockData dataItem = null; if (!dataCollection.Contains(stockName)) { dataItem = new StockData(stockName); dataItem.TopicID = TopicID; dataCollection.Add(dataItem); } else { foreach (StockData sd in dataCollection) { if (sd.Name == stockName) { dataItem = sd; break; } } } return(dataItem.Price); }