Esempio n. 1
0
        public Response DispatchCommand()
        {
            var cmdName = Parameters["cmd"];

            if (string.IsNullOrEmpty(cmdName))
            {
                return new ErrorResponse("Command not set");
            }

            ICommand cmd = null;

            switch (cmdName)
            {
                case "open":
                    if (!string.IsNullOrEmpty(Parameters["init"]) && Parameters["init"] == "true")
                        cmd = new Init();
                    else
                    {
                        cmd = new Open(Parameters["target"]);
                    }
                    break;
                case "mkdir":
                    cmd = new MkDir(Parameters["current"], Parameters["name"]);
                    break;
                case "rm":
                    cmd = new Rm(Parameters["current"], Parameters["targets[]"]);
                    break;
                case "rename":
                    cmd = new Rename(Parameters["current"], Parameters["target"], Parameters["name"]);
                    break;
                case "upload":
                    cmd = new Upload(Parameters["current"], Files);
                    break;
                case "ping":
                    cmd = new Ping();
                    break;
                case "duplicate":
                    cmd = new Duplicate(Parameters["current"], Parameters["target"]);
                    break;
                case "paste":
                    cmd = new Paste(Parameters["src"], Parameters["dst"], Parameters["targets[]"], Parameters["cut"]);
                    break;
            }

            if (cmd == null)
            {
                return new ErrorResponse("Unknown command");
            }

            return cmd.Execute();

            return new ErrorResponse("Unknown error");
        }
Esempio n. 2
0
        public void TestMethod2()
        {
            Duplicate d = new Duplicate();

            Duplicate.formalSetDic.Add("1,2,3",
                                       new SetInfo
            {
                counts = 1
            });

            Duplicate.formalSetDic.Add("1,1,2,3",
                                       new SetInfo
            {
                counts = 1 //no duplicate
                           //counts = 2 // 1 duplicate
            });
            Assert.AreEqual(2, d.GetDuplicatedorNotDuplicateCounts(false));
            //Assert.AreEqual(1, d.GetDuplicatedorNotDuplicateCounts(true));
        }
Esempio n. 3
0
        public void Parse(XmlDocument document)
        {
            var nodeReader = new DuplicateXmlNodeReader();

            foreach (XmlNode node in document.GetElementsByTagName("Duplicate"))
            {
                nodeReader.Read(node);
                var newDuplicate = new Duplicate
                {
                    Cost      = nodeReader.Cost,
                    Fragments = (from item in nodeReader.Fragments select new Fragment
                    {
                        SourceFile = _sourceFile.GetSourceFile(item.Filename),
                        LineStart = item.LineStart,
                        LineEnd = item.LineEnd
                    }).ToArray()
                };
                Notify(newDuplicate);
            }
        }
Esempio n. 4
0
        public void CanFindDuplicates_ReturnAllDuplicates(
            string xmlString,
            DuplicateTestDataClass.ElementAndXPaths[] expecteds,
            string message)
        {
            var doc = XDocument.Parse(xmlString);

            //  #   Act.
            var res = Logic.FindDuplicates(doc);

            //  #   Assert.
            var expectedDuplicates = expecteds
                                     .Select(expected =>
            {
                var element = XDocument.Parse(expected.ElementString).Root !;
                return(Duplicate.Create(element, expected.Xpaths));
            });

            res.Should().BeEquivalentTo(expectedDuplicates, message);
        }
Esempio n. 5
0
        public void Duplicate(int sequenceIndex)
        {
            Duplicate duplicate = new Duplicate();

            var topEnumerator = sequences[sequenceIndex].GetEnumerator();

            duplicate.TopInput = () => { while (topEnumerator.MoveNext())
                                         {
                                             return(topEnumerator.Current);
                                         }
                                         return(Value.Finished); };

            var topresult    = ReadOutput(duplicate.Top).ToArray();
            var bottomresult = ReadOutput(duplicate.Bottom).ToArray();

            Assert.AreEqual(sequences[sequenceIndex].Count() + 1, topresult.Length);    //all inputs plus one finished
            EqualEnumerables(sequences[sequenceIndex].Select(x => x.Get <int>()), topresult.TakeWhile(x => !x.Done).Select(x => x.Get <int>()));
            Assert.AreEqual(sequences[sequenceIndex].Count() + 1, bottomresult.Length); //all inputs plus one finished
            EqualEnumerables(sequences[sequenceIndex].Select(x => x.Get <int>()), bottomresult.TakeWhile(x => !x.Done).Select(x => x.Get <int>()));
        }
Esempio n. 6
0
        public DuplicateManager GetDuplicates()
        {
            DuplicateManager manager = new DuplicateManager();
            var dups = GetDataBase().Fetch <DuplicateIngredients>(" SELECT ItemIngredientName, Calories, Quantity, COUNT(ItemIngredientName) AS NumOccurrences FROM XmlImportIngredients GROUP BY ItemIngredientName, Calories, Quantity HAVING ( COUNT(ItemIngredientName) > 1 ) order by itemingredientname");

            foreach (var xmlImportIngredient in dups)
            {
                //this get all of the ingredient ids where there is an xref and there is a name and calories match
                List <IngredientAggregate> ingredients = new List <IngredientAggregate>();
                var candidates = GetDuplicateIngredientIds(xmlImportIngredient.Calories, xmlImportIngredient.ItemIngredientName, xmlImportIngredient.Quantity);

                if (candidates.Count < xmlImportIngredient.NumOccurrences)   //means there is a null and needs update
                {
                    List <string> added = new List <string>();
                    foreach (var ingredientcandidate in candidates)
                    {
                        if (!added.Contains(ingredientcandidate.DataObjectId.ToString()))
                        {
                            var ingdredient = GetMatchedIngredient(ingredientcandidate.DataObjectId.ToString(), true);
                            if (ingdredient != null)
                            {
                                added.Add(ingredientcandidate.DataObjectId.ToString());
                                ingredients.Add(ingdredient);
                            }
                        }
                    }
                }

                if (ingredients.Count > 0 || candidates.Count == 0)
                {
                    var dup = new Duplicate();
                    dup.Name         = xmlImportIngredient.ItemIngredientName;
                    dup.Calories     = xmlImportIngredient.Calories;
                    dup.Quantity     = xmlImportIngredient.Quantity;
                    dup.DisplayName  = xmlImportIngredient.ItemIngredientName + " with " + xmlImportIngredient.Calories + " calories";
                    dup.NumberOfDups = xmlImportIngredient.NumOccurrences;
                    manager.Duplicates.Add(dup, ingredients);
                }
            }
            return(manager);
        }
Esempio n. 7
0
        static void PrintDuplicates <T>(ref T[] _arr)
        {
            T[] distinct = _arr.Distinct().ToArray();
            Console.WriteLine("duplicates:");

            //we can use foreach only:
            //foreach (T item in distinct) Console.WriteLine($"{item} has {_arr.Where(x => x.Equals(item)).Count() - 1} duplicate(s)");

            //or fill array of structures and print results via the ToString method of the structure
            Duplicate <T>[] duplicates = new Duplicate <T> [distinct.Count()];
            int             i          = -1;

            foreach (T item in distinct)
            {
                duplicates[++i] = new Duplicate <T>(item, _arr.Where(x => x.Equals(item)).Count() - 1);
            }
            foreach (Duplicate <T> d in duplicates)
            {
                Console.WriteLine(d.ToString());
            }
        }
Esempio n. 8
0
        public void ValidDuplicateParamTests(Param param, Duplicate type)
        {
            var request = JsonConvert.SerializeObject(ReadUpdateUserRequest(UserCreator.Data.ToString()));

            request = type == Duplicate.SameValue ?
                      DuplicateParamSameValueMapper[param](request) :
                      DuplicateParamNotSameValueMapper[param](request);

            var manager = new UserManager();
            var result  = manager.Execute <Dictionary <string, string> >(request, HttpMethod.Put);

            PrAssert.That(result, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.NoContent), "Can not uppdate user.");
            var verifyTarget = new Dictionary <string, string>();

            foreach (var item in request.Trim(new[] { '}', '{' }).Split(','))
            {
                var kpv = item.Trim(new[] { '\\', '"' }).Split(':');
                verifyTarget.Add(kpv[0], kpv[1]);
            }
            VerifyUpdate(verifyTarget, result.Result.First().Value);
        }
        public DuplicateManager GetDuplicates()
        {
            DuplicateManager manager = new DuplicateManager();
            var dups = GetDataBase().Fetch<DuplicateIngredients>( " SELECT ItemIngredientName, Calories, Quantity, COUNT(ItemIngredientName) AS NumOccurrences FROM XmlImportIngredients GROUP BY ItemIngredientName, Calories, Quantity HAVING ( COUNT(ItemIngredientName) > 1 ) order by itemingredientname");
            foreach (var xmlImportIngredient in dups)
            {
                //this get all of the ingredient ids where there is an xref and there is a name and calories match
                List<IngredientAggregate> ingredients = new List<IngredientAggregate>();
                var candidates = GetDuplicateIngredientIds(xmlImportIngredient.Calories,  xmlImportIngredient.ItemIngredientName, xmlImportIngredient.Quantity);

                if ( candidates.Count < xmlImportIngredient.NumOccurrences ) //means there is a null and needs update
                {
                    List<string> added = new List<string>();
                    foreach (var ingredientcandidate in candidates)
                    {
                        if ( ! added.Contains(ingredientcandidate.DataObjectId.ToString()))
                        {
                            var ingdredient = GetMatchedIngredient(ingredientcandidate.DataObjectId.ToString(), true);
                            if (ingdredient != null)
                            {
                                added.Add(ingredientcandidate.DataObjectId.ToString());
                                ingredients.Add(ingdredient);
                            }
                        }
                    }
                }

                if ( ingredients.Count > 0 || candidates.Count == 0)
                {
                    var dup = new Duplicate();
                    dup.Name = xmlImportIngredient.ItemIngredientName;
                    dup.Calories = xmlImportIngredient.Calories;
                    dup.Quantity = xmlImportIngredient.Quantity;
                    dup.DisplayName = xmlImportIngredient.ItemIngredientName + " with " + xmlImportIngredient.Calories + " calories";
                    dup.NumberOfDups = xmlImportIngredient.NumOccurrences;
                    manager.Duplicates.Add(dup, ingredients);
                }
            }
            return manager;
        }
Esempio n. 10
0
        public ActionResult CreateNewDuplicateCollection()
        {
            try
            {
                using (var ctx = new WordsContext())
                {
                    //var model = new Models.DuplicatesModel();
                    var col = new Collection()
                    {
                        Type = collectionType.duplicates, Name = "xxx"
                    };
                    ctx.Collections.Add(col);
                    ctx.SaveChanges();

                    //CREATE NEW DUPLICATE
                    for (int i = 0; i < 10; i++)
                    {
                        //int order = ctx.Duplicates.OrderByDescending(i => i.Order).Take(1).Select(x => x.Order).FirstOrDefault();
                        //order++;
                        var dup = new Duplicate()
                        {
                            Answer1 = "xxx", Answer2 = "xxx", Answer3 = "xxx", Answer4 = "xxx", Order = i + 1, Collection = col
                        };
                        ctx.Duplicates.Add(dup);
                        //col.Duplicates.Add(dup);
                    }
                    ctx.SaveChanges();
                    //modelDuplicate = dup;

                    return(null);// View(model);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 11
0
        public void Method4()
        {
            Duplicate d = new Duplicate();

            d.CheckIfDuplicate1("~,1");
            d.CheckIfDuplicate1("~,");
            d.CheckIfDuplicate1("abc1");
            d.CheckIfDuplicate1("1,2,3");
            d.CheckIfDuplicate1("");
            d.CheckIfDuplicate1("1,");
            d.CheckIfDuplicate1("1,a");
            List <string> actualInvalidInput = d.GetInvalidInputs().ToList <string>();
            List <string> expectedResult     = new List <string>
            {
                "~,1",
                "~,",
                "abc1",
                "",
                "1,",
                "1,a"
            };

            CollectionAssert.AreEqual(expectedResult, actualInvalidInput);
        }
        public void ValidDuplicateUpdatePhaseEntry(Duplicate duplicate, string param)
        {
            var handler  = new DefaultManager();
            var result   = new List <Dictionary <string, object> >();
            var dataItem = GetDataItem(RootPhaseOption.Data[ResourceId.Client].Id);

            DuplicateParam(duplicate, param, dataItem);
            var phaseItem = GetUpdatePhaseItem(dataItem, RecordsCreator, PreparedPhaseId);

            DuplicateParam(duplicate, param, phaseItem);
            result.Add(phaseItem);
            var request = new Dictionary <string, object>()
            {
                [ParamUpdate] = result
            };

            DuplicateParam(duplicate, param, request);
            var jsonRequest = ReplaceDuplicateParam(request.ToJson(), param);

            PrAssert.That(jsonRequest, PrIs.Not.EqualTo(string.Empty));
            var updateResponse = handler.SendAsync <CreatePhaseEntryResponse>(PhaseEntryTestData.PhaseEntryApi, jsonRequest, HttpMethod.PUT).Result;

            PrAssert.That(updateResponse, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.BadRequest), "Still able to create Phase Entry");
        }
Esempio n. 13
0
 public RemovedDuplicate(int index, Duplicate duplicate)
 {
     this.Index     = index;
     this.Duplicate = duplicate;
 }
Esempio n. 14
0
 public KeepSide(DuplicatesFormController controller, Duplicate duplicate, int matchIndex, Side keptSide) : base(controller)
 {
     this.duplicate      = duplicate;
     this.duplicateIndex = matchIndex;
     this.keptSide       = keptSide;
 }
Esempio n. 15
0
 public async Task <bool> ExistsAsync(Duplicate data) => await _context.ExistsAsync <Unit>(data);
Esempio n. 16
0
 public Skip(DuplicatesFormController controller, Duplicate duplicate, int matchIndex) : base(controller)
 {
     this.duplicate      = duplicate;
     this.duplicateIndex = matchIndex;
 }
Esempio n. 17
0
        public async Task <bool> SuspendAsync(ulong user, ulong suspender, string reason, Duplicate duplicate = null)
        {
            if (GetUserSuspension(user) != null)
            {
                // if user is already suspended, return feedback to user
                return(false);
            }

            // if there is no suspension, add one to the database
            using (SmeuContext database = smeuBaseFactory.GetSmeuBase())
            {
                Suspension suspension = new Suspension {
                    User = user, Date = DateTime.UtcNow, Suspender = suspender, Reason = reason
                };
                database.Suspensions.Add(suspension);
                if (duplicate != null)
                {
                    // if a duplicate was given, update the duplicate to reflect the suspension
                    duplicate.Suspension = suspension;
                    database.Duplicates.Update(duplicate);
                }
                await database.SaveChangesAsync().ConfigureAwait(false);
            }
            return(true);
        }
Esempio n. 18
0
        static void Main(string[] args)
        {
            RunConfig runConfig;

            if (!TryParseArguments(args, out runConfig))
            {
                Usage();
                return;
            }

            var code = File.ReadAllText(args[0]);

            var pageState = new GraphicsState();

            var stack     = new LinearList <IOperation>();
            var execStack = new LinearList <IOperation>();
            var dictStack = new LinearList <IDictionary <string, IOperation> >();

            var system = new Dictionary <string, IOperation>();

            system["add"]    = new Add();
            system["sub"]    = new Substract();
            system["mul"]    = new Multiplicate();
            system["div"]    = new Divide();
            system["mod"]    = new Mod();
            system["def"]    = new Define();
            system["for"]    = new For();
            system["dup"]    = new Duplicate();
            system["index"]  = new Index();
            system["pop"]    = new Pop();
            system["exch"]   = new Exchange();
            system["repeat"] = new Repeat();
            system["array"]  = new EmptyArray();
            system["astore"] = new LoadArray();
            system["rand"]   = new Rand();
            system["cvi"]    = new ConvertToInteger();
            system["copy"]   = new Copy();
            system["roll"]   = new Roll();
            system["get"]    = new ArrayGet();
            system["put"]    = new ArrayPut();
            system["ne"]     = new NotEqual();
            system["eq"]     = new Equal();
            system["or"]     = new Or();
            system["ifelse"] = new IfElse();
            system["if"]     = new If();
            system["neg"]    = new Neg();
            system["not"]    = new Not();
            system["sqrt"]   = new Sqrt();
            system["lt"]     = new LessThan();
            system["ge"]     = new GreaterOrEqualThan();

            dictStack.Push(system);


            var graphics = new Dictionary <string, IOperation>();

            graphics["newpath"]      = new NewPath(pageState);
            graphics["closepath"]    = new ClosePath(pageState);
            graphics["fillpath"]     = new FillPath(pageState);
            graphics["setgray"]      = new SetGray(pageState);
            graphics["setrgbcolor"]  = new SetRGB(pageState);
            graphics["setlinewidth"] = new SetLineWidth(pageState);
            graphics["fill"]         = new FillPath(pageState);
            graphics["showpage"]     = new ShowPage(pageState);
            graphics["moveto"]       = new MoveTo(pageState);
            graphics["lineto"]       = new LineTo(pageState);
            graphics["rlineto"]      = new RelativeLineTo(pageState);
            graphics["gsave"]        = new SaveGraphicsState(pageState);
            graphics["grestore"]     = new RestoreGraphicsState(pageState);
            graphics["stroke"]       = new StrokePath(pageState);
            graphics["curveto"]      = new CurveTo(pageState);
            graphics["arc"]          = new Arc(pageState);

            dictStack.Push(graphics);

            dictStack.Push(new Dictionary <string, IOperation>());

            //execStack.Push(start);


            CodeParser.LoadCode(execStack,
                                @"
/findfont { pop (somefont) } def
/scalefont { exch pop } def
/setfont { pop } def
/setlinecap { pop } def
/srand { pop } def
");

            CodeParser.LoadCode(execStack, code);

            var state = new PreScriptState(stack, execStack, dictStack);

            while (execStack.Count > 0)
            {
                var operation = execStack.Pop();
                operation.Process(state);
            }
        }
 public void Given_EmptyArray_Expect_ArgrumentException(int[] i)
 {
     Assert.Throws <ArgumentException>(() => Duplicate.ContainsDuplicate(i));
 }
Esempio n. 20
0
 public void TestFunc(Duplicate dup)
 {
 }
        public void SetContext_WhenSingleFileHasDuplicates_ShouldNotSetDuplicateShowdInDuplicateFile()
        {
            const string testFilename = "test.cs";

            var factory = new FileReaderFactoryFake();

            factory.FileContents[testFilename] = new[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m" };

            var sourceFile = new SourceFile(testFilename);
            var duplicate  = new Duplicate
            {
                Fragments = new[]
                {
                    new Fragment
                    {
                        SourceFile = sourceFile,
                        LineStart  = 2,
                        LineEnd    = 3
                    },
                    new Fragment
                    {
                        SourceFile = sourceFile,
                        LineStart  = 5,
                        LineEnd    = 6
                    },
                    new Fragment
                    {
                        SourceFile = sourceFile,
                        LineStart  = 8,
                        LineEnd    = 9
                    }
                }
            };

            IList <SourceFile> duplicatesObtained = new List <SourceFile>();
            IList <Line>       duplicateLines     = new List <Line>();

            var obj = new Core.ViewController.ViewController(factory);

            obj.OnUpdateDuplicateFiles += (sender, list) =>
            {
                duplicatesObtained = list;
            };
            obj.OnUpdateDuplicateFileLines += (sender, list) => { duplicateLines = list; };

            obj.SetContext(sourceFile, new[] { duplicate });
            obj.SetCurrentFileLine(1);
            Assert.AreEqual(0, duplicatesObtained.Count);
            Assert.AreEqual(0, duplicateLines.Count);

            obj.SetCurrentFileLine(2);
            obj.SetCurrentDuplicateFile(sourceFile);
            Assert.IsNull(duplicateLines[1].Duplicate);
            Assert.IsNull(duplicateLines[2].Duplicate);
            Assert.IsNotNull(duplicateLines[4].Duplicate);
            Assert.IsNotNull(duplicateLines[5].Duplicate);

            obj.SetCurrentFileLine(5);
            obj.SetCurrentDuplicateFile(sourceFile);
            Assert.IsNull(duplicateLines[4].Duplicate);
            Assert.IsNull(duplicateLines[5].Duplicate);
            Assert.IsNotNull(duplicateLines[1].Duplicate);
            Assert.IsNotNull(duplicateLines[2].Duplicate);

            obj.SetCurrentFileLine(1);
            obj.SetCurrentDuplicateFile(null);
            Assert.AreEqual(0, duplicateLines.Count);
        }
        public DuplicateManager GetXmlIngredientDuplicates()
        {
            DuplicateManager manager = new DuplicateManager();
            var dups = GetDataBase().Fetch<XmlImportIngredient>(
                    " SELECT ItemIngredientName, Calories, Quantity, COUNT(ItemIngredientName) AS NumOccurrences FROM XmlImportIngredients GROUP BY ItemIngredientName, Calories, Quantity HAVING ( COUNT(ItemIngredientName) > 1 ) order by itemingredientname");
            foreach (var xmlImportIngredient in dups)
            {
                var items = GetXmlIngredientsByName(xmlImportIngredient.ItemIngredientName, xmlImportIngredient.Calories);
                List<IngredientAggregate> ingredients = new List<IngredientAggregate>();
                foreach (var importIngredient in items)
                {
                    var xref = GetIngredientCrossReference(importIngredient.ItemIngredientGuid);
                    if ( xref != null && xref.ingredientsguid != null)
                    {
                        var ingdredient = GetMatchedIngredient(xref.ingredientsguid.ToString(), true);
                        if ( ingdredient != null)
                            ingredients.Add(ingdredient);
                    }

                }
                var dup = new Duplicate();
                dup.Name = xmlImportIngredient.ItemIngredientName;
                dup.DisplayName = xmlImportIngredient.ItemIngredientName + " with " + xmlImportIngredient.Calories + " calories";
                dup.NumberOfDups = items.Count;
                manager.Duplicates.Add(dup, ingredients);
            }
            return manager;
        }
Esempio n. 23
0
        private (int, int) ResolveDuplicates()
        {
            if (db.duplicates.Count == 0)
            {
                return(0, 0);
            }

            int         replaced = 0, removed = 0;
            CompareView compare = new CompareView(db, true);

            compare.Owner = this;
            Enabled       = false;

            bool cancel = false;

            while (db.duplicates.Count > 0 && !cancel)
            {
                Duplicate duplicate = db.duplicates[0];
                int?      complex   = null;
                if (db.duplicates.Any(x => x != duplicate && x.IsSameImage(duplicate)))
                {
                    complex = db.duplicates.Count(x => x != duplicate && x.IsSameImage(duplicate));
                }
                DialogResult result = compare.Show(duplicate.image1, duplicate.image2, duplicate.dist, complex);
                if (result != DialogResult.OK)
                {
                    break;
                }

                switch (compare.CompareResult)
                {
                case CompareView.Result.Left:
                    // replace existing
                    if (duplicate.image2.score != 0)
                    {
                        duplicate.image1.score = duplicate.image2.score;
                        int index = db.sortedImages.IndexOf(duplicate.image2);
                        db.sortedImages[index] = duplicate.image1;
                        db.newImages.Remove(duplicate.image1);
                        db.imagesDict.Remove(duplicate.image2.Filename);
                        Utility.SafeDelete(this, duplicate.image2.path);
                        db.duplicates.RemoveAll(x => x.image1 == duplicate.image2 || x.image2 == duplicate.image2);
                        ++replaced;
                    }
                    else
                    {
                        db.newImages.Remove(duplicate.image2);
                        db.imagesDict.Remove(duplicate.image2.Filename);
                        Utility.SafeDelete(this, duplicate.image2.path);
                        db.duplicates.RemoveAll(x => x.image1 == duplicate.image2 || x.image2 == duplicate.image2);
                        ++removed;
                    }
                    break;

                case CompareView.Result.Right:
                    // keep existing
                    db.newImages.Remove(duplicate.image1);
                    db.imagesDict.Remove(duplicate.image1.Filename);
                    Utility.SafeDelete(this, duplicate.image1.path);
                    db.duplicates.RemoveAll(x => x.image1 == duplicate.image1 || x.image2 == duplicate.image1);
                    ++removed;
                    break;

                case CompareView.Result.Both:
                    // keep both
                    db.duplicates.RemoveAt(0);
                    break;

                case CompareView.Result.Complex:
                {
                    List <Duplicate> dups      = db.duplicates.Where(x => x.IsSameImage(duplicate)).ToList();
                    List <Image>     dupImages = new List <Image>();
                    foreach (Duplicate dup in dups)
                    {
                        if (!dupImages.Contains(dup.image1))
                        {
                            dupImages.Add(dup.image1);
                        }
                        if (!dupImages.Contains(dup.image2))
                        {
                            dupImages.Add(dup.image2);
                        }
                    }
                    List <DuplicateItem> dupItems = dupImages
                                                    .Select(x => new DuplicateItem {
                            image = x
                        })
                                                    .ToList();
                    compare.Hide();
                    using (MultiCompareView view = new MultiCompareView(db, dupItems))
                    {
                        DialogResult result2 = view.ShowDialog(this);
                        if (result2 == DialogResult.Cancel)
                        {
                            cancel = true;
                        }
                        else if (result2 == DialogResult.OK)
                        {
                            db.duplicates.RemoveAll(x => dups.Contains(x));
                            replaced += view.replaced;
                            removed  += view.removed;
                        }
                    }
                }
                break;
                }
            }

            compare.Close();
            Enabled = true;
            Activate();
            return(replaced, removed);
        }
Esempio n. 24
0
 public Task <bool> ExistsAsync(Duplicate data) => _context.ExistsAsync <AccountYear>(data);
Esempio n. 25
0
 //# IM-4001
 private string MoveToProcessing(string filePath, Duplicate duplicate)
 {
     try
     {
         MoveFile(filePath, Path.Combine(_MonitorProcessingPath, Path.GetFileName(filePath)), duplicate);	//# IM-4001
     }
     catch
     {
         //Not able to move file
         throw;
     }
     return Path.Combine(_MonitorProcessingPath, Path.GetFileName(filePath));
 }
Esempio n. 26
0
 //# IM-4001
 private bool MoveToPassed(string filePath, Duplicate duplicate)
 {
     try
     {
         MoveFile(filePath, Path.Combine(_MonitorPassedPath, Path.GetFileName(filePath)), duplicate);	//# IM-4001
     }
     catch
     {
         return false;
     }
     return true;
 }
Esempio n. 27
0
        //# IM-4001
        private void MoveFile(string from, string topath, Duplicate duplicate = Duplicate.Error)
        {
            try
            {
                if (File.Exists(topath))
                {
                    switch (duplicate)
                    {
                        case Duplicate.Error:
                            DebugLog.Write("Duplicate - file already exists: " + topath);
                            return;

                        case Duplicate.Replace:
                            File.Delete(topath);
                            File.Move(from, topath);
                            return;

                        case Duplicate.ReplaceButBackupOriginal:
                            File.Replace(from, topath, AddTimeStamp(topath));
                            return;

                        case Duplicate.CreateWithTimestampAppended:
                            File.Move(from, AddTimeStamp(topath));
                            return;
                    }
                }

                File.Move(from, topath);
            }
            catch (Exception ex)
            {
                DebugLog.Write(ex);
            }
        }
Esempio n. 28
0
 public override int GetHashCode()
 {
     unchecked
     {
         return(New.GetHashCode() ^ Open.GetHashCode() ^ Resolved.GetHashCode() ^ OnHold.GetHashCode() ^ Invalid.GetHashCode() ^ Duplicate.GetHashCode() ^ Wontfix.GetHashCode());
     }
 }
Esempio n. 29
0
 private IEnumerator animationRoutine(Duplicate d)
 {
 public void DuplicateParsed(Duplicate duplicate)
 {
     Duplicates.Add(duplicate);
 }
Esempio n. 31
0
		public IEnumerable<KeyValuePair<Duplicate, Duplicate>> FindDuplicateListItems() {
			using (var reader = SelectReader(@"
				CREATE TEMP VIEW IF NOT EXISTS DupL AS Select V.SetID, V.Phrase, V.Translation, V.ListPosition, S.Name, (SELECT count(*) FROM PracticeHistory AS P WHERE P.SetID = V.SetID AND P.Phrase = V.Phrase AND P.Translation = V.Translation) as PracticeCount FROM VocabItems AS V JOIN Sets AS S ON V.SetID = S.ID;
				CREATE TEMP VIEW IF NOT EXISTS DupR AS Select V.SetID, V.Phrase, V.Translation, V.ListPosition, S.Name, (SELECT count(*) FROM PracticeHistory AS P WHERE P.SetID = V.SetID AND P.Phrase = V.Phrase AND P.Translation = V.Translation) as PracticeCount FROM VocabItems AS V JOIN Sets AS S ON V.SetID = S.ID;                
				SELECT L.SetID, L.Phrase, L.Translation, L.Name, L.PracticeCount, R.SetID, R.Phrase, R.Translation, R.Name, R.PracticeCount FROM DupL AS L JOIN DupR AS R ON (L.Phrase = R.Phrase OR L.Translation = R.Translation) AND (L.SetID < R.SetID OR (L.SetID = R.SetID AND L.ListPosition < R.ListPosition))")) {
				
				while (reader.Read()) {
					var left = new Duplicate {
						SetID = reader.GetInt64(0),
						Phrase = reader.GetString(1),
						Translation = reader.GetString(2),
						ListName = reader.GetString(3),
						PracticeCount = reader.GetInt32(4),
					};
					var right = new Duplicate {
						SetID = reader.GetInt64(5),
						Phrase = reader.GetString(6),
						Translation = reader.GetString(7),
						ListName = reader.GetString(8),
						PracticeCount = reader.GetInt32(9),
					};
					yield return new KeyValuePair<Duplicate, Duplicate>(left, right);
				}
			}
		}
        public void Given_ArrayOfInts_Expect_ReturnContainsDuplicateAsTrue(int[] i)
        {
            bool r = Duplicate.ContainsDuplicate(i);

            Assert.True(r);
        }
        public (IEnumerable <Duplicate> duplicates, int uniqueDuplicates, int duplicateInstances) FindDuplicates(IEnumerable <SourceFile> sourceFiles)
        {
            var sourceFileArray = sourceFiles.ToArray();

            var uniqueDuplicateStatements   = 0;
            var duplicateStatementInstances = 0;

            var duplicates = new Dictionary <string, Duplicate>();

            for (var i = 0; i < sourceFileArray.Length; i++)
            {
                var sourceFile = sourceFileArray[i];

                for (var j = i + 1; j < sourceFileArray.Length; j++)
                {
                    var compareFile = sourceFileArray[j];

                    foreach (var sourceStatement in sourceFile.Statements)
                    {
                        foreach (var compareStatement in compareFile.Statements)
                        {
                            if (string.Equals(sourceStatement.StatementText, compareStatement.StatementText))
                            {
                                if (!duplicates.TryGetValue(sourceStatement.StatementText, out var duplicate))
                                {
                                    duplicate = new Duplicate
                                    {
                                        Instances = new List <DuplicateInstance>()
                                    };

                                    uniqueDuplicateStatements++;

                                    duplicates[sourceStatement.StatementText] = duplicate;
                                }

                                if (!duplicate.Instances.Any(instance => instance.Statements.Any(ii => ii == sourceStatement)))
                                {
                                    duplicate.Instances.Add(
                                        new DuplicateInstance
                                    {
                                        SourceFile = sourceFile,
                                        Statements = new[] { sourceStatement }
                                    });

                                    duplicateStatementInstances++;
                                }

                                if (!duplicate.Instances.Any(instance => instance.Statements.Any(ii => ii == compareStatement)))
                                {
                                    duplicate.Instances.Add(
                                        new DuplicateInstance
                                    {
                                        SourceFile = compareFile,
                                        Statements = new[] { compareStatement }
                                    });

                                    duplicateStatementInstances++;
                                }
                            }
                        }
                    }
                }
            }

            return(duplicates.Values, uniqueDuplicateStatements, duplicateStatementInstances);
        }
Esempio n. 34
0
        public async Task <bool> RemoveAsync(string smeu, ulong author)
        {
            using (SmeuContext database = smeuBaseFactory.GetSmeuBase())
            {
                // first check if this combination is a duplicate
                Duplicate duplicate = (from d in database.Duplicates
                                       where d.Author == author && d.Original.Smeu == smeu
                                       orderby d.Date descending
                                       select d).FirstOrDefault();

                if (duplicate != null)
                {
                    // remove the duplicate
                    IMessage msg = await(client.GetChannel(settings.SmeuChannelId) as IMessageChannel).GetMessageAsync(duplicate.MessageId).ConfigureAwait(false);
                    await msg.DeleteAsync().ConfigureAwait(false);

                    database.Duplicates.Remove(duplicate);
                    await database.SaveChangesAsync().ConfigureAwait(false);

                    return(true);
                }

                // check if there is an original
                Submission submission = await(from s in database.Submissions
                                              where s.Author == author && s.Smeu == smeu
                                              select s).Include(x => x.Duplicates).FirstOrDefaultAsync().ConfigureAwait(false);

                if (submission != null)
                {
                    // remove the original message
                    IMessage msg = await(client.GetChannel(settings.SmeuChannelId) as IMessageChannel).GetMessageAsync(submission.MessageId).ConfigureAwait(false);
                    await msg.DeleteAsync().ConfigureAwait(false);

                    // check if a duplicate must take this submission's place
                    if (submission.Duplicates.Count > 0)
                    {
                        // if so, take the oldest duplicate and change the details of the submission to these.
                        duplicate = (from d in submission.Duplicates
                                     orderby d.Date ascending
                                     select d).First();

                        submission.Author    = duplicate.Author;
                        submission.Date      = duplicate.Date;
                        submission.MessageId = duplicate.MessageId;

                        database.Submissions.Update(submission);
                        database.Duplicates.Remove(duplicate);
                    }
                    else
                    {
                        // if not, just remove the submission from the database
                        database.Submissions.Remove(submission);
                    }

                    await database.SaveChangesAsync().ConfigureAwait(false);

                    return(true);
                }

                // if there was no duplicate and no original, return failure
                return(false);
            }
        }
Esempio n. 35
0
 public async Task <bool> ExistsAsync(Duplicate data) => await _context.ExistsAsync <ProductCategory>(data);
Esempio n. 36
0
        private void StartUpload()
        {
            //prepare all images to upload
            List <ImageForUpload> listOfImagesToUpload = prepareImagesForUpload();

            if (stopEvent.WaitOne(0))
            {
                return;
            }

            //prepare counters and progress bar
            int totalVehicleCount = GetTotalVehicles();

            maxValue = CalculateMaxProgressValue(listOfImagesToUpload);             //calculate max value for total progress (total kB of images)
            //this.InvokeOnMainThread(delegate { pbTotal.Max = (int)maxValue; });

            using (Connection sqlConn = new Connection(SQLiteBoostDB.GetDBPath()))
            {
                //initialize vars
                VehicleDB         vdb  = new VehicleDB(sqlConn);
                VehicleFeaturesDB vfdb = new VehicleFeaturesDB(sqlConn);
                DamageDB          ddb  = new DamageDB(sqlConn);
                TireDB            tdb  = new TireDB(sqlConn);
                PaintDB           pdb  = new PaintDB(sqlConn);
                int vehCounter         = 0;

                foreach (UploadDealerVehiclesList dealerVehicles in listDealerVehicles)
                {
                    mobileUploadID = 0;

                    PauseUpload();
                    uploader.GetMobileUploadID(userId, dealerVehicles.DealershipID);
                    pauseEvent.WaitOne(Timeout.Infinite);
                    if (stopEvent.WaitOne(0))
                    {
                        return;
                    }

                    if (mobileUploadID <= 0)
                    {
                        Upload_Failed("Unable to retrieve a valid upload key.");
                        return;
                    }

                    foreach (int vehicleId in dealerVehicles.VehicleIDs)
                    {
                        pauseEvent.WaitOne(Timeout.Infinite);
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }

                        //initialize variables for next vehicle
                        skipVehicle     = false;
                        mobileVehicleId = 0;
                        dupeResponse    = null;
                        vehCounter++;
                        Vehicle vehicle = vdb.GetVehicle(vehicleId);

                        //reset progress for images and set the vehicle counter
                        this.InvokeOnMainThread(delegate { nbUpload.TopItem.Title = "Uploading Vehicle " + vehCounter + "/" + totalVehicleCount; });

                        //check if vehicle already exists
                        if (!overwriteAll && (!string.IsNullOrEmpty(vehicle.StockNumber) || !string.IsNullOrEmpty(vehicle.VIN)))
                        {
                            PauseUpload();
                            uploader.GetDuplicateData(dealerVehicles.DealershipID, vehicle.StockNumber, vehicle.VIN);
                            pauseEvent.WaitOne(Timeout.Infinite);
                            if (stopEvent.WaitOne(0))
                            {
                                return;
                            }

                            if (dupeResponse != null && dupeResponse.TotalDuplicates > 0)
                            {
                                CheckSkipVehicle(dupeResponse);

                                //wait until the user responds
                                pauseEvent.WaitOne(Timeout.Infinite);
                                if (skipVehicle)
                                {
                                    continue;
                                }
                            }
                        }

                        //Upload vehicle data
                        PauseUpload();

                        uploader.UploadVehicleData(mobileUploadID, vehicle);

                        //wait for upload of data to complete
                        pauseEvent.WaitOne(Timeout.Infinite);
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle || mobileVehicleId <= 0)
                        {
                            continue;
                        }

                        //update the progress for the vehicle data upload
                        updateTotalProgress(10240);

                        //upload feature data
                        PauseUpload();
                        uploader.UploadFeatureData(mobileVehicleId, vfdb.GetSelectedFeatures(vehicle.ID));

                        //wait for upload of features to complete
                        pauseEvent.WaitOne(Timeout.Infinite);
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle)
                        {
                            continue;
                        }

                        //update the progress for the features data upload
                        updateTotalProgress(10240);

                        //damages
                        PauseUpload();
                        uploader.UploadDamageData(mobileVehicleId, ddb.GetDamageList(vehicle.ID));
                        pauseEvent.WaitOne(Timeout.Infinite);                        //wait for upload of damages to complete
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle)
                        {
                            continue;
                        }
                        updateTotalProgress(10240);                          //add damage progress

                        //paint
                        PauseUpload();
                        uploader.UploadPaintData(mobileVehicleId, pdb.GetPaintList(vehicle.ID));
                        pauseEvent.WaitOne(Timeout.Infinite);                        //wait for upload of paint to complete
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle)
                        {
                            continue;
                        }
                        updateTotalProgress(10240);                          //add paint progress

                        //tires
                        PauseUpload();
                        uploader.UploadTireData(mobileVehicleId, tdb.GetTireList(vehicle.ID));
                        pauseEvent.WaitOne(Timeout.Infinite);                        //wait for upload of tires to complete
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle)
                        {
                            continue;
                        }
                        updateTotalProgress(10240);                          //add tire progress

                        //loop images to upload
                        if (listOfImagesToUpload != null && listOfImagesToUpload.Count > 0)
                        {
                            List <ImageForUpload> listOfImagesForVehicle = listOfImagesToUpload.Where(i => i.vehicleId == vehicleId && i.dealershipId == dealerVehicles.DealershipID).ToList();

                            int imgCounter = 0;
                            foreach (ImageForUpload img in listOfImagesForVehicle)
                            {
                                pauseEvent.WaitOne(Timeout.Infinite);
                                if (stopEvent.WaitOne(0))
                                {
                                    return;
                                }

                                //initialize image variables
                                imgCounter++;
                                currentFileSize = (int)img.fileSize;
                                this.InvokeOnMainThread(delegate {
                                    pbCurrentVehicle.Progress = 0f;
                                    //pbIVtotal.Max = (int)img.fileSize;
                                    maxImageSize           = (int)img.fileSize;
                                    lblCurrentVehicle.Text = "Uploading image " + imgCounter + " of " + listOfImagesForVehicle.Count() + " for this vehicle.";
                                });

                                if (img.damageId > 0)
                                {
                                    pauseEvent.Reset();                                    //don't want to pause the "uploader" object, only local - don't use "PauseUpload()"
                                    uploader.UploadDamageFile(mobileUploadID, mobileVehicleId, img.damageId, File.ReadAllBytes(img.filePath));
                                    pauseEvent.WaitOne(Timeout.Infinite);
                                    if (stopEvent.WaitOne(0))
                                    {
                                        return;
                                    }
                                    if (skipVehicle)
                                    {
                                        break;
                                    }

                                    continue;
                                }

                                pauseEvent.Reset();                                //don't want to pause the "uploader" object, only local - don't use "PauseUpload()"
                                uploader.UploadFile(mobileUploadID, mobileVehicleId, img.fileNumber, File.ReadAllBytes(img.filePath));

                                pauseEvent.WaitOne(Timeout.Infinite);
                                if (stopEvent.WaitOne(0))
                                {
                                    return;
                                }
                                if (skipVehicle)
                                {
                                    break;
                                }

                                //insert image to database
                                PauseUpload();
                                uploader.UploadImageData(mobileVehicleId, img.fileNumber);

                                pauseEvent.WaitOne(Timeout.Infinite);
                                if (stopEvent.WaitOne(0))
                                {
                                    return;
                                }
                                if (skipVehicle)
                                {
                                    break;
                                }

                                //update the progress for the image update
                                updateTotalProgress(10240);
                            }
                        }

                        if (stopEvent.WaitOne(0))                         //check if the upload has been cancelled before committing data
                        {
                            return;
                        }
                        if (skipVehicle)                         //check if the vehicle is skipped
                        {
                            continue;
                        }

                        //commit vehicle
                        PauseUpload();
                        uploader.CommitVehicle(mobileVehicleId);

                        pauseEvent.WaitOne(Timeout.Infinite);
                        if (stopEvent.WaitOne(0))
                        {
                            return;
                        }
                        if (skipVehicle)
                        {
                            continue;
                        }

                        //Delete the vehicle from the device
                        vdb.DeleteVehicle(vehicle.ID);

                        //update the progress for the commit
                        updateTotalProgress(10240);
                    }
                }
            }

            if (!stopEvent.WaitOne(0))
            {
                Upload_Complete();
            }
        }
Esempio n. 37
0
 public KdTreeNode(TKey[] point, TValue value)
 {
     Point = point;
     Value = value;
     Duplicate.Add(value);
 }