Exemple #1
0
        public void DeletePorter(int id)
        {
            try
            {
                using (HospitalManagementSystemContext context = TypeFactory.Resolve <HospitalManagementSystemContext>())
                //using (HospitalManagementSystemContext context = new HospitalManagementSystemContext())
                {
                    Porter porter = context.Porter.Include(p => p.Person).FirstOrDefault(p => p.Id == id);

                    if (porter != null)
                    {
                        porter.Person = context.Person.FirstOrDefault(p => p.Id == porter.PersonId);

                        if (porter.Person != null)
                        {
                            //Bad code: place holder
                            porter.Person.Email    = "*****@*****.**";
                            porter.Person.UserName = "******";
                            porter.Person.Active   = false;
                        }
                    }

                    context.SaveChanges();
                }
            }
            catch (System.Exception ex)
            {
                //throw ex;
            }
        }
Exemple #2
0
        static void Main(string[] args)
        {
            try
            {
                var pRus = new Porter();
                var pEng = new PorterStemmer();

                //путь к папкам входных и выходных данных
                var dataPath = Directory.GetParent(Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).ToString()).ToString());

                //чтение входных данных
                var readerWriter = new AnaliseWords.ReadWrite();
                readerWriter.read(String.Format(dataPath.ToString() + "\\InputFolder\\sample.csv"));

                //разбиение файлов на группы словоформ
                var analizerEng  = new WordAnalizer(readerWriter.Englist, pEng, 0.9);
                var analizerRus  = new WordAnalizer(readerWriter.Ruslist, pRus, 0.9);
                var resultDicEng = analizerEng.analiseWords();
                var resultDicRus = analizerRus.analiseWords();

                //запись в html
                readerWriter.writeHTML(new Dictionary <string, string[]>[] { resultDicEng, resultDicRus }, "Results.html", dataPath.ToString());
            }
            catch (Exception ex)
            {
            }
        }
Exemple #3
0
        public void SavePorter(Porter porter)
        {
            try
            {
                using (HospitalManagementSystemContext context = TypeFactory.Resolve <HospitalManagementSystemContext>())
                {
                    if (porter.Id > 0)
                    {
                        Porter savedPorter = context.Porter.FirstOrDefault(p => p.Id == porter.Id);

                        if (savedPorter != null)
                        {
                            savedPorter = porter;
                        }
                    }
                    else
                    {
                        context.Porter.Add(porter);
                    }
                    context.SaveChanges();
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public ActionResult CreatePorter(Porter porter)
        {
            try
            {
                var userId         = Request.IsAuthenticated ? UserId : Guid.Empty;
                var roles          = new string[] { HospitalManagementSystem.Models.Constants.Roles.ADMINISTRATOR };
                var registerHelper = new RegisterHelper(userId, porter.Person, roles);
                registerHelper.Register();

                if (!registerHelper.Response.Item1)
                {
                    porter.Person.Error = registerHelper.Response.Item2;
                    return(View(porter));
                }

                //PorterRegistration.Register(new Porter() { PersonId = porter.Person.Id });
                int personId = porter.Person.Id;
                porter.PersonId = personId;
                porter.Person   = null;
                PorterRegistration.Register(porter);

                return(RedirectToAction("RegisterSuccess", "Account", new { statusMessage = registerHelper.Response.Item2 }));
            }
            catch
            {
                return(View());
            }
        }
Exemple #5
0
        public void PorterCorrectlyMapsTableAttributes()
        {
            var model = Porter.Port <Import>(File.OpenRead(@".\Files\test.xls")).ToArray();

            Assert.AreEqual("Jack Jackson", model[0].Name);
            Assert.AreEqual("Tallahassee, FL", model[0].City);
            Assert.AreEqual(DateTime.Parse("04/04/1995"), model[0].GraduationDate);
        }
Exemple #6
0
        public void PorterCorrectlyMapsPropertySetAttributes()
        {
            var model = Porter.Port <Properties>(File.OpenRead(@".\Files\test.xls")).ToArray();

            Assert.AreEqual("James Jameson", model[0].Name);
            Assert.AreEqual("Seattle, WA", model[0].City);
            Assert.AreEqual(DateTime.Parse("3/5/1980"), model[0].GraduationDate);
        }
Exemple #7
0
        static void Main(string[] args)
        {
            //string path = @"C:\Users\Risha\Desktop\text.txt";

            string a    = "";
            string word = "";
            Porter p    = new Porter();

            Console.WriteLine("Введите адрес исходного файла: ");
            string path = Console.ReadLine();

            while (true)
            {
                Console.WriteLine("Введите слово:");

                string input = Console.ReadLine();

                if (input != "выйти")
                {
                    Console.WriteLine("Основа слова " + "input " + ": " + p.Stemm(input));
                }
                else
                {
                    break;
                }

                word = p.Stemm(input);
                FileStream   stream = new FileStream(@"C:\test\output.txt", FileMode.Create);
                StreamWriter writer = new StreamWriter(stream);

                try
                {
                    Console.WriteLine();
                    Console.WriteLine("Однокоренные слова в файле:");
                    using (StreamReader sr = new StreamReader(path, Encoding.Default))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            a = line;
                            if (a.IndexOf(word) > -1)
                            {
                                Console.WriteLine(a);
                                writer.WriteLine(a);
                            }
                        }
                    }
                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                writer.Close();
            }
        }
Exemple #8
0
        public void PorterCorrectlyFiltersSubTables()
        {
            var model = Porter.Port <Properties>(File.OpenRead(@".\Files\test.xls")).ToArray();

            Assert.AreEqual("James Jameson", model[0].Name);
            Assert.AreEqual("Seattle, WA", model[0].City);
            Assert.AreEqual(DateTime.Parse("3/5/1980"), model[0].GraduationDate);
            Assert.AreEqual(4, model[0].Grades.Count);
            Assert.AreEqual(3, model[0].AllStudents.Count);
        }
Exemple #9
0
        protected override bool Allow(GameHitParameters <GameObject> parameters)
        {
            Lot lot = Porter.GetLot(parameters.mTarget);

            if (lot == null)
            {
                return(false);
            }

            return(lot.Household == null);
        }
Exemple #10
0
        protected override bool Test(IActor a, GameObject target, GameObjectHit hit, ref GreyedOutTooltipCallback greyedOutTooltipCallback)
        {
            Lot lot = Porter.GetLot(target);

            if (lot == null)
            {
                return(false);
            }

            return(lot.IsResidentialLot);
        }
Exemple #11
0
 public override ObjectPicker.ColumnInfo GetValue(SimDescription item)
 {
     if (item == null)
     {
         return(new ObjectPicker.TextColumn(""));
     }
     else
     {
         return(new ObjectPicker.TextColumn(Porter.GetExportCount(item).ToString()));
     }
 }
Exemple #12
0
        private static string PorterForString(string input)
        {
            string[] words  = input.Split(' ');
            string   output = "";

            foreach (var item in words)
            {
                output += Porter.TransformingWord(item.Trim(new Char[] { '(', ')', '.', ',' })) + " ";
            }

            return(output);
        }
 public void DictionaryTest()
 {
     var dict = Resource.StemmingRussianPorterDictionary
         .Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
         .Select(s =>
             {
                 var split = s.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                 return new { Word = split[0], Stem = split[1] };
             });
     foreach (var pair in dict)
         Assert.AreEqual(pair.Stem, Porter.Stemm(pair.Word));
 }
Exemple #14
0
        public Porter Retrieve(string identityNumber)
        {
            Porter result = null;


            using (HospitalManagementSystemContext context = TypeFactory.Resolve <HospitalManagementSystemContext>())
            //using (HospitalManagementSystemContext context = new HospitalManagementSystemContext())
            {
                result = context.Porter.FirstOrDefault(p => p.Person.IdNumber == identityNumber);
            }
            return(result);
        }
 public void SingleWordTest()
 {
     string[][] wordsPair = { 
                                new string[] { "Вышагивающая", "вышагива" }, 
                                new string[] { "авенантненькая", "авенантненьк" },
                                new string[] { "агамемнон", "агамемнон" },
                                new string[] { "ободрившийся", "ободр" },
                                new string[] { "следователей", "следовател" },
                            };
     foreach(var pair in wordsPair)
         Assert.AreEqual(pair[1], Porter.Stemm(pair[0]));
 }
        //существует в списке лематизированных слов
        private List <int> Exist(string word)
        {
            var porter = new Porter();

            //лемитизируем
            word = porter.Stemm(word);
            if (indexedDict.ContainsKey(word))
            {
                return(indexedDict[word]);
            }
            else
            {
                return(new List <int>());
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            var bus = new Bus(new Dispatcher.Dispatcher());
            var printers = new[] { new Printer(bus, 1), new Printer(bus, 2), new Printer(bus, 3), new Printer(bus, 4) };

            var printerPool = printers
                .Select(printer => new WideningHandler<PrintJob, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            var refillPool = printers
                .Select(printer => new WideningHandler<RefillPaper, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            foreach (var printer in refillPool)
            {
                bus.Subscribe<RefillPaper>(new NarrowingHandler<RefillPaper, Message>(printer));
                // subscribe the printer directly to RefillPaper as we don't want to distribute that with the print jobs
            }

            var office = Enumerable.Range(0, 50)
                .Select(i => new Employee(bus, i))
                .ToArray();

            var loadBalancer = new RoundRobinLoadBalancer(printerPool);
            var printerRetryHandler = new RetryHandler(loadBalancer, bus);
            var retryManager = new RetryManager(bus);
            var timerService = new TimerService(bus);

            bus.Subscribe<FutureMessage>(timerService);
            bus.Subscribe<RetryMessage>(retryManager);
            bus.Subscribe<SuccessMessage>(retryManager);

            bus.Subscribe(new NarrowingHandler<PrintJob, Message>(printerRetryHandler));

            var console = new QueuedHandler(new WideningHandler<LogMessage, Message>(new ConsoleHandler()), bus);
            bus.Subscribe<LogMessage>(new NarrowingHandler<LogMessage, Message>(console));

            var porter = new Porter(bus);
            bus.Subscribe(porter);

            var converter = new LogConverter(bus);
            bus.Subscribe<PrintJob>(converter);
            bus.Subscribe<OutOfPaper>(converter);
            bus.Subscribe<PagePrinted>(converter);
            bus.Subscribe<RetryMessage>(converter);
        }
        private List <int> NotExist(string word)
        {
            var porter = new Porter();

            //лемитизация без !
            word = porter.Stemm(word.Replace("!", string.Empty));
            var list = new List <int>();

            //индексы всех элементов
            for (int i = 0; i < docNum; i++)
            {
                list.Add(i);
            }
            if (indexedDict.ContainsKey(word))
            {//Операция Except возвращает последовательность, содержащую все элементы первой последовательности, которых нет во второй последовательности.
                list = list.Except(indexedDict[word]).ToList();
            }

            return(list);
        }
Exemple #19
0
            public override ObjectPicker.ColumnInfo GetValue(HouseholdItem item)
            {
                Household house = item.Value;

                int total = 0;

                if (house.IsServiceNpcHousehold)
                {
                    foreach (SimDescription sim in SimDescription.GetHomelessSimDescriptionsFromUrnstones())
                    {
                        if (Porter.GetExportCount(sim) > 0)
                        {
                            total++;
                        }
                    }
                }
                else
                {
                    foreach (SimDescription sim in house.AllSimDescriptions)
                    {
                        if (Porter.GetExportCount(sim) > 0)
                        {
                            total++;
                        }
                    }
                }

                if (total == Households.NumSims(house))
                {
                    return(new ObjectPicker.TextColumn(Common.Localize("Packed:Yes")));
                }
                else if (total > 0)
                {
                    return(new ObjectPicker.TextColumn(Common.Localize("Packed:Partial")));
                }
                else
                {
                    return(new ObjectPicker.TextColumn(Common.Localize("Packed:No")));
                }
            }
Exemple #20
0
 public HttpPorter(Porter porter)
 {
     _porter = porter;
 }
 public QueuePorter(Porter porter)
 {
     _porter = porter;
 }
        public ActionResult geturls(string searchterms, string type)
        {
            searchquery s = new searchquery();

            s.query = searchterms;
            string[] searchquery_terms = s.Query_to_words();

            char[] searchquery_arr = searchterms.ToCharArray();
            Dictionary <Tuple <string, int>, Tuple <int, List <int> > > dict = new Dictionary <Tuple <string, int>, Tuple <int, List <int> > >();
            Dictionary <String, int> Ndocs = new Dictionary <string, int>();

            bool       exact_search = false;
            List <int> Doc_No       = new List <int>();

            if (searchquery_arr[0] == '"' && searchquery_arr[searchquery_arr.Length - 1] == '"')
            {
                s.query      = searchterms.Substring(1, searchterms.Length - 2);
                exact_search = true;
            }
            List <string> searchquery_terms_stemmed = new List <string>();

            SqlConnection con = new SqlConnection(@"Data Source=HOSSAM\MOHAMEDHOSSAM;Initial Catalog=web_crawler;Integrated Security=True");

            con.Open();

            for (int i = 0; i < searchquery_terms.Length; i++)
            {
                if (!Remove_stopwords(searchquery_terms[i]))
                {
                    Porter stemer = new Porter();                      //object from porter stemmer
                    string output = stemer.stem(searchquery_terms[i]); //pass the term for the stemmer to apply the porter stemmer on it
                    searchquery_terms_stemmed.Add(output);


                    SqlCommand cmd = new SqlCommand("select * from Inverted_index where Term=@term", con);
                    // SqlParameter term = new SqlParameter("@term",output);//current term in dictionary
                    // cmd.Parameters.Add(term);//select all records 'page content' from crawler database
                    cmd.Parameters.Add("@term", SqlDbType.VarChar).Value = output;
                    SqlDataReader reader = cmd.ExecuteReader();  //reader on database
                    if (!reader.HasRows && type == "spell")
                    {
                        misSpelledword = searchquery_terms[i];
                    }
                    else
                    {
                        int repeation = 0;
                        while (reader.Read())
                        {
                            string word   = reader[0].ToString();
                            int    doc_id = (int)reader[1];
                            if (!Doc_No.Contains(doc_id))
                            {
                                Doc_No.Add(doc_id);
                            }
                            int        frequency      = (int)reader[2];
                            string     positions      = reader[3].ToString();
                            List <int> term_positions = new List <int>();
                            string[]   arr            = positions.Split(',');
                            int[]      position       = Array.ConvertAll(arr, int.Parse);

                            for (int j = 0; j < position.Length; j++)
                            {
                                term_positions.Add(position[j]);
                            }
                            dict.Add(Tuple.Create(word, doc_id), Tuple.Create(frequency, term_positions));
                            repeation++;
                        }
                        Ndocs.Add(output, repeation);
                    }
                    reader.Close();
                }
            }

            List <Tuple <int, float, List <Tuple <String, int, List <int> > > > > Exact_Docs   = new List <Tuple <int, float, List <Tuple <string, int, List <int> > > > >();
            List <Tuple <int, float, List <Tuple <String, int, List <int> > > > > Inexact_Docs = new List <Tuple <int, float, List <Tuple <string, int, List <int> > > > >();
            List <String> Urls = new List <string>();

            if (exact_search)
            {
                List <Tuple <int, List <Tuple <String, int, List <int> > > > > docs = new List <Tuple <int, List <Tuple <String, int, List <int> > > > >();
                for (int i = 0; i < Doc_No.Count; i++)
                {
                    int        count = 0, frequency;
                    List <int> allpositions = new List <int>();
                    List <Tuple <String, int, List <int> > > words = new List <Tuple <string, int, List <int> > >();

                    for (int j = 0; j < searchquery_terms_stemmed.Count; j++)
                    {
                        if (dict.ContainsKey(Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])))
                        {
                            count++;
                            allpositions = dict[Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])].Item2;
                            frequency    = dict[Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])].Item1;
                            words.Add(Tuple.Create(searchquery_terms_stemmed[j], frequency, allpositions));
                        }
                    }
                    if (count == searchquery_terms_stemmed.Count)
                    {
                        docs.Add(Tuple.Create(Doc_No[i], words));
                    }
                }

                List <Tuple <int, float, List <Tuple <String, int, List <int> > > > > Docs_distances = check_distance(docs, searchquery_terms_stemmed.Count, Ndocs);
                foreach (var item in Docs_distances.OrderByDescending(Key => Key.Item2))
                {
                    Exact_Docs.Add(item);
                }

                Urls = Read_URls_from_database(Exact_Docs);
            }
            else
            {
                Dictionary <int, List <Tuple <int, List <Tuple <String, int, List <int> > > > > > num_of_occurence = new Dictionary <int, List <Tuple <int, List <Tuple <String, int, List <int> > > > > >();
                for (int i = 0; i < Doc_No.Count; i++)
                {
                    int        count = 0, frequency;
                    List <int> allpositions = new List <int>();
                    List <Tuple <String, int, List <int> > > word = new List <Tuple <string, int, List <int> > >();

                    for (int j = 0; j < searchquery_terms_stemmed.Count; j++)
                    {
                        if (dict.ContainsKey(Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])))
                        {
                            count++;
                            allpositions = dict[Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])].Item2;
                            frequency    = dict[Tuple.Create(searchquery_terms_stemmed[j], Doc_No[i])].Item1;
                            word.Add(Tuple.Create(searchquery_terms_stemmed[j], frequency, allpositions));
                        }
                    }
                    if (num_of_occurence.ContainsKey(count))
                    {
                        num_of_occurence[count].Add(Tuple.Create(Doc_No[i], word));
                    }
                    else
                    {
                        List <Tuple <int, List <Tuple <String, int, List <int> > > > > alldocs = new List <Tuple <int, List <Tuple <String, int, List <int> > > > >();
                        alldocs.Add(Tuple.Create(Doc_No[i], word));
                        num_of_occurence.Add(count, alldocs);
                    }
                }

                foreach (var Item in num_of_occurence.OrderByDescending(key => key.Key))
                {
                    List <Tuple <int, float, List <Tuple <String, int, List <int> > > > > docs_distances = calculate_distance(Item.Value, Item.Key);
                    foreach (var item in docs_distances.OrderBy(key => key.Item2))
                    {
                        Inexact_Docs.Add(item);
                    }
                }
                Urls = Read_URls_from_database(Inexact_Docs);
                if (misSpelledword != "" && type == "spell")
                {
                    List <String> nearest_words = spellchecker_words(misSpelledword);
                    ViewBag.nearest_words = nearest_words;
                }
                else if (type == "soundex")
                {
                    misSpelledword = searchquery_terms[0];
                    List <String> soundex_words = Soundex_words(misSpelledword);
                    ViewBag.nearest_words = soundex_words;
                }
            }

            ViewBag.Urls  = Urls;
            ViewBag.query = searchterms;
            ViewBag.type  = type;
            return(View());
        }
 public void Register(Porter porter)
 {
     PorterRepository.SavePorter(porter);
 }
        public bool CreateEntity(out int entID, EntityType type, GameObject gameObject, int playerNum = 0)
        {
            // The result of creation
            bool result = false;

            // Create the proper type of entity based upon the given type
            switch (type)
            {
                case EntityType.Merchant:
                    {
                        // Create the entity
                        Merchant merchant = new Merchant(nextId, gameObject, GameMaster.Instance.GetPlayerColor(playerNum), GameMaster.Instance.GetPlayerName(playerNum));

                        // Now try to add the entity to the manager
                        if (!EntityManager.Instance.AddEntity(merchant))
                        {
                            // The entity couldn't be added to the manager so return failure
                            result = false;
                        }

                        // Return success
                        result = true;

                        break;
                    } // end case Merchant
                case EntityType.Porter:
                    {
                        // Create the entity
                        Porter porter = new Porter(nextId, gameObject);

                        // Now try to add the entity to the manager
                        if (!EntityManager.Instance.AddEntity(porter))
                        {
                            // The entity coulnd't be added to the manager so return failure
                            result = false;
                        }

                        // Return success
                        result = true;

                        break;
                    } // end case Porter
                case EntityType.Mercenary:
                    {
                        // Create the entity
                        Mercenary mercenary = new Mercenary(nextId, gameObject);

                        // Now try to add the entity to the manager
                        if (!EntityManager.Instance.AddEntity(mercenary))
                        {
                            // The entity coulnd't be added to the manager so return failure
                            result = false;
                        }

                        // Return success
                        result = true;

                        break;
                    } // end Mercenary
                case EntityType.Bandit:
                    {
                        // Create the entity
                        Bandit bandit = new Bandit(nextId, gameObject);

                        // Now try to add the entity to the manager
                        if (!EntityManager.Instance.AddEntity(bandit))
                        {
                            // The entity coulnd't be added to the manager so return failure
                            result = false;
                        }

                        // Return success
                        result = true;

                        break;
                    } // end case Bandit
                case EntityType.Mimic:
                    {
                        // Create the entity
                        Mimic mimic = new Mimic(nextId, gameObject);

                        // Now try to add the entity to the manager
                        if (!EntityManager.Instance.AddEntity(mimic))
                        {
                            // The entity coulnd't be added to the manager so return failure
                            result = false;
                        }

                        // Return success
                        result = true;

                        break;
                    } // end Mimic
            } // end switch type

            // Set the out ID variable
            entID = nextId;

            // Increment to the next ID
            nextId++;

            // Return the result
            return result;
        }
        void DoIt()
        {
            // create the LibGr Search Plan backend we want to use
            LGSPBackend backend = LGSPBackend.Instance;

            // the graph model we'll use
            JavaProgramGraphsGraphModel model = new JavaProgramGraphsGraphModel();

            // the actions object for the rules we'll to use
            IActions ba;

            // import the instance graph we created with gxl2grs, using the the .gm we created by hand
            // (can't use import gxl for the program graph, because the given .gxl is severly rotten)
            // we throw away the named graph cause we don't need names here and they require about the same amount of memory as the graph itself;
            INamedGraph importedNamedGraph = (INamedGraph)Porter.Import("InstanceGraph.grs", backend, model, out ba);
            LGSPGraph   graph = new LGSPGraph((LGSPNamedGraph)importedNamedGraph, "unnamed");

            importedNamedGraph = null;

            // get the actions object for the rules we want to use
            JavaProgramGraphsActions actions = ba != null ? (JavaProgramGraphsActions)ba : new JavaProgramGraphsActions(graph);

            // the graph processing environment we'll use
            LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            // the instance graph script uses variables to build up the graph,
            // we query some of them here, to get the elements to refactor
            // (instead of variables one could use the element names)
            Class src = (Class)procEnv.GetNodeVarValue("I176");          // class Node
            Class tgt = (Class)procEnv.GetNodeVarValue("I194");          // class Packet - use if parameter is used in moving method
            //Class tgt = (Class)graph.GetNodeVarValue("I617"); // class String - use if instance variable is used in moving method
            MethodBody mb = (MethodBody)procEnv.GetNodeVarValue("I409"); // method body of send

            // get operation for method body by:
            // get action, match action pattern with given parameters, apply rewrite filling given out parameters
            IMatchesExact <Rule_getOperation.IMatch_getOperation> matches = actions.getOperation.Match(procEnv, 1, mb);
            IOperation op;

            actions.getOperation.Modify(procEnv, matches.FirstExact, out op);

            // iterated application of action marking the body of the expression
            // (shows second way of getting action)
            int visitedFlagId = graph.AllocateVisitedFlag();

            Debug.Assert(visitedFlagId == 0);
            IGraphElement[] param = new LGSPNode[1];
            param[0] = mb;
            IMatches matchesInexact;

            while ((matchesInexact = actions.GetAction("markExpressionOfBody").Match(procEnv, 1, param)).Count == 1)
            {
                actions.GetAction("markExpressionOfBody").Modify(procEnv, matchesInexact.First);
            }

            // application of a graph rewrite sequence
            procEnv.SetVariableValue("src", src);
            procEnv.SetVariableValue("tgt", tgt);
            procEnv.SetVariableValue("mb", mb);
            procEnv.SetVariableValue("op", op);
            procEnv.ApplyGraphRewriteSequence(
                @"(p)=someParameterOfTargetType(mb,tgt) 
                    && !callToSuperExists && !isStatic(mb) && !methodNameExists(mb,tgt) 
                    && (!thisIsAccessed || thisIsAccessed && (srcparam)=addSourceParameter(op,src) && useSourceParameter(srcparam)*) 
                    && relinkOperationAndMethodBody(op,mb,src,tgt) 
                    && ( (call,pe)=getUnprocessedCallWithActualParameter(op,p) 
                         && ((def(srcparam) && addSourceToCall(call,srcparam)) || true) 
                         && (replaceAccess_Parameter_AccessWithoutLink(c,pe) || replaceAccess_Parameter_AccessWithLinkToExpression(c,pe)) 
                       )*");

            Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
            procEnv.PerformanceInfo.Reset();

            // unmark the body of the expression by searching all occurences and modifying them
            actions.unmarkExpression.ApplyAll(0, procEnv);
            graph.FreeVisitedFlag(visitedFlagId);

            // export changed graph (alternatively you may export it as InstanceGraphAfter.gxl)
            // if we'd use a NamedGraph we'd get the graph exported with its persistent names; so we get it exported with some hash names
            List <String> exportParameters = new List <string>();

            exportParameters.Add("InstanceGraphAfter.grs");
            Porter.Export(graph, exportParameters);
        }
Exemple #26
0
        public void PorterCorrectlyPopulatesSubproperty()
        {
            var model = Porter.Port <Properties>(File.OpenRead(@".\Files\test.xls")).ToArray();

            Assert.AreEqual("Blue", model[0].ExtraInformation.FavoriteColor);
        }
Exemple #27
0
        public void SearchWord(string query)
        {
            var countDocument = 100;
            var porter        = new Porter();
            var words         = query.Split(' ').Select(x => porter.Stemm(x)).ToArray();
            var length        = words.Length;
            var tfs           = new double[length];

            //определяем tf поисковых слов
            for (int i = 0; i < length; i++)
            {
                var count = words.Where(x => x == words[i]).Count();
                tfs[i] = (double)count / length;
            }

            //определяем tdf поисковых слов
            var idfs = new double[length];

            for (int i = 0; i < length; i++)
            {
                if (invertDict.ContainsKey(words[i]))
                {
                    idfs[i] = Math.Log10(countDocument / invertDict[words[i]].Count);
                }
                else
                {
                    idfs[i] = 0;
                }
            }

            //определяем td-idf
            var tfIdf = new Dictionary <string, double>();

            for (int i = 0; i < length; i++)
            {
                tfIdf.Add(words[i], tfs[i] * idfs[i]);
            }

            //Рассчитаем длину запроса
            var queryLenght = Math.Sqrt(tfIdf.Select(x => x.Value).Select(x => Math.Pow(x, 2)).Sum());

            //Документы в которых имеется одно слово
            var indexDocuments = new List <int>();

            foreach (var item in words)
            {
                if (invertDict.ContainsKey(item))
                {
                    indexDocuments.AddRange(invertDict[item]);
                }
            }
            indexDocuments = indexDocuments.Distinct().ToList();

            //
            var docsLenght = new Dictionary <int, double>();

            //вычисляем длину документов
            foreach (var index in indexDocuments)
            {
                docsLenght.Add(index, Math.Sqrt(wordMatrix[index].Values.Select(x => Math.Pow(x, 2)).Sum()));
            }

            //косинусное сходство
            var result = new Dictionary <int, double>();

            foreach (var index in indexDocuments)
            {
                double fstPart = 0;
                foreach (var word in words)
                {
                    if (wordMatrix[index].ContainsKey(word))
                    {
                        //вектор на матрицу
                        fstPart += tfIdf[word] * wordMatrix[index][word];
                        if (index == 7)
                        {
                            Console.Write($"a:{tfIdf[word]} * b:{wordMatrix[index][word]} + ");
                        }
                    }
                }

                if (index == 7)
                {
                    Console.WriteLine($"\n{fstPart}/{docsLenght[index] * queryLenght}");
                    Console.WriteLine($"{docsLenght[index]} * {queryLenght}");
                }



                var point = (fstPart / (docsLenght[index] * queryLenght));
                //Console.WriteLine($"index:{index}, top:{fstPart}/{docsLenght[index] * queryLenght}");
                if (point == double.NaN)
                {
                    //если в запросе нет слов которые определяют какой-то документ(слова имеются во всех документых)
                    point = 0;
                }
                result.Add(index, point);
            }

            foreach (var item in result.OrderByDescending(x => x.Value).Take(10))
            {
                Console.WriteLine($"{item.Key} : {item.Value}");
            }
            Console.WriteLine();
        }
Exemple #28
0
        public void delServicePartOfSpeech(ref List <string> TEXT)
        {
            //      string[] pretext = { "аля","без","безведома","безо","благодаря","близ","близкоот","в","ввиде","вблизи", "ввиду", "вглубь", "вдогон", "вдоль", "взамен", "включая", "вкруг", "вместо", "вне", "внизу", "внутри", "внутрь", "во", "вовнутрь", "возле", "вокруг", "вопреки", "вослед", "впереди", "вразрез", "вроде", "вслед", "вследствие", "встречу", "выключая", "для", "для-ради", "до", "за", "замест", "заместо", "из", "из-за", "из-под", "из-подо", "изнутри", "изо", "исключая", "к", "касаемо", "касательно", "ко", "кончая", "кроме", "кругом", "меж", "между", "мимо", "на", "наверху", "навроде", "навстречу","надо", "назад", "назади", "накануне", "наместо", "наперекор", "наперерез", "наперехват", "наподобие", "наподобье", "напротив", "насупротив", "насчёт", "несмотря", "несмотря на", "ниже", "о", "об",  "обо", "обок", "обочь", "около", "окрест", "окроме", "окромя", "округ", "опосля", "опричь", "от", "относительно", "ото", "перед", "передо", "по", "по-за", "по-над", "по-под", "повдоль", "поверх", "под", "подле", "подо", "подобно", "позади", "позадь", "позднее", "помимо", "поперёд", "поперёк", "порядка", "посверху", "посереди", "посередине", "посерёдке", "посередь", "после", "посреди", "посредине", "посредством", "пред", "предо", "преж", "прежде", "при", "про", "промеж", "промежду", "против", "противно", "противу", "путём", "ради", "с",  "сверх", "сверху", "свыше", "середи", "середь", "сзади", "скрозь", "снизу", "со", "согласно", "спустя", "среди", "средь", "сродни", "супротив", "у", "через", "черезо", "чрез"};
            //      string[] particle = { "кось", "ста", "а", "авось", "авось-либо", "ага", "адьё", "аж", "ажно", "аиньки", "аминь", "ан", "аск", "аушки", "аюшки", "б", "бишь", "будто", "буквально", "бы", "бывает", "было", "ведь", "верно", "вероятно", "вестимо", "вишь", "во", "вон", "вот", "вот-вот", "вроде", "вряд", "всё", "всё-таки", "всего", "го", "да", "давай", "давай-ка", "даже", "дак", "де", "действительно", "дескать", "добре", "дык", "едва", "если", "ещё", "ж", "же", "замётано", "и", "или", "иль", "именно", "имхо", "ин", "инда", "индо", "ино", "ить", "ишь", "ка", "кажется", "кайнэ", "как", "как бы", "конечно", "куда", "ладно", "ладушки", "ли", "лих", "лишь", "лучше", "ль", "мол", "на", "на-тка", "навроде", "накось", "накося", "наоборот", "не", "не-а", "небось", "нет", "нет-нет", "нету", "неуж", "неужели", "неужли", "неужто", "ни", "никак", "ничего", "ништо", "ну", "ну-ну", "ну-с", "отколь", "откуда", "откудова", "отож", "очевидно", "поди", "пожалуй", "пожалуйста", "пока", "с", "так", "таки", "того", "то-то", "тоже", "уж", "уже", "ужели", "хоть", "хотя", "что", "что-то", "чтоб", "чтобы", "чтой-то"};
            //      string[] union = {"а", "абы", "аж", "ажно", "ай", "аки", "ако", "али", "аль", "ан", "аще", "благо", "бо", "буде", "будто", "ведь", "впрочем", "всё", "всё-таки",  "где", "где-то", "да", "дабы", "даже", "докуда", "дотоле", "егда", "едва", "еже", "ежели", "ежель", "если", "ж", "же", "зане", "занеже", "зато", "зачем", "значит", "и", "или", "ибо", "или", "иль", "именно", "имже", "инако", "иначе", "инда", "ино", "итак", "кабы", "как", "каков", "какой", "ковда", "ковды", "когда", "когды", "коли", "коль", "который","куда", "ли","либо","лишь","ль","настолько","нежели","незомь","ни","ниже","нижли","но","обаче","однако","одначе","отколь","откуда","откудова","оттого","отчего","поелику","пока","покамест","покаместь","покеда","поколева","поколику","поколь","покуль","покуля","понеже","поскольку","пота","потолику","потому","почём","почему","правда","преж","притом","причём","просто","пускай","пусть","равно","раз","разве","ровно","тож","тоже","только","хоть","хотя","чем","чи","что","чтоб","чтобы","чуть","штоб","штобы","яко","якобы" };
            //      string[] pronoun = { "я", "мы", "ты", "вы", "он", "она", "оно", "они", "себя", "мой", "моя", "мое", "мои", "наш", "наша", "наше", "наши", "твой", "твоя", "твое", "твои", "ваш", "ваша", "ваше", "ваши", "его", "ее", "их", "кто", "что", "какой", "каков", "чей", "который", "сколько", "где", "когда", "куда", "зачем", "этот", "тот", "такой", "таков", "тут", "здесь", "сюда", "туда", "оттуда", "отсюда", "тогда", "поэтому", "сей", "оный", "затем", "столько", "весь", "всякий", "все", "сам", "самый", "каждый", "любой", "другой", "иной", "всяческий", "всюду", "везде", "всегда", "никто", "ничто", "некого", "нечего", "никакой", "ничей", "некто", "нечто", "некий", "некоторый", "несколько", "кое-кто", "кое-где", "кое-что", "кое-куда", "какой-либо", "сколько-нибудь", "куда-нибудь", "зачем-нибудь", "чей-либо" };

            // Один сплошной массив слов для удаления
            // string[] delWord = { "то", "нас", "них", "нам", "вам", "всех", "нем", "нему", "аля", "без", "безведома", "безо", "благодаря", "близ", "в", "ввиде", "вблизи", "ввиду", "вглубь", "вдогон", "вдоль", "взамен", "включая", "вкруг", "вместо", "вне", "внизу", "внутри", "внутрь", "во", "вовнутрь", "возле", "вокруг", "вопреки", "вослед", "впереди", "вразрез", "вроде", "вслед", "вследствие", "встречу", "выключая", "для", "для-ради", "до", "за", "замест", "заместо", "из", "из-за", "из-под", "из-подо", "изнутри", "изо", "исключая", "к", "касаемо", "касательно", "ко", "кончая", "кроме", "кругом", "меж", "между", "мимо", "на", "наверху", "навроде", "навстречу", "надо", "назад", "назади", "накануне", "наместо", "наперекор", "наперерез", "наперехват", "наподобие", "наподобье", "напротив", "насупротив", "насчёт", "несмотря", "несмотря на", "ниже", "о", "об", "обо", "обок", "обочь", "около", "окрест", "окроме", "окромя", "округ", "опосля", "опричь", "от", "относительно", "ото", "перед", "передо", "по", "по-за", "по-над", "по-под", "повдоль", "поверх", "под", "подле", "подо", "подобно", "позади", "позадь", "позднее", "помимо", "поперёд", "поперёк", "порядка", "посверху", "посереди", "посередине", "посерёдке", "посередь", "после", "посреди", "посредине", "посредством", "пред", "предо", "преж", "прежде", "при", "про", "промеж", "промежду", "против", "противно", "противу", "путём", "ради", "с", "сверх", "сверху", "свыше", "середи", "середь", "сзади", "скрозь", "снизу", "со", "согласно", "спустя", "среди", "средь", "сродни", "супротив", "у", "через", "черезо", "чрез", "кось", "ста", "а", "авось", "авось-либо", "ага", "адьё", "аж", "ажно", "аиньки", "аминь", "ан", "аск", "аушки", "аюшки", "б", "бишь", "будто", "буквально", "бы", "бывает", "было", "ведь", "верно", "вероятно", "вестимо", "вишь", "во", "вон", "вот", "вот-вот", "вроде", "вряд", "всё", "всё-таки", "всего", "го", "да", "давай", "давай-ка", "даже", "дак", "де", "действительно", "дескать", "добре", "дык", "едва", "если", "ещё", "ж", "же", "замётано", "и", "или", "иль", "именно", "имхо", "ин", "инда", "индо", "ино", "ить", "ишь", "ка", "кажется", "кайнэ", "как", "как бы", "конечно", "куда", "ладно", "ладушки", "ли", "лих", "лишь", "лучше", "ль", "мол", "на", "на-тка", "навроде", "накось", "накося", "наоборот", "не", "не-а", "небось", "нет", "нет-нет", "нету", "неуж", "неужели", "неужли", "неужто", "ни", "никак", "ничего", "ништо", "ну", "ну-ну", "ну-с", "отколь", "откуда", "откудова", "отож", "очевидно", "поди", "пожалуй", "пожалуйста", "пока", "с", "так", "таки", "того", "то-то", "тоже", "также", "уж", "уже", "ужели", "хоть", "хотя", "что", "что-то", "чтоб", "чтобы", "чтой-то", "а", "абы", "аж", "ажно", "ай", "аки", "ако", "али", "аль", "ан", "аще", "благо", "бо", "буде", "будто", "ведь", "впрочем", "всё", "всё-таки", "где", "где-то", "да", "дабы", "даже", "докуда", "дотоле", "егда", "едва", "еже", "ежели", "ежель", "если", "ж", "же", "зане", "занеже", "зато", "зачем", "значит", "и", "или", "ибо", "или", "иль", "именно", "имже", "инако", "иначе", "инда", "ино", "итак", "кабы", "как", "каков", "какой", "ковда", "ковды", "когда", "когды", "коли", "коль", "который", "куда", "ли", "либо", "лишь", "ль", "настолько", "нежели", "незомь", "ни", "ниже", "нижли", "но", "обаче", "однако", "одначе", "отколь", "откуда", "откудова", "оттого", "отчего", "поелику", "пока", "покамест", "покаместь", "покеда", "поколева", "поколику", "поколь", "покуль", "покуля", "понеже", "поскольку", "пота", "потолику", "потому", "почём", "почему", "правда", "преж", "притом", "причём", "просто", "пускай", "пусть", "равно", "раз", "разве", "ровно", "тож", "тоже", "только", "хоть", "хотя", "чем", "чи", "что", "чтоб", "чтобы", "чуть", "штоб", "штобы", "яко", "якобы", "я", "мы", "ты", "вы", "он", "она", "оно", "они", "себя", "мой", "моя", "мое", "мои", "наш", "наша", "наше", "наши", "твой", "твоя", "твое", "твои", "ваш", "ваша", "ваше", "ваши", "его", "ее", "их", "кто", "что", "какой", "каков", "чей", "который", "сколько", "где", "когда", "куда", "зачем", "этот", "тот", "такой", "таков", "тут", "здесь", "сюда", "туда", "оттуда", "отсюда", "тогда", "поэтому", "это", "этим", "этому", "этом", "этих", "сей", "оный", "затем", "столько", "весь", "всякий", "все", "сам", "самый", "каждый", "любой", "другой", "иной", "всяческий", "всюду", "везде", "всегда", "никто", "ничто", "некого", "нечего", "никакой", "ничей", "некто", "нечто", "некий", "некоторый", "несколько", "кое-кто", "кое-где", "кое-что", "кое-куда", "какой-либо", "сколько-нибудь", "свой", "куда-нибудь", "зачем-нибудь", "чей-либо", "один", "два", "три", "четыре", "пять", "шесть", "семь", "восемь", "девять", "ноль", "эту" };

            // Один сплошной массив пропущенный через стример для ускорения)
            string[] delWord = { "то", "нас", "них", "нам", "вам", "всех", "н", "нему", "ал", "без", "безведом", "безо", "благодар", "близ", "в", "ввид", "вблиз", "ввиду", "вглуб", "вдогон", "вдол", "взамен", "включ", "вкруг", "вместо", "вн", "внизу", "внутр", "внутр", "во", "вовнутр", "возл", "вокруг", "вопрек", "вослед", "вперед", "вразрез", "врод", "вслед", "вследств", "встречу", "выключ", "дл", "для-рад", "до", "з", "замест", "заместо", "из", "из-з", "из-под", "из-подо", "изнутр", "изо", "исключ", "к", "касаемо", "касательно", "ко", "конч", "кром", "круг", "меж", "между", "мимо", "н", "наверху", "наврод", "навстречу", "надо", "назад", "назад", "наканун", "наместо", "наперекор", "наперерез", "наперехват", "наподоб", "наподоб", "напрот", "насупрот", "насчет", "несмотр", "несмотря", "н", "ниж", "о", "об", "обо", "обок", "обоч", "около", "окрест", "окром", "окром", "округ", "опосл", "оприч", "от", "относительно", "ото", "перед", "передо", "по", "по-з", "по-над", "по-под", "повдол", "поверх", "под", "подл", "подо", "подобно", "позад", "позад", "поздн", "помимо", "поперед", "поперек", "порядк", "посверху", "посеред", "посередин", "посередк", "посеред", "посл", "посред", "посредин", "посредств", "пред", "предо", "преж", "прежд", "пр", "про", "промеж", "промежду", "прот", "противно", "противу", "пут", "рад", "с", "сверх", "сверху", "свыш", "серед", "серед", "сзад", "скроз", "снизу", "со", "согласно", "спуст", "сред", "сред", "сродн", "супрот", "у", "через", "черезо", "чрез", "ко", "ст", "", "аво", "авось-либо", "аг", "ад", "аж", "ажно", "аиньк", "амин", "а", "аск", "аушк", "аюшк", "б", "б", "будто", "буквально", "б", "быва", "было", "вед", "верно", "вероятно", "вестимо", "в", "во", "вон", "вот", "вот-вот", "врод", "вряд", "вс", "все-так", "вс", "го", "д", "дава", "давай-к", "даж", "дак", "д", "действительно", "деска", "добр", "дык", "едв", "есл", "ещ", "ж", "ж", "замета", "", "", "ил", "именно", "имхо", "ин", "инд", "индо", "ино", "", "", "к", "кажет", "кайнэ", "как", "как", "б", "конечно", "куд", "ладно", "ладушк", "л", "лих", "л", "лучш", "ль", "мол", "н", "на-тк", "наврод", "нако", "нако", "наоборот", "н", "не-", "небо", "нет", "нет-нет", "нету", "неуж", "неужел", "неужл", "неужто", "н", "никак", "нич", "ништо", "ну", "ну-ну", "ну-с", "откол", "откуд", "откудов", "отож", "очевидно", "под", "пожал", "пожалуйст", "пок", "с", "так", "так", "т", "то-то", "тож", "такж", "уж", "уж", "ужел", "хот", "хот", "что", "что-то", "чтоб", "чтоб", "чтой-то", "", "аб", "аж", "ажно", "а", "ак", "ако", "а", "ал", "а", "ащ", "благо", "бо", "буд", "будто", "вед", "впроч", "вс", "все-так", "гд", "где-то", "д", "даб", "даж", "докуд", "дотол", "егд", "едв", "еж", "ежел", "ежел", "есл", "ж", "ж", "зан", "занеж", "зато", "зач", "значит", "", "", "ибо", "", "ил", "именно", "имж", "инако", "инач", "инд", "ино", "итак", "каб", "как", "как", "как", "ковд", "ковд", "когд", "когд", "кол", "кол", "котор", "куд", "л", "либо", "л", "ль", "настолько", "нежел", "незом", "н", "ниж", "нижл", "но", "обач", "однако", "однач", "откол", "откуд", "откудов", "отт", "отч", "поелику", "пок", "покамест", "покамест", "покед", "поколев", "поколику", "покол", "покул", "покул", "понеж", "поскольку", "пот", "потолику", "потому", "поч", "почему", "правд", "преж", "прит", "прич", "просто", "пуска", "пуст", "равно", "раз", "разв", "ровно", "тож", "тож", "только", "хот", "хот", "ч", "ч", "что", "чтоб", "чтоб", "чут", "штоб", "штоб", "яко", "якоб", "", "м", "т", "в", "он", "он", "оно", "он", "себ", "м", "мо", "м", "мо", "наш", "наш", "наш", "наш", "тв", "тво", "тв", "тво", "ваш", "ваш", "ваш", "ваш", "", "", "их", "кто", "что", "как", "как", "ч", "котор", "сколько", "гд", "когд", "куд", "зач", "этот", "тот", "так", "так", "тут", "зд", "сюд", "туд", "оттуд", "отсюд", "тогд", "поэтому", "это", "эт", "этому", "эт", "этих", "с", "он", "зат", "столько", "в", "всяк", "вс", "сам", "сам", "кажд", "люб", "друг", "ин", "всяческ", "всюду", "везд", "всегд", "никто", "ничто", "нек", "неч", "никак", "нич", "некто", "нечто", "нек", "некотор", "несколько", "кое-кто", "кое-гд", "кое-что", "кое-куд", "какой-либо", "сколько-нибуд", "св", "куда-нибуд", "зачем-нибуд", "чей-либо", "один", "дв", "тр", "четыр", "пя", "шест", "сем", "восем", "девя", "нол", "нашу", "эту", "сих", "тому", "там", "таких", "тех", "над", "вас" };

            string s = null;

            s = System.Text.RegularExpressions.Regex.Replace(TEXT[8], @"[-\.!,\s:;?(<)>«»—1234567890""%#@&'']", " "); // Убераем все знаки из текста


            List <string> WordsP = new List <string>();
            List <string> Words  = new List <string>();

            String[] words = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Разбиваем весь текст на массив слов


            string T    = null;
            string text = null;


            for (int i = 0; i < words.Length; i++)
            {
                text = text + " " + words[i];
            }

            foreach (var k in words)
            {
                Words.Add(k);
            }

            Console.WriteLine(Words.Count);

            // Применение Стремера портера для удаления частиц и тд


            Porter p = new Porter();

            // string itemP=null;
            //  string WordsP=null;


            //



            for (int k = 0; k < words.Length; k++)
            {
                WordsP.Add(p.Stemm(words[k]));
            }



            foreach (var item in delWord)
            {
                //    itemP = p.Stemm(item); //слово для удаления пропущенное через парсер



                for (int i = 0; i < WordsP.Count; i++)
                {
                    //       WordsP = p.Stemm(Words[i]); // анализируемое слово  пропущенное через парсер



                    if (item == WordsP[i])
                    {
                        WordsP.Remove(WordsP[i]);
                        Words.Remove(Words[i]);
                        i--;
                    }
                }
            }

            Console.WriteLine(Words.Count);

            text = null;
            for (int i = 0; i < Words.Count; i++)
            {
                text = text + " " + Words[i];
            }
            Console.WriteLine(text);

            // Console.WriteLine(text);
        }
Exemple #29
0
 void Start()
 {
     porter = GetComponent <Porter>();
 }
Exemple #30
0
        protected override OptionResult Run(GameHitParameters <GameObject> parameters)
        {
            Lot lot = Porter.GetLot(parameters.mTarget);

            if (lot == null)
            {
                return(OptionResult.Failure);
            }

            List <SimDescription> selection = null;

            List <HouseholdItem> allHouses = new List <HouseholdItem>();

            foreach (Household house in Household.sHouseholdList)
            {
                allHouses.Add(new HouseholdItem(house, house == lot.Household));
            }

            string houseName = null;

            while (selection == null)
            {
                List <Household> houses = HouseholdSelection.Perform(lot.Household.Name, allHouses);
                if ((houses == null) || (houses.Count == 0))
                {
                    return(OptionResult.Failure);
                }

                houseName = houses[0].Name;

                selection = GetSimSelection(houses);
            }

            if ((selection == null) || (selection.Count == 0))
            {
                return(OptionResult.Failure);
            }

            Dictionary <Household, int> finalHouses = new Dictionary <Household, int>();

            int nextID = 1;

            foreach (SimDescription sim in selection)
            {
                if (sim.Household == null)
                {
                    continue;
                }

                if (sim.Household.IsServiceNpcHousehold)
                {
                    continue;
                }

                if (!finalHouses.ContainsKey(sim.Household))
                {
                    finalHouses.Add(sim.Household, nextID);
                    nextID++;
                }
            }

            string name = StringInputDialog.Show(Common.Localize("Title"), Common.Localize("Pack:NamePrompt", false, new object[] { finalHouses.Count, selection.Count }), houseName);

            if (string.IsNullOrEmpty(name))
            {
                return(OptionResult.Failure);
            }

            Household export = Household.Create();

            SpeedTrap.Sleep();

            foreach (Household house in finalHouses.Keys)
            {
                if (house.LotHome != null)
                {
                    export.SetFamilyFunds(export.FamilyFunds + house.FamilyFunds + house.LotHome.Cost);
                }
                else
                {
                    export.SetFamilyFunds(export.FamilyFunds + house.NetWorth());
                }
            }

            Dictionary <SimDescription, Household> saveHouses = new Dictionary <SimDescription, Household>();

            Dictionary <Sim, bool> resetDNP = new Dictionary <Sim, bool>();

            Dictionary <Household, bool> inventoried = new Dictionary <Household, bool>();

            foreach (SimDescription sim in selection)
            {
                if (sim.CreatedSim != null)
                {
                    sim.CreatedSim.SetReservedVehicle(null);

                    if (sim.CreatedSim.DreamsAndPromisesManager != null)
                    {
                        sim.CreatedSim.NullDnPManager();

                        if (!resetDNP.ContainsKey(sim.CreatedSim))
                        {
                            resetDNP.Add(sim.CreatedSim, true);
                        }
                    }

                    if ((sim.Household != null) && (!inventoried.ContainsKey(sim.Household)))
                    {
                        inventoried.Add(sim.Household, true);

                        if ((sim.Household.SharedFamilyInventory != null) &&
                            (sim.Household.SharedFamilyInventory.Inventory != null))
                        {
                            foreach (GameObject obj in Inventories.QuickFind <GameObject>(sim.Household.SharedFamilyInventory.Inventory))
                            {
                                if (Inventories.TryToMove(obj, sim.CreatedSim.Inventory, false))
                                {
                                    continue;
                                }

                                Inventories.TryToMove(obj.Clone(), export.SharedFamilyInventory.Inventory);
                            }
                        }

                        if ((sim.Household.SharedFridgeInventory != null) &&
                            (sim.Household.SharedFridgeInventory.Inventory != null))
                        {
                            foreach (GameObject obj in Inventories.QuickFind <GameObject>(sim.Household.SharedFridgeInventory.Inventory))
                            {
                                if (Inventories.TryToMove(obj, sim.CreatedSim.Inventory, false))
                                {
                                    continue;
                                }

                                Inventories.TryToMove(obj.Clone(), export.SharedFridgeInventory.Inventory);
                            }
                        }
                    }
                }

                int id = 0;
                if ((sim.Household != null) && (finalHouses.ContainsKey(sim.Household)))
                {
                    id = finalHouses[sim.Household];
                }
                else
                {
                    Urnstone grave = Urnstones.CreateGrave(sim, false);
                    if (grave == null)
                    {
                        continue;
                    }

                    SpeedTrap.Sleep();

                    bool success = false;
                    try
                    {
                        success = Urnstones.GhostToPlayableGhost(grave, Household.NpcHousehold, lot.EntryPoint());
                    }
                    catch (Exception exception)
                    {
                        Common.DebugException(grave.DeadSimsDescription, exception);
                    }

                    if (!success)
                    {
                        Porter.Notify(Common.Localize("Pack:SimFailure", sim.IsFemale, new object[] { sim }));

                        Porter.PlaceGraveTask.Perform(sim);
                        //export.SharedFamilyInventory.Inventory.TryToMove(grave);
                        continue;
                    }
                }

                HouseData data = new HouseData(id, sim);

                sim.mBio = data.ToString();

                saveHouses.Add(sim, sim.Household);

                sim.OnHouseholdChanged(export, false);

                export.mMembers.Add(sim, null);

                Porter.AddExport(sim);
            }

            string packageName = null;

            try
            {
                try
                {
                    ProgressDialog.Show(Responder.Instance.LocalizationModel.LocalizeString("Ui/Caption/Global:Processing", new object[0x0]), false);

                    if (export.mMembers.Count > 0)
                    {
                        export.Name = "NRaas.Porter:" + name;

                        ThumbnailHelper.CacheSimAtlasesForHousehold(export);
                        ThumbnailManager.GenerateHouseholdThumbnail(export.HouseholdId, export.HouseholdId, ThumbnailSizeMask.Large);

                        packageName = BinEx.ExportHousehold(Bin.Singleton, export, false);
                        if (packageName != null)
                        {
                            BinModel.Singleton.AddToExportBin(packageName);
                        }
                    }

                    foreach (Sim sim in resetDNP.Keys)
                    {
                        try
                        {
                            sim.ResetDnP();
                        }
                        catch (Exception e)
                        {
                            Common.DebugException(sim, e);
                        }
                    }

                    List <Urnstone> graves = Inventories.QuickFind <Urnstone>(export.SharedFamilyInventory.Inventory);

                    foreach (Urnstone grave in graves)
                    {
                        Porter.PlaceGraveTask.Perform(grave.DeadSimsDescription);
                    }

                    while (export.mMembers.Count > 0)
                    {
                        SimDescription sim = export.mMembers.SimDescriptionList[0];
                        if (sim != null)
                        {
                            sim.OnHouseholdChanged(saveHouses[sim], false);

                            if ((sim.Household == null) || (sim.Household.IsServiceNpcHousehold))
                            {
                                Porter.PlaceGraveTask.Perform(sim);
                            }
                        }

                        export.mMembers.RemoveAt(0);
                    }

                    export.Destroy();
                    export.Dispose();
                }
                finally
                {
                    ProgressDialog.Close();
                }
            }
            catch (ExecutionEngineException)
            {
                // Ignored
            }
            catch (Exception e)
            {
                Common.Exception(name, e);
                packageName = null;
            }

            if (packageName != null)
            {
                SimpleMessageDialog.Show(Common.Localize("Title"), Common.Localize("Pack:Success", false, new object[] { export.Name }));
            }
            else
            {
                SimpleMessageDialog.Show(Common.Localize("Title"), Common.Localize("Pack:Failure"));
            }

            return(OptionResult.SuccessClose);
        }
Exemple #31
0
        protected override OptionResult Run(GameHitParameters <GameObject> parameters)
        {
            Common.StringBuilder log = new Common.StringBuilder("Run");

            try
            {
                Lot targetLot = Porter.GetLot(parameters.mTarget);
                if (targetLot == null)
                {
                    return(OptionResult.Failure);
                }

                Dictionary <ulong, IMiniSimDescription> preExistingSims = SimListing.GetSims <IMiniSimDescription>(null, true);

                Household me = targetLot.Household;
                if (me == null)
                {
                    me = GetImportSelection(targetLot);

                    if (me == null)
                    {
                        return(OptionResult.Failure);
                    }
                }

                Dictionary <ulong, IMiniSimDescription> allSims = SimListing.GetSims <IMiniSimDescription>(null, true);

                Dictionary <int, HouseData> houses       = new Dictionary <int, HouseData>();
                Dictionary <int, HouseData> doppleHouses = new Dictionary <int, HouseData>();

                List <SimDescription> cleanUp = new List <SimDescription>();
                List <SimDescription> fixUp   = new List <SimDescription>();

                List <Household> importedHouses = new List <Household>();
                importedHouses.Add(me);

                List <SimDescription> checkSims = new List <SimDescription>();

                log += Common.NewLine + "A";

                List <SimDescription> sims = new List <SimDescription>(me.AllSimDescriptions);
                foreach (SimDescription sim in sims)
                {
                    if (sim == null)
                    {
                        continue;
                    }

                    log += Common.NewLine + sim.FullName;

                    Porter.AddExport(sim);

                    string description = sim.mBio;
                    if (string.IsNullOrEmpty(description))
                    {
                        continue;
                    }

                    if (!description.Contains("NRaas.Porter:"))
                    {
                        continue;
                    }

                    description = description.Replace("NRaas.Porter:", "");
                    if (string.IsNullOrEmpty(description))
                    {
                        continue;
                    }

                    HouseData lookup = new HouseData(description);

                    lookup.Reconcile(sim);

                    ValidateTask.Perform(sim);

                    List <SimDescription> dependents = new List <SimDescription>();
                    if (HandleDoppleganger(sim, preExistingSims, allSims, dependents))
                    {
                        if (!houses.ContainsKey(lookup.mID))
                        {
                            if (!doppleHouses.ContainsKey(lookup.mID))
                            {
                                doppleHouses.Add(lookup.mID, lookup);
                            }
                        }

                        checkSims.AddRange(dependents);

                        cleanUp.Add(sim);
                        continue;
                    }
                    else
                    {
                        fixUp.Add(sim);
                    }

                    HouseData data;
                    if (!houses.TryGetValue(lookup.mID, out data))
                    {
                        data = lookup;
                        houses.Add(data.mID, data);
                    }

                    doppleHouses.Remove(lookup.mID);

                    data.mSims.Add(sim);
                }

                log += Common.NewLine + "B";

                foreach (SimDescription sim in fixUp)
                {
                    log += Common.NewLine + sim.FullName;

                    new Relationships.RepairParents().Perform(sim, UnusedLog, allSims);
                    new Relationships.RepairChildren().Perform(sim, UnusedLog, allSims);
                    new Relationships.RepairSiblings().Perform(sim, UnusedLog, allSims);
                }

                log += Common.NewLine + "C";

                foreach (SimDescription cleanup in cleanUp)
                {
                    log += Common.NewLine + cleanup.FullName;

                    try
                    {
                        if (cleanup.Household != null)
                        {
                            cleanup.Household.Remove(cleanup);
                        }

                        checkSims.Remove(cleanup);

                        cleanup.Genealogy.ClearAllGenealogyInformation();
                        cleanup.Dispose();
                    }
                    catch (Exception e)
                    {
                        Common.DebugException(log, e);
                    }
                }

                log += Common.NewLine + "D";

                if (houses.Count == 0)
                {
                    SimpleMessageDialog.Show(Common.Localize("Title"), Common.Localize("Unpack:NotProper"));
                    return(OptionResult.Failure);
                }
                else if (houses.Count == 1)
                {
                    int funds = -1;
                    foreach (HouseData data in houses.Values)
                    {
                        if (data.mID != 0)
                        {
                            funds = data.mFunds;
                        }
                    }

                    if (funds >= 0)
                    {
                        me.SetFamilyFunds(funds);

                        SimpleMessageDialog.Show(Common.Localize("Title"), Common.Localize("Unpack:Unneeded"));
                        return(OptionResult.Failure);
                    }
                }

                log += Common.NewLine + "E";

                int unpacked = 0, failed = 0;

                List <HouseData> sorted = new List <HouseData>(houses.Values);
                sorted.Sort(new Comparison <HouseData>(HouseData.SortByCost));

                foreach (HouseData data in sorted)
                {
                    log += Common.NewLine + "House: " + data.mID;

                    if (data.mID != 1)
                    {
                        Household house = null;

                        if (data.mID != 0)
                        {
                            Lot lot = FindLot(data.mFunds, data.mSims);
                            if (lot == null)
                            {
                                lot = FindLot(-1, null);
                                if (lot == null)
                                {
                                    failed++;
                                    continue;
                                }
                            }

                            house = Household.Create();

                            importedHouses.Add(house);

                            lot.MoveIn(house);

                            house.Name = data.mName;

                            int finalFunds = (data.mFunds - lot.Cost);
                            if (finalFunds >= 0)
                            {
                                house.SetFamilyFunds(finalFunds);

                                me.ModifyFamilyFunds(-data.mFunds);
                            }
                            else
                            {
                                house.SetFamilyFunds(0);

                                me.ModifyFamilyFunds(-data.mFunds);
                                me.ModifyFamilyFunds(finalFunds);
                            }

                            if (me.FamilyFunds < 0)
                            {
                                me.SetFamilyFunds(0);
                            }

                            if (house.FamilyFunds < 0)
                            {
                                house.SetFamilyFunds(0);
                            }

                            unpacked++;
                        }

                        foreach (SimDescription sim in data.mSims)
                        {
                            log += Common.NewLine + sim.FullName;

                            if (house != null)
                            {
                                log += Common.NewLine + "Moved";

                                me.Remove(sim);
                                house.Add(sim);

                                Instantiation.Perform(sim, null);
                            }
                            else
                            {
                                log += Common.NewLine + "PlaceGrave";

                                Porter.PlaceGraveTask.Perform(sim);
                            }
                        }

                        if (house != null)
                        {
                            string name = house.LotHome.Name;
                            if (string.IsNullOrEmpty(name))
                            {
                                name = house.LotHome.Address;
                            }

                            Porter.Notify(Common.Localize("Unpack:Success", false, new object[] { house.Name, name }), house.LotHome.ObjectId);
                        }
                    }
                    else
                    {
                        unpacked++;
                    }

                    foreach (SimDescription sim in data.mSims)
                    {
                        sim.mBio = null;
                    }
                }

                log += Common.NewLine + "F";

                foreach (SimDescription checkSim in checkSims)
                {
                    log += Common.NewLine + checkSim.FullName;

                    if (checkSim.ChildOrBelow)
                    {
                        bool found = false;

                        Household parentHousehold = null;
                        foreach (SimDescription parent in Relationships.GetParents(checkSim))
                        {
                            if ((checkSim.Household != null) && (parent.Household == checkSim.Household))
                            {
                                found = true;
                                break;
                            }
                            else
                            {
                                parentHousehold = parent.Household;
                            }
                        }

                        if (!found)
                        {
                            if (parentHousehold == null)
                            {
                                if ((checkSim.Household != null) && (checkSim.Household.NumMembers == 1))
                                {
                                    foreach (Household house in Household.sHouseholdList)
                                    {
                                        foreach (SimDescription sim in Households.All(house))
                                        {
                                            if (Relationships.IsCloselyRelated(checkSim, sim, false))
                                            {
                                                parentHousehold = house;
                                                break;
                                            }
                                        }

                                        if (parentHousehold != null)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }

                            if (parentHousehold != null)
                            {
                                if (checkSim.Household != null)
                                {
                                    checkSim.Household.Remove(checkSim);
                                }

                                parentHousehold.Add(checkSim);

                                Instantiation.AttemptToPutInSafeLocation(checkSim.CreatedSim, false);
                            }
                        }
                    }
                }

                log += Common.NewLine + "G";

                foreach (Household house in importedHouses)
                {
                    foreach (Sim sim in Households.AllSims(house))
                    {
                        foreach (GameObject obj in Inventories.QuickFind <GameObject>(sim.Inventory))
                        {
                            bool moveToFamily = false;

                            if (!sim.Inventory.ValidForThisInventory(obj))
                            {
                                moveToFamily = true;
                            }
                            else if (obj is IStageProp)
                            {
                                moveToFamily = true;
                            }

                            if (moveToFamily)
                            {
                                sim.Inventory.RemoveByForce(obj);

                                Inventories.TryToMove(obj, house.SharedFamilyInventory.Inventory);
                            }
                        }
                    }
                }

                log += Common.NewLine + "H";

                int doppleFunds = 0;
                foreach (HouseData data in doppleHouses.Values)
                {
                    doppleFunds += data.mFunds;
                }

                me.ModifyFamilyFunds(-doppleFunds);

                if (me.FamilyFunds < 0)
                {
                    me.SetFamilyFunds(0);
                }

                SimpleMessageDialog.Show(Common.Localize("Title"), Common.Localize("Unpack:Completion", false, new object[] { unpacked, failed }));
            }
            catch (Exception e)
            {
                Common.Exception(log, e);
            }

            return(OptionResult.SuccessClose);
        }
Exemple #32
0
        static void Main(string[] args)
        {
            if (args.Length < 2 || args.Length > 3)
            {
                Console.WriteLine("usage: MovieDatabaseBenchmarker <name of rule to apply> <name of grs file to import or number of creation iterations of synthetic graph> [\"sequence to execute\"]");
                Console.WriteLine("example: MovieDatabaseBenchmarker findCouplesOpt imdb-0005000-50176.movies.xmi.grs");
                Console.WriteLine("example: MovieDatabaseBenchmarker findCliquesOf3Opt imdb-0130000-712130.movies.xmi.grs \"[cliques3WithRating\\orderDescendingBy<avgRating>\\keepFirst(15)] ;> [cliques3WithRating\\orderDescendingBy<numMovies>\\keepFirst(15)]\"");
                return;
            }

            // the graph we'll work on
            LGSPGraph graph;

            // the actions we'll use
            MovieDatabaseActions actions;

            // the graph processing environment we'll use
            LGSPGraphProcessingEnvironment procEnv;

            int dummy;

            if (Int32.TryParse(args[1], out dummy))
            {
                Console.WriteLine("Synthesizing test graph with iteration count " + args[1] + " ...");

                graph   = new MovieDatabaseModelGraph();
                actions = new MovieDatabaseActions(graph);
                procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

                int startTimeSynth = Environment.TickCount;

                procEnv.ApplyGraphRewriteSequence("createExample(" + args[1] + ")");

                Console.WriteLine("...needed " + (Environment.TickCount - startTimeSynth) + "ms for synthesizing");
            }
            else
            {
                Console.WriteLine("Importing " + args[1] + " ...");

                // the libGr search plan backend we'll use
                LGSPBackend backend = LGSPBackend.Instance;

                // the graph model we'll use
                MovieDatabaseModelGraphModel model = new MovieDatabaseModelGraphModel();

                // import the graph, result (of grs import) will be a named graph
                IActions    ba;
                INamedGraph importedNamedGraph = (INamedGraph)Porter.Import(args[1], backend, model, out ba);

                // we throw away the named graph cause we don't need names here and they require a huge amount of memory
                graph = new LGSPGraph((LGSPNamedGraph)importedNamedGraph, "unnamed");
                importedNamedGraph = null;
                GC.Collect();

                actions = ba != null ? (MovieDatabaseActions)ba : new MovieDatabaseActions(graph);
                procEnv = new LGSPGraphProcessingEnvironment(graph, actions);
            }

            // calculate search plans to optimize performance (I'm not going to fiddle with loading saved analysis data here)
            graph.AnalyzeGraph();
            actions.GenerateActions(args[0]);

            Console.WriteLine("Number of Movie: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Movie").TypeID]);
            Console.WriteLine("Number of Actor: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Actor").TypeID]);
            Console.WriteLine("Number of Actress: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Actress").TypeID]);
            Console.WriteLine("Number of personToMovie: " + graph.edgesByTypeCounts[graph.Model.EdgeModel.GetType("personToMovie").TypeID]);

            Console.WriteLine("Start matching " + args[0] + " ...");

            int startTime = Environment.TickCount;

            // get action, search for all matches, apply rewrite
            IAction  ruleToApply = actions.GetAction(args[0]);
            IMatches matches     = ruleToApply.Match(procEnv, 0, new object[0]);

            Console.WriteLine("...needed " + (Environment.TickCount - startTime) + "ms for finding the matches");

            Console.WriteLine("...continue with rewriting...");

            ruleToApply.ModifyAll(procEnv, matches);

            Console.WriteLine("...needed " + (Environment.TickCount - startTime) + "ms for finding the matches and adding the couples/cliques");

            Console.WriteLine("Number of Couple: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Couple").TypeID]);
            Console.WriteLine("Number of Clique: " + graph.nodesByTypeCounts[graph.Model.NodeModel.GetType("Clique").TypeID]);
            Console.WriteLine("Number of commonMovies: " + graph.edgesByTypeCounts[graph.Model.EdgeModel.GetType("commonMovies").TypeID]);

            if (args.Length == 3)
            {
                procEnv.ApplyGraphRewriteSequence(args[2]);
            }
        }