Пример #1
0
        /// <summary>
        ///A test for TDictionary`2 Constructor
        ///</summary>
        public void TDictionaryConstructorTestHelper()
        {
            IEqualityComparer <TKey>      comparer = EqualityComparer <TKey> .Default;
            LazyDictionary <TKey, TValue> target   = new LazyDictionary <TKey, TValue>(comparer);

            Assert.IsTrue(target.IsEmpty);
        }
Пример #2
0
 public QREBridge(SystemArguments arguments, string topicPrefix)
 {
     arguments_ = arguments;
     if (arguments.runMode() == RunMode.LIVE)
     {
         liveSystem = arguments.liveSystem();
         monitor_   = new LiveTradeMonitor(liveSystem, arguments.symbols, topicPrefix);
     }
     else
     {
         liveSystem = null;
         monitor_   = new TradeMonitor();
     }
     each(arguments.symbols, symbol => bars_[symbol] = new BarSpud(manager));
     system    = System.create <S>(this);
     interval_ = arguments.interval();
     if (!arguments.runInNativeCurrency)
     {
         fxRates = new LazyDictionary <Symbol, SymbolSpud <Bar> >(symbol =>
                                                                  symbol.fxRateSymbol().bars(bars(symbol)).allowStaleTicks()
                                                                  );
     }
     statistics_ = new StatisticsManager(system, arguments);
     arguments.logSystemCreation();
 }
Пример #3
0
 public LocalPlayer(BattleViewer battleViewer, Player kernelPlayer, Model.Battle battle, string name)
     : base(kernelPlayer, battle, name)
 {
     this.battleViewer = battleViewer;
     gridLayoutManager = GridLayoutManager.Instance;
     availableActions  = new LazyDictionary <int, List <TargetableAction> >();
 }
Пример #4
0
        public void LazyByDefaultTest()
        {
            var lazyDictionary = new LazyDictionary <string, string>();
            var initialized    = lazyDictionary.IsInitialized;

            Assert.False(initialized);
        }
Пример #5
0
 public void LazyKeyAddTest()
 {
     var lazyDictionary = new LazyDictionary<string, string>();
     lazyDictionary["key"] = "value";
     var initialized = lazyDictionary.IsInitialized;
     Assert.True(initialized);
 }
Пример #6
0
        public void GenericLazyDictionaryTest()
        {
            LazyDictionary <string, Car> lazy = new LazyDictionary <string, Car>(LoadCar);

            Assert.AreEqual("abc", lazy["abc"].Make);
            Assert.AreEqual(null, lazy["xyz"]);
        }
Пример #7
0
        public IModelDirectory <TModelFileBundle> GatherBundles(
            IFileHierarchy fileHierarchy)
        {
            var fileHierarchyRoot  = fileHierarchy.Root;
            var rootModelDirectory =
                new ModelDirectory <TModelFileBundle>(fileHierarchy.Root.Name);

            var lazyFileHierarchyDirToBundleDir =
                new LazyDictionary <IFileHierarchyDirectory,
                                    IModelDirectory <TModelFileBundle> >(
                    (lazyDict, dir) => {
                var parent = dir.Parent != null
                                 ? lazyDict[dir.Parent]
                                 : rootModelDirectory;
                return(parent.AddSubdir(dir.Name));
            });

            lazyFileHierarchyDirToBundleDir[fileHierarchyRoot] = rootModelDirectory;

            foreach (var directory in fileHierarchy)
            {
                var bundles = handler_(directory);
                if (bundles == null)
                {
                    continue;
                }

                foreach (var bundle in bundles)
                {
                    lazyFileHierarchyDirToBundleDir[directory].AddFileBundle(bundle);
                }
            }

            return(rootModelDirectory);
        }
Пример #8
0
        public SimExchange(Simulation sim, Exchange exch, PriceDataMap price_data)
        {
            try
            {
                Debug.Assert(Model.BackTesting == true);

                Sim       = sim;
                Exchange  = exch;
                PriceData = price_data;
                m_ord     = new LazyDictionary <long, Order>(k => null);
                m_his     = new LazyDictionary <long, OrderCompleted>(k => null);
                m_bal     = new LazyDictionary <Coin, AccountBalance>(k => new AccountBalance(k, 0m._(k)));
                m_depth   = new LazyDictionary <TradePair, MarketDepth>(k => new MarketDepth(k.Base, k.Quote));
                m_rng     = null;

                // Cache settings values
                m_order_value_range = SettingsData.Settings.BackTesting.OrderValueRange;
                m_spread_frac       = SettingsData.Settings.BackTesting.SpreadFrac;
                m_orders_per_book   = SettingsData.Settings.BackTesting.OrdersPerBook;

                Exchange.Sim = this;

                Reset();
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Пример #9
0
        private FontService()
        {
            _fontCollection = new PrivateFontCollection();
            _fontFamilies   = new LazyDictionary <string, FontFamily>();

            _awesomeFontFamily = GetFontFamilyByResourceName("Vkm.Library.Resources.FontAwesome.ttf", Resources.FontAwesome);
        }
Пример #10
0
        public void GenericLazyDictionaryTest()
        {
            LazyDictionary<string, Car> lazy = new LazyDictionary<string, Car>(LoadCar);

            Assert.AreEqual("abc", lazy["abc"].Make);
            Assert.AreEqual(null, lazy["xyz"]);
        }
Пример #11
0
    public void LazyDictionaryIntListInt_LazyAssign_ListIntCreatedValueAssigned()
    {
        var lazyDictionary = new LazyDictionary <int, List <int> >();

        lazyDictionary[4].Add(5);
        Assert.IsTrue(lazyDictionary[4] != null);
        Assert.IsTrue(lazyDictionary[4].Contains(5));
    }
Пример #12
0
        public static Func <TArg, TResult> Memoize <TArg, TResult>(
            [NotNull] this Func <TArg, TResult> func,
            bool threadSafe = false)
        {
            var map = LazyDictionary.Create(func, threadSafe);

            return(arg => map[arg]);
        }
Пример #13
0
        public static Func <TArg, TResult> Memoize <TArg, TResult>(
            [NotNull] this Func <TArg, TResult> func,
            LazyThreadSafetyMode threadSafety)
        {
            var map = LazyDictionary.Create(func, threadSafety);

            return(arg => map[arg]);
        }
Пример #14
0
        public static Func <TArg1, TArg2, TResult> Memoize <TArg1, TArg2, TResult>(
            [NotNull] this Func <TArg1, TArg2, TResult> func,
            bool threadSafe = false)
        {
            var map = LazyDictionary.Create <TupleStruct <TArg1, TArg2>, TResult>(key => func(key.Item1, key.Item2), threadSafe);

            return((arg1, arg2) => map[TupleStruct.Create(arg1, arg2)]);
        }
Пример #15
0
        public static Func <TArg, TResult> Memoize <TArg, TResult>(
            [NotNull] this Func <TArg, TResult> func,
            [CanBeNull] IEqualityComparer <TArg> comparer,
            LazyThreadSafetyMode threadSafety)
        {
            var map = LazyDictionary.Create(func, comparer, threadSafety);

            return(arg => map[arg]);
        }
Пример #16
0
        public void LazyKeyAddTest()
        {
            var lazyDictionary = new LazyDictionary <string, string>();

            lazyDictionary["key"] = "value";
            var initialized = lazyDictionary.IsInitialized;

            Assert.True(initialized);
        }
Пример #17
0
        public DrawingEngine(IDevice device, ThemeOptions themeOptions, IVisualTransitionFactory visualTransitionFactory)
        {
            _device       = device;
            _themeOptions = themeOptions;

            _imagesToDevice        = new LazyDictionary <Location, LayoutDrawElement>();
            _switchedLocations     = new ConcurrentDictionary <Location, Location>();
            _visualEffectProcessor = new VisualEffectProcessor(_device, visualTransitionFactory);
        }
Пример #18
0
 static Entity()
 {
     DBHelpers              = new LazyDictionary <Type, DBHelper>();
     DBHelpers.ItemLoading += delegate(object sender, LazyItemLoadingEventArgs <Type, DBHelper> e)
     {
         e.Value   = new DBHelper(e.Key);
         e.IsFound = true;
     };
 }
Пример #19
0
        /// <summary>
        /// Clears the dialog.
        /// </summary>
        public void ClearDialog()
        {
            Dialog = new LazyDictionary <object, string>();

            if (OnClear != null)
            {
                OnClear(ClearType.DIALOG);
            }
        }
Пример #20
0
        public static Func <TArg, TResult> Memoize <TArg, TResult>(
            this Func <TArg, TResult> func,
            IEqualityComparer <TArg>?comparer,
            LazyThreadSafetyMode threadSafety)
            where TArg : notnull
        {
            var map = LazyDictionary.Create(func, comparer, threadSafety);

            return(arg => map[arg]);
        }
Пример #21
0
 public Simulator(SystemArguments args, BarLoader data, string topicPrefix)
 {
     newBarListeners     = new LazyDictionary <Symbol, Action <Bar> >(symbol => doNothing);
     this.data           = data;
     symbols             = args.symbols;
     bridge              = args.bridgeBase(topicPrefix);
     dateIndex           = 0;
     processBarComplete += doNothing;
     interval            = args.interval();
 }
Пример #22
0
 private static void StoreDateTimeOffset(string fieldName, LazyDictionary <string, ItemField> d, DateTimeOffset dt)
 {
     //store the date
     d.AddOrUpdate(fieldName, new ItemField(dt.DateTime)
     {
         DataType = FieldDataType.DateTime
     });
     //store the offset
     d.AddOrUpdate(fieldName + FixedIndexedFields.DateTimeOffsetSuffix, new ItemField(dt.Offset.TotalHours));
 }
Пример #23
0
        /// <summary>
        /// Clears the state.
        /// </summary>
        public void Clear()
        {
            Dialog       = new LazyDictionary <object, string>();
            Choices      = new List <string>();
            Consequences = new List <List <Node> >();

            if (OnClear != null)
            {
                OnClear(ClearType.ALL);
            }
        }
        public void LazyByDefaultTest()
        {
            // Arrange
            var lazyDictionary = new LazyDictionary<string, string>();

            // Act
            var initialized = lazyDictionary.IsInitialized;

            // Assert
            Assert.False(initialized);
        }
Пример #25
0
        public void LazyByDefaultTest()
        {
            // Arrange
            var lazyDictionary = new LazyDictionary <string, string>();

            // Act
            var initialized = lazyDictionary.IsInitialized;

            // Assert
            Assert.False(initialized);
        }
Пример #26
0
        public static Func <TArg1, TArg2, TArg3, TArg4, TResult> Memoize <TArg1, TArg2, TArg3, TArg4, TResult>(
            [NotNull] this Func <TArg1, TArg2, TArg3, TArg4, TResult> func,
            bool threadSafe = false)
        {
            var map =
                LazyDictionary.Create <ValueTuple <TArg1, TArg2, TArg3, TArg4>, TResult>(
                    key => func(key.Item1, key.Item2, key.Item3, key.Item4),
                    threadSafe);

            return((arg1, arg2, arg3, arg4) => map[ValueTuple.Create(arg1, arg2, arg3, arg4)]);
        }
        public void LazyAddTest()
        {
            // Arrange
            var lazyDictionary = new LazyDictionary<string, string>();

            // Act
            lazyDictionary.Add("key", "value");
            var initialized = lazyDictionary.IsInitialized;

            // Assert
            Assert.True(initialized);
        }
Пример #28
0
        public void LazyAddTest()
        {
            // Arrange
            var lazyDictionary = new LazyDictionary <string, string>();

            // Act
            lazyDictionary.Add("key", "value");
            var initialized = lazyDictionary.IsInitialized;

            // Assert
            Assert.True(initialized);
        }
Пример #29
0
        public VisualEffectProcessor(IDevice device, IVisualTransitionFactory visualTransitionFactory)
        {
            _device = device;
            _visualTransitionFactory = visualTransitionFactory;

            _disposeLock          = new object();
            _cts                  = new CancellationTokenSource();
            _transitionsAdded     = new AsyncAutoResetEvent();
            _currentTransitions   = new LazyDictionary <Location, VisualEffectInfo>();
            _scheduledTransitions = new ConcurrentQueue <LayoutDrawElement>();

            _drawTask = DrawCycle(_cts.Token);
        }
Пример #30
0
        public DeviceManager(GlobalContext globalContext, IDevice device)
        {
            _globalContext = globalContext;
            _globalContext.LayoutRemoved += OnLayoutRemoved;

            _layouts        = new Stack <ILayout>();
            _pressedButtons = new LazyDictionary <Location, ITimerToken>();

            device.ButtonEvent += DeviceOnKeyEvent;

            device.Init();
            _drawingEngine = new DrawingEngine(device, _globalContext.Options.Theme, globalContext.Services.ModulesService.GetModules <IVisualTransitionFactory>().First());
            _layoutContext = new LayoutContext(device, globalContext, SetLayout, () => SetPreviousLayout(), () => _drawingEngine.PauseDrawing(), GetAvailableLayouts);
        }
Пример #31
0
 public STOMetricResults(Path hamsterMetrics, Path hamsterParams)
 {
     info("starting read from hamster db " + hamsterMetrics);
     metricsDb.Open(hamsterMetrics.path());
     parametersDb.Open(hamsterParams.path());
     runs_              = runsFromFile(metricsDb);
     lookup             = runLookup(runs_);
     sortOrder          = sort(runs_);
     metricNames_       = metricsFromFile(metricsDb);
     parameterNames_    = parameterNamesFromFile(parametersDb);
     provider           = new STOMetricResultsTypeDescriptionProvider(new STOMetricResultsTypeDescriptor(parameterNames_, metricNames_));
     cache              = new LazyDictionary <int, RunMetrics>(emptyMetrics);
     CollectionChanged += doNothing;
 }
        public override LazyDictionary <string, ItemField> GetValue(TypedEntity source)
        {
            var d = new LazyDictionary <string, ItemField>();

            foreach (var a in source.Attributes)
            {
                if (a.Values.Count == 1)
                {
                    StoreFieldValue(a.AttributeDefinition.AttributeType.SerializationType,
                                    FixedAttributeIndexFields.AttributePrefix + a.AttributeDefinition.Alias,
                                    a.DynamicValue,
                                    d);
                }
                else if (a.Values.Count > 1)
                {
                    //we need to put multiple values in the index with dot notation
                    foreach (var val in a.Values)
                    {
                        var key = FixedAttributeIndexFields.AttributePrefix + a.AttributeDefinition.Alias + "." + val.Key;
                        StoreFieldValue(a.AttributeDefinition.AttributeType.SerializationType,
                                        key,
                                        val.Value,
                                        d);
                    }
                }

                //put attribute alias/name/id in there
                FixedAttributeIndexFields.AddAttributeAlias(d, a);
                //FixedAttributeIndexFields.AddAttributeName(d, a);
                FixedAttributeIndexFields.AddAttributeId(d, a);
            }

            //Get the parent Id.
            //TODO: We should support all relation types in some magical way
            foreach (var r in source.RelationProxies.GetParentRelations(FixedRelationTypes.DefaultRelationType))
            {
                d.AddOrUpdate(FixedIndexedFields.ParentId, new ItemField(r.Item.SourceId.Value.ToString()));
            }

            d.AddOrUpdate(FixedIndexedFields.SchemaId,
                          new Lazy <ItemField>(() => new ItemField(source.EntitySchema.Id.Value.ToString())),
                          (k, i) => new Lazy <ItemField>(() => new ItemField(source.EntitySchema.Id.Value.ToString())));
            d.Add(FixedIndexedFields.SchemaAlias, new ItemField(source.EntitySchema.Alias));
            d.AddOrUpdate(FixedIndexedFields.SchemaName, new ItemField(source.EntitySchema.Name));
            d.AddOrUpdate(FixedIndexedFields.SchemaType, new ItemField(source.EntitySchema.SchemaType));

            ExamineHelper.SetTimestampsOnEntityAndIndexFields(d, source);
            return(d);
        }
        /// <summary>
        /// Инициализирует экземпляр поставщиком данных конфигурации.
        /// </summary>
        public ConfigService(
            IEnumerable <ConfigSectionInfo> sectionInfos,
            IConfigDataProvider dataProvider,
            IDictionary <string, string> externalVars)
        {
            if (sectionInfos == null)
            {
                throw new ArgumentNullException(nameof(sectionInfos));
            }

            _sectionInfos              = sectionInfos.ToDictionary(info => info.ContractType);
            _serializer                = new ConfigSerializer(dataProvider, externalVars);
            _sections                  = LazyDictionary.Create <ConfigSectionInfo, object>(DeserializeSection, true);
            _serializer.ConfigChanged += SerializerConfigChanged;
        }
Пример #34
0
        /// <summary>
        /// Инициализирует экземпляр.
        /// </summary>
        public ServiceDataManager(string dataFolder)
        {
            if (dataFolder == null)
            {
                throw new ArgumentNullException(nameof(dataFolder));
            }

            if (!Directory.Exists(dataFolder))
            {
                Directory.CreateDirectory(dataFolder);
            }
            _dataFolder           = dataFolder;
            _notificationConsumer = new ChangeNotificationConsumer(this);
            _instances            = LazyDictionary.Create <Type, object>(CreateNewInstance, true);
        }
Пример #35
0
        public void LazyDictionaryTest()
        {
            int callcount = 0;
            LazyDictionary lazy = new LazyDictionary(
                o => {
                    callcount++;
                    string key = o.ToString();
                    if (key.StartsWith("a"))
                        return new Car { Make = key, Model = key };
                    return null;
                }
            );

            Assert.AreEqual("abc", ((Car)lazy["abc"]).Make);
            Assert.AreEqual("abc", ((Car)lazy["abc"]).Model);
            Assert.AreEqual(null, lazy["xyz"]);
            Assert.AreEqual(2, callcount);
        }
Пример #36
0
 public void LazyByDefaultTest()
 {
     var lazyDictionary = new LazyDictionary<string, string>();
     var initialized = lazyDictionary.IsInitialized;
     Assert.False(initialized);
 }
Пример #37
0
 /// <summary>
 /// 提供在需要时被调用以产生延迟初始化值的委托,初始化一个 <see cref="HeadersBase"/> 类的新实例。
 /// </summary>
 /// <param name="headersFactory">在需要时被调用以产生延迟初始化值的委托。</param>
 public HeadersBase(Func<CDictionary> headersFactory)
 {
     this._Headers = new LazyDictionary(headersFactory);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:DesktopSprites.SpriteManagement.WinFormSpriteInterface"/> class.
        /// </summary>
        /// <param name="displayBounds">The initial display boundary the interface should cover. Sprites outside this area will not be
        /// drawn.</param>
        /// <param name="useAlphaBlending">Indicates if alpha blending should be supported. If true, the transparency value in images is
        /// respected, and the color is blended with the color behind it. If false, semi-transparent values will appear opaque. Only fully
        /// transparent pixels will continue to render as transparent.</param>
        public WinFormSpriteInterface(Rectangle displayBounds, bool useAlphaBlending)
        {
            IsAlphaBlended = useAlphaBlending;
            images = new LazyDictionary<string, AnimatedImage<BitmapFrame>>(
                fileName => new AnimatedImage<BitmapFrame>(
                    fileName, BitmapFrameFromFile,
                    (b, p, tI, s, w, h, d, hC) => BitmapFrameFromBuffer(b, p, tI, s, w, h, d, hC, fileName),
                    BitmapFrame.AllowableBitDepths));
            render = new MethodInvoker(Render);
            using (var family = FontFamily.GenericSansSerif)
                font = new Font(family, 12, GraphicsUnit.Pixel);

            Thread appThread = new Thread(ApplicationRun) { Name = "WinFormSpriteInterface.ApplicationRun" };
            appThread.SetApartmentState(ApartmentState.STA);
            object appInitiated = new object();
            lock (appInitiated)
            {
                appThread.Start(Tuple.Create(appInitiated, displayBounds));
                Monitor.Wait(appInitiated);
            }
        }
Пример #39
0
 public void ResetCache()
 {
     _htmlCellCache = new LazyDictionary<int, HtmlCell>(columnIndex => (HtmlCell)_htmlTable.GetCell(RowIndex, columnIndex));
     _columnMetadataCache = new Lazy<ColumnMetadata[]>(GetColumnMetadata, LazyThreadSafetyMode.PublicationOnly);
     _defaultColumnCache = new Lazy<ColumnMetadata>(() => GetDefaultColumn(_columnMetadataCache.Value), LazyThreadSafetyMode.PublicationOnly);
 }
 /// <summary>
 /// Adds the attribute alias.
 /// </summary>
 /// <param name="d">The d.</param>
 /// <param name="ta">The ta.</param>
 public static void AddAttributeAlias(LazyDictionary<string, ItemField> d, TypedAttribute ta)
 {
     d.Add(CreateAttributeAliasField(ta.AttributeDefinition.Alias),
         new ItemField(ta.AttributeDefinition.Alias));
 }
Пример #41
0
 public void SocketsLoader(SocketQueryFactory loader) {
     _SocketsLoader = loader;
     _LazySockets = new LazyDictionary<string, SocketQuery>(_SocketsLoader);
 }
Пример #42
0
        public void CanRoundtripGenericLazyDictionary()
        {
            var dict = new LazyDictionary<string, object>()
                {
                    {"BlahKey", "Blah"},
                    {"FoodKey", "Foo"}
                };
            var json = SerializationService.ToJson(dict);
            var rehydrated = SerializationService.FromJson<LazyDictionary<string, object>>(json);

            Assert.That(dict.Count, Is.EqualTo(rehydrated.Count));
            Assert.That(dict.First().Key, Is.EqualTo(rehydrated.First().Key));
            Assert.That(dict.First().Value, Is.EqualTo(rehydrated.First().Value));
        }
 public LinearHiveIndexOperation()
 {
     Fields = new LazyDictionary<string, ItemField>();
 }
        //public static void AddAttributeName(LazyDictionary<string, ItemField> d, TypedAttribute ta)
        //{
        //    d.Add(
        //        AttributePrefix + ta.AttributeDefinition.Alias + "." + AttributeName,
        //        new ItemField(ta.AttributeDefinition.Name));
        //}

        public static void AddAttributeId(LazyDictionary<string, ItemField> d, TypedAttribute ta)
        {
            d.Add(CreateAttributeIdField(ta.AttributeDefinition.Alias),
                new Lazy<ItemField>(() => new ItemField(ta.Id.Value.ToString()))); //lazy load this id as it might not be set
        }