Esempio n. 1
0
        public List <string> Post([FromBody] JobModel jobList)//MAPPING CH PROBLEM
        {
            List <Diff>      diff   = new List <Diff>();
            List <string>    result = new List <string>();
            diff_match_patch dmp    = new diff_match_patch();

            string title    = jobList.JobClass[0].title;
            string newTitle = jobList.JobClass[1].title;

            string oldDescription = jobList.JobClass[0].description;
            string newDescription = jobList.JobClass[1].description;


            diff = dmp.diff_main(title, newTitle);
            dmp.diff_cleanupSemantic(diff);



            for (int j = 0; j < diff.Count; j++)
            {
                result.Add(diff[j].ToString());
            }

            //Compare description
            diff = dmp.diff_main(oldDescription, newDescription);
            dmp.diff_cleanupSemantic(diff);
            for (int j = 0; j < diff.Count; j++)
            {
                result.Add(diff[j].ToString());
            }

            return(result);
        }
Esempio n. 2
0
    void TestDiffMatchPatch()
    {
        var s1 = @"//.
using Au; using Au.Types; using System; using System.Collections.Generic;
class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;
	
	var s=""one"";
";
        var s2 = @"/*/ role exeProgram;		outputPath %AFolders.Workspace%\bin; console true; /*/ //.
using Au; using Au.Types; using System; using System.Collections.Generic;
using My.NS1; //ąčę îôû
using My.NS2;
class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;
	var i=2;
";

        var         dmp  = new diff_match_patch();
        List <Diff> diff = dmp.diff_main(s1, s2, true);

        dmp.diff_cleanupSemantic(diff);
        var delta = dmp.diff_toDelta(diff);

        AOutput.Write(delta);
        AOutput.Write("----");
        var d2 = dmp.diff_fromDelta(s1, delta);

        //AOutput.Write(d2);
        AOutput.Write(dmp.diff_text2(d2));
    }
        public static List <Diferencia> sacarDiferencias(Informe informe)
        {
            List <Diferencia> diferenciasRelevantes = new List <Diferencia>();
            string            textoInicial          = PreprocemientoDeTexto.LimpiarTextoInicial(informe.CuerpoRealizaEnc);
            string            textoFinal            = PreprocemientoDeTexto.LimpiarTextoInicial(informe.CuerpoValidaEnc);

            Diff[] diferencias        = recolectorDeDiferencias.diff_main(textoInicial, textoFinal, true).ToArray();
            var    listaDeDiferencias = diferencias.ToList();

            recolectorDeDiferencias.diff_cleanupSemantic(listaDeDiferencias);
            diferencias = listaDeDiferencias.ToArray();
            for (int i = 0; i < diferencias.Count() - 1; i++)
            {
                if (EsRelevante(diferencias, i))
                {
                    Diferencia diferenciaRelevante = new Diferencia()
                    {
                        Tecnico          = informe.medicoinforma,
                        MedicoSupervisor = informe.medicorevisa,
                        CadenaInicial    = diferencias[i].text,
                        CadenaFinal      = diferencias[i + 1].text
                    };
                    diferenciasRelevantes.Add(diferenciaRelevante);
                }
            }
            return(diferenciasRelevantes);
        }
        protected override void ProcessRecord()
        {
            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(LeftText, RightText);

            dmp.diff_cleanupSemantic(diff);
            var output = new CompareTextDiff();

            output.Diff = diff;
            var psObj = new PSObject(output);

            if (_leftFile != null)
            {
                psObj.Properties.Add(new PSNoteProperty("LeftFile", _leftFile));
            }

            if (_rightFile != null)
            {
                psObj.Properties.Add(new PSNoteProperty("RightFile", _rightFile));
            }

            if (View == CompareTextView.SideBySide)
            {
                psObj.TypeNames.Insert(0, "Microsoft.PowerShell.TextUtility.CompareTextDiff#SideBySide");
            }

            WriteObject(psObj);
        }
Esempio n. 5
0
        private static async Task Client_MessageUpdated(DiscordSocketClient client, Cacheable <IMessage, ulong> oldCache,
                                                        SocketMessage newMessage, ISocketMessageChannel channel)
        {
            if (newMessage.Author.IsBot)
            {
                return;
            }

            if (newMessage.Content == null)
            {
                return;
            }

            if (newMessage is IUserMessage userMessage)
            {
                var oldMessage = ToMessage(oldCache);

                var oldContent = oldMessage?.Content ?? string.Empty;
                var newContent = userMessage.Resolve();
                if (oldContent == newContent)
                {
                    return;
                }

                var diffMatchPatch = new diff_match_patch();
                var diffs          = diffMatchPatch.diff_main(oldContent, newContent);
                diffMatchPatch.diff_cleanupSemantic(diffs);

                var md = ToMarkdown(diffs);
                await PostEmbedAsync(client, "edited", new Color(0xF0E68C), userMessage.Author.Id, userMessage.Author,
                                     channel, md, oldMessage?.Attachment, userMessage.Id);
            }
        }
Esempio n. 6
0
        /// <summary>
        /// performs a google diff between stdin and the file identified by args[0] and outputs to stdout
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                throw new Exception("modified file path argument is required");
            }

            diff_match_patch googleDiff = new diff_match_patch();

            // read stdin raw, including separators
            string source = ReadStdin();
            string target;

            using (StreamReader streamReader = new StreamReader(args[0], Encoding.UTF8))
            {
                target = streamReader.ReadToEnd();
            }

            // NOTE: do our own diffs so we just do semantic cleanup. We don't want to optimize for efficiency.
            List <Diff> diffs;

            if (args.Length > 1 && args[1] == "--reverse")
            {
                diffs = googleDiff.diff_main(target, source);
            }
            else
            {
                diffs = googleDiff.diff_main(source, target);
            }

            googleDiff.diff_cleanupSemantic(diffs);
            List <Patch> patches = googleDiff.patch_make(diffs);

            Console.Write(googleDiff.patch_toText(patches));
        }
Esempio n. 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Get inputLeft and inputRight
            string left  = inputLeft.Text;
            string right = inputRight.Text;

            // store differences in the displaytext, and line number
            string diffs = "";

            //            for (int line = 1; line <= left.Length; line++) {

            //            }

            diff_match_patch dmp = new diff_match_patch();

            List <Diff> diff = dmp.diff_main(left, right);

            dmp.diff_cleanupSemantic(diff);


            for (int i = 0; i < diff.Count; i++)
            {
                Console.WriteLine(diff[i]);
                diffs = diffs + diff[i] + Environment.NewLine;
            }



            // display in display box
            resultText.Text = diffs;
            Console.Read();
        }
Esempio n. 8
0
        private void getDiffInfo(FileHistoryDTO fileHistory, string newContent, string oldContent)
        {
            var dmp  = new diff_match_patch();
            var diff = dmp.diff_main(newContent, oldContent);

            dmp.diff_cleanupSemantic(diff);
            dmp.diff_prettyHtml(diff);

            var htmlContent    = new StringBuilder("");
            var linesIncreased = 0;
            var linesDecreased = 0;

            for (int i = 0; i < diff.Count; i++)
            {
                htmlContent.Append(diff[i]);
                if (diff[i].operation == Operation.DELETE)
                {
                    linesDecreased++;
                }
                if (diff[i].operation == Operation.INSERT)
                {
                    linesIncreased++;
                }
            }
            fileHistory.ContentDiffHtml = htmlContent.ToString();
            fileHistory.LinesDecreased  = linesDecreased;
            fileHistory.LinesIncreased  = linesIncreased;
            fileHistory.SizeDiff        = newContent.Length - oldContent.Length;
        }
Esempio n. 9
0
        private List <Patch> ProcessFile(string f)
        {
            string destinationContent = "";
            string sourceContent      = "";

            destinationContent = File.ReadAllText(f);

            //corresponding source path to destination file
            var sourcePath = f.Replace("\\destination\\", "\\source\\");

            if (!File.Exists(sourcePath))
            {
                patchResults.Add(new PatchResult {
                    DestinationFile = MakeRelativePath(f), SourceFile = MakeRelativePath(sourcePath), PatchResultType = PatchResultType.CopyFile
                });
                return(null);
            }

            //content of users original file
            sourceContent = File.ReadAllText(sourcePath);

            var dmp  = new diff_match_patch();
            var diff = dmp.diff_main(sourceContent, destinationContent);

            dmp.diff_cleanupSemantic(diff);

            var patchResult = dmp.patch_make(diff);

            patchResults.Add(new PatchResult {
                DestinationFile = MakeRelativePath(f), SourceFile = MakeRelativePath(sourcePath), PatchList = patchResult, PatchResultType = patchResult.Count > 0 ? PatchResultType.Patch : PatchResultType.Identical
            });

            return(patchResult);
        }
        public IEnumerable <Diff> GetDiffBetween(string text1, string text2)
        {
            var         dmp  = new diff_match_patch();
            List <Diff> diff = dmp.diff_main(text1, text2);

            dmp.diff_cleanupSemantic(diff);
            return(diff);
        }
Esempio n. 11
0
        private string GetTextDifferences(string a, string b)
        {
            var diff        = new diff_match_patch();
            var differences = diff.diff_main(a + "", b + "");

            diff.diff_cleanupSemantic(differences);
            //Format as pretty html
            return(diff.diff_prettyHtml(differences));
        }
Esempio n. 12
0
        protected override string DoExecute(ITaskContextInternal context)
        {
            if (!File.Exists(_firstFilePathToCompare))
            {
                if (_failOnFileNotFound)
                {
                    throw new TaskExecutionException($"first file not found '{_firstFilePathToCompare}'.", 20);
                }

                context.LogInfo($"first file not found '{_firstFilePathToCompare}'. Skipping compare.");
                return(null);
            }

            if (!File.Exists(_secondFilePathToCompare))
            {
                if (_failOnFileNotFound)
                {
                    throw new TaskExecutionException($"second file not found '{_secondFilePathToCompare}'.", 20);
                }

                context.LogInfo($"second file not found '{_secondFilePathToCompare}'. Skipping compare.");
                return(null);
            }

            string newConfig = File.ReadAllText(_secondFilePathToCompare);

            var oldCOnf          = File.ReadAllText(_firstFilePathToCompare);
            diff_match_patch dmp = new diff_match_patch();

            dmp.Diff_EditCost = 4;
            List <Diff> diff = dmp.diff_main(oldCOnf, newConfig);

            if (diff.Count == 1)
            {
                if (diff[0].operation == Operation.EQUAL)
                {
                    //// Files are the same.
                    return(null);
                }
            }

            dmp.diff_cleanupSemantic(diff);

            var html = dmp.diff_prettyHtml(diff);

            if (!_noExportToFile)
            {
                File.WriteAllText(_htmlReportOutputPath, html);
            }

            if (_failOnDiff)
            {
                throw new TaskExecutionException($"File {_firstFilePathToCompare} and {_secondFilePathToCompare} are not the same", 21);
            }

            return(html);
        }
        static IEnumerable <Span> DiffInline(ILine originalLine, ILine modifiedLine)
        {
            var dmp   = new diff_match_patch();
            var diffs = dmp.diff_main(originalLine.Value, modifiedLine.Value);

            dmp.diff_cleanupSemantic(diffs);

            return(diffs
                   .Select(x => new Span(x.text, OperationToKind(x.operation)))
                   .ToArray());
        }
Esempio n. 14
0
        private async Task Unterschied2(IDialogContext context, IAwaitable <IEnumerable <Attachment> > argument)
        {
            var result = await argument as List <Attachment>;

            context.UserData.SetValue("doc2", result[0]);

            var dmp = new diff_match_patch()
            {
                Diff_EditCost = 10
            };

            var doc1 = context.UserData.GetValue <Attachment>("doc1");
            var doc2 = context.UserData.GetValue <Attachment>("doc2");

            var text1 = "";
            var text2 = "";

            using (HttpClient httpClient = new HttpClient())
            {
                var response1 = await httpClient.GetAsync(doc1.ContentUrl);

                var jobject1 = JObject.Parse(response1.Content.ReadAsStringAsync().Result);
                var token1   = jobject1.SelectToken("data");
                var bytes1   = token1.ToObject <byte[]>();
                text1 = System.Text.Encoding.UTF8.GetString(bytes1);

                var response2 = await httpClient.GetAsync(doc2.ContentUrl);

                var jobject2 = JObject.Parse(response2.Content.ReadAsStringAsync().Result);
                var token2   = jobject2.SelectToken("data");
                var bytes2   = token2.ToObject <byte[]>();
                text2 = System.Text.Encoding.UTF8.GetString(bytes2);
            }

            var diffs = dmp.diff_main(text1, text2);

            dmp.diff_cleanupSemantic(diffs);
            var htmlContent = dmp.diff_prettyHtml(diffs);

            var html = "<div style='border: #181818 solid 1px; width: 550px; margin: 0 auto; margin-top: 100px; padding: 30px; box-shadow: 10px 10px 5px grey;'>";

            html += htmlContent + "</div>";

            StreamWriter sw = new StreamWriter(diffFile, false);

            sw.Write(html);
            sw.Flush();
            sw.Close();

            await context.PostAsync($"Ich habe {diffs.Count} unterschiedliche Stellen gefunden.\n\n Die Änderungen habe ich dir in die Datei 'differences.html' in dein Verzeichnis gelegt.");

            PromptDialog.Choice(context, Unterschied3, new string[] { "ja", "nein" }, "Willst du die Datei gleich öffnen?", promptStyle: PromptStyle.PerLine, descriptions: new string[] { "Ja, bitte im Browser öffnen", "Nein zurück zur Auswahl" });
        }
Esempio n. 15
0
        public static Embed GetEditEmbed(IUser author, string title, string oldContent, string newContent)
        {
            if (oldContent == newContent)
            {
                return(null);
            }

            var diffMatchPatch = new diff_match_patch();
            var diffs          = diffMatchPatch.diff_main(oldContent, newContent);

            diffMatchPatch.diff_cleanupSemantic(diffs);

            var md = ToMarkdown(diffs);

            return(GetEmbed(title, new Color(0xF0E68C), author, null, md, null, null));
        }
Esempio n. 16
0
        public static string GetHTMLDiff(this List <BackupDetail> list, string id)
        {
            var backupDetail       = list.Get(id);
            var localFileLocation  = Path.Combine(BackupDetails.ServerDir(), backupDetail.BackupDirectory.ToString(), backupDetail.SavedName);
            var remoteFileLocation = Path.Combine(BackupDetails.ServerDir(), "temp", backupDetail.ActualName);

            var localFileContents  = File.ReadAllText(localFileLocation);
            var remoteFileContents = File.ReadAllText(remoteFileLocation);

            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(localFileContents, remoteFileContents);

            dmp.diff_cleanupSemantic(diff);
            var html = dmp.diff_prettyHtml(diff).Replace("&para;", "");

            return(html);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            string before = StringData.Before;
            string after  = StringData.After;

            //string before = @$"測試文字123";
            //string after = @$"測試文字456";

            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(before, after);

            // Result: [(-1, "Hell"), (1, "G"), (0, "o"), (1, "odbye"), (0, " World.")]
            dmp.diff_cleanupSemantic(diff);
            // Result: [(-1, "Hello"), (1, "Goodbye"), (0, " World.")]
            for (int i = 0; i < diff.Count; i++)
            {
                switch (diff[i].operation)
                {
                case Operation.EQUAL:     //未修改字段
                    Console.Write(diff[i].text);
                    break;

                case Operation.DELETE:                            //刪除字段
                    Console.BackgroundColor = ConsoleColor.Red;   //紅色背景
                    Console.Write(diff[i].text);
                    Console.BackgroundColor = ConsoleColor.Black; //還原為黑色背景
                    break;

                case Operation.INSERT:                            //新增字段
                    Console.BackgroundColor = ConsoleColor.Green; //綠色背景
                    Console.Write(diff[i].text);
                    Console.BackgroundColor = ConsoleColor.Black; //還原為黑色背景
                    break;

                default:
                    break;
                }
            }

            string html = dmp.diff_prettyHtml(diff);

            Console.WriteLine("Html結果-------------------------------");
            Console.WriteLine(html);
            Console.ReadKey();
        }
Esempio n. 18
0
        private static void WritePatch(string source, string target, string outputPath)
        {
            // NOTE: do our own diffs so we just do semantic cleanup.
            // We don't want to optimize for efficiency.
            diff_match_patch googleDiff = new diff_match_patch();
            List <Diff>      diffs      = googleDiff.diff_main(source, target);

            googleDiff.diff_cleanupSemantic(diffs);

            // write patch
            List <Patch> patches = googleDiff.patch_make(diffs);

            using (StreamWriter streamWriter = new StreamWriter(outputPath, false, Encoding.UTF8))
            {
                string patchText = googleDiff.patch_toText(patches);
                streamWriter.Write(patchText);
            }
        }
Esempio n. 19
0
        public static void ShouldMatchTextFile(this Stream actual, string expectedFilePath)
        {
            var actualReader = new StreamReader(actual);
            var actualText   = actualReader.ReadToEnd();
            var expectedText = File.ReadAllText(expectedFilePath);

            diff_match_patch algorithm = new diff_match_patch();

            var diffs = algorithm.diff_main(expectedText, actualText);

            algorithm.diff_cleanupSemantic(diffs);

            if (diffs.Any(IsSignificantDiff))
            {
                var message = BuildDiffMessage(expectedFilePath, diffs);
                Assert.Fail(message);
            }
        }
Esempio n. 20
0
        public static string DiffTwoFiles(string file1, string file2)
        {
            diff_match_patch dmp = new diff_match_patch();

            dmp.Diff_Timeout = 0;

            List <Diff> diffs;

            using (StreamReader r = new StreamReader(File.Open(file1, FileMode.Open)))
                using (StreamReader r2 = new StreamReader(File.Open(file2, FileMode.Open)))
                {
                    diffs = dmp.diff_main(r.ReadToEnd(), r2.ReadToEnd());
                    dmp.diff_cleanupEfficiency(diffs);
                    dmp.diff_cleanupSemantic(diffs);
                }

            return(dmp.diff_prettyHtml(diffs));
        }
        public void Diff(ITaskContext context, string newConfigPath, string oldConfigPath, string htmlExportPath)
        {
            string newConfig = File.ReadAllText(newConfigPath);

            if (Contains(newConfig, "todo", StringComparison.InvariantCultureIgnoreCase) ||
                Contains(newConfig, "tbd", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new TaskExecutionException(
                          $"Config: '{newConfigPath}' contains todo or tbd! Check and fix config.", 99);
            }

            if (!File.Exists(oldConfigPath))
            {
                context.LogInfo($"old config not found '{oldConfigPath}'. Skipping compare.");
                return;
            }

            context.LogInfo($"Comparing {oldConfigPath}, {newConfigPath}");

            var oldCOnf          = File.ReadAllText(oldConfigPath);
            diff_match_patch dmp = new diff_match_patch();

            dmp.Diff_EditCost = 4;
            List <Diff> diff = dmp.diff_main(oldCOnf, newConfig);

            if (diff.Count == 1)
            {
                if (diff[0].operation == Operation.EQUAL)
                {
                    context.LogInfo("Configs are the same");
                    return;
                }
            }

            _anyDiffsInConfigs = true;
            context.LogInfo($"Configs are not the same. Generating report {htmlExportPath}.");

            dmp.diff_cleanupSemantic(diff);
            var html = dmp.diff_prettyHtml(diff);

            File.WriteAllText(htmlExportPath, html);
        }
Esempio n. 22
0
        private static void TestBrokenImperfectMatch()
        {
            // this is a test that fails on the master version of this library
            // and is fixed in my fork (reported to master repo)
            string           referenceInput  = "diff matching patching";
            string           referenceOutput = "diff match patch";
            string           imperfectInput  = "diff matching pthing";
            diff_match_patch googleDiff      = new diff_match_patch();
            List <Diff>      diffs           = googleDiff.diff_main(referenceInput, referenceOutput);

            googleDiff.diff_cleanupSemantic(diffs);
            List <Patch> patches = googleDiff.patch_make(diffs);

            Debug.WriteLine(googleDiff.patch_toText(patches));
            string patched = (string)googleDiff.patch_apply(patches, imperfectInput, out List <Patch> effectivePatches)[0];

            Debug.WriteLine(effectivePatches.Count);
            Debug.WriteLine(patched);
            Debug.Assert(patched == "diff match pth");
        }
Esempio n. 23
0
        private void GenerateDiff(MarkdownPage page, string newPage)
        {
            var diffEngine = new diff_match_patch();

            var a         = diffEngine.diff_linesToChars(page.Content, newPage);
            var text1     = (string)a[0];
            var text2     = (string)a[1];
            var lineArray = (List <string>)a[2];


            var diff = diffEngine.diff_main(text1, text2, false);

            diffEngine.diff_charsToLines(diff, lineArray);

            diffEngine.diff_cleanupSemantic(diff);

            var htmlDiff = diffEngine.diff_prettyHtml(diff);

            Frame.Navigate(typeof(ImportDiffPage), Tuple.Create(diff, Page.Id));
        }
Esempio n. 24
0
        private static void TestGeneralCases()
        {
            const string testsRoot   = "..\\..\\..\\test";
            string       sourcesPath = Path.Combine(testsRoot, "source");
            string       patchedPath = Path.Combine(testsRoot, "patched");

            diff_match_patch googleDiff = new diff_match_patch();

            foreach (string testRootPath in Directory.EnumerateDirectories(Path.Combine(testsRoot, "cases")))
            {
                string testSourcePath = Path.Combine(testRootPath, "a");
                Debug.WriteLine(testSourcePath);
                foreach (string testFilePath in Directory.EnumerateFiles(testSourcePath, "*.lua",
                                                                         SearchOption.AllDirectories))
                {
                    Debug.WriteLine(
                        "=====================================================================================");
                    Debug.WriteLine(testFilePath);
                    string source       = File.ReadAllText(testFilePath.Replace(testSourcePath, sourcesPath));
                    string target       = File.ReadAllText(testFilePath.Replace(testSourcePath, patchedPath));
                    string testInput    = File.ReadAllText(testFilePath);
                    string testExpected = File.ReadAllText(testFilePath.Replace("\\a\\", "\\b\\"));

                    // NOTE: do our own diffs so we just do semantic cleanup. We don't want to optimize for efficiency.
                    List <Diff> diffs = googleDiff.diff_main(source, target);
                    googleDiff.diff_cleanupSemantic(diffs);
                    List <Patch> patches = googleDiff.patch_make(diffs);
                    Debug.WriteLine(
                        "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
                    Debug.WriteLine(googleDiff.patch_toText(patches));
                    string patched = ApplyPatches(googleDiff, testInput, patches);
                    Debug.WriteLine(
                        "=====================================================================================");
                    Debug.WriteLine(patched);
                    CompareEquals(googleDiff, testFilePath, testExpected, patched);
                }
            }
        }
        private static void DiffMatchText(DiffTextkBlock dtb, string first, string second)
        {
            var diffs = _DIFF.diff_main(first, second);

            _DIFF.diff_cleanupSemantic(diffs);

            foreach (var diff in diffs)
            {
                switch (diff.operation)
                {
                case Operation.EQUAL: dtb.Inlines.Add(diff.text); break;

                case Operation.DELETE:
                    dtb.Inlines.Add(new Run(diff.text)
                    {
                        Background = Brushes.Orange
                    });
                    break;

                case Operation.INSERT: break;
                }
            }
        }
Esempio n. 26
0
        static async Task Main(string[] args)
        {
            if (args.Length != 2)
            {
                Exit("Call application with parameters: [sourcepath] [destinationpath].");
            }

            Console.WriteLine("Setting up...");
            var sourcePath = args[0];
            var destPath   = args[1];
            var sourceDir  = new DirectoryInfo(sourcePath);
            var destDir    = new DirectoryInfo(destPath);

            if (!sourceDir.Exists)
            {
                Exit("Source Path does not exist");
            }
            if (!destDir.Exists)
            {
                Exit("Destination Path does not exist");
            }

            var gitComparer = new GitComparer(sourcePath, destPath);
            //TODO: get files
            var filesToCompare = gitComparer.GetEditedFiles();

            var changedList = new List <ChangedFile>();
            var filer       = new Filer();
            var troubleList = new List <FileObject>();

            var options = new ProgressBarOptions
            {
                ProgressCharacter   = '-',
                ProgressBarOnBottom = false
            };



            using (var pbar = new ProgressBar(filesToCompare.Count, "Converting Files", options))

                foreach (var file in filesToCompare)
                {
                    pbar.Message = file.RelativePath;
                    if (gitComparer.IsGitIgnored(new FileInfo(file.SourcePath)))
                    {
                        continue;
                    }
                    var progressBar = pbar;
                    var sourceTask  = new Task <string>(() => filer.GetFileContents(file.SourcePath, progressBar));
                    sourceTask.Start();
                    var targetTask = new Task <string>(() => filer.GetFileContents(file.TargetPath, progressBar));
                    targetTask.Start();
                    await Task.WhenAll(sourceTask, targetTask);

                    if (sourceTask.Result == null | targetTask.Result == null)
                    {
                        troubleList.Add(file);
                        continue;
                    }

                    var diff  = new diff_match_patch();
                    var diffs = diff.diff_main(sourceTask.Result, targetTask.Result);

                    var changed = new ChangedFile();
                    changed.FileObject = file;

                    diff.diff_cleanupSemantic(diffs);
                    diffs = diffs.Where(d => d.operation != Operation.EQUAL).ToList();
                    if (diffs.Count != 0)
                    {
                        changed.ChangedItems = diffs;
                        changedList.Add(changed);
                    }
                    pbar.Tick();
                }

            var fi = new FileInfo(Assembly.GetExecutingAssembly().Location);

            var outputFile = Path.Combine(fi.DirectoryName,
                                          $"output-{DateTime.Now.ToLongTimeString().Replace(":", ".")}.txt");

            using (var writer = new StreamWriter(outputFile))
            {
                foreach (var file in changedList)
                {
                    writer.WriteLine(file.FileObject.RelativePath);
                    for (var i = 0; i < file.ChangedItems.Count; i++)
                    {
                        writer.WriteLine($":Diff {i}. Operation: {file.ChangedItems[i].operation} Item: {file.ChangedItems[i]}");
                        writer.WriteLine("---------------------------------");
                        //writer.Write("Source:");
                        //writer.Write("---------------------------------");
                        //writer.Write(file.ChangedItems[i].SourceDiff);
                        //writer.Write("=================================");
                        //writer.Write("Target:");
                        //writer.Write("---------------------------------");
                        //writer.Write(file.ChangedItems[i].TargetDiff);
                        //writer.Write("_________________________________");
                    }

                    writer.WriteLine("=============================================");
                    writer.WriteLine();
                }

                writer.WriteLine("Errors below");
                writer.WriteLine("=============================================");
                foreach (var trouble in troubleList)
                {
                    writer.WriteLine(trouble.RelativePath);
                }
            }
            //File.WriteAllLines(outputFile, changedList.Select(f=>f.RelativePath));
        }
Esempio n. 27
0
        public IEnumerable <string> Get()
        {
            diff_match_patch dmp = new diff_match_patch();
            //List<Diff> diff = dmp.diff_main(@"This position will be responsible for the on-going management of Vertex’s contract third party logistics providers (89PLs) and commercial distributor network in Europe and internationally. In addition, this position will work closely with the Supply Chain/Pharm Ops team based in the US, the Quality team, and with the International Commercial team to synchronize drug supply with demand based on country/regional level needs.Key Responsibilities:
            //Responsible for the execution of customer service and distribution operations at 3PLs
            //Manage contracts & promote positive effective relationships between Vertex and 3PLs, distributors, wholesalers, home care providers, and transportation partners
            //Play a primary role in supply chain logistics, including product return investigations, and Customer Service team interaction to support order processing and customer Follow-ups
            //We are currently recruiting for a Site Manager to work in our Leaways School in Clapton.Leaways School provides a safe learning environment for pupils struggling with social, emotional and mental health problems(SEMH), attention deficit hyperactivity disorder(ADHD), obsessive compulsive disorder(OCD), opposition defiance disorder, conduct disorder or foetal


            //Monitor target inventory levels, track replenishments from supply sites, and support inventory reconciliation
            //Ensure Vertex logistics operations are at high service levels, GDP compliant, and cost efficient
            //Ensure appropriate process controls and documentation are in place within Vertex and at suppliers, utilizing change control platforms, SOPs, and other processes / tools
            //Support projects and launch activities for commercial programs in Europe and internationally
            //Oversee occasional stickering / packaging activity at 3PLs
            //Support supply to managed access programs and handle named patient supply requests
            //Participate in audits and support audit remediation, as needed
            //Support risk management activities related to distribution
            //Track shipping and warehouse data to produce monthly metrics and dashboards
            //Seek operational excellence and implement process improvements
            //Monitors distribution activities ex - North America, understanding complexities of channels and finding innovative solutions for supply of product to patient.
            // Key requirements:


            // Strong experience in customer services, order management and logistics for pharmaceutical product
            // Proven experience in working cross - functionally to achieve successful outcomes
            // Knowledge of Good Distribution Practice guidelines and compliant practices
            // Proven ability in working with rd party logistics providers(3PL’s)
            // Experience in export shipping requirements for destinations outside of EU desirable
            // Proven experience of managing day to day operations and issue resolution in a learings, high volume environment
            // Experience of analysing data and compiling reports
            // Used to working with the boundaries of Standard Operating Procedures
            // Knowledge of Managed Access Programmes and Named Patient Supply desirable.


            // ", @"This position will be responsible for the on-going management of Vertex’s contract third party logistics providers (89PLs) and commercial distributor network in Europe and internationally. In addition, this position will work closely with the Supply Chain/Pharm Ops team based in the US, the Quality team, and with the International Commercial team to synchronize drug supply with demand based on country/regional level needs.

            //Key Responsibilities:

            //Responsible for the execution of customer service and distribution operations at 3PLs
            //Manage contracts & promote positive effective relationships between Vertex and 3PLs, distributors, wholesalers, home care providers, and transportation partners
            //Play a primary role in supply chain logistics, including product return investigations, and Customer Service team interaction to support order processing and customer Follow-ups
            //We are currently recruiting for a Site Manager to work in our Leaways School in Clapton. Leaways School provides a safe learning environment for pupils struggling with social, emotional and mental health problems (SEMH), attention deficit hyperactivity disorder (ADHD), obsessive compulsive disorder (OCD), opposition defiance disorder, conduct disorder or foetal

            //Monitor target inventory levels, track replenishments from supply sites, and support inventory reconciliation
            //Ensure Vertex logistics operations are at high service levels, GDP compliant, and cost efficient
            //Ensure appropriate process controls and documentation are in place within Vertex and at suppliers, utilizing change control platforms, SOPs, and other processes/tools
            //Support projects and launch activities for commercial programs in Europe and internationally
            //Oversee occasional stickering/packaging activity at 3PLs
            //Support supply to managed access programs and handle named patient supply requests
            //Participate in audits and support audit remediation, as needed
            //Support risk management activities related to distribution
            //Track shipping and warehouse data to produce monthly metrics and dashboards
            //Seek operational excellence and implement process improvements
            //Monitors distribution activities ex-North America, understanding complexities of channels and finding innovative solutions for supply of product to patient.
            //Key requirements:

            //Strong experience in customer services, order management and logistics for pharmaceutical product
            //Proven experience in working cross-functionally to achieve successful outcomes
            //Knowledge of Good Distribution Practice guidelines and compliant practices
            //Proven ability in working with rd party logistics providers (3PL’s)
            //Experience in export shipping requirements for destinations outside of EU desirable
            //Proven experience of managing day to day operations and issue resolution in a learings , high volume environment
            //Experience of analysing data and compiling reports
            //Used to working with the boundaries of Standard Operating Procedures
            //Knowledge of Managed Access Programmes and Named Patient Supply desirable.

            //");


            string originalText = @"This position will be responsible for the on-going management of Vertex’s contract third party logistics providers (3PLs) and commercial distributor network in Europe and internationally. In addition, this position will work closely with the Supply Chain/Pharm Ops team based in the US, the Quality team, and with the International Commercial team to synchronize drug supply with demand based on country/regional level needs.

Key Responsibilities:

Responsible for the execution of customer service and distribution operations at 3PLs
Manage contracts & promote positive effective relationships between Vertex and 3PLs, distributors, wholesalers, home care providers, and transportation partners
Play a primary role in supply chain logistics, including product return investigations, and Customer Service team interaction to support order processing and customer Follow-ups
Monitor target inventory levels, track replenishments from supply sites, and support inventory reconciliation
Ensure Vertex logistics operations are at high service levels, GDP compliant, and cost efficient
Ensure appropriate process controls and documentation are in place within Vertex and at suppliers, utilizing change control platforms, SOPs, and other processes/tools
Support projects and launch activities for commercial programs in Europe and internationally
Oversee occasional stickering/packaging activity at 3PLs
Support supply to managed access programs and handle named patient supply requests
Participate in audits and support audit remediation, as needed
Support risk management activities related to distribution
Track shipping and warehouse data to produce monthly metrics and dashboards
Seek operational excellence and implement process improvements
Monitors distribution activities ex-North America, understanding complexities of channels and finding innovative solutions for supply of product to patient.
Key requirements:

Strong experience in customer services, order management and logistics for pharmaceutical product
Proven experience in working cross-functionally to achieve successful outcomes
Knowledge of Good Distribution Practice guidelines and compliant practices
Proven ability in working with 3rd party logistics providers (3PL’s)
Experience in export shipping requirements for destinations outside of EU desirable
Proven experience of managing day to day operations and issue resolution in a dynamic, high volume environment
Experience of analysing data and compiling reports
Used to working with the boundaries of Standard Operating Procedures
Knowledge of Managed Access Programmes and Named Patient Supply desirable.
";


            string replacedText = @"This position will be responsible for the on-going management of Vertex’s contract third party logistics providers (89PLs) and commercial distributor network in Europe and internationally. In addition, this position will work closely with the Supply Chain/Pharm Ops team based in the US, the Quality team, and with the International Commercial team to synchronize drug supply with demand based on country/regional level needs.

Key Responsibilities:

Responsible for the execution of customer service and distribution operations at 3PLs
Manage contracts & promote positive effective relationships between Vertex and 3PLs, distributors, wholesalers, home care providers, and transportation partners
Play a primary role in supply chain logistics, including product return investigations, and Customer Service team interaction to support order processing and customer Follow-ups
We are currently recruiting for a Site Manager to work in our Leaways School in Clapton. Leaways School provides a safe learning environment for pupils struggling with social, emotional and mental health problems (SEMH), attention deficit hyperactivity disorder (ADHD), obsessive compulsive disorder (OCD), opposition defiance disorder, conduct disorder or foetal 

Monitor target inventory levels, track replenishments from supply sites, and support inventory reconciliation
Ensure Vertex logistics operations are at high service levels, GDP compliant, and cost efficient
Ensure appropriate process controls and documentation are in place within Vertex and at suppliers, utilizing change control platforms, SOPs, and other processes/tools
Support projects and launch activities for commercial programs in Europe and internationally
Oversee occasional stickering/packaging activity at 3PLs
Support supply to managed access programs and handle named patient supply requests
Participate in audits and support audit remediation, as needed
Support risk management activities related to distribution
Track shipping and warehouse data to produce monthly metrics and dashboards
Seek operational excellence and implement process improvements
Monitors distribution activities ex-North America, understanding complexities of channels and finding innovative solutions for supply of product to patient.
Key requirements:

Strong experience in customer services, order management and logistics for pharmaceutical product
Proven experience in working cross-functionally to achieve successful outcomes
Knowledge of Good Distribution Practice guidelines and compliant practices
Proven ability in working with rd party logistics providers (3PL’s)
Experience in export shipping requirements for destinations outside of EU desirable
Proven experience of managing day to day operations and issue resolution in a learings , high volume environment
Experience of analysing data and compiling reports
Used to working with the boundaries of Standard Operating Procedures
Knowledge of Managed Access Programmes and Named Patient Supply desirable.
";

            List <Diff>   diff    = new List <Diff>();
            List <string> results = new List <string>();

            diff = dmp.diff_main(originalText, replacedText);

            dmp.diff_cleanupSemantic(diff);


            for (int j = 0; j < diff.Count; j++)
            {
                results.Add(diff[j].ToString());
            }
            return(results);
        }
Esempio n. 28
0
        private static BlameResult GetBlameOutput(string repositoryPath, string fileName, string blameCommitId, string[] currentLines)
        {
            BlameResult blameResult;

            using (var repo = new Repository(repositoryPath))
            {
                // try to determine if the remote URL is plausibly a github.com or GitHub Enterprise URL
                Uri webRootUrl = repo.Network.Remotes
                                 .OrderBy(x => x.Name == "origin" ? 0 : 1)
                                 .ThenBy(x => x.Name)
                                 .Select(x =>
                {
                    Match m = Regex.Match(x.Url, @"^(git@(?'host'[^:]+):(?'user'[^/]+)/(?'repo'[^/]+)\.git|(git|https?)://(?'host'[^/]+)/(?'user'[^/]+)/(?'repo'[^/]+)\.git)$", RegexOptions.ExplicitCapture);
                    if (m.Success)
                    {
                        string host = m.Groups["host"].Value;
                        return(new Uri(string.Format("http{0}://{1}/{2}/{3}/", host == "github.com" ? "s" : "", host, m.Groups["user"].Value, m.Groups["repo"].Value)));
                    }
                    else
                    {
                        return(null);
                    }
                }).FirstOrDefault(x => x != null);

                var loadingPerson = new Person("Loading…", "loading");
                var commit        = new Commit(UncommittedChangesCommitId, loadingPerson, DateTimeOffset.Now, loadingPerson, DateTimeOffset.Now, "", null, null);

                // create a fake blame result that assigns all the code to the HEAD revision
                blameResult = new BlameResult(webRootUrl, new[] { new Block(1, currentLines.Length, commit, fileName, 1) }.AsReadOnly(),
                                              currentLines.Select((l, n) => new Line(n + 1, l, true)).ToList(),
                                              new Dictionary <string, Commit> {
                    { commit.Id, commit }
                });
            }

            Task.Run(() =>
            {
                // run "git blame"
                ExternalProcess git     = new ExternalProcess(GetGitPath(), Path.GetDirectoryName(repositoryPath));
                List <string> arguments = new List <string> {
                    "blame", "--incremental", "--encoding=utf-8"
                };
                if (blameCommitId != null)
                {
                    arguments.Add(blameCommitId);
                }
                arguments.AddRange(new[] { "--", fileName });
                var results = git.Run(new ProcessRunSettings(arguments.ToArray()));
                if (results.ExitCode != 0)
                {
                    return;
                }

                // parse output
                List <Block> blocks = new List <Block>();
                Dictionary <string, Commit> commits = new Dictionary <string, Commit>();
                ParseBlameOutput(results.Output, blocks, commits);

                // allocate a (1-based) array for all lines in the file
                int lineCount = blocks.Sum(b => b.LineCount);
                Invariant.Assert(lineCount == currentLines.Length, "Unexpected number of lines in file.");

                // initialize all lines from current version
                Line[] lines = currentLines
                               .Select((l, n) => new Line(n + 1, l, false))
                               .ToArray();

                blameResult.SetData(blocks, lines, commits);
                Dictionary <string, Task <string> > getFileContentTasks = CreateGetFileContentTasks(repositoryPath, blocks, commits, currentLines);

                // process the blocks for each unique commit
                foreach (var groupLoopVariable in blocks.OrderBy(b => b.StartLine).GroupBy(b => b.Commit))
                {
                    // check if this commit modifies a previous one
                    var group               = groupLoopVariable;
                    Commit commit           = group.Key;
                    string commitId         = commit.Id;
                    string previousCommitId = commit.PreviousCommitId;

                    if (previousCommitId != null)
                    {
                        // diff the old and new file contents when they become available
                        Task <string> getOldFileContentTask = getFileContentTasks[previousCommitId];
                        Task <string> getNewFileContentTask = getFileContentTasks[commitId];
                        Task.Factory.ContinueWhenAll(new[] { getOldFileContentTask, getNewFileContentTask }, tasks =>
                        {
                            // diff the two versions
                            var oldFileContents = tasks[0].Result;
                            var newFileContents = tasks[1].Result;

                            // diff_match_patch can generate incorrect output if there are more than 65536 lines being diffed
                            var checkLines = GetLineCount(oldFileContents) < 65000 && GetLineCount(newFileContents) < 65000;

                            var diff = new diff_match_patch {
                                Diff_Timeout = 10
                            };
                            var diffs = diff.diff_main(oldFileContents, newFileContents, checkLines);
                            diff.diff_cleanupSemantic(diffs);

                            // process all the lines in the diff output, matching them to blocks
                            using (IEnumerator <Line> lineEnumerator = ParseDiffOutput(diffs).GetEnumerator())
                            {
                                // move to first line (which is expected to always be present)
                                Invariant.Assert(lineEnumerator.MoveNext(), "Expected at least one line from diff output.");
                                Line line = lineEnumerator.Current;

                                // process all the blocks, finding the corresponding lines from the diff for each one
                                foreach (Block block in group)
                                {
                                    // skip all lines that occurred before the start of this block
                                    while (line.LineNumber < block.OriginalStartLine)
                                    {
                                        Invariant.Assert(lineEnumerator.MoveNext(), "diff does not contain the expected number of lines.");
                                        line = lineEnumerator.Current;
                                    }

                                    // process all lines in the current block
                                    while (line.LineNumber >= block.OriginalStartLine && line.LineNumber < block.OriginalStartLine + block.LineCount)
                                    {
                                        // assign this line to the correct index in the blamed version of the file
                                        blameResult.SetLine(line.LineNumber - block.OriginalStartLine + block.StartLine, line);

                                        // move to the next line (if available)
                                        if (lineEnumerator.MoveNext())
                                        {
                                            line = lineEnumerator.Current;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        // this is the initial commit (but has not been modified since); grab its lines from the current version of the file
                        foreach (Block block in group)
                        {
                            for (int lineNumber = block.StartLine; lineNumber < block.StartLine + block.LineCount; lineNumber++)
                            {
                                blameResult.SetLine(lineNumber, new Line(lineNumber, currentLines[lineNumber - 1], true));
                            }
                        }
                    }
                }
            });

            return(blameResult);
        }
Esempio n. 29
0
        private void ButtonCompare_Click(object sender, EventArgs e)
        {
            Console.WriteLine("Button click!");

            if ((pdfPanel1.pdfViewer.Document == null) || (pdfPanel2.pdfViewer.Document == null))
            {
                labelResult.Text = "0.0";
                return;
            }

            var stopwatch = new System.Diagnostics.Stopwatch();

            int page1 = pdfPanel1.pdfViewer.Renderer.Page;
            int page2 = pdfPanel2.pdfViewer.Renderer.Page;

            //if ((pdfPanel1.GetComparedPage(page1) == page2) && (pdfPanel2.GetComparedPage(page2) == page1))
            //{
            //    labelResult.Text = "0.0";
            //    return;
            //}

            if (pdfPanel1.GetComparedPage(page1) >= 0)
            {
                pdfPanel1.ClearDiffMarker(page1);
            }
            if (pdfPanel2.GetComparedPage(page2) >= 0)
            {
                pdfPanel2.ClearDiffMarker(page2);
            }

            // Draw without the marker.
            pdfPanel1.Update();
            pdfPanel2.Update();

            //stopwatch.Stop();
            //Console.WriteLine("Clear:{0}", stopwatch.Elapsed);
            //stopwatch.Start();

            String             text1  = pdfPanel1.GetPageText();
            String             text2  = pdfPanel2.GetPageText();
            List <PdfTextSpan> index1 = new List <PdfTextSpan>();
            List <PdfTextSpan> index2 = new List <PdfTextSpan>();

            stopwatch.Stop();
            Console.WriteLine("Get:{0}", stopwatch.Elapsed);
            labelResult.Text = ".";
            labelResult.Update();
            stopwatch.Start();

            diff_match_patch dmp;
            List <Diff>      diffs;

            int diffType = comboBoxDiffType.SelectedIndex;

            switch (diffType)
            {
            case 0:         // NetDiff
                var results = DiffUtil.Diff(text1, text2);
                ExtractDiffSpan(index1, index2, results, page1, page2);
                break;

            case 1:         // Google Diff - Semantic
                dmp   = new diff_match_patch();
                diffs = dmp.diff_main(text1, text2);
                dmp.diff_cleanupSemantic(diffs);
                ExtractDiffSpan2(index1, index2, diffs, page1, page2);
                break;

            case 2:         // Google Diff - Effective 4
                dmp = new diff_match_patch();
                dmp.Diff_EditCost = 4;
                diffs             = dmp.diff_main(text1, text2);
                dmp.diff_cleanupEfficiency(diffs);
                ExtractDiffSpan2(index1, index2, diffs, page1, page2);
                break;

            case 3:         // Google Diff - Effective 5
                dmp = new diff_match_patch();
                dmp.Diff_EditCost = 5;
                diffs             = dmp.diff_main(text1, text2);
                dmp.diff_cleanupEfficiency(diffs);
                ExtractDiffSpan2(index1, index2, diffs, page1, page2);
                break;

            case 4:         // Google Diff - Effective 3
                dmp = new diff_match_patch();
                dmp.Diff_EditCost = 3;
                diffs             = dmp.diff_main(text1, text2);
                dmp.diff_cleanupEfficiency(diffs);
                ExtractDiffSpan2(index1, index2, diffs, page1, page2);
                break;

            case 5:         // Google Diff - Raw
                dmp   = new diff_match_patch();
                diffs = dmp.diff_main(text1, text2);
                ExtractDiffSpan2(index1, index2, diffs, page1, page2);
                break;

            default:
                throw new Exception();
            }


            stopwatch.Stop();
            Console.WriteLine("Diff:{0}", stopwatch.Elapsed);
            labelResult.Text = "..";
            labelResult.Update();
            stopwatch.Start();

            pdfPanel1.SetPageDiff(index1);
            pdfPanel2.SetPageDiff(index2);


            pdfPanel1.AddDiffMarker(page2);
            labelResult.Text = "...";
            labelResult.Update();
            pdfPanel2.AddDiffMarker(page1);
            labelResult.Text = "....";
            labelResult.Update();

            stopwatch.Stop();
            Console.WriteLine("Marker:{0}", stopwatch.Elapsed);
            stopwatch.Start();

            //results.ToList().ForEach(r => Console.WriteLine(r.ToFormatString()));
            if (stopwatch.ElapsedMilliseconds < 50)
            {
                Thread.Sleep(30);
            }

            // Draw with the markers.
            pdfPanel1.Update();
            pdfPanel2.Update();

            stopwatch.Stop();
            Console.WriteLine("Draw:{0}", stopwatch.Elapsed);

            labelResult.Text = String.Format("{0:0.0}", stopwatch.ElapsedMilliseconds / 1000.0);
        }
Esempio n. 30
0
        // GET: Topics/ViewHistory/5
        /// <summary>
        /// Zeigt die Änderungen, die an dem Thema vorgenommen wurden.
        /// </summary>
        /// <param name="id">Die TopicID</param>
        public ActionResult ViewHistory(int id)
        {
            Topic topic = db.Topics.Find(id);
            var history = db.TopicHistory.Where(th => th.TopicID == topic.ID).OrderBy(th => th.ValidFrom).ToList();

            if (history.Count == 0)
                return RedirectToAction("Details", new {id});

            history.Add(TopicHistory.FromTopic(topic, 0));

            var vm = new TopicHistoryViewModel
            {
                Usernames = db.Users.Where(u => u.IsActive).ToDictionary(u => u.ID, u => u.ShortName),
                SessionTypes = db.SessionTypes.ToDictionary(s => s.ID, s => s.Name),
                Current = topic,
                Initial = history[0]
            };

            var diff = new diff_match_patch
            {
                Diff_Timeout = 0.4f
            };

            // Anonyme Funktion, um die Biliothek diff_match_patch handlich zu verpacken.
            Func<string, string, List<Diff>> textDiff = (a, b) =>
            {
                var list = diff.diff_main(a, b);
                diff.diff_cleanupSemantic(list);
                return list;
            };

            foreach (var p in history.Pairwise())
            {
                vm.Differences.Add(new TopicHistoryDiff
                {
                    // Ein Eintrag entspricht später einer Box auf der Seite. Wenn keine Änderung existiert, sollte hier null gespeichert werden. Bei einer Änderung wird der NEUE Wert (der in Item2 enthalten ist) genommen.
                    // SimpleDiff ist eine kleine Helferfunktion, da die Zeilen sonst arg lang werden würden. Hier wird kein Text vergleichen - entweder hat sich alles geändert, oder gar nichts. (Daher "simple")
                    // textDiff ist komplexer, hier wird der Text analysiert und auf ähnliche Abschnitte hin untersucht.
                    Modified = p.Item1.ValidUntil,
                    Editor = vm.Usernames[p.Item1.EditorID],
                    SessionType = SimpleDiff(p.Item1.SessionTypeID, p.Item2.SessionTypeID, vm.SessionTypes),
                    TargetSessionType = SimpleDiff(p.Item1.TargetSessionTypeID, p.Item2.TargetSessionTypeID, vm.SessionTypes, "(kein)"),
                    Owner = SimpleDiff(p.Item1.OwnerID, p.Item2.OwnerID, vm.Usernames),
                    Priority = p.Item1.Priority == p.Item2.Priority ? null : p.Item2.Priority.DisplayName(),
                    Title = textDiff(p.Item1.Title, p.Item2.Title),
                    Time = p.Item1.Time == p.Item2.Time ? null : p.Item2.Time,
                    Description = textDiff(p.Item1.Description, p.Item2.Description),
                    Proposal = textDiff(p.Item1.Proposal, p.Item2.Proposal)
                });
            }

            return View(vm);
        }
        public string Patch(string sourceConfigPath, string destConfigPath)
        {
            string patchedFile = null;

            if (!(File.Exists(sourceConfigPath) && File.Exists(destConfigPath)))
            {
                Console.WriteLine("Config Patch error - could not find source or destination files");
                return(patchedFile);
            }

            string sourceData = File.ReadAllText(sourceConfigPath);
            string destData   = File.ReadAllText(destConfigPath);

            List <string> luaConfigs = new List <string>();
            int           openBraces = 0;

            foreach (string l in File.ReadAllLines(destConfigPath))
            {
                if (l.Contains('{'))
                {
                    ++openBraces;
                }
                if (l.Contains('}'))
                {
                    --openBraces;
                }

                if (l.Contains('=') && openBraces == 0)
                {
                    string def = l.Substring(0, l.IndexOf('='));
                    def = def.Trim().Trim('\t').Trim('\r').Trim('\n');
                    luaConfigs.Add(def);
                }
            }

            diff_match_patch dmp  = new diff_match_patch();
            List <Diff>      diff = dmp.diff_main(sourceData, destData);

            dmp.diff_cleanupSemantic(diff);

            List <Patch> patches = dmp.patch_make(sourceData, diff);

            List <Patch> filteredPatches = new List <Patch>();

            foreach (Patch p in patches)
            {
                bool foundPatch = false;
                foreach (Diff d in p.diffs)
                {
                    if (d.operation == Operation.INSERT || d.operation == Operation.DELETE)
                    {
                        foreach (string f in luaConfigs)
                        {
                            if (d.text.IndexOf(f) >= 0)
                            {
                                filteredPatches.Add(p);
                                foundPatch = true;
                                break;
                            }
                        }
                    }

                    if (foundPatch)
                    {
                        break;
                    }
                }
            }

            Console.WriteLine("Applying the following patches: ");
            foreach (Patch p in filteredPatches)
            {
                Console.WriteLine(p);
            }

            object[] v = dmp.patch_apply(filteredPatches, sourceData);

            return(Convert.ToString(v[0]));
        }