示例#1
0
文件: Program.cs 项目: rmacfie/Words
        static void anagramsMode(LanguageInfo language)
        {
            Console.Write("Get top 20 anagrams for: ");
            var input = Console.ReadLine();

            if (string.IsNullOrEmpty(input))
            {
                Console.WriteLine("Input was empty. Try again.");
            }
            else if (!input.All(x => x == AnagramFinder.WILDCARD || language.Letters.Keys.Contains(x)))
            {
                Console.WriteLine("Invalid character(s) in the input. Try again.");
            }
            else
            {
                var anagramFinder = new AnagramFinder(language);
                var foundAny = false;

                foreach (var anagram in anagramFinder.GetTopAnagrams(input.ToCharArray(), 20))
                {
                    Console.WriteLine("  {0} ({1}p)", anagram.Word, anagram.Points);
                    foundAny = true;
                }

                if (!foundAny)
                    Console.WriteLine("No anagrams found.");
            }

            Console.WriteLine();
        }
示例#2
0
        public override bool Initialize(Framework.Interfaces.ICore core)
        {
            bool result = false;

            _customDictionaryDatabaseFile = System.IO.Path.Combine(core.PluginDataPath, "LanguageEng.db3" );

            if (base.Initialize(core))
            {
                LanguageInfo li = new LanguageInfo();
                li.Action = "English";
                li.CultureInfo = new System.Globalization.CultureInfo(1033); //en-US
                li.Action = li.CultureInfo.NativeName;
                SupportedLanguages.Add(li);

                try
                {
                    string fld = System.IO.Path.GetDirectoryName(_customDictionaryDatabaseFile);
                    if (!System.IO.Directory.Exists(fld))
                    {
                        System.IO.Directory.CreateDirectory(fld);
                    }
                }
                catch
                {
                }


                initDatabase();

                result = true;
            }
            return result;
        }
        /// <summary>
        /// Handles culture initialization.
        /// </summary>
        protected override void InitializeCulture()
        {
            try
            {
                // language bar
                {
                    this.languages = Utils.GetLanguages ("Aion.Languages");
                    string lang = (this.Request.QueryString["lang"] ?? string.Empty).Trim ().ToLowerInvariant ();

                    this.currentLanguage = this.languages.SingleOrDefault (x => x.Name == lang);
                    if (this.currentLanguage == null)
                        this.currentLanguage = this.languages[0];

                    this.SetCulture (this.currentLanguage.Culture, this.currentLanguage.Culture);
                }

                if (this.Session["CurrentUICulture"] != null && this.Session["CurrentCulture"] != null)
                {
                    Thread.CurrentThread.CurrentUICulture = (CultureInfo) this.Session["CurrentUICulture"];
                    Thread.CurrentThread.CurrentCulture = (CultureInfo) this.Session["CurrentCulture"];
                }
            }
            catch
            {
            }

            base.InitializeCulture ();
        }
        public void CopiesTheScoreToTheResult()
        {
            var classUnderTest = new DetectedLanguageBuilder(CreateLanguageIsoCodeMappings());
            var languageInfo = new LanguageInfo("", "eng", "", "");
            double score = new Random().NextDouble();
            DetectedLangage result = classUnderTest.BuildFromResult(languageInfo, score);

            Assert.That(result.MatchScore, Is.EqualTo(score));
        }
        public DetectedLangage BuildFromResult(LanguageInfo languageInfo, double score)
        {
            Iso639VariantMappings matchingMapping =
                _iso639Mappings.SingleOrDefault(mapping => mapping.Iso6393Code == languageInfo.Iso639_3);

            if (matchingMapping == null)
                matchingMapping = new Iso639VariantMappings("", "", "", "");

            return new DetectedLangage(languageInfo.Iso639_3, matchingMapping.Iso6391Code, matchingMapping.EnglishName, matchingMapping.NativeName ,score);
        }
        public void WhenNoMatchingMappingReturnsOnlyValuesInLanguageInfo()
        {
            var classUnderTest = new DetectedLanguageBuilder(new StubIso639CodeMappingLoader());
            var languageInfo = new LanguageInfo("", "eng", "", "");
            double score = new Random().NextDouble();
            DetectedLangage result = classUnderTest.BuildFromResult(languageInfo, score);

            Assert.That(result.MatchScore, Is.EqualTo(score));
            Assert.That(result.Iso6393LanguageCode, Is.EqualTo("eng"));
        }
        public void GivenListOfIso639VariantMappingsCorrectlyBuilDetectedLanauge    ()
        {
            var classUnderTest = new DetectedLanguageBuilder(CreateLanguageIsoCodeMappings());
            var languageInfo = new LanguageInfo("", "eng", "", "");
            DetectedLangage result = classUnderTest.BuildFromResult(languageInfo, 0);

            Assert.That(result.Iso6391LanguageCode, Is.EqualTo("en"));
            Assert.That(result.EnglishName, Is.EqualTo("English"));
            Assert.That(result.NativeName, Is.EqualTo("English"));
        }
        public void CopiesLangugeInfoValuesToDetectedLanguageResponse()
        {
            var classUnderTest = new DetectedLanguageBuilder(CreateLanguageIsoCodeMappings());
            var iso6393 = "eng";
            var languageInfo = new LanguageInfo("", iso6393, "", "");
            const double score = 0;
            DetectedLangage result = classUnderTest.BuildFromResult(languageInfo, score);

            Assert.That(result.Iso6393LanguageCode, Is.EqualTo(iso6393));
        }
示例#9
0
        private bool RegionalDialectsFilter(LanguageInfo li)
        {
            if (IncludeRegionalDialects)
            {
                return(true);
            }

            // always include Chinese languages with region codes
            if (li.LanguageTag.IsOneOf("zh-CN", "zh-TW"))
            {
                return(true);
            }

            return(string.IsNullOrEmpty(IetfLanguageTag.GetRegionPart(li.LanguageTag)));
        }
示例#10
0
        public void FromModel_LanguageInfo_ToRdbms()
        {
            // Arrange
            var model = new LanguageInfo()
            {
                Key  = "en-gb",
                Name = "myname"
            };

            // Act
            var rdbms = _rdbmsTypeMapper.Map <Locale>(model);

            // Assert
            Assert_CompareLocale(rdbms, model);
        }
示例#11
0
        /// <summary>
        /// Creates an LocalizedTextJavascriptResult filtered to the texts from the specified type's assembly and default namespaces.
        /// </summary>
        public static LocalizedTextJavascriptResult Create <TAssemblyRef>(
            string clientClassName,
            LanguageInfo language              = null,
            Func <string, bool> keyFilter      = null,
            Func <string, string, bool> filter = null,
            bool gzip = true)
        {
            var tm = LocalizationHelper.TextManager;
            var defaultNamespace = tm.GetNamespace(typeof(TAssemblyRef).Assembly);

            keyFilter = keyFilter ?? ((key) => true);
            filter    = filter ?? ((ns, key) => ns == defaultNamespace && keyFilter(key));

            return(new LocalizedTextJavascriptResult(clientClassName, language, defaultNamespace, filter, gzip));
        }
示例#12
0
 public LocalizedTextJavascriptResult(
     string clientClassName,
     LanguageInfo language              = null,
     string defaultNamespace            = null,
     Func <string, string, bool> filter = null,
     bool gzip  = true,
     bool jsonp = false)
 {
     ClientClassName  = clientClassName;
     Language         = language;
     DefaultNamespace = defaultNamespace;
     Filter           = filter;
     Gzip             = gzip;
     JsonP            = jsonp;
 }
示例#13
0
        private BackTranslationProject GetBackProject(Customer customer, string projectName, CultureInfo sourceLanguage, IEnumerable <CultureInfo> targetLanguages)
        {
            var project = new BackTranslationProject
            {
                Customer    = customer,
                Created     = DateTime.Now.Subtract(new TimeSpan(10, 0, 0, 0, 0)),
                DueDate     = DateTime.Now.AddDays(10),
                Id          = Guid.NewGuid().ToString(),
                Name        = projectName,
                Path        = projectName,
                ProjectType = "RWS Project"
            };

            var sourceLanguageInfo = new LanguageInfo
            {
                CultureInfo = sourceLanguage,
                Image       = _imageService.GetImage(sourceLanguage.Name)
            };

            project.SourceLanguage = sourceLanguageInfo;

            project.TargetLanguages = new List <LanguageInfo>();
            foreach (var targetLanguage in targetLanguages)
            {
                var targetLanguageInfo = new LanguageInfo
                {
                    CultureInfo = targetLanguage,
                    Image       = _imageService.GetImage(targetLanguage.Name)
                };
                project.TargetLanguages.Add(targetLanguageInfo);
            }

            foreach (var targetLanguage in project.TargetLanguages)
            {
                project.ProjectFiles.Add(GetProjectFileAction(project, targetLanguage,
                                                              Enumerators.Action.Export, DateTime.Now.Subtract(new TimeSpan(5, 0, 0, 0, 0))));
                project.ProjectFiles.Add(GetProjectFileAction(project, targetLanguage,
                                                              Enumerators.Action.Import, DateTime.Now));
                project.ProjectFiles.Add(GetProjectFileAction(project, targetLanguage,
                                                              Enumerators.Action.Import, DateTime.Now));
                project.ProjectFiles.Add(GetProjectFileAction(project, targetLanguage,
                                                              Enumerators.Action.Import, DateTime.Now));
                project.ProjectFiles.Add(GetProjectFileAction(project, targetLanguage,
                                                              Enumerators.Action.Import, DateTime.Now));
            }

            return(project);
        }
示例#14
0
        /// <summary>
        /// Returns the token type of the string.
        /// </summary>
        /// <param name="s">A string containing the token to convert</param>
        /// <param name="version">The version of Visual Basic. The version determines if a token is a keyword or not.</param>
        /// <param name="includeUnreserved">Defifes if a non-keyword token will be treated as a keyword.</param>
        /// <returns>A TokenType equivalent to the value contained in s.</returns>
        static public TokenType Parse(string s, LanguageVersion version, bool includeUnreserved)
        {
            if (KeywordTable.ContainsKey(s))
            {
                Keyword Table      = KeywordTable[s];
                bool    isKeyword  = LanguageInfo.Implements(Table.Versions, version);
                bool    isReserved = LanguageInfo.Implements(Table.ReservedVersions, version);

                if (isKeyword && (isReserved || includeUnreserved))
                {
                    return(Table.TokenType);
                }
            }

            return(TokenType.Identifier);
        }
示例#15
0
        public ActionResult Save_Language(string isOnlyDelete, string LanguageId, string LanguageName, string IsActive)
        {
            using (Master_Svc.MasterServiceClient iGstSvc = new Master_Svc.MasterServiceClient())
            {
                LanguageInfo objLanguage = new LanguageInfo();
                objLanguage.LanguageId   = LanguageId;
                objLanguage.LanguageName = LanguageName;
                objLanguage.IsActive     = IsActive.Trim().ToUpper() == "Y";

                if (iGstSvc.Save_Language(isOnlyDelete.Trim().ToUpper() == "Y", objLanguage, ((UserInfo)Session["UserDetails"]), out ErrorMessage))
                {
                    return(Json("Ok", JsonRequestBehavior.AllowGet));
                }
                return(Json(ErrorMessage, JsonRequestBehavior.AllowGet));
            }
        }
示例#16
0
        private ProjectModel GetProject(string clientName, string projectName, CultureInfo sourceLanguage, List <CultureInfo> targetLanguages)
        {
            var projectModel = new ProjectModel
            {
                ClientName              = clientName,
                Created                 = DateTime.Now.Subtract(new TimeSpan(10, 0, 0, 0, 0)),
                DueDate                 = DateTime.Now.AddDays(10),
                Id                      = Guid.NewGuid().ToString(),
                Name                    = projectName,
                Path                    = projectName,
                ProjectType             = "SDL Project",
                ProjectFileActionModels = new List <ProjectFileActionModel>()
            };

            var sourceLanguageInfo = new LanguageInfo();

            sourceLanguageInfo.CultureInfo = sourceLanguage;
            sourceLanguageInfo.ImageName   = sourceLanguage.Name + ".ico";
            sourceLanguageInfo.Image       = _imageService.GetImage(sourceLanguageInfo.ImageName, new Size(24, 24));
            projectModel.SourceLanguage    = sourceLanguageInfo;

            projectModel.TargetLanguages = new List <LanguageInfo>();
            foreach (var targetLanguage in targetLanguages)
            {
                var targetLanguageInfo = new LanguageInfo();
                targetLanguageInfo.CultureInfo = targetLanguage;
                targetLanguageInfo.ImageName   = targetLanguage.Name + ".ico";
                targetLanguageInfo.Image       = _imageService.GetImage(targetLanguageInfo.ImageName, new Size(24, 24));
                projectModel.TargetLanguages.Add(targetLanguageInfo);
            }

            foreach (var targetLanguage in projectModel.TargetLanguages)
            {
                projectModel.ProjectFileActionModels.Add(GetProjectFileAction(projectModel, targetLanguage,
                                                                              Enumerators.Action.Export, DateTime.Now.Subtract(new TimeSpan(5, 0, 0, 0, 0))));
                projectModel.ProjectFileActionModels.Add(GetProjectFileAction(projectModel, targetLanguage,
                                                                              Enumerators.Action.Import, DateTime.Now));
                projectModel.ProjectFileActionModels.Add(GetProjectFileAction(projectModel, targetLanguage,
                                                                              Enumerators.Action.Import, DateTime.Now));
                projectModel.ProjectFileActionModels.Add(GetProjectFileAction(projectModel, targetLanguage,
                                                                              Enumerators.Action.Import, DateTime.Now));
                projectModel.ProjectFileActionModels.Add(GetProjectFileAction(projectModel, targetLanguage,
                                                                              Enumerators.Action.Import, DateTime.Now));
            }

            return(projectModel);
        }
示例#17
0
        public static LanguageItem CreateItem(LanguageInfo info)
        {
            if (info == null)
            {
                return(null);
            }
            LanguageItem item = new LanguageItem();

            item.LangID      = info.LangID;
            item.Name        = info.Name;
            item.Display     = info.Display;
            item.ModuleID    = info.Module;
            item.SubModuleID = info.SubModule;
            item.Info        = info;
            item.State       = LangItemState.None;
            return(item);
        }
示例#18
0
 public DataTemplate SelectTemplate(object item, DependencyObject container)
 {
     if (item != null)
     {
         if (item is LanguageInfo)
         {
             LanguageInfo info = item as LanguageInfo;
             if (info.IsDefault)
             {
                 return(DefaultLanguageTemplate);
             }
             return(DownloadedLanguageTemplate);
         }
     }
     Debug.Assert(false);
     return(null);
 }
示例#19
0
        void UnZipAndProcess(string filename, ArchiveFileType archiveFileType)
        {
            //zip itself may be too huge for timely processing
            if (new FileInfo(filename).Length > WARN_ZIP_FILE_SIZE)
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_FILESIZE_WARN));
            }
            else
            {
                WriteOnce.General(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_PROCESSING));
            }

            LastUpdated = File.GetLastWriteTime(filename);
            _appProfile.MetaData.PackageTypes.Add(ErrMsg.GetString(ErrMsg.ID.ANALYZE_COMPRESSED_FILETYPE));

            try
            {
                IEnumerable <FileEntry> files = Extractor.ExtractFile(filename);

                if (files.Count() > 0)
                {
                    _appProfile.MetaData.TotalFiles += files.Count();//additive in case additional child zip files processed

                    foreach (FileEntry file in files)
                    {
                        //check for supported language
                        LanguageInfo languageInfo = new LanguageInfo();
                        if (FileChecksPassed(file.FullPath, ref languageInfo, file.Content.Length))
                        {
                            byte[] streamByteArray = file.Content.ToArray();
                            ProcessInMemory(file.FullPath, Encoding.UTF8.GetString(streamByteArray, 0, streamByteArray.Length), languageInfo);
                        }
                    }
                }
                else
                {
                    throw new OpException(ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_ERROR, filename));
                }
            }
            catch (Exception e)
            {
                string errmsg = ErrMsg.FormatString(ErrMsg.ID.ANALYZE_COMPRESSED_ERROR, filename);
                WriteOnce.Error(errmsg);
                throw new Exception(errmsg + e.Message + "\n" + e.StackTrace);
            }
        }
示例#20
0
        private void ApplyTranslation()
        {
            if (Program.LanguageManager.Loaded)
            {
                LanguageInfo info = Program.LanguageManager.Translation;

                this.Text                = info.optionTitle;
                GameTab.Text             = info.optionGameTab;
                groupBox1.Text           = info.optionGb1;
                groupBox2.Text           = info.optionGb2;
                groupBox3.Text           = info.optionGb3;
                groupBox4.Text           = info.optionGb4;
                groupBox5.Text           = info.optionGb5;
                label1.Text              = info.optionUser;
                label5.Text              = info.optionDeck;
                label6.Text              = info.optionAntialias;
                EnableSound.Text         = info.optionCbSound;
                EnableMusic.Text         = info.optionCbMusic;
                Enabled3d.Text           = info.optionCbDirect;
                Fullscreen.Text          = info.optionCbFull;
                label2.Text              = info.optionTexts;
                label3.Text              = info.optionTextf;
                QuickSettingsBtn.Text    = info.optionBtnQuick;
                SaveBtn.Text             = info.optionBtnSave;
                CancelBtn.Text           = info.optionBtnCancel;
                AutoPlacing.Text         = info.optionCbAutoPlacing;
                RandomPlacing.Text       = info.optionCbRandomPlacing;
                AutoChain.Text           = info.optionCbAutoChain;
                NoDelay.Text             = info.optionCbNoChainDelay;
                EnableSleeveLoading.Text = info.optionCbEnableSleeves;
                MuteOpp.Text             = info.optionMuteOpp;
                MuteSpec.Text            = info.optionMuteSpec;

                accountTab.Text     = info.optionAccountTab;
                label7.Text         = info.optionCurrentPW;
                label8.Text         = info.optionNewPW;
                label9.Text         = info.optionConfirmPW;
                UpdatePassword.Text = info.optionUpdatePW;

                LanguageInfo lang = info;

                RequestSettingsbtn.Text = lang.chatoptionsBtnRequestSettings;
                SaveBtn.Text            = lang.chatoptionsBtnSave;
                CancelBtn.Text          = lang.chatoptionsBtnCancel;
            }
        }
示例#21
0
        private LanguageInfo GetOrCreateLanguageFromCode(string code, string threelettercode, string countryName)
        {
            LanguageInfo language;

            if (!_codeToEthnologueData.TryGetValue(code, out language))
            {
                language = new LanguageInfo {
                    LanguageTag = code, ThreeLetterTag = threelettercode
                };
                _codeToEthnologueData.Add(code, language);
            }
            if (!string.IsNullOrEmpty(countryName))
            {
                language.Countries.Add(countryName);
            }
            return(language);
        }
示例#22
0
 private void InitLanguagesXml()
 {
     try
     {
         ListLanguageInfosXml.Clear();
         WebRequest webRequest = new WebRequest();
         webRequest.Session = Session;
         webRequest.Code    = (int)S1200Codes.GetLanguageInfoListXml;
         webRequest.ListData.Add(Session.UserID.ToString());
         webRequest.ListData.Add(Session.LangTypeID.ToString());
         Service12001Client client = new Service12001Client(WebHelper.CreateBasicHttpBinding(Session),
                                                            WebHelper.CreateEndpointAddress(Session.AppServerInfo, "Service12001"));
         WebReturn webReturn = client.DoOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             WriteLog("InitLang", string.Format("{0}\t{1}", webReturn.Code, webReturn.Message));
             return;
         }
         if (webReturn.ListData == null)
         {
             WriteLog("InitLang", "ListData is null");
             return;
         }
         for (int i = 0; i < webReturn.ListData.Count; i++)
         {
             OperationReturn optReturn = XMLHelper.DeserializeObject <LanguageInfo>(webReturn.ListData[i]);
             if (!optReturn.Result)
             {
                 WriteLog("InitLang", string.Format("{0}\t{1}", optReturn.Code, optReturn.Message));
                 return;
             }
             LanguageInfo langInfo = optReturn.Data as LanguageInfo;
             if (langInfo == null)
             {
                 WriteLog("InitLang", string.Format("LanguageInfo is null"));
                 return;
             }
             ListLanguageInfosXml.Add(langInfo);
         }
     }
     catch (Exception ex)
     {
         WriteLog("InitLang", string.Format("Fail.\t{0}", ex.Message));
     }
 }
示例#23
0
        public CldrLocale GetLocale(string localeName)
        {
            LanguageInfo localeInfo = FindLanguage(ref localeName);

            if (localeInfo?.Locale != null)
            {
                return(localeInfo.Locale);
            }
            CldrLocale rootLocale = GetLocaleInfo("root").Locale;

            if (rootLocale == null)
            {
                rootLocale = TryLoadLanguage("root", null);
                if (localeName.Equals("root", StringComparison.OrdinalIgnoreCase))
                {
                    return(rootLocale);
                }
            }
            CldrLocale parentLocale = null;

            if (localeInfo == null)
            {
                localeInfo = GetLocaleInfo(localeName);
            }
            LanguageInfo parentInfo = localeInfo.Parent;
            string       parentName = localeName;

            while (parentInfo == null)
            {
                int idx = parentName.LastIndexOf('_');
                if (idx > 0)
                {
                    parentName = localeName.Substring(0, idx);
                    parentInfo = FindLanguage(ref parentName);
                }
                else
                {
                    break;
                }
            }
            if (parentInfo != null)
            {
                parentLocale = GetLocale(parentInfo.Code);
            }
            return(TryLoadLanguage(localeName, parentLocale ?? rootLocale));
        }
示例#24
0
        public void ApplyTranslation()
        {
            LanguageInfo info = Program.LanguageManager.Translation;

            groupBox1.Text         = info.GameUnranked;
            groupBox3.Text         = info.GameRanked;
            groupBox2.Text         = info.GameSearch;
            label6.Text            = info.GameDefaultDeck;
            label4.Text            = info.GameFormat;
            label3.Text            = info.GameType;
            label2.Text            = info.GameBanList;
            label5.Text            = info.GameTimeLimit;
            ActiveGames.Text       = info.GameActive;
            IllegalGames.Text      = info.GameIlligal;
            lockedChk.Text         = info.GameLocked;
            label1.Text            = info.GameUserFilter;
            minEloLbl.Text         = info.GameMinElo;
            maxEloLbl.Text         = info.GameMaxElo;
            SearchRequest_Btn.Text = info.GameBtnSearch;
            Host_btn.Text          = info.GameBtnHost;
            Quick_Btn.Text         = info.GameBtnQuick;
            UpdateLabel.Text       = info.GameNotUpdating;
            SpectateBtn.Text       = info.GameSpectate;
            CheckmateBtn.Text      = info.GameCheckmate;

            Format.Items[0] = info.GameAll;

            GameType.Items[0] = info.GameAll;
            GameType.Items[1] = info.GameSingle;
            GameType.Items[2] = info.GameMatch;
            GameType.Items[3] = info.GameTag;

            BanList.Items[0] = info.GameAll;

            TimeLimit.Items[0] = info.GameAll;
            TimeLimit.Items[1] = "2 " + info.GameMinutes;
            TimeLimit.Items[2] = "1 " + info.GameMinutes;

            joinBtn.Text     = info.GameJoin;
            leaveBtn.Text    = info.GameLeave;
            qJoinBtn.Text    = info.GameQuick;
            rankedLbl.Text   = info.Ranked;
            unrankedLbl.Text = info.Unranked;
            QueueLabel.Text  = info.GameQueueLabel;
        }
示例#25
0
        private void ChooseExportLangFileForm_Load(object sender, EventArgs e)
        {
            int languageCount = _languageInfoList.Count;

            // 根据语种个数,调整窗口高度
            this.Height = _INIT_FORM_HEIGHT + languageCount * _DISTANCE_Y;
            // 根据母表中语种信息,生成操作控件
            for (int i = 0; i < languageCount; ++i)
            {
                LanguageInfo info = _languageInfoList[i];
                // 复选框
                CheckBox chk = new CheckBox();
                chk.Name     = string.Concat(_CHECKBOX_NAME_START_STRING, info.Name);
                chk.AutoSize = false;
                chk.Size     = _CHECKBOX_SIZE;
                chk.Text     = info.Name;
                chk.Location = new Point(_CHECKBOX_POSITION_X, _CHECKBOX_POSITION_START_Y + i * _DISTANCE_Y);
                this.Controls.Add(chk);
                // 路径输入文本框
                TextBox txt = new TextBox();
                txt.Name     = string.Concat(_TEXTBOX_NAME_START_STRING, info.Name);
                txt.Size     = _TEXTBOX_SIZE;
                txt.Location = new Point(_TEXTBOX_POSITION_X, _TEXTBOX_POSITION_START_Y + i * _DISTANCE_Y);
                this.Controls.Add(txt);
                // 选择路径按钮
                Button btnExport = new Button();
                btnExport.Name     = string.Concat(_BUTTON_NAME_START_STRING, info.Name);
                btnExport.Size     = _BUTTON_SIZE;
                btnExport.Text     = "选择";
                btnExport.Location = new Point(_BUTTON_POSITION_X, _BUTTON_POSITION_START_Y + i * _DISTANCE_Y);
                btnExport.Click   += new System.EventHandler(_HandleExportButtonClicked);
                this.Controls.Add(btnExport);
            }

            // 如果选择的是导出lang文件到统一路径,自动填写好导出路径以及文件名
            if (_isExportUnifiedDir == true)
            {
                foreach (LanguageInfo info in _languageInfoList)
                {
                    string  textBoxName = string.Concat(_TEXTBOX_NAME_START_STRING, info.Name);
                    TextBox txt         = this.Controls[textBoxName] as TextBox;
                    txt.Text = Path.Combine(AppValues.ExportLangFileUnifiedDir, string.Concat(info.Name, ".", AppValues.LangFileExtension));
                }
            }
        }
示例#26
0
 private void LoadOptLanguages()
 {
     try
     {
         mListOptLanguages.Clear();
         WebRequest webRequest = new WebRequest();
         webRequest.Code    = (int)RequestCode.WSGetLangList;
         webRequest.Session = CurrentApp.Session;
         webRequest.ListData.Add(CurrentApp.Session.LangTypeInfo.LangID.ToString());
         webRequest.ListData.Add("FO");
         webRequest.ListData.Add(string.Empty);
         webRequest.ListData.Add(string.Empty);
         webRequest.ListData.Add(string.Empty);
         webRequest.ListData.Add(string.Empty);
         Service11012Client client = new Service11012Client(
             WebHelper.CreateBasicHttpBinding(CurrentApp.Session)
             , WebHelper.CreateEndpointAddress(CurrentApp.Session.AppServerInfo, "Service11012"));
         WebReturn webReturn = client.DoOperation(webRequest);
         client.Close();
         if (!webReturn.Result)
         {
             ShowException(string.Format("{0}\t{1}", webReturn.Code, webReturn.Message));
         }
         for (int i = 0; i < webReturn.ListData.Count; i++)
         {
             OperationReturn optReturn = XMLHelper.DeserializeObject <LanguageInfo>(webReturn.ListData[i]);
             if (!optReturn.Result)
             {
                 ShowException(string.Format("{0}\t{1}", optReturn.Code, optReturn.Message));
                 return;
             }
             LanguageInfo langInfo = optReturn.Data as LanguageInfo;
             if (langInfo == null)
             {
                 ShowException(string.Format("LanguageInfo is null"));
                 return;
             }
             mListOptLanguages.Add(langInfo);
         }
     }
     catch (Exception ex)
     {
         ShowException(ex.Message);
     }
 }
示例#27
0
        void lvLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            #region 准备数据
            LanguageInfo row = lvLanguage.SelectedItem as LanguageInfo;
            if (row == null)
            {
                return;
            }
            string strMessageId = row.MessageID;

            List <LanguageInfo> lstLans = lstViewrSource.Where(p => p.MessageID == strMessageId).ToList();
            App.GLstLanguageItemInEdit.Clear();
            App.GLstLanguageItemInEdit = lstLans;

            #endregion
            #region 加载控件
            UC_LanguageInfo uc_Lan;
            if (LanManagerWindow.dpDetail.Children.Count > 0)
            {
                try
                {
                    //如果dpDetail中加载的是UC_LanguageInfo控件 则直接填充控件 而不New一个新的UC_LanguageInfo
                    uc_Lan = LanManagerWindow.dpDetail.Children[0] as UC_LanguageInfo;
                    uc_Lan.lstLanguageInfos = lstLans;
                    uc_Lan.InitControl();
                }
                catch
                {
                    //反之 则new一个新的 加载到dpDetail
                    uc_Lan = new UC_LanguageInfo(lstLans, LanManagerWindow);
                    LanManagerWindow.dpDetail.Children.Clear();
                    LanManagerWindow.dpDetail.Children.Add(uc_Lan);
                }
                LanManagerWindow.spOperator.Children.RemoveAt(1);
                UC_DBOpeartionDefault edit = new UC_DBOpeartionDefault(LanManagerWindow);
                LanManagerWindow.spOperator.Children.Add(edit);
            }
            else
            {
                uc_Lan = new UC_LanguageInfo(lstLans, LanManagerWindow);
                LanManagerWindow.dpDetail.Children.Clear();
                LanManagerWindow.dpDetail.Children.Add(uc_Lan);
            }
            #endregion
        }
示例#28
0
 public void SetKey(string[] keys)
 {
     this.keys.Clear();
     foreach (var key in keys)
     {
         KeyInfo info = new KeyInfo();
         info.key       = key;
         info.languages = new List <LanguageInfo>();
         foreach (var area in areas)
         {
             LanguageInfo languageInfo = new LanguageInfo();
             languageInfo.areaName = area.name;
             languageInfo.value    = "123";
             info.languages.Add(languageInfo);
         }
         this.keys.Add(info);
     }
 }
示例#29
0
        public LanguageInfo GetActiveLanguage()
        {
            LanguageSavedData languageSavedData =
                ServiceLocator.Resolve <IStorageService>().ResolveData <LanguageSavedData>() ?? new LanguageSavedData();
            LanguageInfo result =
                InfoResolver.Resolve <FortInfo>().Language.ActiveLanguages.Where(info => info != null).FirstOrDefault(
                    info => info.Id == languageSavedData.LanguageId);

            if (result == null)
            {
                result = InfoResolver.Resolve <FortInfo>().Language.DefaultLanguage;
                if (result == null)
                {
                    result = InfoResolver.Resolve <FortInfo>().Language.ActiveLanguages.FirstOrDefault(info => info != null);
                }
            }
            return(result);
        }
示例#30
0
        public LanguageInfo[] DetectLanguage(string text)
        {
            if (text.IsNullOrWhiteSpace())
            {
                return(null);
            }

            var weight = ProcessInternal(text);

            if (weight == NULL_WEIGHT || weight < _Threshold)
            {
                return(LANGUAGEINFO_EMPTY);
            }

            var languageInfo = new LanguageInfo(Language.RU, weight);

            return(new[] { languageInfo });
        }
示例#31
0
 public static string GetLanguageInfoXml(string name, string display)
 {
     try
     {
         LanguageInfo lang =
             ListLanguageInfosXml.FirstOrDefault(l => l.LangID == Session.LangTypeInfo.LangID && l.Name == name);
         if (lang == null)
         {
             return(display);
         }
         return(lang.Display);
     }
     catch (Exception ex)
     {
         WriteLog("GetLang", string.Format("GetLang fail.\t{0}", ex.Message));
         return(display);
     }
 }
        public async Task <int> AddAsync(string cvId, LanguageType languageType,
                                         LanguageLevel comprehension, LanguageLevel speaking, LanguageLevel writing)
        {
            var languageInfo = new LanguageInfo
            {
                CurriculumVitaeId = cvId,
                LanguageType      = languageType,
                Comprehension     = comprehension,
                Speaking          = speaking,
                Writing           = writing
            };

            await this.repository.AddAsync(languageInfo);

            await this.repository.SaveChangesAsync();

            return(languageInfo.Id);
        }
示例#33
0
        public async override Task<bool> InitializeAsync(Framework.Interfaces.ICore core)
        {
            bool result = false;

            if (await base.InitializeAsync(core))
            {
                LanguageInfo li = new LanguageInfo();
                li.Action = "English";
                li.CultureInfo = new System.Globalization.CultureInfo(1033); //en-US
                li.Action = li.CultureInfo.NativeName;
                SupportedLanguages.Add(li);

                initDatabase();

                result = true;
            }
            return result;
        }
示例#34
0
        public async override Task <bool> InitializeAsync(Framework.Interfaces.ICore core)
        {
            bool result = false;

            if (await base.InitializeAsync(core))
            {
                LanguageInfo li = new LanguageInfo();
                li.Action      = "Nederlands";
                li.CultureInfo = new System.Globalization.CultureInfo(1043);
                li.Action      = li.CultureInfo.NativeName;
                SupportedLanguages.Add(li);

                initDatabase();

                result = true;
            }
            return(result);
        }
示例#35
0
        public SettingsViewModel(Settings settings, ConnectionManager connectionManager)
        {
            _connectionManager = connectionManager;
            Settings           = settings;
            _selectedLanguage  = settings.Language;
            _theme             = settings.Theme;
            RefreshRestartRequired();

            AccentColorMenuDatas =
                new[]
            {
                "Blue", "Cobalt", "Purple", "Emerald", "Teal", "Brown", "Orange", "Red", "Crimson", "Pink",
                "Magenta",
                "Steel"
            }.Select(
                x => new AccentColorViewModel(x)).ToList();
            _selectedAccentColor = AccentColorMenuDatas.First(x => x.Name == Settings.AccentColor);
        }
        public void EqualsCheck()
        {
            ILanguageInfo a = new LanguageInfo {
                Code = "en", Support = LanguageSupportLevel.FullLocalized
            };
            ILanguageInfo b = new JsonLanguageInfo(new LanguageInfo {
                Code = "en", Support = LanguageSupportLevel.SFX
            });
            ILanguageInfo c = new LanguageInfo {
                Code = "de", Support = LanguageSupportLevel.FullLocalized
            };
            var d = LanguageInfo.Default;

            Assert.Equal(a, b);
            Assert.NotEqual(a, c);
            Assert.Equal(a, d);
            Assert.Equal(LanguageSupportLevel.FullLocalized, d.Support);
        }
        public static MvcHtmlString GetText(this HtmlHelper htmlHelper, string key, object values = null,
                                            LanguageInfo language = null, string ns = null, Type type = null, string @default = null)
        {
            var manager = LocalizationHelper.TextManager;

            if (type != null)
            {
                ns = manager.GetNamespace(type.Assembly);
            }

            var text = manager.Get(key, values, ns: ns, language: language, returnNullOnMissing: @default != null);

            if (text == null)
            {
                text = HttpUtility.HtmlEncode(@default);
            }
            return(new MvcHtmlString(text));
        }
示例#38
0
        private CodeGen MakeRawKeysMethod(LanguageInfo li, Dictionary <SymbolId, Slot> fields)
        {
            Slot    rawKeysCache = li.TypeGen.AddStaticField(typeof(SymbolId[]), "ExtraKeysCache");
            CodeGen init         = li.TypeGen.TypeInitializer;

            init.EmitInt(0);
            init.Emit(OpCodes.Newarr, typeof(SymbolId));

            rawKeysCache.EmitSet(init);

            CodeGen cg = li.TypeGen.DefineMethodOverride(typeof(CustomSymbolDictionary).GetMethod("GetExtraKeys", BindingFlags.Public | BindingFlags.Instance));

            rawKeysCache.EmitGet(cg);
            cg.EmitReturn();
            cg.Finish();

            return(cg);
        }
        private async Task IniLanguages()
        {
            var selectedLanguageName = await JsRuntime.InvokeAsync <string>(
                "localStorage.getItem",
                "Abp.SelectedLanguage"
                );

            _otherLanguages = await LanguageProvider.GetLanguagesAsync();

            if (!_otherLanguages.Any())
            {
                return;
            }

            if (!selectedLanguageName.IsNullOrWhiteSpace())
            {
                _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == selectedLanguageName);
            }

            if (_currentLanguage == null)
            {
                _currentLanguage = _otherLanguages.FirstOrDefault(l => l.UiCultureName == CultureInfo.CurrentUICulture.Name);
            }

            if (_currentLanguage == null)
            {
                _currentLanguage = _otherLanguages.FirstOrDefault();
            }

            //language menu
            List <string> _locales = new List <string>();

            LanguageLabels = new Dictionary <string, string>();
            LanguageIcons  = new Dictionary <string, string>();
            foreach (LanguageInfo language in _otherLanguages)
            {
                Logger.LogDebug("language:{0}", language.CultureName);
                _locales.Add(language.CultureName);
                LanguageLabels.Add(language.CultureName, language.FlagIcon);
                LanguageIcons.Add(language.CultureName, language.DisplayName);
            }
            this.Locales    = _locales.ToArray();
            _otherLanguages = _otherLanguages.Where(l => l != _currentLanguage).ToImmutableList();
        }
        private void OnLoad(object sender, EventArgs e)
        {
            if (DesignMode)
                return;
            if (_model.LanguageInfo != null)
            {
                _searchText.Text = _model.LanguageInfo.Code;
                if (!string.IsNullOrEmpty(_model.LanguageInfo.DesiredName))
                {
                    _incomingLanguageInfo = _model.LanguageInfo;
                    _desiredLanguageDisplayName.Text = _model.LanguageInfo.DesiredName;
                }
            }
            if (_desiredLanguageDisplayName.Visible)
                AdjustDesiredLanguageNameFieldLocations();
            AdjustCannotFindLanguageLocation();

            UpdateReadiness();
            _searchTimer.Start();
        }
 /// <summary>
 /// Creates a JavaScript class to use the TextManager's texts client-side
 /// </summary>
 /// <param name="manager">The manager.</param>
 /// <param name="clientClassName">Name of the class.</param>
 /// <param name="language">The language for the generated texts (if different from current language).</param>
 /// <param name="defaultNamespace">The default namespace for texts. (Set this to your assembly's namespace in plugins)</param>
 /// <param name="filter">Specify this to only include a subset of the TextManager's texts.</param>
 /// <param name="includeScriptTags">Wraps the generated script in &lt;script&gt; blocks if <c>true</c>.</param>
 /// <returns></returns>
 public static HtmlString WriteScript(this TextManager manager, string clientClassName, LanguageInfo language = null,
     string defaultNamespace = null, Func<string, string, bool> filter = null, bool includeScriptTags = true)
 {
     var generator = new JavaScriptGenerator();
     using (var s = new StringWriter())
     {
         generator.WriteScript(manager, clientClassName, s, language, defaultNamespace, filter, includeScriptTags);
         return new HtmlString(s.ToString());
     }
 }
 protected void Write(string ns, string key, LanguageInfo language, Expression expr, TextWriter output, string clientClassName)
 {
     var context = new EvaluationContext
     {
         Namespace = ns,
         Language = language,
         StringEncoder = x => x
     };
     var writer = new JavaScriptExpressionWriter(Writers, output, context);
     writer.ClientClassName = clientClassName;
     expr.Accept(writer);            
 }
        /// <summary>
        /// Generates JavaScript functions to evaluate patterns client side
        /// </summary>
        /// <param name="manager">The text manager to extract texts from.</param>
        /// <param name="clientClassName">The client name of the generated object. (The script will be var clientClassName = ...)</param>
        /// <param name="output">The generated javascript will be written to this generator.</param>
        /// <param name="language">The language for the generated texts (if different from current language).</param>
        /// <param name="defaultNamespace">The default namespace for texts. (Set this to your assembly's namespace in plugins)</param>
        /// <param name="filter">Specify this to only include a subset of the TextManager's texts.</param>
        /// <param name="includeScriptTags">Wraps the generated script in &lt;script&gt; blocks if <c>true</c>.</param>
        public void WriteScript(TextManager manager, string clientClassName, TextWriter output, LanguageInfo language = null, string defaultNamespace = null, Func<string,string,bool> filter = null, bool includeScriptTags = true)
        {            
            language = language ?? manager.GetCurrentLanguage();
            defaultNamespace = defaultNamespace ?? manager.DefaultNamespace;            
            filter = filter ?? ((ns, key) => true);

            if (includeScriptTags)
            {
                output.Write("<script type='text/javascript'>/*<![CDATA[*/");
            }

            var foundationNamespace = manager.GetNamespace(typeof(TextManager).Assembly);
            Func<string, string, bool> foundationTextFilter = (ns, key) =>
                ns == foundationNamespace &&
                    _foundationTextKeyMatcher.IsMatch(key);                                           



            var texts = manager.CurrentEntries
                .SelectMany(ns => ns.Value
                    .Where(key => foundationTextFilter(ns.Key, key.Key) || filter(ns.Key, key.Key))                    
                    .Select(key =>
                            new
                            {
                                Namespace = ns.Key,
                                Key = key.Key,
                                CacheEntry = manager.GetTextEntry(ns.Key, key.Key, language, true)
                            })).Where(x=>x.CacheEntry != null).ToList();

            var json = new JavaScriptSerializer();

            output.Write("var ");
            output.Write(clientClassName);
            output.Write("=new Umbraco.Framework.Localization.TextManager(");
            output.Write(json.Serialize(defaultNamespace));
            output.Write(",");
            output.Write(GetClientCultureInfoSpecification(json, (CultureInfo) language.Culture));            

            //Namespace keys
            output.Write(",{");
            var namespaceKeys = new Dictionary<string, string>();
            int i = 0;
            foreach (var ns in texts.Select(x => x.Namespace).Distinct())
            {
                var key = "" + i;
                namespaceKeys.Add(ns, key);
                if (i++ > 0) output.Write(",");
                output.Write(json.Serialize(ns));
                output.Write(":");
                output.Write(json.Serialize(key));                             
            }

            output.Write("}");

            output.Write(",");
            output.Write(json.Serialize(manager.FallbackNamespaces.ToArray()));

            //Texts (function takes: manager, applySwitch, defaultFormattedValue, htmlEncode, applyFormat, getValue, reflectionParameter
            output.Write(",function(m,sw,dv,e,af,val,rp,sf) {");            
                                            

            //Write prerequisite code                                   

            //Prerequisites for used writers
            var checker = new JavaScriptExpressionChecker(Writers);
            var usedWriters = new HashSet<IJavaScriptGenerator>();
            foreach (var text in texts)
            {
                var exprWriters = checker.CheckExpression(text.CacheEntry.Evaluator.Expression).UsedWriters;
                foreach (var writer in exprWriters)
                {
                    usedWriters.Add(writer);
                }
            }

            foreach (var writer in usedWriters)
            {
                writer.WritePrerequisites(output);
            }            

            bool first = true;        
            output.Write("return {");
            //Write texts
            foreach (var text in texts)
            {        
                if (first) first = false; else output.Write(",\n");                        
                output.Write(json.Serialize(namespaceKeys[text.Namespace] + text.Key));
                output.Write(":");
                //TODO: Maybe it should be put somewhere if the text is a fallback text
                //bool fallback = text.CacheEntry.Text.Language != language.Key;
                Write(text.Namespace, text.Key, language, text.CacheEntry.Evaluator.Expression, output, clientClassName);                
            }
            output.Write("};");

            output.Write("});");

            if (includeScriptTags)
            {
                output.Write("//]]></script>");
            }
        }
        IEnumerator TranslateAsync()
        {
            var localLang = LocalizationService.Instance.Language;
            var files = LocalizationService.Instance.Files.ToArray();
            LangTotal = Options.Count(o => o.Translate);
            FileTotal = files.Length * LangTotal;
            StringTotal = LocalizationService.Instance.StringsByFile.Sum(o => o.Value.Count) * LangTotal;
            StringDone = FileDone = LangDone = 0;

            Debug.Log(StringTotal);

            foreach (var language in Options)
            {
                if (Cancel)
                    yield break;

                if (!language.Translate || language.lang.Abbreviation == localLang.Abbreviation)
                {
                    Debug.Log("Skipping language : " + language.lang.Name);
                    continue;
                }

                Debug.Log("Starting language : " + language.lang.Name);
                Language = language.lang;

                foreach (var file in files)
                {
                    if (Cancel)
                        yield break;
                    Debug.Log("Starting file : " + file);
                    FileName = file;

                    var strings = LocalizationService.Instance.GetFile(file);

                    var translated = new Dictionary<string, string>();

                    foreach (var pair in strings)
                    {
                        if (Cancel)
                            yield break;

                        var s = GetTranslation(language.lang, pair.Value);

                        //yield return s;
                        while (!s.isDone)
                        {
                            yield return 1;
                        }

                        if (!string.IsNullOrEmpty(s.error))
                        {
                            Debug.LogError("Error " + pair.Key);
                            Debug.LogError(s.error);
                            yield break;
                        }
                        translated.Add(pair.Key, Deserialize(s));
                        StringDone++;
                    }

                    WriteFile(language.lang, FileName, translated);
                    FileDone++;
                }
                LangDone++;
            }

            Debug.Log("Complete");
            IsWorking = false;
            IsComplete = true;
        }
        private void _searchTimer_Tick(object sender, EventArgs e)
        {
            var oldIso = _model.ISOCode;
            var typedText = _searchText.Text.Trim();
            if (typedText == _lastSearchedForText)
            {
                return;
            }
            _lastSearchedForText = typedText;
            _listView.SuspendLayout();

            _listView.Items.Clear();
            _listView.SelectedIndices.Clear();
            var toShow = new List<ListViewItem>();

            if (_searchText.Text == "?")
            {
                var description = L10NSharp.LocalizationManager.GetString("LanguageLookup.UnlistedLanguage", "Unlisted Language");
                List<string> names = new List<string>(new string[] {description});
                LanguageInfo unlistedLanguage = new LanguageInfo() {Code = "qaa", Country = "", Names = names};
                ListViewItem item = new ListViewItem(description);
                item.SubItems.Add("qaa");
                item.Tag = unlistedLanguage;
                item.Selected = true;
                _listView.Items.Add(item);

            }
            else
            {
                var itemSelected = false;
                foreach (LanguageInfo lang in _model.GetMatchingLanguages(typedText))
                {
                    ListViewItem item = new ListViewItem(lang.Names[0]);
                    item.SubItems.Add(lang.Code);
                    item.SubItems.Add(lang.Country);
                    item.SubItems.Add(string.Join(", ", lang.Names.Skip(1)));
                    item.SubItems.Add(lang.Country);
                    item.Tag = lang;
                    toShow.Add(item);

            //					if (!itemSelected && typedText.Length > 1 &&
            //					    (lang.Code.ToLower() == typedText || lang.Names[0].ToLower().StartsWith(typedText.ToLower())))
                    if (!itemSelected)
                    {
                        item.Selected = true;
                        itemSelected = true; //we only want to select the first one
                    }
                }
                if (!itemSelected)
                {
                    _model.LanguageInfo = null;
                    //_desiredLanguageDisplayName.Text = _searchText.Text;
                }
                _desiredLanguageDisplayName.Enabled = itemSelected;
                _listView.Items.AddRange(toShow.ToArray());

            }
            _listView.ResumeLayout();
            //            if (_listView.Items.Count > 0)
            //            {
            //                _listView.SelectedIndices.Add(0);
            //            }			if(_model.ISOCode != oldIso)
            UpdateReadiness();
        }
 private void MakeSetMethod(LanguageInfo li, Dictionary<SymbolId, Slot> fields)
 {
     CodeGen cg = li.TypeGen.DefineMethodOverride(typeof(CustomSymbolDictionary).GetMethod("TrySetExtraValue", BindingFlags.NonPublic | BindingFlags.Instance));
     Slot valueSlot = cg.GetArgumentSlot(1);
     cg.EmitInt(0);
     cg.EmitReturn();
     cg.Finish();
 }
        private CodeGen MakeRawKeysMethod(LanguageInfo li, Dictionary<SymbolId, Slot> fields)
        {
            Slot rawKeysCache = li.TypeGen.AddStaticField(typeof(SymbolId[]), "ExtraKeysCache");
            CodeGen init = li.TypeGen.TypeInitializer;

            init.EmitInt(0);
            init.Emit(OpCodes.Newarr, typeof(SymbolId));

            rawKeysCache.EmitSet(init);

            CodeGen cg = li.TypeGen.DefineMethodOverride(typeof(CustomSymbolDictionary).GetMethod("GetExtraKeys", BindingFlags.Public | BindingFlags.Instance));
            rawKeysCache.EmitGet(cg);
            cg.EmitReturn();
            cg.Finish();

            return cg;
        }
 private void BuildDictionary(LanguageInfo li, Dictionary<SymbolId, Slot> fields)
 {
     MakeGetMethod(li, fields);
     MakeSetMethod(li, fields);
     MakeRawKeysMethod(li, fields);
     MakeInitialization(li, fields);
 }
        private static void MakeInitialization(LanguageInfo li, Dictionary<SymbolId, Slot> fields)
        {
            li.TypeGen.TypeBuilder.AddInterfaceImplementation(typeof(IModuleDictionaryInitialization));
            CodeGen cg = li.TypeGen.DefineExplicitInterfaceImplementation(typeof(IModuleDictionaryInitialization).GetMethod("InitializeModuleDictionary"));

            Label ok = cg.DefineLabel();
            cg.ContextSlot.EmitGet(cg);
            cg.Emit(OpCodes.Brfalse_S, ok);
            cg.EmitReturn();
            cg.MarkLabel(ok);

            cg.EmitArgGet(0);
            cg.ContextSlot.EmitSet(cg);

            foreach (KeyValuePair<SymbolId, Slot> kv in fields) {
                Slot slot = kv.Value;
                ModuleGlobalSlot builtin = slot as ModuleGlobalSlot;

                Debug.Assert(builtin != null);
                if (builtin != null)
                {
                  cg.EmitCodeContext();
                  cg.EmitSymbolId(kv.Key);
                  builtin.EmitWrapperAddr(cg);
                  cg.EmitCall(typeof(RuntimeHelpers), "InitializeModuleFieldBoxed");
                }

                StaticFieldSlot sfs = slot as StaticFieldSlot;
                if (sfs != null)
                {
                  cg.EmitCodeContext();
                  cg.EmitSymbolId(kv.Key);
                  sfs.EmitGetAddr(cg);
                  cg.EmitCall(typeof(RuntimeHelpers).GetMethod("InitializeFieldBoxed").MakeGenericMethod( sfs.Type ));

                }
            }

            cg.EmitReturn();
            cg.Finish();
        }
示例#50
0
            public static LanguageInfo Parse(string data)
            {
                try
                {
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(data);

                    XmlElement root = xml.DocumentElement;
                    XmlElement nameNode = root["name"];
                    XmlElement cultureCodeNode = root["culture"];
                    XmlElement packageUrlNode = root["packageurl"];

                    string name = nameNode.InnerText.Trim();
                    string cultureCode = cultureCodeNode.InnerText.Trim();
                    string packageUrl = packageUrlNode.InnerText.Trim();

                    LanguageInfo info = new LanguageInfo(name, cultureCode, packageUrl);
                    return info;
                }
                catch
                {
                    return null;
                }
            }
        WWW GetTranslation(LanguageInfo lang, string s)
        {
            const string pathRaw = "https://translate.yandex.net/api/v1.5/tr.json/translate?key={0}&lang={1}-{2}&text={3}";
            var path = string.Format(pathRaw, ApiKey, LocalizationService.Instance.Language.Abbreviation, lang.Abbreviation, s.Replace(" ", "%20"));

            return new WWW(path);
        }
示例#52
0
		private void _searchTimer_Tick(object sender, EventArgs e)
		{
			var oldIso = _model.ISOCode;
			var typedText = _searchText.Text.Trim();
			if(typedText == _lastSearchedForText)
			{
				return;
			}
			_lastSearchedForText = typedText;
			_listView.SuspendLayout();

			_listView.Items.Clear();
			_listView.SelectedIndices.Clear();
			var toShow = new List<ListViewItem>();

			var multipleCountriesLabel = LocalizationManager.GetString("LanguageLookup.CountryCount", "{0} Countries", "Shown when there are multiple countries and it is just confusing to list them all.");

			if(_searchText.Text == "?")
			{
				var description = L10NSharp.LocalizationManager.GetString("LanguageLookup.UnlistedLanguage", "Unlisted Language");
				List<string> names = new List<string>(new string[] { description });
				LanguageInfo unlistedLanguage = new LanguageInfo() { Code = "qaa", Country = "", Names = names };
				ListViewItem item = new ListViewItem(description);
				item.SubItems.Add("qaa");
				item.Tag = unlistedLanguage;
				item.Selected = true;
				_listView.Items.Add(item);
			}
			else
			{
				var itemSelected = false;
				foreach(LanguageInfo lang in _model.GetMatchingLanguages(typedText))
				{
					var mainName = string.IsNullOrEmpty(lang.LocalName) ? lang.Names[0] : lang.LocalName;
					var item = new ListViewItem(mainName);
					item.SubItems.Add(lang.Code);

					// Users were having problems when they looked up things like "English" and were presented with "United Arab Emirates"
					// and such, as these colonial languages are spoken in so many countries. So this just displays the number of countries.
					var country = lang.Country;
					if(lang.CountryCount > 2) // 3 or more was chosen because generally 2 languages fit in the space allowed
					{
						country = string.Format(multipleCountriesLabel, lang.CountryCount);
					}
					item.SubItems.Add(country);
					var numberOfNamesAlreadyUsed = string.IsNullOrEmpty(lang.LocalName) ? 1 : 0;
					item.SubItems.Add(string.Join(", ", lang.Names.Skip(numberOfNamesAlreadyUsed)));
					item.Tag = lang;
					toShow.Add(item);

					//					if (!itemSelected && typedText.Length > 1 &&
					//					    (lang.Code.ToLower() == typedText || lang.Names[0].ToLower().StartsWith(typedText.ToLower())))
					if(!itemSelected)
					{
						item.Selected = true;
						itemSelected = true; //we only want to select the first one
					}
				}
				if(!itemSelected)
				{
					_model.LanguageInfo = null;
					//_desiredLanguageDisplayName.Text = _searchText.Text;
				}
				_desiredLanguageDisplayName.Enabled = itemSelected;
				_listView.Items.AddRange(toShow.ToArray());
				//scroll down to the selected item
				if(_listView.SelectedItems.Count > 0)
				{
					_listView.SelectedItems[0].EnsureVisible();
				}
			}
			_listView.ResumeLayout();
			//            if (_listView.Items.Count > 0)
			//            {
			//                _listView.SelectedIndices.Add(0);
			//            }			if(_model.ISOCode != oldIso)
			UpdateReadiness();
		}
示例#53
0
        private static List<LanguageInfo> CollectSupportedLanguages(Assembly parserAssembly)
        {
            var languages = new List<LanguageInfo>();
            var resourceNames = parserAssembly.GetManifestResourceNames();
            foreach (var resourceName in resourceNames)
            {
                var match = i18NResourceRe.Match(resourceName);
                if (!match.Success)
                    continue;

                LanguageInfo languageInfo = new LanguageInfo();
                languageInfo.Code = match.Groups["lang"].Value.Replace("_", "-");
                if (languageTranslations.ContainsKey(languageInfo.Code))
                {
                    languageInfo.CompatibleGherkinCode = languageInfo.Code;
                    languageInfo.Code = languageTranslations[languageInfo.Code];
                }

                CultureInfo cultureInfo = GetCultureInfo(languageInfo.Code);
                if (cultureInfo == null)
                    continue;

                languageInfo.CultureInfo = cultureInfo.Name;
                languageInfo.EnglishName = cultureInfo.EnglishName;
                if (cultureInfo.IsNeutralCulture)
                {
                    CultureInfo defaultSpecificCulture = GetDefaultSpecificCulture(languageInfo.Code);
                    if (defaultSpecificCulture != null)
                        languageInfo.DefaultSpecificCulture = defaultSpecificCulture.Name;
                }
                languages.Add(languageInfo);
            }
            return languages;
        }
        void WriteFile(LanguageInfo language, string fileName, Dictionary<string, string> file)
        {
            var csv = new StringBuilder();

            foreach (var f in file)
            {
                csv.AppendLine(string.Format("{0},{1}", f.Key, RemoveNewline(f.Value)));
            }

            var path = RootPath + "/Resources/Localization/" + language.Name;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var fPath = string.Format("{0}/{1}.txt", path, fileName);

            if (File.Exists(fPath))
            {
                File.Delete(fPath);
            }

            File.WriteAllText(fPath, csv.ToString());

            Debug.Log(fPath);
        }