/////////////////////////////////////////////////////////////////////////////////////////////// #region Public Constructors public StringRandomComparer( Interpreter interpreter, bool ascending, string indexText, bool leftOnly, bool unique, CultureInfo cultureInfo, RandomNumberGenerator random, ref IntDictionary duplicates ) : this() { if (duplicates == null) { duplicates = new IntDictionary(new Custom(this, this)); } this.levels = 0; this.interpreter = interpreter; this.ascending = ascending; this.indexText = indexText; this.leftOnly = leftOnly; this.unique = unique; this.cultureInfo = cultureInfo; this.random = random; this.duplicates = duplicates; }
public void ReplacePocoObject_WithEscaping_Succeeds() { // Arrange var key1 = "Foo/Name"; var value1 = 100; var key2 = "Foo"; var value2 = 200; var model = new IntDictionary(); model.DictionaryOfStringToInteger[key1] = value1; model.DictionaryOfStringToInteger[key2] = value2; var patchDocument = new JsonPatchDocument(); patchDocument.Replace($"/DictionaryOfStringToInteger/Foo~1Name", 300); // Act patchDocument.ApplyTo(model); // Assert Assert.Equal(2, model.DictionaryOfStringToInteger.Count); var actualValue1 = model.DictionaryOfStringToInteger[key1]; var actualValue2 = model.DictionaryOfStringToInteger[key2]; Assert.Equal(300, actualValue1); Assert.Equal(200, actualValue2); }
/////////////////////////////////////////////////////////////////////////////////////////////// public static int GetDuplicateCount( /* O(N) */ IComparer <string> comparer, IntDictionary duplicates, string value ) { // // HACK: Since the ContainsKey method of the Dictionary object // insists on using both the Equals and GetHashCode methods // of the custom IEqualityComparer interface we provide // to find the key, we must resort to a linear search // because we cannot reasonably implement the GetHashCode // method in terms of the Compare method in a semantically // compatible way. // int result = 0; if ((comparer != null) && (duplicates != null) && (value != null)) { foreach (string element in duplicates.Keys) { if (comparer.Compare(element, value) == 0 /* EQUAL */) { // // NOTE: Found the key value, get the count. // result = duplicates[element]; break; } } } return(result); }
public TestContext( Interpreter interpreter, int threadId ) { this.interpreter = interpreter; this.threadId = threadId; interpreter = null; statistics = new int[(int)TestInformationType.SizeOf]; constraints = new StringList(); skipped = new StringListDictionary(); failures = new StringList(); counts = new IntDictionary(); match = new StringList(); skip = new StringList(); returnCodeMessages = TestOps.GetReturnCodeMessages(); /////////////////////////////////////////////////////////////////// #if DEBUGGER breakpoints = new StringDictionary(); #endif path = null; verbose = TestOutputType.Default; repeatCount = Count.Invalid; }
public virtual void AddBufferEntityParser(int gmuId, int appId, IFFParser parser, FFTgtParseBufferHandler action) { using (ILogMethod method = Log.LogMethod(this.DYN_MODULE_NAME, "AddBufferEntityParser")) { try { FF_FlowInitiation flowDirection = this.FlowInitiation; if (_subParsers == null) { _subParsers = new FFParserDictionary(); } if (_parserMappings == null) { _parserMappings = new IntDictionary <int>(); } if (parser != null && parser.FlowInitiation != FF_FlowInitiation.Any) { flowDirection = parser.FlowInitiation; } _subParsers.AddParserItem(flowDirection, gmuId, appId, parser, action); if (appId != -1 && !_parserMappings.ContainsKey(appId)) { _parserMappings.Add(appId, gmuId); } } catch (Exception ex) { method.Exception(ex); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// #region Public Constructors public StringSubStringComparer( Interpreter interpreter, bool ascending, string indexText, bool leftOnly, bool noCase, bool unique, CultureInfo cultureInfo, ref IntDictionary duplicates ) { if (duplicates == null) { duplicates = new IntDictionary(new Custom(this, this)); } this.levels = 0; this.interpreter = interpreter; this.ascending = ascending; this.indexText = indexText; this.leftOnly = leftOnly; this.noCase = noCase; this.unique = unique; this.cultureInfo = cultureInfo; this.duplicates = duplicates; }
/// <summary> /// Set up the server, bind to a socket. Use Start to fully start the server after running this /// </summary> /// <param name="configuration"></param> public static void InitializeServer(ServerConfiguration configuration) { Configuration = configuration; if (peer != null && peer.Status != NetPeerStatus.NotRunning) { Debug.LogError("cannot start server while already running"); return; } _netPeerConfiguration = new NetPeerConfiguration(Configuration.AppIdentifier); _netPeerConfiguration.Port = Configuration.ListenPort; _netPeerConfiguration.MaximumConnections = Configuration.MaximumConnections; connections = new IntDictionary <NetConnection>(Configuration.MaximumConnections); _netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true); peer = new NetServer(_netPeerConfiguration); peer.Start(); var serverId = connections.Add(null); var serverPlayer = new Player(); serverPlayer.Id = (ushort)serverId; Player.Server = serverPlayer; GameState.update += Update; }
/////////////////////////////////////////////////////////////////////// private static void ResetTraceCategories() { lock (syncRoot) /* TRANSACTIONAL */ { if (traceCategories != null) { traceCategories.Clear(); traceCategories = null; } } }
internal ReplaceFieldValueToDocId(bool isLong) { if (isLong) { _ReplaceFieldValueLongToDocId = new Dictionary <long, int>(); } else { _ReplaceFieldValueIntToDocId = new IntDictionary <int>(); } }
public void TestIntegerValue_IsSuccessful() { // Arrange var model = new IntDictionary(); model.DictionaryOfStringToInteger["one"] = 1; model.DictionaryOfStringToInteger["two"] = 2; var patchDocument = new JsonPatchDocument(); patchDocument.Test("/DictionaryOfStringToInteger/two", 2); // Act & Assert patchDocument.ApplyTo(model); }
public void MoveIntegerValue_Succeeds() { // Arrange var model = new IntDictionary(); model.DictionaryOfStringToInteger["one"] = 1; model.DictionaryOfStringToInteger["two"] = 2; var patchDocument = new JsonPatchDocument(); patchDocument.Move("/DictionaryOfStringToInteger/one", "/DictionaryOfStringToInteger/two"); // Act patchDocument.ApplyTo(model); // Assert Assert.Equal(1, model.DictionaryOfStringToInteger.Count); Assert.Equal(1, model.DictionaryOfStringToInteger["two"]); }
/////////////////////////////////////////////////////////////////////// private static void SetTraceCategories( IEnumerable <string> categories, int value ) { lock (syncRoot) /* TRANSACTIONAL */ { // // NOTE: If the dictionary of "allowed" trace categories has // not been created yet, do so now. // if (traceCategories == null) { traceCategories = new IntDictionary(); } // // NOTE: If there are no trace categories specified, the trace // category dictionary may be created; however, it will // not be added to. // if (categories != null) { foreach (string category in categories) { // // NOTE: Skip null categories. // if (category == null) { continue; } // // NOTE: Add or modify the trace category. // traceCategories[category] = value; } } } }
/////////////////////////////////////////////////////////////////////////////////////////////// public static bool SetDuplicateCount( /* O(N) */ IComparer <string> comparer, IntDictionary duplicates, string value, int count ) { // // HACK: Since the ContainsKey method of the Dictionary object // insists on using both the Equals and GetHashCode methods // of the custom IEqualityComparer interface we provide // to find the key, we must resort to a linear search // because we cannot reasonably implement the GetHashCode // method in terms of the Compare method in a semantically // compatible way. // if ((comparer != null) && (duplicates != null) && (value != null)) { foreach (string element in duplicates.Keys) { if (comparer.Compare(element, value) == 0 /* EQUAL */) { // // NOTE: Found the key value, set the count. // duplicates[element] = count; return(true); } } // // NOTE: The value was not found in the dictionary, // add it now. // duplicates.Add(value, count); return(true); } return(false); }
public virtual Mesh ToMesh() { Mesh mesh = new Mesh(); mesh.name = Name; List <Vector3> pVertices = new List <Vector3>(); List <Vector3> pNormals = new List <Vector3>(); List <Vector2> pUVs = new List <Vector2>(); List <List <int> > pIndices = new List <List <int> >(); IDictionary <int, int> map = new IntDictionary <int>(); HashSet <string> materials = new HashSet <string>(); foreach (KeyValuePair <string, List <OBJFace> > facesPerMat in Faces) { string mat = facesPerMat.Key; List <OBJFace> faces = facesPerMat.Value; if (faces.Count == 0) { continue; } List <int> indices = new List <int>(); for (int fi = 0; fi < faces.Count; fi++) { OBJFace face = faces[fi]; indices.Add(face[0]); indices.Add(face[1]); indices.Add(face[2]); } if (!materials.Contains(mat)) { materials.Add(mat); mesh.subMeshCount++; } for (int ii = 0; ii < indices.Count; ii++) { int index = indices[ii]; if (map.ContainsKey(index)) { indices[ii] = map[index]; } else { indices[ii] = map[index] = pVertices.Count; pVertices.Add(UVertices[index]); pNormals.Add(UNormals[index]); pUVs.Add(UUVs[index]); } } pIndices.Add(indices); } mesh.SetVertices(pVertices); mesh.SetNormals(pNormals); mesh.SetUVs(0, pUVs); for (int i = 0; i < pIndices.Count; i++) { mesh.SetTriangles(pIndices[i], i); } if (!ContainsNormals) { mesh.RecalculateNormals(); } mesh.RecalculateBounds(); mesh.Optimize(); return(mesh); }
private void Destroy() { RPCProcessors = null; FieldProcessors = null; Destroy(gameObject); }
/////////////////////////////////////////////////////////////////////// private /* protected virtual */ void Dispose( bool disposing ) { TraceOps.DebugTrace(String.Format( "Dispose: disposing = {0}, interpreter = {1}, disposed = {2}", disposing, FormatOps.InterpreterNoThrow(interpreter), disposed), typeof(TestContext).Name, TracePriority.CleanupDebug); if (!disposed) { if (disposing) { //////////////////////////////////// // dispose managed resources here... //////////////////////////////////// interpreter = null; /* NOT OWNED: Do not dispose. */ threadId = 0; /////////////////////////////////////////////////////////// targetInterpreter = null; /* NOT OWNED: Do not dispose. */ /////////////////////////////////////////////////////////// statistics = null; /////////////////////////////////////////////////////////// if (constraints != null) { constraints.Clear(); constraints = null; } /////////////////////////////////////////////////////////// if (failures != null) { failures.Clear(); failures = null; } /////////////////////////////////////////////////////////// if (counts != null) { counts.Clear(); counts = null; } /////////////////////////////////////////////////////////// if (match != null) { match.Clear(); match = null; } /////////////////////////////////////////////////////////// if (skip != null) { skip.Clear(); skip = null; } /////////////////////////////////////////////////////////// if (returnCodeMessages != null) { returnCodeMessages.Clear(); returnCodeMessages = null; } /////////////////////////////////////////////////////////// #if DEBUGGER if (breakpoints != null) { breakpoints.Clear(); breakpoints = null; } #endif /////////////////////////////////////////////////////////// path = null; verbose = TestOutputType.None; repeatCount = 0; } ////////////////////////////////////// // release unmanaged resources here... ////////////////////////////////////// disposed = true; } }
public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { ReturnCode code = ReturnCode.Ok; if (interpreter != null) { if (arguments != null) { if (arguments.Count >= 2) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, 1, Index.Invalid, "-ascii", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-dictionary", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-integer", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-real", null), new Option(null, OptionFlags.None, 2, Index.Invalid, "-decreasing", null), new Option(null, OptionFlags.None, 2, Index.Invalid, "-increasing", null), new Option(null, OptionFlags.None, 3, Index.Invalid, "-exact", null), new Option(null, OptionFlags.None, 3, Index.Invalid, "-substring", null), new Option(null, OptionFlags.None, 3, Index.Invalid, "-glob", null), new Option(null, OptionFlags.None, 3, Index.Invalid, "-regexp", null), new Option(null, OptionFlags.None, 3, Index.Invalid, "-sorted", null), // NOTE: Implies "-exact" new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-variable", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-inverse", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-subindices", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-all", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-inline", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nocase", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-not", null), new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-start", null), new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-index", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 2) == arguments.Count)) { StringList list = null; /////////////////////////////////////////////////////////////////////// // // HACK: *PERF* This option enables an optimization that allows us to // use the cached list representation for a particular script // variable, if any, instead of re-parsing the string. If this // option is enabled, the first non-option argument is NOT the // list to search; rather, it is the variable name containing // the list to search. // bool isVariable = false; if (options.IsPresent("-variable")) { isVariable = true; } if (isVariable) { /* IGNORED */ interpreter.GetListVariableValue( VariableFlags.None, arguments[argumentIndex], false, true, true, ref list); } /////////////////////////////////////////////////////////////////////// // // NOTE: If no list representation is available, then parse the first // non-option argument string into a list. // if (list == null) { code = Parser.SplitList( interpreter, arguments[argumentIndex], 0, Length.Invalid, true, ref list, ref result); } if (code == ReturnCode.Ok) { Variant value = null; string indexText = null; if (options.IsPresent("-index", ref value)) { indexText = value.ToString(); } bool inverse = false; if (options.IsPresent("-inverse")) { inverse = true; } bool subIndexes = false; if (options.IsPresent("-subindices")) { subIndexes = true; } if ((indexText != null) || !subIndexes) { string start = null; if (options.IsPresent("-start", ref value)) { start = value.ToString(); } int startIndex = Index.Invalid; if (start != null) { code = Value.GetIndex( start, list.Count, ValueFlags.AnyIndex, interpreter.CultureInfo, ref startIndex, ref result); } if (code == ReturnCode.Ok) { bool all = false; if (options.IsPresent("-all")) { all = true; } bool inline = false; if (options.IsPresent("-inline")) { inline = true; } if (startIndex < list.Count) { if (startIndex < 0) { startIndex = 0; } bool ascending = true; // FIXME: PRI 5: Default handling. if (options.IsPresent("-decreasing")) { ascending = false; } else if (options.IsPresent("-increasing")) { ascending = true; } MatchMode mode = StringOps.DefaultMatchMode; bool sorted = false; if (options.IsPresent("-sorted")) { mode = MatchMode.Exact; sorted = true; } else if (options.IsPresent("-exact")) { mode = MatchMode.Exact; } else if (options.IsPresent("-substring")) { mode = MatchMode.SubString; } else if (options.IsPresent("-regexp")) { mode = MatchMode.RegExp; } else if (options.IsPresent("-glob")) { mode = MatchMode.Glob; } bool noCase = false; if (options.IsPresent("-nocase")) { noCase = true; } bool not = false; if (options.IsPresent("-not")) { not = true; } IntDictionary duplicates = null; IComparer <string> comparer = null; if (options.IsPresent("-exact") || options.IsPresent("-sorted")) { if (options.IsPresent("-dictionary")) { comparer = new _Comparers.StringDictionaryComparer( interpreter, ascending, indexText, true, false, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-integer")) { comparer = new _Comparers.StringIntegerComparer( interpreter, ascending, indexText, true, false, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-real")) { comparer = new _Comparers.StringRealComparer( interpreter, ascending, indexText, true, false, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-ascii") || true) // FIXME: PRI 5: Default handling. { // // NOTE: Check for things that the .NET Framework will not do by // default (via String.Compare). // if (!ascending || (indexText != null) || noCase) { comparer = new _Comparers.StringAsciiComparer( interpreter, ascending, indexText, true, noCase, false, interpreter.CultureInfo, ref duplicates); } } } else if (options.IsPresent("-regexp")) { comparer = new _Comparers.StringRegexpComparer( interpreter, ascending, indexText, true, noCase, false, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-substring")) { comparer = new _Comparers.StringSubStringComparer( interpreter, ascending, indexText, true, noCase, false, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-glob") || true) // FIXME: PRI 5: Default handling. { comparer = new _Comparers.StringGlobComparer( interpreter, ascending, indexText, true, noCase, false, interpreter.CultureInfo, ref duplicates); } try { string pattern = arguments[argumentIndex + 1]; int listIndex = Index.Invalid; StringList matches = all ? new StringList() : null; if (sorted && ((indexText == null) || (comparer != null)) && !all && !not && !inverse) { // // NOTE: Use the built-in binary search with the selected comparer. // listIndex = list.BinarySearch(startIndex, list.Count - startIndex, pattern, comparer); if (listIndex < 0) { listIndex = Index.Invalid; } } else if ((comparer != null) || all || not || inverse) { // // NOTE: Some custom handling is required, use the selected comparer // and options. // for (int searchIndex = startIndex; searchIndex < list.Count; searchIndex++) { // // NOTE: If we have a comparer object, use it; otherwise, use our // fallback matching routine. // bool match; if (inverse) { if (comparer != null) { match = (comparer.Compare(pattern, list[searchIndex]) == 0); } else { match = StringOps.Match(interpreter, mode, pattern, list[searchIndex], noCase); } } else { if (comparer != null) { match = (comparer.Compare(list[searchIndex], pattern) == 0); } else { match = StringOps.Match(interpreter, mode, list[searchIndex], pattern, noCase); } } // // NOTE: Do we want to consider this to be a match? // if ((match && !not) || (!match && not)) { if (all) { if (inline) { if (subIndexes) { string subValue = null; code = ListOps.SelectFromSubList( interpreter, list[searchIndex], indexText, false, interpreter.CultureInfo, ref subValue, ref result); if (code != ReturnCode.Ok) { break; } matches.Add(subValue); } else { matches.Add(list[searchIndex]); } } else { if (subIndexes) { IntList indexList = new IntList(new int[] { searchIndex }); code = ListOps.SelectFromSubList( interpreter, list[searchIndex], indexText, false, interpreter.CultureInfo, ref indexList, ref result); if (code != ReturnCode.Ok) { break; } matches.Add(indexList.ToString()); } else { matches.Add(searchIndex.ToString()); } } } else { listIndex = searchIndex; break; } } } } else { // // NOTE: No special handling required, use built-in find routine. // listIndex = list.IndexOf(pattern, startIndex); } // // NOTE: Make sure nothing in the search loop failed. // if (code == ReturnCode.Ok) { // // NOTE: Handle the result(s) of the search and build the result. // if (all) { // // NOTE: This may be an empty list. // result = matches; } else { if (listIndex != Index.Invalid) { // // NOTE: Match found, returning index or value, based on // "-inline" option. // if (inline) { result = list[listIndex]; } else { if (subIndexes) { IntList indexList = new IntList(new int[] { listIndex }); code = ListOps.SelectFromSubList( interpreter, list[listIndex], indexText, false, interpreter.CultureInfo, ref indexList, ref result); if (code == ReturnCode.Ok) { result = indexList.ToString(); } } else { result = listIndex; } } } else { // // NOTE: Match not found, returning invalid index or empty // value, based on "-inline" option. // if (inline) { result = String.Empty; } else { result = Index.Invalid; } } } } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); if (e.InnerException != null) { result = e.InnerException.Message; } else if (e is ScriptException) { result = e.Message; } else { result = e; } code = ReturnCode.Error; } } else { if (all || inline) { result = String.Empty; } else { result = Index.Invalid; } } } } else { result = "-subindices cannot be used without -index option"; code = ReturnCode.Error; } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption(options, arguments[argumentIndex]); } else { result = "wrong # args: should be \"lsearch ?options? list pattern\""; } code = ReturnCode.Error; } } } else { result = "wrong # args: should be \"lsearch ?options? list pattern\""; code = ReturnCode.Error; } } else { result = "invalid argument list"; code = ReturnCode.Error; } } else { result = "invalid interpreter"; code = ReturnCode.Error; } return(code); }
public void MyTestInitialize() { _target = new IntDictionary<object>(); }
public void MyTestCleanup() { _target = null; }
/// <summary> /// Set up the server, bind to a socket. Use Start to fully start the server after running this /// </summary> /// <param name="configuration"></param> public static void InitializeServer(ServerConfiguration configuration) { Configuration = configuration; if (peer != null && peer.Status != NetPeerStatus.NotRunning) { Debug.LogError("cannot start server while already running"); return; } _netPeerConfiguration = new NetPeerConfiguration(Configuration.AppIdentifier); _netPeerConfiguration.Port = Configuration.ListenPort; _netPeerConfiguration.MaximumConnections = Configuration.MaximumConnections; connections = new IntDictionary<NetConnection>(Configuration.MaximumConnections); _netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true); peer = new NetServer(_netPeerConfiguration); peer.Start(); var serverId = connections.Add(null); var serverPlayer = new Player(); serverPlayer.Id = (ushort)serverId; Player.Server = serverPlayer; GameState.update += Update; }
public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { ReturnCode code = ReturnCode.Ok; if (interpreter != null) { if (arguments != null) { if (arguments.Count >= 2) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.None, 1, Index.Invalid, "-ascii", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-dictionary", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-integer", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-random", null), new Option(null, OptionFlags.None, 1, Index.Invalid, "-real", null), new Option(null, OptionFlags.None, 2, Index.Invalid, "-increasing", null), new Option(null, OptionFlags.None, 2, Index.Invalid, "-decreasing", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nocase", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-unique", null), new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-command", null), new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-index", null) // NOTE: Of sub-lists, not list. }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions(options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if ((argumentIndex != Index.Invalid) && ((argumentIndex + 1) == arguments.Count)) { StringList list = null; // // WARNING: Cannot cache list representation here, the list // is modified below. // code = Parser.SplitList( interpreter, arguments[argumentIndex], 0, Length.Invalid, false, ref list, ref result); if (code == ReturnCode.Ok) { Variant value = null; string indexText = null; if (options.IsPresent("-index", ref value)) { indexText = value.ToString(); } bool ascending = true; // FIXME: PRI 5: Default handling. if (options.IsPresent("-decreasing")) { ascending = false; } else if (options.IsPresent("-increasing")) { ascending = true; } bool noCase = false; if (options.IsPresent("-nocase")) { noCase = true; } bool unique = false; if (options.IsPresent("-unique")) { unique = true; } IntDictionary duplicates = null; IComparer <string> comparer = null; if (options.IsPresent("-command", ref value)) { StringList callbackArguments = null; if (value.IsList()) { callbackArguments = (StringList)value.Value; } else { string temporary = value.ToString(); code = Parser.SplitList( interpreter, temporary, 0, Length.Invalid, true, ref callbackArguments); } if (code == ReturnCode.Ok) { ICallback callback = CommandCallback.Create( MarshalFlags.Default, CallbackFlags.Default, ObjectFlags.Callback, ByRefArgumentFlags.None, interpreter, _Public.ClientData.Empty, null, callbackArguments, ref result); if (callback != null) { comparer = new _Comparers.StringCommandComparer( interpreter, callback, ascending, indexText, false, unique, interpreter.CultureInfo, ref duplicates); } else { code = ReturnCode.Error; } } } else if (options.IsPresent("-dictionary")) { comparer = new _Comparers.StringDictionaryComparer( interpreter, ascending, indexText, false, unique, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-integer")) { comparer = new _Comparers.StringIntegerComparer( interpreter, ascending, indexText, false, unique, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-random")) { comparer = new _Comparers.StringRandomComparer( interpreter, ascending, indexText, false, unique, interpreter.CultureInfo, interpreter.RandomNumberGenerator, ref duplicates); } else if (options.IsPresent("-real")) { comparer = new _Comparers.StringRealComparer( interpreter, ascending, indexText, false, unique, interpreter.CultureInfo, ref duplicates); } else if (options.IsPresent("-ascii") || true) // FIXME: PRI 5: Default handling. { comparer = new _Comparers.StringAsciiComparer( interpreter, ascending, indexText, false, noCase, unique, interpreter.CultureInfo, ref duplicates); } if (code == ReturnCode.Ok) { try { lock (interpreter.SyncRoot) /* TRANSACTIONAL */ { if (comparer != null) { list.Sort(comparer); } else { // // FIXME: This will never be hit because we always default // to using the StringAsciiComparer (above). // list.Sort(); // use .NET Framework defaults } } // // NOTE: If we are in unique mode, remove any duplicates from // the final resulting list now. // if (unique) { StringList uniqueList = new StringList(); // // NOTE: Process each element in the list to see if it has // been counted as a duplicate value by the comparer. // // If the value has not been added to the final resulting // list yet, add it now and mark the value so that it will // never be added again (i.e. we only want the first value // from every group of duplicates and we want all the other // values as well). // // HACK: In the worst possible case, this loop can have a runtime // of O(N^2), including called functions, primarily due to // the inability of .NET to provide proper context to // IComparer callbacks. This code could be avoided entirely // if there was an interface for sorting comparison callbacks // that provided the indexes of the elements being compared // in addition to their values. // foreach (string element in list) /* O(N) */ { // // NOTE: Has this value been marked as having been previously // added to the final resulting list? // int count = ListOps.GetDuplicateCount(comparer, duplicates, element); if (count != Count.Invalid) { // // NOTE: Add this element into the final resulting list. // Either it has no duplicates or we have not yet // added it to the final resulting list. // uniqueList.Add(element); // // NOTE: If this value had any duplicates, mark the value // as having been added to the final resulting list. // if (!ListOps.SetDuplicateCount(comparer, duplicates, element, Count.Invalid)) { result = String.Format( "failed to update duplicate count for element \"{0}\"", element); code = ReturnCode.Error; break; } } } // // NOTE: The list of unique elements is now the result. // if (code == ReturnCode.Ok) { list = uniqueList; } } if (code == ReturnCode.Ok) { result = list; } } catch (Exception e) { Engine.SetExceptionErrorCode(interpreter, e); if (e.InnerException != null) { result = e.InnerException.Message; } else if (e is ScriptException) { result = e.Message; } else { result = e; } code = ReturnCode.Error; } } } } else { if ((argumentIndex != Index.Invalid) && Option.LooksLikeOption(arguments[argumentIndex])) { result = OptionDictionary.BadOption(options, arguments[argumentIndex]); } else { result = "wrong # args: should be \"lsort ?options? list\""; } code = ReturnCode.Error; } } } else { result = "wrong # args: should be \"lsort ?options? list\""; code = ReturnCode.Error; } } else { result = "invalid argument list"; code = ReturnCode.Error; } } else { result = "invalid interpreter"; code = ReturnCode.Error; } return(code); }
/////////////////////////////////////////////////////////////////////////////////////////////// public static void UpdateDuplicateCount( /* 2 * O(N) */ IComparer <string> comparer, IntDictionary duplicates, string left, string right, bool unique, int result, ref int levels ) /* throw */ { if (unique && (result == 0 /* EQUAL */)) { if ((duplicates != null) && (left != null) && (right != null)) { // // NOTE: Skip instances where the sort algorithm is actually // having us compare the exact same string. // if (!Object.ReferenceEquals(left, right)) { // // NOTE: Only continue if we are not already processing // duplicate counts already. // if (Interlocked.Increment(ref levels) == 1) { try { // // NOTE: Search for all the list elements that are duplicates // of the left element. This is an O(N) operation in // the worst case (i.e. if every element in the list is // a duplicate of the provided left element). // int count = GetDuplicateCount(comparer, duplicates, left); if (count != Count.Invalid) { // // NOTE: Set the duplicate count of the first list element // that is a duplicate of the provided left element. // This is an O(N) operation in the worst case (i.e. // if the last element in the list is the first // duplicate of the provided left element). // if (!SetDuplicateCount(comparer, duplicates, left, ++count)) { throw new ScriptException(String.Format( "failed to update duplicate count for element \"{0}\"", left)); } } } finally { // // NOTE: Even if we are throwing an exception, we want // to keep the number of active levels at the // correct value. // Interlocked.Decrement(ref levels); } } else { // // NOTE: When we incremented the number of active levels it // resulted in a value higher than one; notwithstanding // that state of affairs, we still need to decremenet // the number of active levels because we did successfully // increment it. // Interlocked.Decrement(ref levels); } } } } }
public void IntDictionaryComparisonTest() { const int TestSize = 10000000; var intDic = new IntDictionary <MockObject>(32); var dic = new Dictionary <int, MockObject>(32); //jit shit. var add = new MockObject(); add.Id = intDic.Add(add); foreach (var kvp in intDic) { kvp.DoNothing(); } intDic.Remove(add.Id); add.Id = 0; dic.Add(add.Id, add); foreach (var kvp in dic) { kvp.Value.DoNothing(); } dic.Remove(add.Id); Stopwatch watch = new Stopwatch(); watch.Reset(); //the real tests watch.Start(); for (int i = 0; i < TestSize; i++) { var foo = new MockObject(); foo.Id = intDic.Add(foo); } watch.Stop(); Debug.WriteLine("IntDic add: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < TestSize; i++) { var foo = new MockObject(); foo.Id = i; dic.Add(i, foo); } watch.Stop(); Debug.WriteLine("Dic add: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in intDic) { if (kvp != null) { kvp.DoNothing(); } } watch.Stop(); Debug.WriteLine("Intdic foreach: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in dic) { kvp.Value.DoNothing(); } watch.Stop(); Debug.WriteLine("Dic foreach: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < intDic.Capacity; i++) { MockObject value; if (intDic.TryGetValue(i, out value)) { value.DoNothing(); } } watch.Stop(); Debug.WriteLine("Intdic for: {0}", watch.Elapsed); watch.Reset(); const int halfSize = TestSize / 2; watch.Start(); for (int i = 0; i < halfSize; i++) { intDic.Remove(i); } watch.Stop(); Debug.WriteLine("Intdic remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < halfSize; i++) { dic.Remove(i); } watch.Stop(); Debug.WriteLine("dic remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in intDic) { if (kvp != null) { kvp.DoNothing(); } } watch.Stop(); Debug.WriteLine("intdic foreach after remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in dic) { kvp.Value.DoNothing(); } watch.Stop(); Debug.WriteLine("dic foreach after remove: {0}", watch.Elapsed); watch.Reset(); }
public static void Assert() { Assert(new KeyClassComparer().Equals(new KeyClass(1, 2, 3), new KeyClass(1, 2, 3))); Assert(!new KeyClassComparer().Equals(new KeyClass(3, 2, 1), new KeyClass(1, 2, 3))); Assert(new KeyClassComparer().GetHashCode(new KeyClass(1, 2, 3)) == new KeyClassComparer().GetHashCode(new KeyClass(1, 2, 3))); Assert(new KeyClassComparer().GetHashCode(new KeyClass(3, 2, 1)) != new KeyClassComparer().GetHashCode(new KeyClass(1, 2, 3))); Assert(new KeyStructComparer().Equals(new KeyStruct(1, 2, 3), new KeyStruct(1, 2, 3))); Assert(!new KeyStructComparer().Equals(new KeyStruct(3, 2, 1), new KeyStruct(1, 2, 3))); Assert(new KeyStructComparer().GetHashCode(new KeyStruct(1, 2, 3)) == new KeyStructComparer().GetHashCode(new KeyStruct(1, 2, 3))); Assert(new KeyStructComparer().GetHashCode(new KeyStruct(3, 2, 1)) != new KeyStructComparer().GetHashCode(new KeyStruct(1, 2, 3))); Assert(new KeyStructProperties(1, 2, 3).Equals(new KeyStructProperties(1, 2, 3))); Assert(!new KeyStructProperties(3, 2, 1).Equals(new KeyStructProperties(1, 2, 3))); Assert(new KeyStruct(1, 2, 3).Equals(new KeyStruct(1, 2, 3))); Assert(!new KeyStruct(3, 2, 1).Equals(new KeyStruct(1, 2, 3))); Assert(new KeyStructTightlyPacked(1, 2, 3).Equals(new KeyStructTightlyPacked(1, 2, 3))); Assert(!new KeyStructTightlyPacked(3, 2, 1).Equals(new KeyStructTightlyPacked(1, 2, 3))); Assert(new KeyStructNotTightlyPacked(1, 2, 3).Equals(new KeyStructNotTightlyPacked(1, 2, 3))); Assert(!new KeyStructNotTightlyPacked(3, 2, 1).Equals(new KeyStructNotTightlyPacked(1, 2, 3))); Assert(new KeyStructEquals(1, 2, 3).Equals(new KeyStructEquals(1, 2, 3))); Assert(!new KeyStructEquals(3, 2, 1).Equals(new KeyStructEquals(1, 2, 3))); Assert(new KeyStructEquals(1, 2, 3).GetHashCode() == new KeyStructEquals(1, 2, 3).GetHashCode()); Assert(new KeyStructEquals(3, 2, 1).GetHashCode() != new KeyStructEquals(1, 2, 3).GetHashCode()); Assert(new KeyStructEquatableManual(1, 2, 3).Equals(new KeyStructEquatableManual(1, 2, 3))); Assert(!new KeyStructEquatableManual(3, 2, 1).Equals(new KeyStructEquatableManual(1, 2, 3))); Assert(new KeyStructEquatableManual(1, 2, 3).GetHashCode() == new KeyStructEquatableManual(1, 2, 3).GetHashCode()); Assert(new KeyStructEquatableManual(3, 2, 1).GetHashCode() != new KeyStructEquatableManual(1, 2, 3).GetHashCode()); Assert(new KeyStructEquatableValueTuple(1, 2, 3).Equals(new KeyStructEquatableValueTuple(1, 2, 3))); Assert(!new KeyStructEquatableValueTuple(3, 2, 1).Equals(new KeyStructEquatableValueTuple(1, 2, 3))); var intDictionaryInt = new IntDictionary <int>(); intDictionaryInt[1] = int.MaxValue; intDictionaryInt[2] = int.MaxValue; intDictionaryInt[3] = int.MaxValue; intDictionaryInt[1] = 100; intDictionaryInt[2] = 200; intDictionaryInt[3] = 300; Assert(intDictionaryInt[1] == 100); Assert(intDictionaryInt[2] == 200); Assert(intDictionaryInt[3] == 300); var equatableDictionaryInt = new EquatableDictionary <int, int>(); equatableDictionaryInt[1] = int.MaxValue; equatableDictionaryInt[2] = int.MaxValue; equatableDictionaryInt[3] = int.MaxValue; equatableDictionaryInt[1] = 100; equatableDictionaryInt[2] = 200; equatableDictionaryInt[3] = 300; Assert(equatableDictionaryInt[1] == 100); Assert(equatableDictionaryInt[2] == 200); Assert(equatableDictionaryInt[3] == 300); var equatableDictionaryKey = new EquatableDictionary <KeyStructEquatableManual, int>(); equatableDictionaryKey[new KeyStructEquatableManual(1, 1, 1)] = int.MaxValue; equatableDictionaryKey[new KeyStructEquatableManual(2, 2, 2)] = int.MaxValue; equatableDictionaryKey[new KeyStructEquatableManual(3, 3, 3)] = int.MaxValue; equatableDictionaryKey[new KeyStructEquatableManual(1, 1, 1)] = 100; equatableDictionaryKey[new KeyStructEquatableManual(2, 2, 2)] = 200; equatableDictionaryKey[new KeyStructEquatableManual(3, 3, 3)] = 300; Assert(equatableDictionaryKey[new KeyStructEquatableManual(1, 1, 1)] == 100); Assert(equatableDictionaryKey[new KeyStructEquatableManual(2, 2, 2)] == 200); Assert(equatableDictionaryKey[new KeyStructEquatableManual(3, 3, 3)] == 300); }
public void IntDictionaryComparisonTest() { const int TestSize = 10000000; var intDic = new IntDictionary<MockObject>(32); var dic = new Dictionary<int, MockObject>(32); //jit shit. var add = new MockObject(); add.Id = intDic.Add(add); foreach (var kvp in intDic) { kvp.DoNothing(); } intDic.Remove(add.Id); add.Id = 0; dic.Add(add.Id, add); foreach (var kvp in dic) { kvp.Value.DoNothing(); } dic.Remove(add.Id); Stopwatch watch = new Stopwatch(); watch.Reset(); //the real tests watch.Start(); for (int i = 0; i < TestSize; i++) { var foo = new MockObject(); foo.Id = intDic.Add(foo); } watch.Stop(); Debug.WriteLine("IntDic add: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < TestSize; i++) { var foo = new MockObject(); foo.Id = i; dic.Add(i, foo); } watch.Stop(); Debug.WriteLine("Dic add: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in intDic) { if (kvp != null) kvp.DoNothing(); } watch.Stop(); Debug.WriteLine("Intdic foreach: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in dic) { kvp.Value.DoNothing(); } watch.Stop(); Debug.WriteLine("Dic foreach: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < intDic.Capacity; i++) { MockObject value; if (intDic.TryGetValue(i, out value)) value.DoNothing(); } watch.Stop(); Debug.WriteLine("Intdic for: {0}", watch.Elapsed); watch.Reset(); const int halfSize = TestSize / 2; watch.Start(); for (int i = 0; i < halfSize; i++) { intDic.Remove(i); } watch.Stop(); Debug.WriteLine("Intdic remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); for (int i = 0; i < halfSize; i++) { dic.Remove(i); } watch.Stop(); Debug.WriteLine("dic remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in intDic) { if (kvp != null) kvp.DoNothing(); } watch.Stop(); Debug.WriteLine("intdic foreach after remove: {0}", watch.Elapsed); watch.Reset(); watch.Start(); foreach (var kvp in dic) { kvp.Value.DoNothing(); } watch.Stop(); Debug.WriteLine("dic foreach after remove: {0}", watch.Elapsed); watch.Reset(); }
/////////////////////////////////////////////////////////////////////// #region IExecute Members public override ReturnCode Execute( Interpreter interpreter, IClientData clientData, ArgumentList arguments, ref Result result ) { ReturnCode code; if (arguments.Count >= 2) { OptionDictionary options = new OptionDictionary( new IOption[] { new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-path", null), new Option(null, OptionFlags.MustHaveValue, Index.Invalid, Index.Invalid, "-directory", null), new Option(null, OptionFlags.MustHaveListValue, Index.Invalid, Index.Invalid, "-types", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-join", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-tails", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-nocomplain", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, "-noerror", null), new Option(null, OptionFlags.None, Index.Invalid, Index.Invalid, Option.EndOfOptions, null) }); int argumentIndex = Index.Invalid; code = interpreter.GetOptions( options, arguments, 0, 1, Index.Invalid, false, ref argumentIndex, ref result); if (code == ReturnCode.Ok) { if (argumentIndex != Index.Invalid) { Variant value = null; string pathPrefix = null; if (options.IsPresent("-path", ref value)) { pathPrefix = value.ToString(); } string directory = null; if (options.IsPresent("-directory", ref value)) { directory = value.ToString(); } IntDictionary types = new IntDictionary(); if (options.IsPresent("-types", ref value)) { types = new IntDictionary((StringList)value.Value); } bool join = false; if (options.IsPresent("-join")) { join = true; } bool tailOnly = false; if (options.IsPresent("-tails")) { tailOnly = true; } bool strict = true; if (options.IsPresent("-nocomplain")) { strict = false; } bool noError = false; if (options.IsPresent("-noerror")) { noError = true; } if ((pathPrefix == null) || (directory == null)) { if (!tailOnly || (pathPrefix != null) || (directory != null)) { StringList patterns = new StringList( arguments, argumentIndex); StringList fileNames = FileOps.GlobFiles( interpreter, patterns, types, pathPrefix, directory, join, tailOnly, strict, ref result); if (fileNames != null) { result = fileNames; code = ReturnCode.Ok; } else if (!noError) { code = ReturnCode.Error; } else { result = String.Empty; code = ReturnCode.Ok; } } else { result = "\"-tails\" must be used with either \"-directory\" or \"-path\""; code = ReturnCode.Error; } } else { result = "\"-path\" cannot be used with \"-directory\""; code = ReturnCode.Error; } } else { result = "wrong # args: should be \"glob ?options? pattern ?pattern ...?\""; code = ReturnCode.Error; } } } else { result = "wrong # args: should be \"glob ?options? pattern ?pattern ...?\""; code = ReturnCode.Error; } return(code); }
public void MyTestInitialize() { _target = new IntDictionary <MockObject>(); }