public static void NewDictionary() { bool[] busy_numbers = new bool[AlphabetInfo.word_count]; List <int> numbers_list = new List <int>(); int number; for (int i = 0; i < 125; i++) { number = Random.Range(0, AlphabetInfo.word_count); number = FindUniqueNumber(ref busy_numbers, number); numbers_list.Add(number); } List <DictionaryItem> words_list = new List <DictionaryItem>(); DictionaryItem item; string word; for (int i = 0; i < 125; i++) { word = ""; //Чтение строчки из файла Words item = new DictionaryItem(word, numbers_list[i]); words_list.Add(item); } words = words_list.ToArray(); }
public String GridFromViewModel <T>(IEnumerable <GridViewModel <T> > model) { DictionaryItemComparer ItemComparer = new DictionaryItemComparer(); Dictionary <DictionaryItem, List <String> > value_dict = new Dictionary <DictionaryItem, List <string> >(ItemComparer); foreach (GridViewModel <T> item in model) { Type t = item.GetType(); System.Reflection.PropertyInfo[] infos = t.GetProperties(); foreach (System.Reflection.PropertyInfo info in infos) { DictionaryItem dItem = new DictionaryItem(getAttributes(info)); if (!value_dict.ContainsKey(dItem)) { value_dict.Add(dItem, new List <string>(infos.Length)); } value_dict[dItem].Add((string)info.GetValue(item, null)); } } Console.WriteLine(createTable(value_dict)); return(createTable(value_dict)); }
public static DictionaryItem Import(XmlNode xmlData, DictionaryItem parent) { string key = xmlData.Attributes["Key"].Value; XmlNodeList values = xmlData.SelectNodes("./Value"); XmlNodeList childItems = xmlData.SelectNodes("./DictionaryItem"); DictionaryItem newItem; bool retVal = false; if (!hasKey(key)) { if (parent != null) { addKey(key, " ", parent.key); } else { addKey(key, " "); } if (values.Count > 0) { //Set language values on the dictionary item newItem = new DictionaryItem(key); foreach (XmlNode xn in values) { string cA = xn.Attributes["LanguageCultureAlias"].Value; string keyValue = xmlHelper.GetNodeValue(xn); Language valueLang = Language.GetByCultureCode(cA); if (valueLang != null) { newItem.setValue(valueLang.id, keyValue); } } } if (parent == null) { retVal = true; } } newItem = new DictionaryItem(key); foreach (XmlNode childItem in childItems) { Import(childItem, newItem); } if (retVal) { return(newItem); } else { return(null); } }
private DictionaryItem getAttributes(System.Reflection.PropertyInfo info) { object[] attributes = info.GetCustomAttributes(true); DictionaryItem DI = new DictionaryItem(info.Name); DI.sortable = false; DI.displayOrder = 0; DI.displayName = DI.variableName; foreach (Object att in attributes) { if (att is DisplayNameAttribute) { DI.displayName = ((DisplayNameAttribute)att).DisplayName; } if (att is SortableAttribute) { DI.sortable = ((SortableAttribute)att).value; } if (att is DisplayOrderAttribute) { DI.displayOrder = ((DisplayOrderAttribute)att).value; } } return(DI); }
public ActionResult WorkloadStatistic() { DictionaryLogic dictLogic = new DictionaryLogic(); List <DictionaryItem> projectTypes = dictLogic.GetEnabledDictionaryItems(DictionaryLogic.ProjectType); var projectStatus = dictLogic.GetEnabledDictionaryItems(DictionaryLogic.ProjectStatus); //ForRole IUserData user = UserContext.CurrentUser; if (user.HasRole("Consultant")) { ViewBag.forRole = true; var i = 0; DictionaryItem dict = new DictionaryItem(); var newProjectTypes = new List <DictionaryItem>(); for (i = 0; i < projectTypes.Count(); i++) { dict = projectTypes[i]; if (dict.DictItemId == "101-04" || dict.DictItemId == "101-05") { newProjectTypes.Add(dict); } } ViewBag.QueryProjectTypes = new DropDownList(newProjectTypes, DictionaryLogic.ValueField, DictionaryLogic.TextField, false); } else { ViewBag.forRole = false; ViewBag.QueryProjectTypes = new DropDownList(projectTypes, DictionaryLogic.ValueField, DictionaryLogic.TextField, true); } ViewBag.QueryProjectStatus = new DropDownList(projectStatus, DictionaryLogic.ValueField, DictionaryLogic.TextField, true); return(View()); }
public override bool Update(TransactionManager transactionManager, DictionaryItem entity) { SqlDatabase database = new SqlDatabase(this._connectionString); DbCommand command = StoredProcedureProvider.GetCommandWrapper(database, "dbo.DictionaryItem_Update", this._useStoredProcedure); database.AddInParameter(command, "@DictionaryItemCode", DbType.AnsiString, entity.DictionaryItemCode); database.AddInParameter(command, "@OriginalDictionaryItemCode", DbType.AnsiString, entity.OriginalDictionaryItemCode); database.AddInParameter(command, "@ProjectCode", DbType.AnsiString, entity.ProjectCode); database.AddInParameter(command, "@DictionaryNameCode", DbType.AnsiString, entity.DictionaryNameCode); database.AddInParameter(command, "@SortID", DbType.Int32, entity.SortID.HasValue ? ((object)entity.SortID) : ((object)DBNull.Value)); database.AddInParameter(command, "@Name", DbType.AnsiString, entity.Name); int num = 0; if (transactionManager != null) { num = Utility.ExecuteNonQuery(transactionManager, command); } else { num = Utility.ExecuteNonQuery(database, command); } if (DataRepository.Provider.EnableEntityTracking) { EntityManager.StopTracking(entity.EntityTrackingKey); } entity.OriginalDictionaryItemCode = entity.DictionaryItemCode; entity.AcceptChanges(); return(Convert.ToBoolean(num)); }
public void Can_Deep_Clone() { DictionaryItem item = _builder .WithRandomTranslations(2) .Build(); var clone = (DictionaryItem)item.DeepClone(); Assert.AreNotSame(clone, item); Assert.AreEqual(clone, item); Assert.AreEqual(clone.CreateDate, item.CreateDate); Assert.AreEqual(clone.Id, item.Id); Assert.AreEqual(clone.ItemKey, item.ItemKey); Assert.AreEqual(clone.Key, item.Key); Assert.AreEqual(clone.ParentId, item.ParentId); Assert.AreEqual(clone.UpdateDate, item.UpdateDate); Assert.AreEqual(clone.Translations.Count(), item.Translations.Count()); for (var i = 0; i < item.Translations.Count(); i++) { Assert.AreNotSame(clone.Translations.ElementAt(i), item.Translations.ElementAt(i)); Assert.AreEqual(clone.Translations.ElementAt(i), item.Translations.ElementAt(i)); } // This double verifies by reflection PropertyInfo[] allProps = clone.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in allProps) { Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(item, null)); } }
public long?Insert(string tableName, DictionaryItem data) { var objClass = Schema.FindClassByID(tableName); if (objClass == null) { if (Schema.FindRelationshipByID(tableName) != null) { StorageDalc.Insert(tableName, (System.Collections.IDictionary)data.Data); return(null); } throw new Exception(String.Format("Unknown table {0}", tableName)); } var objContainer = new ObjectContainer(objClass); foreach (var entry in data.Data) { var prop = objClass.FindPropertyByID(entry.Key); if (prop != null && !prop.PrimaryKey) { objContainer[entry.Key] = entry.Value; } } ObjStorage.Insert(objContainer); return(objContainer.ID); }
public void Can_Perform_Add_On_DictionaryRepository() { // Arrange var provider = TestObjects.GetScopeProvider(Logger); using (var scope = provider.CreateScope()) { var languageRepository = Factory.GetInstance <ILanguageRepository>(); var repository = CreateRepository(); var language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read") }; read.Translations = translations; // Act repository.Save(read); var exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); Assert.That(exists, Is.True); } }
/// <summary> /// Reads all items from the database and stores in local cache /// </summary> private static void EnsureCache() { using (var lck = new UpgradeableReadLock(Locker)) { if (_cacheIsEnsured) return; lck.UpgradeToWriteLock(); using (var dr = SqlHelper.ExecuteReader("Select pk, id, [key], parent from cmsDictionary")) { while (dr.Read()) { //create new dictionaryitem object and put in cache var item = new DictionaryItem(dr.GetInt("pk"), dr.GetString("key"), dr.GetGuid("id"), dr.GetGuid("parent")); DictionaryItems.TryAdd(item.key, item); } } _cacheIsEnsured = true; } }
public void CreateTestData() { var language = ServiceContext.LocalizationService.GetLanguageByCultureCode("en-US"); var languageDK = new Language("da-DK") { CultureName = "da-DK" }; ServiceContext.LocalizationService.Save(languageDK);//Id 2 var readMore = new DictionaryItem("Read More"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read More"), new DictionaryTranslation(languageDK, "Læs mere") }; readMore.Translations = translations; ServiceContext.LocalizationService.Save(readMore);//Id 1 var article = new DictionaryItem("Article"); var translations2 = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Article"), new DictionaryTranslation(languageDK, "Artikel") }; article.Translations = translations2; ServiceContext.LocalizationService.Save(article);//Id 2 }
public DictionaryItem(KeyValuePair <TKey, TValue> pair, DictionaryItem parent = null, DictionaryItem left = null, DictionaryItem right = null) { _pair = pair; _parent = parent; _left = left; _right = right; }
public void CreateTestData() { ILocalizationService localizationService = GetRequiredService <ILocalizationService>(); ILanguage language = localizationService.GetLanguageByIsoCode("en-US"); var languageDK = new Language("da-DK", "Danish (Denmark)"); localizationService.Save(languageDK);//Id 2 var readMore = new DictionaryItem("Read More"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read More"), new DictionaryTranslation(languageDK, "Læs mere") }; readMore.Translations = translations; localizationService.Save(readMore); // Id 1 var article = new DictionaryItem("Article"); var translations2 = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Article"), new DictionaryTranslation(languageDK, "Artikel") }; article.Translations = translations2; localizationService.Save(article); // Id 2 }
private void sendWordToServer(DictionaryItem dItem) { String jsonObj = "{\"id\":" + dItem.Id + ",\"word\":" + "\"" + dItem.Word + "\"" + ",\"translation\":" + "\"" + dItem.Translation + "\"" + ",\"correct_answers\":" + dItem.CorrectAnswers + ",\"iteration\":" + dItem.Iteration; DateTime nextDate = dItem.NextShowDate; if (!Object.Equals(nextDate, default(DateTime))) //if date != null { string nextDateStr = nextDate.ToString("yyyy-MM-dd HH:mm:ss"); jsonObj = jsonObj + ",\"next_show_date\":" + "\"" + nextDateStr + "\""; } else { jsonObj = jsonObj + ",\"next_show_date\":" + "null"; } DateTime currentDate = DateTime.Now; string updateDateStr = currentDate.ToString("yyyy-MM-dd HH:mm:ss"); jsonObj = jsonObj + ",\"last_update_date\":" + "\"" + updateDateStr + "\"" + "}";; String jsonStr = "{\"words\": [" + jsonObj + "] }"; logger.Info("JsonStr: " + jsonStr); if (config.Synchronization == Const.SYNC_ON) { Synchronizator.sendRequestAsync(jsonStr); } }
public void AddItem(DictionaryItem item) { _locker.WaitOne(); lock (_locker) { try { DictionaryItem realItem = item.GetRealItem(); if (realItem == null) { return; } Items.Remove(realItem); if (Items.Count == _maxItemsCount) { Items.RemoveAt(_maxItemsCount - 1); } Items.Insert(0, realItem); WriteData(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
public async Task <IReadOnlyCollection <DictionaryItem> > ReadData() { List <DictionaryItem> items = new List <DictionaryItem>(); try { string file = await _fileAccessor.ReadFile(_fileUri); if (!string.IsNullOrEmpty(file)) { string[] parts = file.Split('*'); foreach (string part in parts) { Dictionary.ListItemIndex itemIndex = Dictionary.ListItemIndex.FromString(part); DictionaryItem item = _dictionaryService.GetItemByIndex(itemIndex); DictionaryItem realItem = _dictionaryService.GetItemByWord(item.Title, item.LanguageCode); items.Add(realItem); } } } catch (Exception ex) { Debug.WriteLine(ex); } return(items); }
public ActionResult SaveDictionaryItem(DictionaryItem item) { DictionaryLogicBase logic = new DictionaryLogicBase(); bool result = logic.SaveDictionaryItem(item); return(Json(new { Result = result, Data = item })); }
public static void Fill() { var repo = new Repository(); var allKeys = repo.GetAllKeys(); var allTexts = repo.GetAllText(); var ls = ApplicationContext.Current.Services.LocalizationService; var allLanguages = ls.GetAllLanguages(); foreach (var text in allTexts) { var key = allKeys.FirstOrDefault(x => x.id == text.UniqueId); var language = allLanguages.FirstOrDefault(x => x.Id == text.languageId); if (key != null && language != null) { var dictionary = new DictionaryItem() { Id = key.id, Key = key.key, Value = text.value, Culture = language.CultureInfo.Name }; _cache.TryAdd(dictionary.Key + "-" + dictionary.Culture, dictionary); } } }
private void dateTypeComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (!FormLoading) { FormLoading = true; Date monthComboValue = (Date)monthToolStripComboBox.ComboBox.SelectedValue; LoadMonthComboBoxItems(); bool contains = false; foreach (var item in monthToolStripComboBox.ComboBox.Items) { DictionaryItem <Date, string> dicItem = (DictionaryItem <Date, string>)item; if (dicItem.Key == monthComboValue) { contains = true; break; } } if (contains) { monthToolStripComboBox.ComboBox.SelectedValue = monthComboValue; } LoadTransactionGrid(); EnableDisableControls(); FormLoading = false; } }
/// <summary> /// ¼ì²â×ÖµäÏî±àºÅ /// </summary> /// <param name="id"></param> /// <param name="category"></param> private void CheckId(int id, out DictionaryItem dictionaryItem) { var condtionId = ConditionEqualId(id); dictionaryItem = this._dictionaryItemRepository.GetEntity(condtionId); AssertUtil.IsNotNull(dictionaryItem, LanguageUtil.Translate("api_Business_DictionaryItem_CheckId")); }
/// <summary> /// Reads all items from the database and stores in local cache /// </summary> private static void EnsureCache() { using (var lck = new UpgradeableReadLock(Locker)) { if (_cacheIsEnsured) { return; } lck.UpgradeToWriteLock(); using (var dr = SqlHelper.ExecuteReader("Select pk, id, [key], parent from cmsDictionary")) { while (dr.Read()) { //create new dictionaryitem object and put in cache var item = new DictionaryItem(dr.GetInt("pk"), dr.GetString("key"), dr.GetGuid("id"), dr.GetGuid("parent")); DictionaryItems.TryAdd(item.key, item); } } _cacheIsEnsured = true; } }
/* * Show message with random word from database */ private void OnMainTimerTick(object sender, EventArgs e) { logger.Trace("Main timer tick"); taskbarIcon.CloseBalloon(); //force close balloon if it's already open DictionaryItem randomWord = GetRandomWord(); if (randomWord != null) { FancyBalloon balloon = new FancyBalloon(mainTimer, randomWord, processAnswerFunction); //show balloon and close it after maxBalloonStayTime if (taskbarIcon != null) { taskbarIcon.ShowCustomBalloon(balloon, PopupAnimation.Slide, maxBalloonStayTime); } } else { ErrorBaloon balloon = new ErrorBaloon(); if (taskbarIcon != null) { taskbarIcon.ShowCustomBalloon(balloon, PopupAnimation.Slide, maxBalloonStayTime); } } timeLeftCounter = config.ShowInterval; deleteOldLogFiles(); //delete log files older than 10 days }
public void Can_Perform_Add_On_DictionaryRepository() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(); var unitOfWork = provider.GetUnitOfWork(); var languageRepository = new LanguageRepository(unitOfWork); var repository = new DictionaryRepository(unitOfWork, languageRepository); var language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read") }; read.Translations = translations; // Act repository.AddOrUpdate(read); unitOfWork.Commit(); var exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); Assert.That(exists, Is.True); }
/// <summary> /// Reads all items from the database and stores in local cache /// </summary> private static void EnsureCache() { if (!_cacheIsEnsured) { lock (Locker) { if (!_cacheIsEnsured) { using (IRecordsReader dr = SqlHelper.ExecuteReader("Select pk, id, [key], parent from cmsDictionary")) { while (dr.Read()) { //create new dictionaryitem object and put in cache var item = new DictionaryItem(dr.GetInt("pk"), dr.GetString("key"), dr.GetGuid("id"), dr.GetGuid("parent")); DictionaryItems.TryAdd(item.key, item); } } _cacheIsEnsured = true; } } } }
public DictionaryItem(TKey key, TValue value, DictionaryItem parent = null, DictionaryItem left = null, DictionaryItem right = null) { _pair = new KeyValuePair <TKey, TValue>(key, value); _parent = parent; _left = left; _right = right; }
public void Can_Perform_Add_On_DictionaryRepository() { // Arrange IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { ILanguageRepository languageRepository = GetRequiredService <ILanguageRepository>(); IDictionaryRepository repository = CreateRepository(); ILanguage language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read") }; read.Translations = translations; // Act repository.Save(read); bool exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); Assert.That(exists, Is.True); } }
private void OnItemClicked(DictionaryItem item) { RenderingItem renderingItem = new RenderingItem(item, false); _parametersManager.Set(Parameters.RenderingItem, renderingItem); ShowViewModel <ArticleViewModel>(); }
public async Task <IReadOnlyList <DictionaryItem> > ReadData() { List <DictionaryItem> items = new List <DictionaryItem>(); try { string file = await _fileAccessor.ReadFile(_fileUri); XmlSerializer serializer = new XmlSerializer(typeof(Data)); using (TextReader reader = new StringReader(file)) { Data data = (Data)serializer.Deserialize(reader); foreach (DataItem itemModel in data.Items) { DictionaryItem item = _dictionaryService.GetItemByWord(itemModel.Title, (uint)itemModel.Language); if (item != null) { items.Add(item); } } } } catch (Exception ex) { Debug.WriteLine(ex); } return(items); }
private Tuple <string, string> getNormalizedWordPair(DictionaryItem item) { String word = "word not specified", translation = "translation not specified"; if (item != null) { if (item.Iteration == 0) //(easy) translate foreign word to mother language { if (item.Word != null) { word = item.Word; } if (item.Translation != null) { translation = item.Translation; } } else //(harder) translate from own language to foreign one { if (item.Word != null) { word = item.Translation; } if (item.Translation != null) { translation = item.Word; } } } return(new Tuple <string, string>(word, translation)); }
public void Can_Perform_Add_On_DictionaryRepository() { // Arrange var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var languageRepository = new LanguageRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Mock.Of <ILogger>(), SqlSyntax)) using (var repository = CreateRepository(unitOfWork)) { var language = languageRepository.Get(1); var read = new DictionaryItem("Read"); var translations = new List <IDictionaryTranslation> { new DictionaryTranslation(language, "Read") }; read.Translations = translations; // Act repository.AddOrUpdate(read); unitOfWork.Commit(); var exists = repository.Exists(read.Id); // Assert Assert.That(read.HasIdentity, Is.True); Assert.That(exists, Is.True); } }
protected void rptDictionaryItem_ItemDataBound(object sender, RepeaterItemEventArgs e) { // // <a href="javascript:Edit('<%# Eval("ItemCode")%>',true)">新增子项</a> RepeaterItem item = e.Item; DictionaryItem group = item.DataItem as DictionaryItem; if (group != null && group.ItemType == DictionaryItemType.Group) { Panel panel = item.FindControl("OperationPanel") as Panel; if (panel != null) { HtmlAnchor ank = new HtmlAnchor(); ank.HRef = string.Format("javascript:Edit('{0}',true)", group.ItemCode); ank.InnerText = "新增子项"; panel.Controls.Add(ank); } Repeater rptSubItems = item.FindControl("rptSubItems") as Repeater; if (rptSubItems != null) { IList <DictionaryItem> subItems = DictionaryItem.GetDictionaryItemsByGroup(_session, group.ItemCode); if (subItems != null && subItems.Count > 0) { rptSubItems.DataSource = subItems; rptSubItems.DataBind(); } } } }
public static void AddLowestDistance(DictionaryItem item, string suggestion, Int32 suggestionint, string delete) { // Verbose < 2 then remove all the existed suggestions. if ((VerBose < 2) && (item.suggestions.Count > 0) && (wordList[item.suggestions[0]].Length - delete.Length > suggestion.Length - delete.Length)) item.suggestions.Clear(); // Exceeding verbose, does not suggestion the edit distance longer than request. if ((VerBose == 2) || (item.suggestions.Count == 0) || (wordList[item.suggestions[0]].Length - delete.Length >= suggestion.Length - delete.Length)) item.suggestions.Add(suggestionint); }
protected override Stream CreateStreamImpl(Guid id) { if (index == null) { ReadIndex (); } if (dataStream == null) { OpenDataStream (); } DictionaryItem item = new DictionaryItem (); item.StreamId = id; item.Position = dataStream.Position; item.Length = -1; index.Add (id, item); indexChanged = true; return new SubStream (dataStream, item); }
/// <summary> /// 初始化 DictionaryDataItem 的新实例。 /// </summary> /// <param name="dictionaryItem"></param> public DictionaryDataItem(DictionaryItem dictionaryItem) { this.dictionaryItem = dictionaryItem; }
private void Scan(SerializationMemberInfo memberInfo, TypeSerializerCache cache, SerializerOptions options) { XmlSerializationAttribute[] attribs; var attributes = new List<Attribute>(); // Get the ElementType attributes specified on the type itself as long // as we're not the type itself! if (memberInfo.MemberInfo != memberInfo.ReturnType) { var smi = new SerializationMemberInfo(memberInfo.ReturnType, options, cache); attribs = smi.GetApplicableAttributes(typeof(XmlDictionaryElementTypeAttribute)); foreach (XmlSerializationAttribute a in attribs) { attributes.Add(a); } } // Get the ElementType attributes specified on the member. attribs = memberInfo.GetApplicableAttributes(typeof(XmlDictionaryElementTypeAttribute)); foreach (var a in attribs) { attributes.Add(a); } foreach (XmlDictionaryElementTypeAttribute attribute in attributes) { var dictionaryItem = new DictionaryItem(); var smi2 = new SerializationMemberInfo(attribute.ElementType, options, cache); if (attribute.TypeAlias == null) { attribute.TypeAlias = smi2.SerializedName; } dictionaryItem.attribute = attribute; dictionaryItem.typeAlias = attribute.TypeAlias; // Check if a specific type of serializer is specified. if (attribute.SerializerType == null) { // Figure out the serializer based on the type of the element. dictionaryItem.serializer = cache.GetTypeSerializerBySupportedType(attribute.ElementType, smi2); } else { // Get the type of serializer they specify. dictionaryItem.serializer = cache.GetTypeSerializerBySerializerType(attribute.SerializerType, smi2); } primaryDictionaryItem = dictionaryItem; typeToItemMap[attribute.ElementType] = dictionaryItem; aliasToItemMap[attribute.TypeAlias] = dictionaryItem; } if (aliasToItemMap.Count != 1) { primaryDictionaryItem = null; } }
void ReadIndex() { index = new Dictionary<Guid, DictionaryItem> (); if (multiStream.Exists (indexStreamId)) { using (BinaryReader reader = new BinaryReader(multiStream.OpenStream(indexStreamId))) { int cnt = reader.ReadInt32 (); while (cnt-- > 0) { DictionaryItem item = new DictionaryItem (); item.StreamId = new Guid (reader.ReadBytes (16)); item.Position = reader.ReadInt64 (); item.Length = reader.ReadInt64 (); index.Add (item.StreamId, item); } } } indexChanged = false; }
private static int createKey(string key, Guid parentId, string defaultValue) { if (!hasKey(key)) { Guid newId = Guid.NewGuid(); SqlHelper.ExecuteNonQuery("Insert into cmsDictionary (id,parent,[key]) values (@id, @parentId, @dictionaryKey)", SqlHelper.CreateParameter("@id", newId), SqlHelper.CreateParameter("@parentId", parentId), SqlHelper.CreateParameter("@dictionaryKey", key)); using (IRecordsReader dr = SqlHelper.ExecuteReader("Select pk, id, [key], parent from cmsDictionary where id=@id", SqlHelper.CreateParameter("@id", newId))) { if (dr.Read()) { //create new dictionaryitem object and put in cache var item = new DictionaryItem(dr.GetInt("pk"), dr.GetString("key"), dr.GetGuid("id"), dr.GetGuid("parent")); item.setValue(defaultValue); item.OnNew(EventArgs.Empty); return item.id; } else { throw new DataException("Could not load newly created dictionary item with id " + newId.ToString()); } } } else { throw new ArgumentException("Key being added already exists!"); } }
public static DictionaryItem Import(XmlNode xmlData, DictionaryItem parent) { string key = xmlData.Attributes["Key"].Value; XmlNodeList values = xmlData.SelectNodes("./Value"); XmlNodeList childItems = xmlData.SelectNodes("./DictionaryItem"); DictionaryItem newItem; bool retVal = false; if (!hasKey(key)) { if (parent != null) addKey(key, " ", parent.key); else addKey(key, " "); if (values.Count > 0) { //Set language values on the dictionary item newItem = new DictionaryItem(key); foreach (XmlNode xn in values) { string cA = xn.Attributes["LanguageCultureAlias"].Value; string keyValue = xmlHelper.GetNodeValue(xn); Language valueLang = Language.GetByCultureCode(cA); if (valueLang != null) { newItem.setValue(valueLang.id, keyValue); } } } if (parent == null) retVal = true; } newItem = new DictionaryItem(key); foreach (XmlNode childItem in childItems) { Import(childItem, newItem); } if (retVal) return newItem; else return null; }
public SubStream(Stream stream, DictionaryItem item) { this.stream = stream; this.item = item; stream.Position = item.Position; }
// Look up the words in the list and do comparison in terms of the MaxEditDistance and return the suggestions. public static List<SuggestItem> Lookup(string input, string language, int MaxEditDistance) { if (input.Length - MaxEditDistance > MaxLength) return new List<SuggestItem>(); List<string> candidates = new List<string>(); HashSet<string> hashset1 = new HashSet<string>(); List<SuggestItem> suggestions = new List<SuggestItem>(); HashSet<string> hashset2 = new HashSet<string>(); object valueO; candidates.Add(input); while (candidates.Count > 0) { string candidate = candidates[0]; candidates.RemoveAt(0); if ((VerBose < 2) && (suggestions.Count > 0) && (input.Length - candidate.Length > suggestions[0].distance)) goto sort; if (dictionary.TryGetValue(language + candidate, out valueO)) { DictionaryItem value = new DictionaryItem(); if (valueO is Int32) value.suggestions.Add((Int32)valueO); else value = (DictionaryItem)valueO; if ((value.count > 0) && hashset2.Add(candidate)) { SuggestItem si = new SuggestItem(); si.term = candidate; si.count = value.count; si.distance = input.Length - candidate.Length; suggestions.Add(si); if ((VerBose < 2) && (input.Length - candidate.Length == 0)) goto sort; } object value2; foreach (int suggestionint in value.suggestions) { string suggestion = wordList[suggestionint]; if (hashset2.Add(suggestion)) { int distance = 0; if (suggestion != input) { if (suggestion.Length == candidate.Length) distance = input.Length - candidate.Length; else if (input.Length == candidate.Length) distance = suggestion.Length - candidate.Length; else { // Need no operation for common pre/sufix. int ii = 0; int jj = 0; while ((ii < suggestion.Length) && (ii < input.Length) && (suggestion[ii] == input[ii])) ii++; while ((jj < suggestion.Length - ii) && (jj < input.Length - ii) && (suggestion[suggestion.Length - jj - 1] == input[input.Length - jj - 1])) jj++; if ((ii > 0) || (jj > 0)) { distance = DamerauLevenshteinDistance(suggestion.Substring(ii, suggestion.Length - ii - jj), input.Substring(ii, input.Length - ii - jj)); } else distance = DamerauLevenshteinDistance(suggestion, input); } } // Remove the suggestion if the edit distance is longer than Max. if ((VerBose < 2) && (suggestions.Count > 0) && (suggestions[0].distance > distance)) suggestions.Clear(); if ((VerBose < 2) && (suggestions.Count > 0) && (distance > suggestions[0].distance)) continue; if (distance <= MaxEditDistance) { if (dictionary.TryGetValue(language + suggestion, out value2)) { SuggestItem si = new SuggestItem(); si.term = suggestion; si.count = (value2 as DictionaryItem).count; si.distance = distance; suggestions.Add(si); } } } } } // Exit the recursion when exceeding MaxEditDistance. if (input.Length - candidate.Length < MaxEditDistance) { if ((VerBose < 2) && (suggestions.Count > 0) && (input.Length - candidate.Length >= suggestions[0].distance)) continue; for (int i = 0; i < candidate.Length; i++) { string delete = candidate.Remove(i, 1); if (hashset1.Add(delete)) candidates.Add(delete); } } } sort: // Sort by asending edit distance, descending frequency. if (VerBose < 2) suggestions.Sort((x, y) => -x.count.CompareTo(y.count)); else suggestions.Sort((x, y) => 2 * x.distance.CompareTo(y.distance) - x.count.CompareTo(y.count)); if ((VerBose == 0) && (suggestions.Count > 1)) return suggestions.GetRange(0, 1); else return suggestions; }
// Everytime there is a delete operation, the list will have a list of suggestions for the next step of edit distance. // Creating words list in terms of the corpus text file and the language provided. private static bool CreateDictionaryEntry(string key, string language) { bool result = false; DictionaryItem value = null; object valueO; if (dictionary.TryGetValue(language + key, out valueO)) { if (valueO is Int32) { Int32 tmp = (Int32)valueO; value = new DictionaryItem(); value.suggestions.Add(tmp); dictionary[language + key] = value; } else { value = (valueO as DictionaryItem); } // Prevent oversize. if (value.count < Int32.MaxValue) value.count++; } else if (wordList.Count < Int32.MaxValue) { value = new DictionaryItem(); (value as DictionaryItem).count++; dictionary.Add(language + key, value as DictionaryItem); if (key.Length > MaxLength) MaxLength = key.Length; } // Whenever read a word from the corpus, system will create edits and suggestions. if ((value as DictionaryItem).count == 1) { wordList.Add(key); Int32 keyInt = (Int32)(wordList.Count - 1); result = true; foreach (string delete in Edits(key, 0, new HashSet<string>())) { object value2; if (dictionary.TryGetValue(language + key, out value2)) { if (value2 is Int32) { Int32 tmp = (Int32)value2; DictionaryItem item = new DictionaryItem(); item.suggestions.Add(tmp); dictionary[language + delete] = item; if (!item.suggestions.Contains(keyInt)) AddLowestDistance(item, key, keyInt, delete); } else if (!(value2 as DictionaryItem).suggestions.Contains(keyInt)) AddLowestDistance(value2 as DictionaryItem, key, keyInt, delete); } else { dictionary.Add(language + delete, keyInt); } } } return result; }