Beispiel #1
0
        protected void PostProcessAllTranslatedAssemblies(
            Configuration configuration, string assemblyPath, TranslationResult result)
        {
            string basePath = Path.GetDirectoryName(Path.GetFullPath(assemblyPath));
            List<string> assemblyPaths = new List<string>();

            foreach (var item in result.Assemblies)
            {
                var path = Path.Combine(basePath, item.Name.Name + ".dll");
                if (File.Exists(path))
                {
                    assemblyPaths.Add(path);
                }
                else
                {
                    path = Path.Combine(basePath, item.Name.Name + ".exe");
                    if (File.Exists(path))
                    {
                        assemblyPaths.Add(path);
                    }
                }
            }

            foreach (var path in assemblyPaths)
            {
                PostProcessAssembly(configuration, path, result);
            }
        }
Beispiel #2
0
 public override void ProcessSkippedAssembly(
     Configuration configuration, string assemblyPath, TranslationResult result
 )
 {
     ResourceConverter.ConvertResources(configuration, assemblyPath, result);
     ManifestResourceExtractor.ExtractFromAssembly(configuration, assemblyPath, result);
 }
Beispiel #3
0
        public virtual void WriteOutputs(TranslationResult result, string path, string manifestPrefix)
        {
            Console.WriteLine(manifestPrefix + "manifest.js");

            foreach (var fe in result.OrderedFiles)
                Console.WriteLine(fe.Filename);

            result.WriteToDirectory(path, manifestPrefix);
        }
Beispiel #4
0
        public virtual void WriteOutputs (VariableSet variables, TranslationResult result, string path, string manifestPrefix) {
            AssemblyTranslator.GenerateManifest(result.AssemblyManifest, result.AssemblyPath, result);

            Console.WriteLine(manifestPrefix + "manifest.js");

            foreach (var fe in result.OrderedFiles)
                Console.WriteLine(fe.Filename);

            result.WriteToDirectory(path, manifestPrefix);
        }
Beispiel #5
0
        public void WhereWithInvalidMethod()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Take(2);
            var translation = new TranslationResult();

            // Act
            Assert.Throws <ArgumentOutOfRangeException>(() => translator.Translate((MethodCallExpression)query.Body, translation));

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.Null(translation.TableQuery.FilterString);
        }
Beispiel #6
0
        public TranslationResult TranslateTextWithModel()
        {
            TranslationClient client = TranslationClient.Create();
            TranslationResult result = client.TranslateText(
                text: tb.Text,
                targetLanguage: "ko",  // Korean
                sourceLanguage: "en",  // English
                model: TranslationModel.NeuralMachineTranslation);

            Console.WriteLine($"Model: {result.Model}");
            Console.WriteLine(result.TranslatedText);

            return(result);
        }
Beispiel #7
0
        public void BinaryExpressionWithComplexExpression()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => Math.Abs(p.Area - Convert.ToDouble(555)) < 0.2);
            var translation = new TranslationResult();

            // Act
            Assert.Throws <NotSupportedException>(() => translator.Translate((MethodCallExpression)query.Body, translation));

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.Null(translation.TableQuery.FilterString);
        }
Beispiel #8
0
        private void TranslateLine(string inputWords)
        {
            //TransResult = TranslationResult.Full;
            string[] fehlerWords = inputWords.Split(' ');

            int    fehlerWordsEndPos = fehlerWords.Length - 1;
            int    lastTransPos      = fehlerWordsEndPos;
            string decreasedWords    = SubString(fehlerWords, 0, fehlerWordsEndPos);

            string transWordsBlock = "";

            int iStart;

            for (iStart = 0; iStart <= fehlerWordsEndPos; iStart++)
            {
                decreasedWords  = SubString(fehlerWords, iStart, fehlerWordsEndPos);
                transWordsBlock = decreasedWords;
                if (TranslateWord(decreasedWords, ref transWordsBlock))
                {
                    lastTransPos = iStart;
                    break;
                }
            }

            if (iStart == 0)//full translated exit translate loop
            {
                TranslatedBlock = transWordsBlock + TranslatedBlock;
                // return TranslatedBlock;
            }
            else if (lastTransPos == 0 && iStart > 0)// non translation of the last wordblock
            {
                TransResult     = TranslationResult.Partial;
                TranslatedBlock = transWordsBlock + " " + TranslatedBlock;;
                //return OriginalBlock;
            }
            else
            {
                if (iStart > lastTransPos)
                {
                    transWordsBlock = transWordsBlock + " "; //no word be translated then add space to the last word
                    TransResult     = TranslationResult.Partial;
                }
                TranslatedBlock = transWordsBlock + TranslatedBlock;

                string subWords = SubString(fehlerWords, 0, lastTransPos - 1);
                TranslateLine(subWords);
            }

            //return "error occured!!!!!";
        }
        public override TranslationResult Translate(TranslationContext context)
        {
            if (!(this.Identifier is IdentifierExpressionSharpnode))
            {
                return(TranslationResult.Error(this.OriginalNode, Diagnostics.SSIL110_InvalidSyntax, "illegal goto target"));
            }
            IdentifierExpressionSharpnode identifierExpression = (IdentifierExpressionSharpnode)this.Identifier;
            ISymbol symbol     = identifierExpression.GetIdentifierSymbol(context);
            var     identifier = context.Process.IdentifierTranslator.GetIdentifierReference(symbol);

            return(TranslationResult.FromSilvernode(
                       new GotoSilvernode(identifier, this.OriginalNode)
                       ));
        }
Beispiel #10
0
        public void FirstAfterWhere()
        {
            // Arrange
            var translator = new FirstTranslator(_nameChanges);
            Expression <Func <Country> > query = () => _countries.Where(p => !p.IsExists).First();
            var translation = new TranslationResult();

            // Act && Assert
            translator.Translate((MethodCallExpression)query.Body, translation);

            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("not IsExists", translation.TableQuery.FilterString);
        }
Beispiel #11
0
        public override TranslationResult Translate(TranslationContext context)
        {
            var left  = this.Left.Translate(context);
            var right = this.Right.Translate(context.ChangePurityContext(PurityContext.Purifiable));
            IEnumerable <Error> errors = CommonUtils.CombineErrors(left, right);

            return
                (TranslationResult.FromSilvernode(
                     new AssignmentSilvernode(
                         left.Silvernode,
                         new BinaryExpressionSilvernode(left.Silvernode, this.operation, right.Silvernode,
                                                        this.OriginalNode), this.OriginalNode), errors)
                 .AndPrepend(right.PrependTheseSilvernodes));
        }
Beispiel #12
0
        public string Index()
        {
            //var credential = GoogleCredential.FromJson
            TranslationClient client = TranslationClient.Create();//Google.Apis.Auth.OAuth2.GoogleCredential.
            TranslationResult result = client.TranslateText(
                text: "Hello World.",
                targetLanguage: "kn",  // Japanese
                sourceLanguage: "en",  // English
                model: TranslationModel.NeuralMachineTranslation);

            //Console.WriteLine($"Model: {result.Model}");
            //Console.WriteLine(result.TranslatedText);
            return(result.TranslatedText);
        }
Beispiel #13
0
        public void AddFiltersWithComplexAndComplexExpression()
        {
            // Arrange
            var          result = new TranslationResult();
            const string filter = "name eq '123' or name eq '222'";

            // Act
            result.AddFilter(filter);
            result.AddFilter(filter);

            // Assert
            Assert.NotNull(result.TableQuery);
            Assert.Equal(string.Format("({0}) and ({1})", filter, filter), result.TableQuery.FilterString);
        }
Beispiel #14
0
        public Task GoogleAsync([Remainder][Summary("The thing to search for")] string search)
        {
            foreach (string tag in search.Split(" "))
            {
                IncreaseTagCoung(tag);
            }

            GoogleTranslator translator = new GoogleTranslator();

            TranslationResult portuguese = translator.TranslateLiteAsync(search, Language.English, Language.Portuguese).GetAwaiter().GetResult();
            TranslationResult english    = translator.TranslateLiteAsync(search, Language.Portuguese, Language.English).GetAwaiter().GetResult();

            return(ReplyAsync($"Pesquisa em portugues: https://www.google.com/search?q={portuguese.MergedTranslation.Replace("+", "%2B").Replace(' ', '+')} \nEnglish search: https://www.google.com/search?q={english.MergedTranslation.Replace("+", "%2B").Replace(' ', '+')}"));
        }
Beispiel #15
0
        public void TakeWithInvalidMethod()
        {
            // Arrange
            var translator             = new TakeTranslator();
            IQueryable <Country> query = GetQueryable().Where(p => p.Name == string.Empty);
            var translation            = new TranslationResult();

            // Act
            Assert.Throws <ArgumentOutOfRangeException>(() => translator.Translate((MethodCallExpression)query.Expression, translation));

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.Null(translation.TableQuery.TakeCount);
        }
Beispiel #16
0
        public void AddFilterTwice()
        {
            // Arrange
            var          result = new TranslationResult();
            const string filter = "name eq '123'";

            // Act
            result.AddFilter(filter);
            result.AddFilter(filter);

            // Assert
            Assert.NotNull(result.TableQuery);
            Assert.Equal(string.Format("{0} and {0}", filter), result.TableQuery.FilterString);
        }
        /// <summary>
        /// Translate.
        ///
        /// Translates the input text from the source language to the target language.
        /// </summary>
        /// <param name="request">The translate request containing the text, and either a model ID or source and target
        /// language pair.</param>
        /// <param name="customData">Custom data object to pass data including custom request headers.</param>
        /// <returns><see cref="TranslationResult" />TranslationResult</returns>
        public TranslationResult Translate(TranslateRequest request, Dictionary <string, object> customData = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrEmpty(VersionDate))
            {
                throw new ArgumentNullException("versionDate cannot be null.");
            }

            TranslationResult result = null;

            try
            {
                IClient client = this.Client;
                if (_tokenManager != null)
                {
                    client = this.Client.WithAuthentication(_tokenManager.GetToken());
                }
                if (_tokenManager == null)
                {
                    client = this.Client.WithAuthentication(this.UserName, this.Password);
                }

                var restRequest = client.PostAsync($"{this.Endpoint}/v3/translate");

                restRequest.WithArgument("version", VersionDate);
                restRequest.WithBody <TranslateRequest>(request);
                if (customData != null)
                {
                    restRequest.WithCustomData(customData);
                }

                restRequest.WithHeader("X-IBMCloud-SDK-Analytics", "service_name=language_translator;service_version=v3;operation_id=Translate");
                result = restRequest.As <TranslationResult>().Result;
                if (result == null)
                {
                    result = new TranslationResult();
                }
                result.CustomData = restRequest.CustomData;
            }
            catch (AggregateException ae)
            {
                throw ae.Flatten();
            }

            return(result);
        }
            public ByRefReplacementTranslationResultDetails(TranslationResult translationResult, int distanceToIndentCodeWithMappedValues)
            {
                if (translationResult == null)
                {
                    throw new ArgumentNullException("translationResult");
                }
                if (distanceToIndentCodeWithMappedValues < 0)
                {
                    throw new ArgumentOutOfRangeException("distanceToIndentCodeWithMappedValues", "must be zero or greater");
                }

                TranslationResult = translationResult;
                DistanceToIndentCodeWithMappedValues = distanceToIndentCodeWithMappedValues;
            }
Beispiel #19
0
        private async Task Translate(TextBox txtSource, TextBox txtDest)
        {
            var translator = new GoogleTranslator();

            Language from = Language.Auto;
            Language to   = GoogleTranslator.GetLanguageByISO("ar");

            TranslationResult result = await translator.TranslateLiteAsync(txtSource.Text, from, to);

            //You can get all text using MergedTranslation property
            string resultMerged = result.MergedTranslation;

            txtDest.Text = resultMerged;
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            string[] samples =
            {
                "FunctionalityTestShader.cs",
                //"SampleShader.cs",
                //"SampleTextureShader.cs",
                //"MoltenSpriteShader.cs"
            };

            Translator        translator = new Translator();
            TranslationResult output     = null;
            OutputLanguage    language   = OutputLanguage.HLSL;

            // Load all of the sources into a dictionary,
            // so that all of them can be translated in a single converter.Convert() call.
            Dictionary <string, string> sources = new Dictionary <string, string>();

            foreach (string fn in samples)
            {
                Console.WriteLine($"Reading {fn}");

                FileInfo fInfo    = new FileInfo(fn);
                string   strInput = File.ReadAllText(fn);
                sources.Add(fn, strInput);
            }

            output = translator.Translate(sources, language);

            // Store the output to file so we can take a look at it ourselves.
            if (output != null)
            {
                string langExtension = $"{language.ToString().ToLower()}";

                foreach (KeyValuePair <string, ShaderTranslationResult> kvp in output)
                {
                    using (FileStream fs = new FileStream($"{kvp.Key}.{langExtension}", FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(fs))
                        {
                            writer.Write(kvp.Value.SourceCode);
                        }
                    }
                }
            }

            Console.ReadKey();
            translator.Dispose();
        }
Beispiel #21
0
        public override TranslationResult Translate(TranslationContext context)
        {
            var  constructorSymbol    = context.Semantics.GetSymbolInfo(this.OriginalNode).Symbol as IMethodSymbol;
            var  classSymbol          = constructorSymbol.ContainingType;
            bool isDefaultConstructor = constructorSymbol.IsImplicitlyDeclared;

            // Special case:
            if (classSymbol.GetQualifiedName() == SeqTranslator.SeqClassWithoutEndDot)
            {
                return(SeqTranslator.Constructor(this.Arguments, context, classSymbol.TypeArguments[0], this.OriginalNode));
            }

            var identifier = context.Process.IdentifierTranslator.RegisterNewUniqueIdentifier();

            // Normal case: As method call
            var arguments    = new List <Silvernode>();
            var errors       = new List <Error>();
            var prependThese = new List <StatementSilvernode>();

            foreach (var arg in this.Arguments)
            {
                var res = arg.Translate(context.ChangePurityContext(PurityContext.Purifiable));
                arguments.Add(res.Silvernode);
                errors.AddRange(res.Errors);
                prependThese.AddRange(res.PrependTheseSilvernodes);
            }

            Silvernode constructorCall = new CallSilvernode(context.Process.IdentifierTranslator.GetIdentifierReferenceWithTag(classSymbol, isDefaultConstructor ? Constants.InitializerTag : Constants.ConstructorTag),
                                                            arguments,
                                                            SilverType.Ref,
                                                            this.OriginalNode);

            prependThese.Add(new VarStatementSilvernode(identifier, SilverType.Ref, this.OriginalNode));
            prependThese.Add(new AssignmentSilvernode(new IdentifierSilvernode(identifier), constructorCall,
                                                      this.OriginalNode));

            switch (context.PurityContext)
            {
            case PurityContext.PurityNotRequired:
            case PurityContext.Purifiable:
                return(TranslationResult.FromSilvernode(new IdentifierSilvernode(identifier), errors).AndPrepend(
                           prependThese
                           ));

            case PurityContext.PureOrFail:
                return(TranslationResult.Error(this.OriginalNode, Diagnostics.SSIL114_NotPureContext, "Object creation is inherently impure."));
            }
            throw new System.Exception("This should never be reached.");
        }
Beispiel #22
0
        public void UseWhereOnDouble()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => p.Area < 350000);
            var translation = new TranslationResult();

            // Act
            translator.Translate((MethodCallExpression)query.Body, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("Area lt 350000.0", translation.TableQuery.FilterString);
        }
Beispiel #23
0
        public void AddColumn()
        {
            // Arrange
            var          result = new TranslationResult();
            const string column = "column";

            // Act
            result.AddColumn(column);

            // Assert
            Assert.NotNull(result.TableQuery);
            Assert.NotNull(result.TableQuery.SelectColumns);
            Assert.Equal(1, result.TableQuery.SelectColumns.Count);
            Assert.Equal(column, result.TableQuery.SelectColumns[0]);
        }
Beispiel #24
0
        public void AddFiltersWithSimpleAndComplexExpression()
        {
            // Arrange
            var          result  = new TranslationResult();
            const string simple  = "name eq '333'";
            const string complex = "name eq '123' or name eq '222'";

            // Act
            result.AddFilter(simple);
            result.AddFilter(complex);

            // Assert
            Assert.NotNull(result.TableQuery);
            Assert.Equal(string.Format("{0} and ({1})", simple, complex), result.TableQuery.FilterString);
        }
Beispiel #25
0
        public static async Task <string> Translate(string word, LanguagePair languagePair)
        {
            string apiKey     = ConfigurationHelper.GetAppSetting("YandexTranslatorApiKey");
            string requestUrl = String.Format("translate?key={0}&lang={1}&text={2}",
                                              apiKey, languagePair, WebUtility.UrlEncode(word));

            TranslationResult result = await HttpClientHelper.GetSerializedObject <TranslationResult>(TranslatorBaseUrl, requestUrl).ConfigureAwait(false);

            if (result != null && result.Text != null && result.Text.Length > 0)
            {
                return(result.Text[0]);
            }

            return(null);
        }
        public void UseCompareOrdinalInWhereOnRowKeyTest()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => String.CompareOrdinal(p.Name, "F") >= 0 && String.CompareOrdinal(p.Name, "G") <= 0);
            var translation = new TranslationResult();

            // Act
            translator.Translate((MethodCallExpression)query.Body, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("RowKey ge 'F' and RowKey le 'G'", translation.TableQuery.FilterString);
        }
Beispiel #27
0
        public void UseWhereOnPartitionKey()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => p.Continent == Europe);
            var translation = new TranslationResult();

            // Act
            translator.Translate((MethodCallExpression)query.Body, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("PartitionKey eq 'Europe'", translation.TableQuery.FilterString);
        }
Beispiel #28
0
        public void UseWhereOnBytes()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => p.TopSecretKey == new byte[] { 0xff, 0xee, 0xdd });
            var translation = new TranslationResult();

            // Act
            translator.Translate((MethodCallExpression)query.Body, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("TopSecretKey eq X'ffeedd'", translation.TableQuery.FilterString);
        }
        public TranslationResult Translate(TranslationContext context, IParameterSymbol symbol)
        {
            Error               err;
            ISymbol             parameterSymbol = context.Semantics.GetDeclaredSymbol(this.ParameterSyntax);
            Identifier          identifier      = context.Process.IdentifierTranslator.RegisterAndGetIdentifier(parameterSymbol);
            ParameterSilvernode ps = new ParameterSilvernode(identifier,
                                                             new TypeSilvernode(this.Type.TypeSyntax, TypeTranslator.TranslateType(symbol.Type, this.Type.TypeSyntax, out err)), this.OriginalNode);
            var errlist = new List <Error>();

            if (err != null)
            {
                errlist.Add(err);
            }
            return(TranslationResult.FromSilvernode(ps, errlist));
        }
 public void SetPrefix_RemoveWord_TranslationCorrect()
 {
     using (var smtModel = new ThotSmtModel(TestHelpers.ToyCorpusConfigFileName))
         using (IInteractiveSmtEngine engine = smtModel.CreateInteractiveEngine())
             using (IInteractiveTranslationSession session = engine.TranslateInteractively(1,
                                                                                           "me marcho hoy por la tarde .".Split()))
             {
                 TranslationResult result = session.CurrentResults[0];
                 Assert.That(result.TargetSegment, Is.EqualTo("i leave today in the afternoon .".Split()));
                 result = session.SetPrefix("i am".Split(), true)[0];
                 Assert.That(result.TargetSegment, Is.EqualTo("i am leave today in the afternoon .".Split()));
                 result = session.SetPrefix("i".Split(), true)[0];
                 Assert.That(result.TargetSegment, Is.EqualTo("i leave today in the afternoon .".Split()));
             }
 }
Beispiel #31
0
        public void SingleOrDefaultWithInvalidMethod()
        {
            // Arrange
            var translator = new SingleOrDefaultTranslator(_nameChanges);
            Expression <Func <Country> > query = () => _countries.Single(p => !p.IsExists);
            var translation = new TranslationResult();

            // Act
            Assert.Throws <ArgumentOutOfRangeException>(() => translator.Translate((MethodCallExpression)query.Body, translation));

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.Null(translation.TableQuery.FilterString);
            Assert.Null(translation.PostProcessing);
        }
Beispiel #32
0
        /// <summary>
        /// 将中文翻译为英文
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public string translation(string source, string to)
        {
            TranslationResult result = GetTranslationFromBaiduFanyi(source, to);

            //判断是否出错
            if (result.Error_code == null)
            {
                return(result.Trans_result[0].Dst);
            }
            else
            {
                //检查appid和密钥是否正确
                return("翻译出错,错误码:" + result.Error_code + ",错误信息:" + result.Error_msg);
            }
        }
Beispiel #33
0
        /// <summary>
        ///     Executes expression query.
        /// </summary>
        /// <param name="expression">Expression.</param>
        /// <returns>Result.</returns>
        public override object Execute(Expression expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var result = new TranslationResult();

            _queryTranslator.Translate(expression, result);

            IEnumerable <DynamicTableEntity> tableEntities = _cloudTable.ExecuteQuery(result.TableQuery);

            return(GetProcessedResult(tableEntities, result));
        }
Beispiel #34
0
        public void UseEnumValueInWhereOnRowKey()
        {
            // Arrange
            var translator = new WhereTranslator(_nameChanges);
            Expression <Func <IQueryable <Country> > > query = () => _countries.Where(p => p.Name == Countries.Germany.ToString());
            var translation = new TranslationResult();

            // Act
            translator.Translate((MethodCallExpression)query.Body, translation);

            // Assert
            Assert.NotNull(translation.TableQuery);
            Assert.NotNull(translation.TableQuery.FilterString);
            Assert.Equal("RowKey eq 'Germany'", translation.TableQuery.FilterString);
        }
Beispiel #35
0
        static void EmitLog(string logPath, Configuration configuration, string inputFile, TranslationResult outputs)
        {
            var logText = new StringBuilder();
            var asmName = Assembly.GetExecutingAssembly().GetName();
            logText.AppendLine(String.Format("// JSILc v{0}.{1}.{2}", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision));
            logText.AppendLine(String.Format("// The following settings were used when translating '{0}':", inputFile));
            logText.AppendLine((new JavaScriptSerializer()).Serialize(configuration));
            logText.AppendLine("// The following outputs were produced:");
            foreach (var kvp2 in outputs.Files)
                logText.AppendLine(kvp2.Key);

            File.WriteAllText(
                Path.Combine(logPath, String.Format("{0}.jsillog", Path.GetFileName(inputFile))),
                logText.ToString()
            );
        }
Beispiel #36
0
        public static void ConvertEmbeddedResources(Configuration configuration, string assemblyPath, TranslationResult result)
        {
            var asm = Assembly.ReflectionOnlyLoadFrom(assemblyPath);

            var resourceFiles = (from fn in asm.GetManifestResourceNames() where fn.EndsWith(".resources") select fn).ToArray();
            var encoding = new UTF8Encoding(false);

            foreach (var resourceName in resourceFiles) {
                if (!resourceName.EndsWith(".resources"))
                    continue;

                var resourceJson = ConvertEmbeddedResourceFile(configuration, assemblyPath, asm, resourceName);
                var bytes = encoding.GetBytes(resourceJson);

                result.AddFile(
                    "Resources",
                    Path.GetFileNameWithoutExtension(resourceName) + ".resj",
                    new ArraySegment<byte>(bytes)
                );
            }
        }
Beispiel #37
0
 protected override void PostProcessAllTranslatedAssemblies (Configuration configuration, string assemblyPath, TranslationResult result) {
     base.PostProcessAllTranslatedAssemblies(configuration, assemblyPath, result);
     result.AddFile("Script", "XNA.Colors.js", new ArraySegment<byte>(Encoding.UTF8.GetBytes(Common.MakeXNAColors())), 0);
 }
Beispiel #38
0
 public override void ProcessSkippedAssembly (
     Configuration configuration, string assemblyPath, TranslationResult result
 ) {
     PostProcessAssembly(configuration, assemblyPath, result);
 }
Beispiel #39
0
 public virtual void ProcessSkippedAssembly (
     Configuration configuration, string assemblyPath, TranslationResult result
 ) {
 }
Beispiel #40
0
 protected void PostProcessAssembly(Configuration configuration, string assemblyPath, TranslationResult result)
 {
     ResourceConverter.ConvertResources(configuration, assemblyPath, result);
     ManifestResourceExtractor.ExtractFromAssembly(configuration, assemblyPath, result);
 }
Beispiel #41
0
        static void EmitLog(
            string logPath, Configuration configuration, 
            string inputFile, TranslationResult outputs,
            IEnumerable<KeyValuePair<string, string[]>> ignoredMethods
        )
        {
            var logText = new StringBuilder();
            var asmName = Assembly.GetExecutingAssembly().GetName();
            logText.AppendLine(String.Format("// JSILc v{0}.{1}.{2}", asmName.Version.Major, asmName.Version.Minor, asmName.Version.Revision));
            logText.AppendLine(String.Format("// Build took {0:0000.00} second(s).", outputs.Elapsed.TotalSeconds));
            logText.AppendLine(String.Format("// The following configuration was used when translating '{0}':", inputFile));
            logText.AppendLine((new JavaScriptSerializer()).Serialize(configuration));
            logText.AppendLine("// The configuration was generated from the following configuration files:");

            foreach (var cf in configuration.ContributingPaths)
                logText.AppendLine(cf);

            logText.AppendLine("// The following outputs were produced:");

            foreach (var fe in outputs.OrderedFiles)
                logText.AppendLine(fe.Filename);

            logText.AppendLine("// The following method(s) were ignored due to untranslatable variables:");

            foreach (var im in ignoredMethods)
                logText.AppendFormat("{0} because of {1}{2}", im.Key, String.Join(", ", im.Value), Environment.NewLine);

            logText.AppendLine("// Miscellaneous log output follows:");
            logText.AppendLine(outputs.Log.ToString());

            File.WriteAllText(
                Path.Combine(logPath, String.Format("{0}.jsillog", Path.GetFileName(inputFile))),
                logText.ToString()
            );
        }
		private	TranslationResult ParseResponse(JObject json)
		{
            /* {
                 "From": "en",
                 "Translations": [
                   {
                     "Count": 0,
                     "MatchDegree": 100,
                     "MatchedOriginalText": "",
                     "Rating": 5,
                     "TranslatedText": "\u043f\u0435\u0440\u0435\u0439\u0442\u0438"
                   },
                   {
                     "Count": 0,
                     "MatchDegree": 100,
                     "MatchedOriginalText": "go",
                     "Rating": 0,
                     "TranslatedText": "\u0438\u0434\u0442\u0438"
                   }
                 ]
               }           
           * */
            
			TranslationResult res = new TranslationResult();            
            JToken jTranslations = json["Translations"];

            IEnumerable<string> translations = jTranslations
                .Select(t => new BingTranslation{
                    MatchDegree = t["MatchDegree"].Value<int>(),
                    Rating = t["Rating"].Value<int>(),
                    Text = t["TranslatedText"].Value<string>()
                })
                .OrderByDescending(t => t.MatchDegree)
                .ThenByDescending(t => t.Rating)
                .Select(t => t.Text);

            //filtering duplicates
            //LINQ Distinct is not guaranteed to preserve order
            HashSet<string> distinctValues = new HashSet<string>();
            foreach (string t in translations) {
                if (!distinctValues.Contains(t)) { 
                    res.Sentences.Add(t);
                    distinctValues.Add(t);
                }
            }
            
			res.SourceLanguage = json.Value<string>("From");
			return res;
		}