示例#1
0
 /// <summary>
 /// 指定文件写入刷入缓存。
 /// </summary>
 /// <param name="filePath">文件路径</param>
 public void FileSave(string filePath)
 {
     try
     {
         if (!_fileWriteDic.ContainsKey(filePath))
         {
             return;
         }
         // 刷新日志到内存
         _fileWriteDic[filePath].Flush();
         // 超过10分钟未活动,关闭文件句柄
         if (_fileWriteDic[filePath].LastActivityTime.AddMinutes(10) >= DateTime.Now)
         {
             return;
         }
         FileWriter write;
         if (_fileWriteDic.TryRemove(filePath, out write))
         {
             write.Dispose();
         }
     }
     catch (Exception ex)
     {
         if (_exceptionCallback != null)
         {
             _exceptionCallback(ex);
         }
     }
 }
示例#2
0
        /// <summary>重置一个表的ID</summary>
        /// <param name="tableName">表名</param>
        /// <param name="colName">列名</param>
        /// <param name="val">为null时直接删除这个表和这个列的ID生成控制</param>
        /// <returns></returns>
        public void ResetID(string tableName, string colName, int?val)
        {
            string key     = GeneKey(tableName, colName);
            object lockobj = GetLock(tableName, colName);

            lock (lockobj)
            {
                if (val == null)
                {
                    if (ht_ids.ContainsKey(key))
                    {
                        object obj;
                        ht_ids.TryRemove(key, out obj);
                    }
                }
                else
                {
                    if (ht_ids.ContainsKey(key))
                    {
                        ht_ids[key] = val;
                    }
                    else
                    {
                        ht_ids.TryAdd(key, val);
                    }
                }
            }
        }
示例#3
0
        /// <summary>
        /// Adds a <see cref="ContainerPropertyBag{TContainer}"/> to the store.
        /// </summary>
        /// <param name="propertyBag">The <see cref="ContainerPropertyBag{TContainer}"/> to add.</param>
        /// <typeparam name="TContainer">The container type this <see cref="ContainerPropertyBag{TContainer}"/> describes.</typeparam>
        internal static void AddPropertyBag <TContainer>(IPropertyBag <TContainer> propertyBag)
        {
            if (!RuntimeTypeInfoCache <TContainer> .IsContainerType)
            {
                throw new Exception($"PropertyBagStore Type=[{typeof(TContainer)}] is not a valid container type. Type can not be primitive, enum or string.");
            }

            if (RuntimeTypeInfoCache <TContainer> .IsAbstractOrInterface)
            {
                throw new Exception($"PropertyBagStore Type=[{typeof(TContainer)}] is not a valid container type. Type can not be abstract or interface.");
            }

#if !NET_DOTS
            if (null != TypedStore <TContainer> .PropertyBag)
            {
                if (propertyBag.GetType().GetCustomAttributes <System.Runtime.CompilerServices.CompilerGeneratedAttribute>().Any())
                {
                    return;
                }
            }
#endif

            TypedStore <TContainer> .PropertyBag = propertyBag;
            if (!s_PropertyBags.ContainsKey(typeof(TContainer)))
            {
                s_RegisteredTypes.Add(typeof(TContainer));
            }

            s_PropertyBags[typeof(TContainer)] = propertyBag;
            NewTypeRegistered?.Invoke(typeof(TContainer), propertyBag);
        }
        public static PyObject ImportModule(string name)
        {
            if (!objs.ContainsKey(name))
            {
                IntPtr op = Runtime.PyImport_ImportModule(name);
                if (op == IntPtr.Zero || op == Runtime.PyNone)
                {
                    for (int i = 0; i < 10; i++)
                    {
                        System.Threading.Thread.Sleep(100);
                        Console.WriteLine("-------------------- Import Error TRY(" + i + "): " + name);
                        op = Runtime.PyImport_ImportModule(name);
                        if (op != IntPtr.Zero && op != Runtime.PyNone)
                        {
                            break;
                        }
                    }

                    if (op == IntPtr.Zero || op == Runtime.PyNone)
                    {
                        Console.WriteLine("-------------------- Import Error FINAL: " + name);
                        Runtime.CheckExceptionOccurred();
                    }
                }

                objs.TryAdd(name, new PyObject(op));
            }

            return(objs[name]);
        }
示例#5
0
 public System.Numerics.BigInteger NativeContract_BalanceOf(string addr)
 {
     if (storage.ContainsKey(addr) == false)
     {
         return(0);
     }
     return(storage[addr]);
 }
示例#6
0
        public void deleteSession(int timeout, string sessionKey)
        {
            RemoveTimeOut();
            Session session = null;

            while (Local.ContainsKey(sessionKey) && Local.TryRemove(sessionKey, out session) == false)
            {
                ;
            }
        }
示例#7
0
 public bool Enqueue(T item)
 {
     if (bag.ContainsKey(item))
     {
         return(false);
     }
     queue.Enqueue(item);
     bag[item] = 1;
     return(true);
 }
示例#8
0
        public bool Add(string key, TValue value)
        {
            if (key == null || _cache.ContainsKey(key))
            {
                return(false);
            }

            _cache[key] = value;
            return(true);
        }
示例#9
0
        public void AddJsonRPC(string path, string method, JSONRPCController.ActionRPC action)
        {
            if (onHttpEvents.ContainsKey(path) == false)
            {
                onHttpEvents[path] = new JSONRPCController();
            }
            var jsonc = onHttpEvents[path] as JSONRPCController;

            jsonc.AddAction(method, action);
        }
示例#10
0
 public bool Add(T item)
 {
     if (!_rules.ContainsKey(item.Tag))
     {
         _rules.GetOrAdd(item.Tag, item);
         return(true);
     }
     return(false);
 }
示例#11
0
 private static Tuple<int, int, int> ComputeStatisticsForDirectory(string directory)
 {
     // results[directory].Add(Tuple.Create(tag, i, foundLoops, option, result, timeInSeconds));
     int numVerified = 0, numError = 0, numUnknown = 0;
     if (!results.ContainsKey(directory)) { return new Tuple<int, int, int>(0, 0, 0); }
     //foreach (Tuple<string, int, ProgramAttributes, BoogieResult, int> t in results[directory])
     foreach (Tuple<string, ProgramAttributes, BoogieResult, int> t in results[directory].Values)
     {
       if (t.Item3 == BoogieResult.VERIFIED) { numVerified++; }
       if (t.Item3 == BoogieResult.ERROR) { numError++; }
       if (t.Item3 == BoogieResult.UNKNOWN) { numUnknown++; }
     }
     return new Tuple<int, int, int>(numVerified, numError, numUnknown);
 }
        public async Task OnDB_UseSnapShot(NetMessage msgRecv, byte[] id)
        {
            var msg = NetMessage.Create("_db.usesnapshot.back");

            msg.Params["_id"] = id;
            try
            {
                UInt64?wantheight = msgRecv.Params.ContainsKey("snapheight") ? (UInt64?)BitConverter.ToUInt64(msgRecv.Params["snapheight"], 0) : null;
                if (wantheight == null)
                {
                    var snapshot = Program.storage.maindb.UseSnapShot();
                    wantheight = snapshot.DataHeight;
                    peerSnapshots[snapshot.DataHeight] = snapshot;
                }
                else
                {
                    if (peerSnapshots.ContainsKey(wantheight.Value) == false)
                    {
                        msg.Params["_error"] = "do not have that snapheight".ToBytes_UTF8Encode();
                    }
                }
                if (msg.Params.ContainsKey("_error") == false)
                {
                    msg.Params["snapheight"] = BitConverter.GetBytes(wantheight.Value);
                }
            }
            catch (Exception err)
            {
                msg.Params["_error"] = err.Message.ToBytes_UTF8Encode();
            }
            SendToClient(msg);
        }
示例#13
0
        public async Task <bool> AddSagas(IAsyncEnumerable <SagasGroupEntity> sagasGroupEntities)
        {
            await foreach (var sagasGroupEntity in sagasGroupEntities)
            {
                if (!Sagas.ContainsKey(sagasGroupEntity.ServiceName))
                {
                    var bufferBlock = new BufferBlock <SagaEntity>();
                    sagasGroupEntity.SagaEntities.ForEach(m =>
                    {
                        bufferBlock.SendAsync(m);
                    });

                    Sagas.TryAdd(sagasGroupEntity.ServiceName, bufferBlock);
                }
                else
                {
                    // 这里必然为true
                    Sagas.TryGetValue(sagasGroupEntity.ServiceName, out BufferBlock <SagaEntity> bufferBlock);
                    sagasGroupEntity.SagaEntities.ForEach(m =>
                    {
                        bufferBlock.SendAsync(m);
                    });
                }
            }
            return(true);
        }
示例#14
0
        private void EnsureProperMessageOrder(byte[] messageBytes)
        {
            var stream  = new System.IO.MemoryStream(messageBytes);
            var message = TanksCommon.MessageDecoder.DecodeMessage <TanksCommon.SharedObjects.DataReceived>(stream);

            _incommingMessages.TryAdd(message.MessageId, messageBytes);
            var justRecievedId = message.MessageId;

            _log.Debug("Just receved MessageId: " + justRecievedId);
            CallReceivedDataLog("Just receved MessageId: " + justRecievedId);

            if (!_incommingMessages.IsEmpty)
            {
                while (_incommingMessages.ContainsKey(_nextReceivedMessageId))
                {
                    HandleRecievedMessage?.Invoke(_incommingMessages[_nextReceivedMessageId]);
                    _nextReceivedMessageId++;
                }
                if (_nextReceivedMessageId < justRecievedId)
                {
                    ReceivedDataLog?.Invoke("Request to resend Message: " + _nextReceivedMessageId);
                    _log.Debug("Request to resend Message: " + _nextReceivedMessageId);
                    SendObjectToTcpClient_Imp(new TanksCommon.SharedObjects.MessageResend()
                    {
                        MessageId = _nextReceivedMessageId
                    }, "EnsureProperMessageOrder");                                                                                                             //bypass message id and queue logic
                }
            }
        }
示例#15
0
        public async Task Semaphore_ContendFast()
        {
            const string keyName       = "test/semaphore/contend";
            const int    contenderPool = 15;

            var acquired = new System.Collections.Concurrent.ConcurrentDictionary <int, bool>();

            var tasks = new List <Task>();

            for (var i = 0; i < contenderPool; i++)
            {
                var v = i;
                tasks.Add(Task.Run(async() =>
                {
                    var semaphore = _client.Semaphore(keyName, 2);
                    await semaphore.Acquire(CancellationToken.None);
                    acquired[v] = semaphore.IsHeld;
                    await semaphore.Release();
                }));
            }

            await TimeoutUtils.WithTimeout(Task.WhenAll(tasks));

            for (var i = 0; i < contenderPool; i++)
            {
                Assert.True(acquired.ContainsKey(i), $"Contender {i} did not acquire the lock");
                Assert.True(acquired[i], $"IsHeld was false for contender {i}");
            }
        }
示例#16
0
        static int _m_ContainsKey(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.Collections.Concurrent.ConcurrentDictionary <long, ulong> gen_to_be_invoked = (System.Collections.Concurrent.ConcurrentDictionary <long, ulong>)translator.FastGetCSObj(L, 1);



                {
                    long _key = LuaAPI.lua_toint64(L, 2);

                    bool gen_ret = gen_to_be_invoked.ContainsKey(
                        _key);
                    LuaAPI.lua_pushboolean(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
        static private void CountWords(string content)
        {
            List <char> splitChars = new List <char>();

            //for simplicity, consider everything that isn't a letter to be a separator
            //since input is ASCII, only need up to 255
            for (int c = 0; c <= 255; ++c)
            {
                if (!char.IsLetter((char)c))
                {
                    splitChars.Add((char)c);
                }
            }
            string[] words = content.Split(splitChars.ToArray <char>(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string word in words)
            {
                if (wordCount.ContainsKey(word))
                {
                    ++wordCount[word];
                }
                else
                {
                    wordCount[word] = 1;
                }
            }
        }
示例#18
0
 internal static void SetAddinContanier(string addinName, IApplicationContext container)
 {
     if (!addindata.ContainsKey(addinName))
     {
         addindata[addinName] = container;
     }
 }
        public void MultiThreadProxy()
        {
            HttpClientPool pool       = new HttpClientPool();
            var            spider     = new DefaultSpider();
            var            downloader = new HttpClientDownloader();

            System.Collections.Concurrent.ConcurrentDictionary <HttpClientElement, int> tonggi = new System.Collections.Concurrent.ConcurrentDictionary <HttpClientElement, int>();
            Parallel.For(0, 1000, new ParallelOptions {
                MaxDegreeOfParallelism = 1
            }, (i) =>
            {
                var port  = i % 10;
                var proxy = new UseSpecifiedUriWebProxy(new Uri($"http://192.168.10.1:{port}"), null, false);
                var item  = pool.GetHttpClient(spider, downloader, new System.Net.CookieContainer(), proxy, null);

                if (tonggi.ContainsKey(item))
                {
                    tonggi[item] = tonggi[item] + 1;
                }
                else
                {
                    tonggi.TryAdd(item, 1);
                }
            });

            Assert.Equal(10, tonggi.Count);
            foreach (var pair in tonggi)
            {
                Assert.Equal(100, pair.Value);
            }
        }
示例#20
0
 public Info GetInfo(string key)
 {
     if (infos.ContainsKey(key) == false)
     {
         return(null);
     }
     return(infos[key].Clone());
 }
    /// <summary>If this converter is able to handle a given conversion.</summary>
    /// <param name="objectType">The type to be handled.</param>
    /// <returns>Returns if this converter is able to handle a given conversion.</returns>
    public override bool CanConvert(Type objectType)
    {
        if (resolvedTypes.ContainsKey(objectType))
        {
            return(true);
        }
        var result = typeof(IDictionary).IsAssignableFrom(objectType) || objectType.IsOfType(typeof(IDictionary));

        if (result)     //check key is string or enum because it comes from Jvascript object which forces the key to be a string
        {
            if (objectType.IsGenericType && objectType.GetGenericArguments()[0] != typeof(string) && !objectType.GetGenericArguments()[0].IsEnum)
            {
                result = false;
            }
        }
        return(result);
    }
示例#22
0
        public async Task <IActionResult> StarResult(StarSearch search)
        {
            int threads = 4;

            if (ModelState.IsValid)
            {
                search.SearchDays  = Math.Min(search.SearchDays, 14);
                search.Destination = search.Destination.MyTrim();
                search.Origin      = search.Origin.MyTrim();
                if (search.Origin.MyLength() == 3 && search.Destination.MyLength() == 3)
                {
                    var dates = System.Linq.Enumerable.Range(0, search.SearchDays).Select(i => search.OutDate.AddDays(i)).ToList();
                    dates.Shuffle();
                    var res = new System.Collections.Concurrent.ConcurrentDictionary <DateTime, FlysasLib.SearchResult>();
                    await Dasync.Collections.ParallelForEachExtensions.ParallelForEachAsync <DateTime>(dates,
                                                                                                       async date =>
                    {
                        if (!res.ContainsKey(date))    //this looks smart, but doesn't realy save a lot of calls...
                        {
                            var q = new SASQuery
                            {
                                OutDate = date,
                                From    = search.Origin,
                                To      = search.Destination,
                                Adults  = search.Pax,
                                Mode    = SASQuery.SearhMode.STAR
                            };
                            var c = new FlysasLib.SASRestClient();
                            FlysasLib.SearchResult searchResult = await c.SearchAsync(q);

                            if (searchResult.tabsInfo != null && searchResult.tabsInfo.outboundInfo != null)
                            {
                                foreach (var dayWithNoSeats in searchResult.tabsInfo.outboundInfo.Where(tab => tab.points == 0))
                                {
                                    res.TryAdd(dayWithNoSeats.date, null);
                                }
                            }

                            res.TryAdd(date, searchResult);
                        }
                    },
                                                                                                       threads,
                                                                                                       false
                                                                                                       );

                    search.Results = res.Where(r => r.Value?.outboundFlights != null).SelectMany(r => r.Value.outboundFlights).ToList();
                    if (search.MaxLegs > 0)
                    {
                        search.Results = search.Results.Where(r => r.segments.Count() <= search.MaxLegs).ToList();
                    }
                }
                else
                {
                    search.Results = new List <FlysasLib.FlightBaseClass>();
                }
            }
            return(View(nameof(Star), search));
        }
示例#23
0
 public bool InitStorage(System.Collections.Concurrent.ConcurrentDictionary <string, System.Numerics.BigInteger> storage)
 {
     this.storage = storage;
     if (storage.ContainsKey(key) == false)
     {
         storage[key] = 0;
     }
     return(true);
 }
        /// <summary>
        /// Returns true if the authority for the request is in the list of allowed authorities.
        /// </summary>
        /// <param name="requestMessage">The request to analyse.</param>
        /// <returns>True if the authority is allowed by this condition.</returns>
        public bool ShouldProcess(HttpRequestMessage requestMessage)
        {
            if (requestMessage == null)
            {
                throw new ArgumentNullException(nameof(requestMessage));
            }

            return(_AllowedAuthorities.ContainsKey(requestMessage.RequestUri.Authority));
        }
示例#25
0
 public int FaultLevel(int protocolId, string faultName)
 {
     if (_faultDic == null || !_faultDic.ContainsKey(protocolId) ||
         !_faultDic[protocolId].ContainsKey(faultName))
     {
         return(0);
     }
     return(_faultDic[protocolId][faultName].PROTOCOLFAULTLEVEL);
 }
示例#26
0
文件: Helper.cs 项目: ProDog/zoro.one
 public byte[] Get(byte[] key)
 {
     System.Numerics.BigInteger nkey = new System.Numerics.BigInteger(key);
     if (cache.ContainsKey(nkey))
     {
         return(cache[nkey]);
     }
     return(db.Get(snapshot, key));
 }
示例#27
0
        /// <summary>
        /// Tries to let a mapobject enter the map.
        /// </summary>
        /// <param name="MapObject">The map object.</param>
        /// <returns>Returns true if the object was added.</returns>
        public bool EnterMap(Maps.IMapObject MapObject)
        {
            if (MapObject is Data.GroundItem)
            {
                if (Items.ContainsKey(MapObject.EntityUID))
                {
                    return(false);
                }

                Items.TryAdd(MapObject.EntityUID, MapObject);
            }
            else
            {
                if (MapObjects.ContainsKey(MapObject.EntityUID))
                {
                    if (MapObject is Entities.GameClient)
                    {
                        (MapObject as Entities.GameClient).NetworkClient.Disconnect("Multiple map locations.");
                    }
                    return(false);
                }

                if (MapObject is Entities.GameClient)
                {
                    if (!MapObjects.TryAdd(MapObject.EntityUID, MapObject))
                    {
                        if (MapObject is Entities.GameClient)
                        {
                            (MapObject as Entities.GameClient).NetworkClient.Disconnect("Failed to add the client to the map.");
                        }
                        return(false);
                    }
                }
                else if (!MapObjects.TryAdd(MapObject.EntityUID, MapObject))
                {
                    return(false);
                }
            }

            MapObject.Map = this;
            return(true);
        }
示例#28
0
 public static CacheInfo Get(string guid)
 {
     if (sessionStores.ContainsKey(guid))
     {
         return(sessionStores[guid]);
     }
     else
     {
         return(null);
     }
 }
示例#29
0
        /// <summary>
        /// Returns true if the authority for the request is in the list of allowed authorities.
        /// </summary>
        /// <param name="requestMessage">The request to analyse.</param>
        /// <remarks>
        /// <para>If the content or the content type header of the request is null or empty, the return value is false.</para>
        /// </remarks>
        /// <returns>True if the authority is allowed by this condition.</returns>
        public bool ShouldProcess(HttpRequestMessage requestMessage)
        {
            var contentType = requestMessage?.Content?.Headers?.ContentType.MediaType;

            if (String.IsNullOrWhiteSpace(contentType))
            {
                return(false);
            }

            return(_AllowedMediaTypes.ContainsKey(contentType));
        }
示例#30
0
        public Address(string city, string street, string houseNumber, string apartment, string province, string cityType = null)
        {
            if (string.IsNullOrEmpty(cityType))
            {
                if (string.IsNullOrWhiteSpace(city) == false)
                {
                    string[] parts = city.Split('.');

                    if (parts.Length == 2)
                    {
                        this.CityType = parts[0] + ".";
                        this.City     = parts[1];
                    }
                    else if (parts.Length == 1)
                    {
                        this.CityType = parts[0].StartsWith("Дач")
                            ? "дачи"
                            : "?";
                        this.City = parts[0];
                    }
                    else
                    {
                        this.CityType = string.Empty;
                        this.City     = city;
                    }
                }
                else
                {
                    this.City = this.CityType = string.Empty;
                }
            }
            else
            {
                this.City     = city;
                this.CityType = cityType;
            }

            this.Street      = string.IsNullOrWhiteSpace(street) ? string.Empty : street;
            this.HouseNumber = string.IsNullOrWhiteSpace(houseNumber) ? string.Empty : houseNumber;
            this.Apartment   = string.IsNullOrWhiteSpace(apartment) ? string.Empty : apartment;

            this.Province = string.IsNullOrWhiteSpace(province) ? string.Empty : province;

            string s = this.CityAndStreetWithHouse;

            if (DictionaryStreetWithHouseNumber.ContainsKey(s) == false)
            {
                DictionaryStreetWithHouseNumber.AddOrUpdate(s, 1u, (string key, uint value) => { return(value); });
            }
            else
            {
                DictionaryStreetWithHouseNumber[s] = DictionaryStreetWithHouseNumber[s] + 1;
            }
        }