Example #1
0
 public void JoinedStreams()
 {
     StartPoint<int> s1 = new StartPoint<int>(
         (IWritableQueue<int> o)=>
         {
             o.Send(1);
             o.Send(3);
             o.Send(5);
             o.Send(7);
         }
         );
     StartPoint<int> s2 = new StartPoint<int>(
         (IWritableQueue<int> o) =>
         {
             o.Send(11);
             o.Send(13);
             o.Send(15);
             o.Send(17);
         }
         );
     Collector<int> end = new Collector<int>();
     Flow f = Flow.FromAsciiArt(@"
     a--+
        V
     b--#-->c
     ", new Dictionary<char, TaskNode>() { {'a', s1}, {'b', s2}, {'c', end} });
     f.Start();
     f.RunToCompletion();
     Assert.AreEqual(8, end.Items.Count);
 }
Example #2
0
        /// <summary>
        /// Factory method to create a graph
        /// </summary>
        /// <param name="content">
        /// Sequence of nodes, edges, graphs and sequences of these.</param>
        /// <returns>Newly created graph instance.</returns>
        public Graph CreateGraph(params object[] content)
        {
            var collector = new Collector();
            collector.Scan(content);

            return new Graph(collector.Nodes, collector.Edges, collector.Graphs);
        }
Example #3
0
        public void Run()
        {
            udpclient = new UdpClient();

            collector = new Collector(countersInfo);

            startedEvent.Set();

            while (continueProcess)
            {
                try
                {
                    byte[] sendBytes = collector.CollectInfoForAllCounters();

                    //ShowBytes(sendBytes);
                    udpclient.Send(sendBytes, sendBytes.Length, endPoint);
                }
                catch (NullReferenceException ex)
                {
                    Trace.TraceError("SendBytes array is null, {0}", ex.ToString());
                }
                catch (SocketException ex)
                {
                    Trace.TraceError("Socket error mesage: {0}, code: {1}", ex.Message, ex.ErrorCode);
                }

                Thread.Sleep(DataSendInterval);
            }

        }
Example #4
0
        public Television(TLFeed feed, Database database, Collector collector, Torrenter torrenter)
        {
            feed.New += item =>
            {
                if (item.Categories[0].Name != "Episodes")
                    return;
                var shows = database.Get<Show>();
                if (shows.Any(show => item.Title.Text.ToLower().Contains(show.Title.ToLower())))
                {
                    var model = new Torrent(item.Title.Text, item.Links.First().Uri.ToString(), item.Categories.First().Name);
                    collector.Event(model);
                    torrenter.Download(item.Links.First().Uri.ToString());
                }
            };

            collector.On<Search>(search =>
            {
                var wc = new WebClient();
                var result = wc.DownloadString("http://www.imdb.com/xml/find?json=1&tt=on&q=" + search.Query);
                try
                {

                    var json = JObject.Parse(result);
                    var exact = json["title_popular"];
                    if (exact == null) return;
                    if(!exact["description"].ToString().Contains("TV")) return;
                    var show = new Show(exact[0]["title"].ToString());
                    collector.Event(show);
                }
                catch { }
            });
        }
Example #5
0
        public SearchParser(Collector collector)
        {
            collector.On<Browse>(browse =>
            {
                if (browse.Url.Contains("google.com"))
                {
                    var match = Regex.Match(browse.Url, "q=([^&]+)");
                    if (!match.Success) return;
                    _last = new Search()
                    {
                        Query = match.Groups[1].Value.Replace("+", " ").Replace("%20", " ")
                    };
                    collector.Event(_last);
                }

                if (browse.Referrer.Contains("google.com"))
                {
                    if(_last == null) return;
                    var found = new Found()
                    {
                        Query = _last.Query,
                        Url = browse.Url
                    };
                    collector.Event(found);
                }
            });
        }
Example #6
0
 public void TestAddingToCollection()
 {
     var mi = new MediaInfo(@".\TestFolder\Judge.Judy.S14E157.2010.02.25.mp5");
      mi.Analyse();
      var sut = new Collector();
      var result = sut.AddToTvCollection(mi);
      Assert.IsTrue(result.Equals(sut.LatestAddition));
 }
Example #7
0
    public void Start()
    {
        player = GetComponent<Player>();
        controller = GetComponent<CharacterController2D>();
        collector = GetComponent<Collector>();

        scale = Camera.main.orthographicSize;
    }
Example #8
0
 public void TestCollectorHasIt()
 {
     var mi = new MediaInfo(@".\TestFolder\Judge.Judy.S14E157.2010.02.25.mp4");
      mi.Analyse();
      var sut = new Collector();
      var hasIt = sut.HaveIt(mi);
      Assert.IsTrue(hasIt);
 }
Example #9
0
 public ScalableDataList(Collector col)
 {
     collector = col;
     myPED = null;//!
     points[(int)DisplayValue.Step] = new PointPairListPlus(null, this);
     points[(int)DisplayValue.Voltage] = new PointPairListPlus(null, this);
     points[(int)DisplayValue.Mass] = new PointPairListPlus(null, this);
 }
Example #10
0
 internal DrillSidewaysQuery(Query baseQuery, Collector drillDownCollector, Collector[] drillSidewaysCollectors, Query[] drillDownQueries, bool scoreSubDocsAtOnce)
 {
     this.baseQuery = baseQuery;
     this.drillDownCollector = drillDownCollector;
     this.drillSidewaysCollectors = drillSidewaysCollectors;
     this.drillDownQueries = drillDownQueries;
     this.scoreSubDocsAtOnce = scoreSubDocsAtOnce;
 }
Example #11
0
 // Use this for initialization
 void Start()
 {
     collector = FindObjectOfType<Collector>();
     if(collector == null)
     {
         Debug.LogError("COLLECTABLE COULD NOT FIND A COLLECTOR... IS IT IN THE SCENE?");
     }
 }
Example #12
0
 void OnTriggerEnter2D(Collider2D col)
 {
     if(col.CompareTag("Player"))
     {
         playerscript = col.gameObject.GetComponent<Collector>();
         InRange = true;
     }
 }
Example #13
0
 void OnTriggerExit2D(Collider2D col)
 {
     if (col.CompareTag("Player"))
     {
         playerscript = null;
         InRange = false;
     }
 }
Example #14
0
        /**
	     * 
	     */
        public override void OnCollect(Collector collector)
        {
            base.OnCollect(collector);

            owner.ammo.arrows.Upgrade(30);
            owner.ammo.arrows.Restore();
            owner.ammo.arrows.Enable();
        }
Example #15
0
	    /// <summary>Scores and collects all matching documents.</summary>
		/// <param name="collector">The collector to which all matching documents are passed.
		/// </param>
		public virtual void  Score(Collector collector)
		{
			collector.SetScorer(this);
			int doc;
			while ((doc = NextDoc()) != NO_MORE_DOCS)
			{
				collector.Collect(doc);
			}
		}
Example #16
0
 public void ReadValuesUsingTheCollector()
 {
     using (var collector = new Collector(Supplier, new[] { Sink }))
     {
         collector.Start();
         Thread.Sleep(400);
         collector.Stop();
         Assert.True(SentValues.Count>5);
     }
 }
Example #17
0
		/// <summary> Expert: Collects matching documents in a range. Hook for optimization.
		/// Note, <paramref name="firstDocID" /> is added to ensure that <see cref="DocIdSetIterator.NextDoc()" />
		/// was called before this method.
		/// 
		/// </summary>
		/// <param name="collector">The collector to which all matching documents are passed.
		/// </param>
		/// <param name="max">Do not score documents past this.
		/// </param>
		/// <param name="firstDocID">
        /// The first document ID (ensures <see cref="DocIdSetIterator.NextDoc()" /> is called before
		/// this method.
		/// </param>
		/// <returns> true if more matching documents may remain.
		/// </returns>
		public /*protected internal*/ virtual bool Score(Collector collector, int max, int firstDocID)
		{
			collector.SetScorer(this);
			int doc = firstDocID;
			while (doc < max)
			{
				collector.Collect(doc);
				doc = NextDoc();
			}
			return doc != NO_MORE_DOCS;
		}
    public void Before()
    {
        var context = Helper.CreateContext();
        var group = context.GetGroup(Matcher.AllOf(new [] { CP.ComponentA }));
        _collector = group.CreateCollector();

        for(int i = 0; i < 1000; i++) {
            var e = context.CreateEntity();
            e.AddComponent(CP.ComponentA, new ComponentA());
        }
    }
Example #19
0
        public void OnCollect(Collector collector)
        {
            var damagable = collector.GetComponent<Damagable>();

            if (damagable)
            {
                damagable.Heal(1);
            }

            Destroy(gameObject);
        }
Example #20
0
 public static void Start(string key)
 {
     if (Enabled)
         if (_timeStamps.ContainsKey(key))
         {
             if (_timeStamps[key].Stopped)
                 _timeStamps[key] = new Collector();
             else
                 _timeStamps[key].StartTime = DateTime.Now;
         }
         else
             _timeStamps.Add(key, new Collector());
 }
Example #21
0
        /**
	     * 
	     */
        public virtual void OnCollect(Collector collector)
        {
            if (collector.hasItem(this))
            {
                return;
            }

            collector.items.Add(this);

            owner = collector;

            //this.gameObject.SetActive(false); // TODO: Find a way to remove the object instance from the game world while still allowing the item to be used.
        }
        public void Test()
        {
            var lParen = new Symbol("(");
            var rParen = new Symbol(")");
            var num    = new Symbol("NUM");
            var ident  = new Symbol("ID");
            var qStr   = new Symbol("QSTR");

            var grammar = new Grammar
            {
                Symbols =
                {
                    lParen,
                    rParen,
                    num,
                    ident,
                    qStr
                },

                Conditions =
                {
                    new Condition("main")
                    {
                        Matchers =
                        {
                            new Matcher(@"blank+"),
                            new Matcher(@"digit+ ('.' digit+)?  | '.' digit+", num),
                            new Matcher(
                                    @"(alpha | [:.!@#$%^&|?*/+*=\\_-]) (alnum | [:.!@#$%^&|?*/+*=\\_-])*",
                                    ident),
                            new Matcher("'\"' ('\\\\\"' | ~'\"')* '\"'", qStr),
                            new Matcher(ScanPattern.CreateLiteral("("), lParen),
                            new Matcher(ScanPattern.CreateLiteral(")"), rParen),
                        }
                    }
                }
            };

            var target = new DfaSimulationLexer(
                " (1 (\"bar\" +))",
                ScannerDescriptor.FromScanRules(grammar.Conditions[0].Matchers, ExceptionLogging.Instance));

            var collector = new Collector<Msg>();
            target.Accept(collector);
            Assert.AreEqual(
                new int[] { lParen.Index, num.Index, lParen.Index, qStr.Index, ident.Index, rParen.Index, rParen.Index },
                collector.Select(msg => msg.Id).ToArray());
            Assert.AreEqual(
                new object[] { "(", "1", "(", "\"bar\"", "+", ")", ")" },
                collector.Select(msg => msg.Value).ToArray());
        }
Example #23
0
 public bool follow(Collector collect)
 {
     if (collect == null)
     {
         target = collect;
         return true;
     }
     if (target == null)
     {
         target = collect;
         return true;
     }
     return false;
 }
Example #24
0
        public IMDBParser(Collector collector)
        {
            collector.On<Browse>(browse =>
            {
                if(!browse.Url.Contains("imdb.com/title")) return;
                var page = new WebPage(browse.Url);

                var title = page.DocumentNode.SelectSingleNode("//*[@id='overview-top']/h1/span[1]").InnerText;
                if (page.DocumentNode.SelectSingleNode("//*[@id='overview-top']/div[1]").InnerText.Contains("TV"))
                    collector.Event(new Show(title));
                else
                    collector.Event(new Movie(title));
            });
        }
Example #25
0
        public XmlTemplater(XmlNode templateNode)
        {
            _templateXml = templateNode.OuterXml;

            XmlAttribute substitutionAttribute = templateNode.Attributes[InstanceMemento.SUBSTITUTIONS_ATTRIBUTE];
            if (substitutionAttribute == null)
            {
                var collector = new Collector(templateNode);
                _substitutions = collector.FindSubstitutions();
            }
            else
            {
                _substitutions = substitutionAttribute.InnerText.Split(',');
            }
        }
Example #26
0
 void Start()
 {
     /*if (handler == null)
     {
         DontDestroyOnLoad(gameObject);
         handler = this;
     }
     else if (handler != this)
     {
         Destroy(gameObject);
     }*/
     collScript = FindObjectOfType<Collector> ();
     handler = this;
     UpdateTorches (startTorch);
 }
Example #27
0
    // Use this for initialization
    void Start()
    {
        if (null == ourGameObject )
        {
            ourGameObject = gameObject;
        }
        if (null == ourCollector )
        {
            ourCollector = ourGameObject.GetComponent<Collector>();
        }
        animator = ourGameObject.GetComponent<Animator>();

        if(animator.layerCount >= 2)
            animator.SetLayerWeight(1, 1);
    }
Example #28
0
        public void EventsAndStatePresentation()
        {
            StartPoint<int> start = StandardTasks.GetRangeEnumerator(1, 100);
            TaskNode<int, string> filter = Helpers.GetFilter();
            filter.ThreadNumber = 2;
            Collector<string> end = new Collector<string>();

            filter.ItemProcessed += new EventHandler<TaskNode.ItemEventArgs>(EndItemProcessed);
            Flow f = Flow.FromAsciiArt("a-->b->z", start, filter, end);
            f.Start();
            f.RunToCompletion();
            // all items have left the flow, but some threads may still be running. The status of the tasks
            // could still be Stopping, or even Running
            Thread.Sleep(10);
            // Now everything should have status Stopped
            Assert.AreEqual(RunStatus.Stopped, f.Status);
            Console.WriteLine("last: {0}\n\n", f.GetStateSnapshot());
        }
Example #29
0
 public void JoinedStreams2()
 {
     StartPoint<int> r1 = StandardTasks.GetRangeEnumerator(21, 50);
     StartPoint<int> r2 = StandardTasks.GetRangeEnumerator(41, 90);
     StartPoint<int> r3 = StandardTasks.GetRangeEnumerator(-9, 10);
     Collector<int> c = new Collector<int>();
     Flow f = Flow.FromAsciiArt(@"
      a  b  c
      |  |  |
      +->#<-+
         |
         V
         d
      ", new Dictionary<char, TaskNode>() { {'a', r1},{'b', r2},{'c', r3},{'d', c}});
     f.Start();
     f.RunToCompletion();
     Assert.AreEqual(100, c.Items.Count);
 }
Example #30
0
        public void StopRightInTheMiddle()
        {
            InputPoint<int> inp = new InputPoint<int>();
            TaskNode<int,int> process = new TaskNode<int, int>(
                    (input, output) => output.Send(input)
                        );
            process.ThreadNumber = 2;
            process.KeepOrder = true;
            Collector<int> coll = new Collector<int>();

            Flow flow = Flow.FromAsciiArt("a->b->c",
                inp,
                process,
                coll
                );
            coll.ItemProcessed += (o,a) =>
                {
                    if ((int)a.Item == 0)
                    {
                        flow.Stop();
                    }
                    var state = flow.GetStateSnapshot();
                    Console.WriteLine(state.ToStringAsciiArt());
                };

            flow.Start();
            for (int i = 1; i < 100; i++)
            {
                inp.Send(i);
            }
            inp.Send(0);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            inp.Send(1);
            //for (int i = 1; i < 1000; i++)
            //{
            //    inp.Send(i);
            //}
            flow.RunToCompletion();
            Assert.AreEqual(coll.Items.Count,100);
        }
Example #31
0
 // Use this for initialization
 void Start()
 {
     cl    = GetComponent <Collector>();
     it    = GetComponent <Inventory>();
     stuck = false;
 }
 /// <summary>
 /// Adds the given script as an invoker
 /// </summary>
 /// <param name="invoker">the invoker</param>
 public static void AddInvoker_AddPoints(Collector invoker)
 {
     // add invoker to list and add all listeners to invoker
     invokers_AddPoints = invoker;
     invoker.AddListener_AddPoints(listeners_AddPoints);
 }
Example #33
0
 public override void  Score(Collector collector)
 {
     scorer.Score(collector);
 }
Example #34
0
        /// <summary>
        /// This method will transmit a message.
        /// </summary>
        /// <param name="message">The message to transmit.</param>
        /// <param name="retry">The current number of retries.</param>
        public override async Task Transmit(TransmissionPayload payload, int retry = 0)
        {
            bool tryAgain = false;
            bool fail     = true;

            try
            {
                LastTickCount = Environment.TickCount;

                if (retry > MaxRetries)
                {
                    throw new RetryExceededTransmissionException();
                }

                var message = MessagePack(payload);
                await MessageTransmit(message);

                if (BoundaryLoggingActive)
                {
                    Collector?.BoundaryLog(ChannelDirection.Outgoing, payload, ChannelId, Priority);
                }
                fail = false;
            }
            catch (NoMatchingSubscriptionException nex)
            {
                //OK, this happens when the remote transmitting party has closed or recycled.
                LogException($"The sender has closed: {payload.Message.CorrelationServiceId}", nex);
                if (BoundaryLoggingActive)
                {
                    Collector?.BoundaryLog(ChannelDirection.Outgoing, payload, ChannelId, Priority, nex);
                }
            }
            catch (TimeoutException tex)
            {
                LogException("TimeoutException (Transmit)", tex);
                tryAgain = true;
                if (BoundaryLoggingActive)
                {
                    Collector?.BoundaryLog(ChannelDirection.Outgoing, payload, ChannelId, Priority, tex);
                }
            }
            catch (MessagingException dex)
            {
                //OK, something has gone wrong with the Azure fabric.
                LogException("Messaging Exception (Transmit)", dex);
                //Let's reinitialise the client
                if (ClientReset == null)
                {
                    throw;
                }

                ClientReset(dex);
                tryAgain = true;
            }
            catch (Exception ex)
            {
                LogException("Unhandled Exception (Transmit)", ex);
                if (BoundaryLoggingActive)
                {
                    Collector?.BoundaryLog(ChannelDirection.Outgoing, payload, ChannelId, Priority, ex);
                }
                throw;
            }
            finally
            {
                if (fail)
                {
                    StatisticsInternal.ExceptionHitIncrement();
                }
            }

            if (tryAgain)
            {
                await Transmit(payload, ++retry);
            }
        }
Example #35
0
        CollectEvent(object sender, CollectorEventArgs e)
        {
            // cast the sender object to the SnoopCollector we are expecting
            Collector snoopCollector = sender as Collector;

            if (snoopCollector == null)
            {
                Debug.Assert(false);    // why did someone else send us the message?
                return;
            }

            // see if it is a type we are responsible for
            Document doc = e.ObjToSnoop as Document;

            if (doc != null)
            {
                Stream(snoopCollector.Data(), doc);
                return;
            }

            Selection sel = e.ObjToSnoop as Selection;

            if (sel != null)
            {
                Stream(snoopCollector.Data(), sel);
                return;
            }

            Settings settings = e.ObjToSnoop as Settings;

            if (settings != null)
            {
                Stream(snoopCollector.Data(), settings);
                return;
            }

            Category cat = e.ObjToSnoop as Category;

            if (cat != null)
            {
                Stream(snoopCollector.Data(), cat);
                return;
            }

            PaperSize paperSize = e.ObjToSnoop as PaperSize;

            if (paperSize != null)
            {
                Stream(snoopCollector.Data(), paperSize);
                return;
            }

            PaperSource paperSource = e.ObjToSnoop as PaperSource;

            if (paperSource != null)
            {
                Stream(snoopCollector.Data(), paperSource);
                return;
            }

            PrintSetup prnSetup = e.ObjToSnoop as PrintSetup;

            if (prnSetup != null)
            {
                Stream(snoopCollector.Data(), prnSetup);
                return;
            }

            PrintParameters prnParams = e.ObjToSnoop as PrintParameters;

            if (prnParams != null)
            {
                Stream(snoopCollector.Data(), prnParams);
                return;
            }

            PlanTopology planTopo = e.ObjToSnoop as PlanTopology;

            if (planTopo != null)
            {
                Stream(snoopCollector.Data(), planTopo);
                return;
            }

            PlanCircuit planCircuit = e.ObjToSnoop as PlanCircuit;

            if (planCircuit != null)
            {
                Stream(snoopCollector.Data(), planCircuit);
                return;
            }

            PrintManager printManager = e.ObjToSnoop as PrintManager;

            if (printManager != null)
            {
                Stream(snoopCollector.Data(), printManager);
                return;
            }
        }
Example #36
0
        private static void LoadDiagnosticTools(XDocument settingsDoc, ref Dictionary <String, Collector> collectors, ref Dictionary <String, Analyzer> analyzers)
        {
            if (collectors == null)
            {
                collectors = new Dictionary <string, Collector>();
            }
            if (analyzers == null)
            {
                analyzers = new Dictionary <string, Analyzer>();
            }

            var diagnosticSettingsXml = settingsDoc.Element(SettingsXml.DiagnosticSettings);

            if (diagnosticSettingsXml == null)
            {
                return;
            }
            var collectorsXml = diagnosticSettingsXml.Element(SettingsXml.Collectors);
            var analyzersXml  = diagnosticSettingsXml.Element(SettingsXml.Analyzers);

            IEnumerable <XElement> tools = new List <XElement>();

            if (collectorsXml != null)
            {
                tools = collectorsXml.Elements();
            }
            if (analyzersXml != null)
            {
                tools = tools.Union(analyzersXml.Elements());
            }

            foreach (var toolXml in tools)
            {
                var toolType = Assembly.GetExecutingAssembly()
                               .GetTypes()
                               .FirstOrDefault(
                    t =>
                    t.IsClass &&
                    t.Name.Equals(toolXml.Name.LocalName, StringComparison.OrdinalIgnoreCase));

                if (toolType == null)
                {
                    throw new ArgumentException(string.Format("{0} is not a valid type",
                                                              toolXml.Name.LocalName));
                }

                var constructor = toolType.GetConstructor(System.Type.EmptyTypes);
                var instance    = constructor.Invoke(null);

                foreach (var settingXml in toolXml.Elements())
                {
                    var propertyInfo = toolType.GetProperty(settingXml.Name.LocalName);
                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(instance, settingXml.Value, null);
                        //throw new ArgumentException(string.Format("{0} is not a valid setting type",
                        //    settingXml.Name.LocalName));
                    }
                    //propertyInfo.SetValue(instance, settingXml.Value, null);
                }

                foreach (var settingXml in toolXml.Attributes())
                {
                    var propertyInfo = toolType.GetProperty(settingXml.Name.LocalName);
                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(instance, settingXml.Value, null);
                        //throw new ArgumentException(string.Format("{0} is not a valid setting type",
                        //    settingXml.Name.LocalName));
                    }
                    //propertyInfo.SetValue(instance, settingXml.Value, null);
                }

                if (typeof(Collector).IsAssignableFrom(toolType))
                {
                    Collector collector = instance as Collector;
                    collectors[collector.Name.ToLower()] = collector;
                }
                else if (typeof(Analyzer).IsAssignableFrom(toolType))
                {
                    Analyzer analyzer = instance as Analyzer;
                    analyzers[analyzer.Name.ToLower()] = analyzer;
                }
                else
                {
                    throw new Exception("Hey, what kind of tool is this?");
                }
            }
        }
Example #37
0
        public void Test_ErrorSetupCollector()
        {
            Collector collector = new Collector(null);

            collector.Setup();
        }
Example #38
0
 /// <summary>
 /// Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly
 /// in the element, not in any of its descendants.
 /// </summary>
 /// <param name="searchText">to look for in the element's own text</param>
 /// <returns>elements that contain the string, case insensitive.</returns>
 /// <see cref="Element.OwnText()"/>
 public Elements GetElementsContainingOwnText(string searchText)
 {
     return(Collector.Collect(new Evaluator.ContainsOwnText(searchText), this));
 }
Example #39
0
        CollectEvent(object sender, CollectorEventArgs e)
        {
            // cast the sender object to the SnoopCollector we are expecting
            Collector snoopCollector = sender as Collector;

            if (snoopCollector == null)
            {
                Debug.Assert(false); // why did someone else send us the message?
                return;
            }


            // see if it is a type we are responsible for
            Connector connector = e.ObjToSnoop as Connector;

            if (connector != null)
            {
                Utils.StreamWithReflection(snoopCollector.Data(), typeof(Connector), connector);
                return;
            }

            ConnectorManager connectorMgr = e.ObjToSnoop as ConnectorManager;

            if (connectorMgr != null)
            {
                Stream(snoopCollector.Data(), connectorMgr);
                return;
            }

            CorrectionFactor correctionFactor = e.ObjToSnoop as CorrectionFactor;

            if (correctionFactor != null)
            {
                Stream(snoopCollector.Data(), correctionFactor);
                return;
            }

            ElectricalSetting elecSetting = e.ObjToSnoop as ElectricalSetting;

            if (elecSetting != null)
            {
                Stream(snoopCollector.Data(), elecSetting);
                return;
            }

            GroundConductorSize groundConductorSize = e.ObjToSnoop as GroundConductorSize;

            if (groundConductorSize != null)
            {
                Stream(snoopCollector.Data(), groundConductorSize);
                return;
            }

            MEPModel mepModel = e.ObjToSnoop as MEPModel;

            if (mepModel != null)
            {
                Stream(snoopCollector.Data(), mepModel);
                return;
            }

            WireSize wireSize = e.ObjToSnoop as WireSize;

            if (wireSize != null)
            {
                Stream(snoopCollector.Data(), wireSize);
                return;
            }
        }
Example #40
0
 /// <summary>
 /// Find elements whose text matches the supplied regular expression.
 /// </summary>
 /// <param name="pattern">regular expression to match text against</param>
 /// <returns>elements matching the supplied regular expression.</returns>
 /// <see cref="Element.Text()"/>
 public Elements GetElementsMatchingText(Regex regex)
 {
     return(Collector.Collect(new Evaluator.MatchesRegex(regex), this));
 }
        public ConfigAndLogCollectorViewModel()
        {
            string archiveOptionConfigFileName = ConfigurationManager.AppSettings["ArchiveOptionFile"];

            Collector = new Collector(archiveOptionConfigFileName);
        }
Example #42
0
        public void Can_collect_exact_phrase_joined_by_not()
        {
            var dir = Path.Combine(Setup.Dir, "Can_collect_exact_phrase_joined_by_not");

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

            var docs = new List <Dictionary <string, string> >
            {
                new Dictionary <string, string> {
                    { "_id", "0" }, { "title", "rambo first blood" }
                },
                new Dictionary <string, string> {
                    { "_id", "1" }, { "title", "rambo 2" }
                },
                new Dictionary <string, string> {
                    { "_id", "2" }, { "title", "rocky 2" }
                },
                new Dictionary <string, string> {
                    { "_id", "3" }, { "title", "the raiders of the lost ark" }
                },
                new Dictionary <string, string> {
                    { "_id", "4" }, { "title", "the rain man" }
                },
                new Dictionary <string, string> {
                    { "_id", "5" }, { "title", "the good, the bad and the ugly" }
                }
            };

            string indexName;

            using (var writer = new StreamWriteOperation(dir, new Analyzer(), docs.ToStream()))
            {
                indexName = writer.Execute();
            }

            var query = new QueryParser(new Analyzer()).Parse("+title:the");

            using (var collector = new Collector(dir, IxInfo.Load(Path.Combine(dir, indexName + ".ix")), new Tfidf()))
            {
                var scores = collector.Collect(query).ToList();

                Assert.That(scores.Count, Is.EqualTo(3));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 3));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 4));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 5));
            }

            query = new QueryParser(new Analyzer()).Parse("+title:the -title:ugly");

            using (var collector = new Collector(dir, IxInfo.Load(Path.Combine(dir, indexName + ".ix")), new Tfidf()))
            {
                var scores = collector.Collect(query).ToList();

                Assert.That(scores.Count, Is.EqualTo(2));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 3));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 4));
            }
        }
Example #43
0
        /// <summary>
        /// 缓存采集器发电量统计
        /// 要进行修正缓存丢失
        ///
        /// </summary>
        /// <param name="tcpmessage"></param>
        private static void CacheCollectorEnergyData(IDictionary <string, double?> collectorEnergyMap)
        {
            int collectorID;

            string[]  keyArr;
            int       year;
            int       month;
            int       day;
            float?    data;
            Collector collector = null;

            //string[] keys = collectorEnergyMap.Keys.ToArray();
            foreach (string ekey in collectorEnergyMap.Keys)
            {
                try
                {
                    keyArr = ekey.Split(':');

                    collectorID = int.Parse(keyArr[0]);
                    //原来是通过消息头部取得,现在改为
                    data = collectorEnergyMap[ekey] == null ? 0 : float.Parse(collectorEnergyMap[ekey].ToString());
                    if (data == 0)//如果头部未传或者为0则再从设备累计下看看
                    {
                        //现在改为通过采集器的设备的今日电量来累加
                        collector = CollectorInfoService.GetInstance().Get(collectorID);
                        if (keyArr.Length < 4 || (string.IsNullOrEmpty(keyArr[1]) || string.IsNullOrEmpty(keyArr[2]) || string.IsNullOrEmpty(keyArr[3])))
                        {
                            continue;
                        }
                        data = collector.deviceTodayEnergy(keyArr[1] + keyArr[2] + keyArr[3]);
                    }
                    year  = int.Parse(keyArr[1]);
                    month = int.Parse(keyArr[2]);
                    day   = int.Parse(keyArr[3]);
                    string d_column = "d_" + day;

                    //取得月天数据对象
                    CollectorMonthDayData collectorMonthDayData = CollectorMonthDayDataService.GetInstance().GetCollectorMonthDayData(year, collectorID, month);
                    collectorMonthDayData.curDay = day;
                    //给相应属性赋值
                    if (collectorMonthDayData != null)
                    {
                        object ovalue = ReflectionUtil.getProperty(collectorMonthDayData, d_column);
                        if (ovalue == null || float.Parse(ovalue.ToString()) < data)
                        {
                            ReflectionUtil.setProperty(collectorMonthDayData, d_column, data);
                        }
                    }
                    CollectorMonthDayDataService.GetInstance().Cache(collectorMonthDayData);

                    //更新年月发电量数据
                    //统计年月
                    string m_column = "m_" + month;
                    float? m_value  = collectorMonthDayData.count();
                    CollectorYearMonthData ymdData = CollectorYearMonthDataService.GetInstance().GetCollectorYearMonthData(collectorID, year);;
                    ymdData.curMonth = month;
                    //给年月数据对象相应属性赋值
                    if (ymdData != null)
                    {
                        object ovalue = ReflectionUtil.getProperty(ymdData, m_column);
                        if (ovalue == null || float.Parse(ovalue.ToString()) < m_value)
                        {
                            ReflectionUtil.setProperty(ymdData, m_column, m_value);
                        }
                    }
                    CollectorYearMonthDataService.GetInstance().Cache(ymdData);

                    //统计总体发电量
                    float?            y_value = ymdData.count();
                    CollectorYearData yd      = CollectorYearDataService.GetInstance().GetCollectorYearData(collectorID, year);
                    if (yd == null)
                    {
                        yd = new CollectorYearData()
                        {
                            dataValue = 0, collectorID = collectorID, year = year
                        }
                    }
                    ;
                    yd.localAcceptTime = DateTime.Now;
                    //给年月数据对象相应属性赋值
                    if (yd != null)
                    {
                        object ovalue = yd.dataValue;
                        if (ovalue == null || float.Parse(ovalue.ToString()) < y_value)
                        {
                            yd.dataValue = y_value == null ? 0 : float.Parse(y_value.ToString());
                        }
                    }
                    CollectorYearDataService.GetInstance().Cache(yd);
                }
                catch (Exception onee) {//捕获单个异常,保证一个错误不影响其他采集器数据处理
                    LogUtil.error("Cache collectorEnergyMap of ekey is " + ekey + " error:" + onee.Message);
                }
            }
        }
Example #44
0
 private async Task DoSomething(TransmissionPayload rq, List <TransmissionPayload> rs)
 {
     Collector?.LogMessage("all done");
 }
Example #45
0
        static void mThread()
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";

            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

            Collector.Collect();

            ActivityLog();

            LoadStaticSpawnData();

            InitSystemVariables();

            LoadLuaMod();

            InitModules();

            while (true)
            {
                Collector.Collect();

                GetHotKeys();

                if (Collector.requestReload)
                {
                    InitModules();
                    LoadLuaMod();
                }

                if (!fishing.isFishing && !_autoItemBuyTrigger)
                {
                    Console.Title = String.Format("X:{0} Y:{1} Z:{2}", Collection.Actors.Local.PlayerData.WorldPosition[0], Collection.Actors.Local.PlayerData.WorldPosition[1], Collection.Actors.Local.PlayerData.WorldPosition[2]);
                }

                workerRestore.Run();
                hackUi.Run();
                speedHack.Run();
                autoPot.Run();
                autoItemRegister.Run();

                if (_autoItemBuyTrigger && !autoItemBuy.ItemMarket.isVisible())
                {
                    _autoItemBuyTrigger = false;
                }

                autoItemBuy.Run(_autoItemBuyTrigger);
                autoItemBuy.PostStats();

                autoProcessing.Run();
                fishing.Run(Collector.requestReload);
                fishing.PostStats();

                if (Settings.Overlay.Enabled)
                {
                    Overlay._draw = true;

                    while (Overlay._draw)
                    {
                        Thread.Sleep(1);
                    }
                }
            }
        }
        private void ResourceUtilization(bool finalCall, List <ISimulationTask> operationTasks, IList <ISimulationTask> setupTasks)
        {
            Collector.messageHub.SendToAllClients(msg: "(" + Collector.Time + ") Update Feed from DataCollection");

            var setupKpiType = KpiType.ResourceSetup;
            var utilKpiType  = KpiType.ResourceUtilization;

            if (finalCall)
            {
                // reset LastIntervallStart
                lastIntervalStart = Collector.Config.GetOption <SettlingStart>().Value;
                setupKpiType      = KpiType.ResourceSetupTotal;
                utilKpiType       = KpiType.ResourceUtilizationTotal;
            }

            double divisor   = Collector.Time - lastIntervalStart;
            var    tupleList = new List <Tuple <string, string> >();

            //resource to ensure entries, even the resource it not used in interval
            var resourceList = _resources.Select(selector: x => new Tuple <string, long>(x.Value.Name.Replace(" ", ""), 0));

            var lower_borders = from sw in operationTasks
                                where sw.Start <lastIntervalStart &&
                                                sw.End> lastIntervalStart &&
                                sw.Mapping != null
                                group sw by sw.Mapping
                                into rs
                                select new Tuple <string, long>(rs.Key,
                                                                rs.Sum(selector: x => x.End - lastIntervalStart));


            var upper_borders = from sw in operationTasks
                                where sw.Start <Collector.Time &&
                                                sw.End> Collector.Time &&
                                sw.Mapping != null
                                group sw by sw.Mapping
                                into rs
                                select new Tuple <string, long>(rs.Key,
                                                                rs.Sum(selector: x => Collector.Time - x.Start));


            var from_work = from sw in operationTasks
                            where sw.Start >= lastIntervalStart &&
                            sw.End <= Collector.Time &&
                            sw.Mapping != null
                            group sw by sw.Mapping
                            into rs
                            select new Tuple <string, long>(rs.Key,
                                                            rs.Sum(selector: x => x.End - x.Start));

            var merge = from_work.Union(second: lower_borders).Union(second: upper_borders).Union(second: resourceList).ToList();

            var final = from m in merge
                        group m by m.Item1
                        into mg
                        select new Tuple <string, long>(mg.Key, mg.Sum(x => x.Item2));

            foreach (var item in final.OrderBy(keySelector: x => x.Item1))
            {
                var value = Math.Round(value: item.Item2 / divisor, digits: 3).ToString(provider: _cultureInfo);
                if (value == "NaN" || value == "Infinity")
                {
                    value = "0";
                }
                tupleList.Add(new Tuple <string, string>(item.Item1, value));
                Collector.CreateKpi(agent: Collector, value: value.Replace(".", ","), name: item.Item1, kpiType: utilKpiType, finalCall);
            }


            var totalLoad = Math.Round(value: final.Sum(selector: x => x.Item2) / divisor / final.Count() * 100, digits: 3).ToString(provider: _cultureInfo);

            if (totalLoad == "NaN" || totalLoad == "Infinity")
            {
                totalLoad = "0";
            }
            Collector.CreateKpi(agent: Collector, value: totalLoad.Replace(".", ","), name: "TotalWork", kpiType: utilKpiType, finalCall);

            //ResourceSetupTimes for interval
            var setups_lower_borders = from sw in setupTasks
                                       where sw.Start <lastIntervalStart &&
                                                       sw.End> lastIntervalStart &&
                                       sw.Mapping != null
                                       group sw by sw.Mapping
                                       into rs
                                       select new Tuple <string, long>(rs.Key,
                                                                       rs.Sum(selector: x => x.End - lastIntervalStart));

            var setups_upper_borders = from sw in setupTasks
                                       where sw.Start <Collector.Time &&
                                                       sw.End> Collector.Time &&
                                       sw.Mapping != null
                                       group sw by sw.Mapping
                                       into rs
                                       select new Tuple <string, long>(rs.Key,
                                                                       rs.Sum(selector: x => Collector.Time - x.Start));

            var totalSetups = from m in setupTasks
                              where m.Start >= lastIntervalStart &&
                              m.End <= Collector.Time
                              group m by m.Mapping
                              into rs
                              select new Tuple <string, long>(rs.Key,
                                                              rs.Sum(selector: x => x.End - x.Start));

            var union = totalSetups.Union(setups_lower_borders).Union(setups_upper_borders).Union(resourceList).ToList();

            var finalSetup = from m in union
                             group m by m.Item1
                             into mg
                             select new Tuple <string, long>(mg.Key, mg.Sum(x => x.Item2));

            foreach (var resource in finalSetup.OrderBy(keySelector: x => x.Item1))
            {
                var value = Math.Round(value: resource.Item2 / divisor, digits: 3).ToString(provider: _cultureInfo);
                if (value == "NaN" || value == "Infinity")
                {
                    value = "0";
                }
                var machine   = resource.Item1.Replace(oldValue: ")", newValue: "").Replace(oldValue: "Resource(", newValue: "").Replace(oldValue: " ", newValue: "");
                var workValue = tupleList.Single(x => x.Item1 == machine).Item2;
                var all       = workValue + " " + value;
                Collector.messageHub.SendToClient(listener: machine, msg: all);
                Collector.CreateKpi(agent: Collector, value: value.Replace(".", ","), name: resource.Item1, kpiType: setupKpiType, finalCall);
            }

            var totalSetup = Math.Round(value: finalSetup.Where(x => !x.Item1.Contains("Operator")).Sum(selector: x => x.Item2) / divisor / finalSetup.Count() * 100, digits: 3).ToString(provider: _cultureInfo);

            if (totalSetup == "NaN" || totalSetup == "Infinity")
            {
                totalSetup = "0";
            }
            Collector.CreateKpi(agent: Collector, value: totalSetup.Replace(".", ","), name: "TotalSetup", kpiType: setupKpiType, finalCall);

            Collector.messageHub.SendToClient(listener: "TotalTimes", msg: JsonConvert.SerializeObject(value:
                                                                                                       new {
                Time = Collector.Time,
                Load = new { Work = totalLoad, Setup = totalSetup }
            }));
        }
Example #47
0
        private static void InitModules()
        {
            Collector.Collect();

            Console.WriteLine("Initiating Modules");

            fishing                     = new AutoFish();
            fishing.Enabled             = Settings.AutoFish.Enabled;
            fishing.FishDataLog         = Settings.AutoFish.FishDataLog;
            fishing.HighLatencyMode     = Settings.AutoFish.HighLatencyMode;
            fishing.PredictMode         = Settings.AutoFish.PredictMode;
            fishing.catchGrade          = Settings.AutoFish.catchGrade;
            fishing.itemIdFilter_White  = Settings.AutoFish.itemIdFilter_White;
            fishing.itemIdFilter_Green  = Settings.AutoFish.itemIdFilter_Green;
            fishing.itemIdFilter_Blue   = Settings.AutoFish.itemIdFilter_Blue;
            fishing.itemIdFilter_Yellow = Settings.AutoFish.itemIdFilter_Yellow;
            fishing.familyNameWhiteList = Settings.AutoFish.familyNameWhiteList;

            workerRestore         = new AutoRestore();
            workerRestore.Enabled = Settings.AutoRestore.Enabled;

            hackUi         = new UI();
            hackUi.Enabled = Settings.UIHack.Enabled;

            autoPot           = new AutoPotion();
            autoPot.Enabled   = Settings.AutoPotion.Enabled;
            autoPot.HPPercent = Settings.AutoPotion.HPPercent;
            autoPot.MPPercent = Settings.AutoPotion.MPPercent;

            autoItemRegister         = new AutoItemRegister();
            autoItemRegister.Enabled = Settings.AutoItemRegister.Enabled;
            autoItemRegister.Filters = Settings.AutoItemRegister.Items;

            autoItemBuy         = new AutoItemBuy();
            autoItemBuy.Enabled = Settings.AutoItemBuy.Enabled;
            autoItemBuy.Filters = Settings.AutoItemBuy.Items;

            speedHack             = new SpeedHack();
            speedHack.GhillieMode = Settings.SpeedHack.GhillieMode;
            speedHack.Horse       = new SpeedHack.SpeedHackActor(
                Settings.SpeedHack.Horse.Enabled,
                Settings.SpeedHack.Horse.Accel,
                Settings.SpeedHack.Horse.Speed,
                Settings.SpeedHack.Horse.Turn,
                Settings.SpeedHack.Horse.Brake,
                Settings.SpeedHack.Horse.DefaultAccel,
                Settings.SpeedHack.Horse.DefaultSpeed,
                Settings.SpeedHack.Horse.DefaultTurn,
                Settings.SpeedHack.Horse.DefaultBrake);
            speedHack.Ship = new SpeedHack.SpeedHackActor(
                Settings.SpeedHack.Ship.Enabled,
                Settings.SpeedHack.Ship.Accel,
                Settings.SpeedHack.Ship.Speed,
                Settings.SpeedHack.Ship.Turn,
                Settings.SpeedHack.Ship.Brake,
                Settings.SpeedHack.Ship.DefaultAccel,
                Settings.SpeedHack.Ship.DefaultSpeed,
                Settings.SpeedHack.Ship.DefaultTurn,
                Settings.SpeedHack.Ship.DefaultBrake);
            speedHack.Player = new SpeedHack.SpeedHackPlayerActor(
                Settings.SpeedHack.Player.Enabled,
                Settings.SpeedHack.Player.Movement,
                Settings.SpeedHack.Player.Attack,
                Settings.SpeedHack.Player.Cast,
                Settings.SpeedHack.Player.AdvancedMode,
                Settings.SpeedHack.Player.Factor);
            speedHack.familyNameWhiteList = Settings.AutoFish.familyNameWhiteList;

            autoProcessing         = new AutoProcessing();
            autoProcessing.Enabled = Settings.AutoProcessing.Enabled;
            autoProcessing.Items   = Settings.AutoProcessing.Items;

            hackNavigation = new Navigation();
            hackNavigation.SetFlags();

            if (Overlay != null)
            {
                Overlay.Enabled        = Settings.Overlay.Enabled;
                Overlay.settingsActors = Settings.Overlay.Actors;
                Overlay.GoldenChests   = Settings.Overlay.GoldenChests;
            }
        }
Example #48
0
        public static async Task <Collector> GetCollectorDetails(long collectorId)
        {
            Collector response = await SurveyMonkeyRequest.GetRequest <Collector>(string.Format("/collectors/{0}", collectorId));

            return(response);
        }
        /// <summary>
        /// This method is used to process the returning message response.
        /// </summary>
        /// <typeparam name="KT"></typeparam>
        /// <typeparam name="ET"></typeparam>
        /// <param name="rType"></param>
        /// <param name="payload"></param>
        /// <param name="processAsync"></param>
        /// <returns></returns>
        protected virtual RepositoryHolder <KT, ET> ProcessResponse <KT, ET>(TaskStatus rType, TransmissionPayload payload, bool processAsync)
        {
            StatisticsInternal.ActiveDecrement(payload != null ? payload.Extent : TimeSpan.Zero);

            if (processAsync)
            {
                return(new RepositoryHolder <KT, ET>(responseCode: 202, responseMessage: "Accepted"));
            }

            try
            {
                switch (rType)
                {
                case TaskStatus.RanToCompletion:
                    if (payload.Message.Holder == null)
                    {
                        int rsCode = 500;

                        int.TryParse(payload.Message?.Status, out rsCode);

                        string rsMessage = payload.Message?.StatusDescription ?? "Unexpected response (no payload)";

                        return(new RepositoryHolder <KT, ET>(responseCode: rsCode, responseMessage: rsMessage));
                    }

                    try
                    {
                        if (payload.Message.Holder.HasObject)
                        {
                            return((RepositoryHolder <KT, ET>)payload.Message.Holder.Object);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        StatisticsInternal.ErrorIncrement();
                        return(new RepositoryHolder <KT, ET>(responseCode: 500, responseMessage: $"Unexpected cast error: {payload.Message.Holder.Object.GetType().Name}-{ex.Message}"));
                    }

                case TaskStatus.Canceled:
                    StatisticsInternal.ErrorIncrement();
                    return(new RepositoryHolder <KT, ET>(responseCode: 408, responseMessage: "Time out"));

                case TaskStatus.Faulted:
                    StatisticsInternal.ErrorIncrement();
                    return(new RepositoryHolder <KT, ET>()
                    {
                        ResponseCode = (int)PersistenceResponse.GatewayTimeout504, ResponseMessage = "Response timeout."
                    });

                default:
                    StatisticsInternal.ErrorIncrement();
                    return(new RepositoryHolder <KT, ET>(responseCode: 500, responseMessage: rType.ToString()));
                }
            }
            catch (Exception ex)
            {
                Collector?.LogException("Error processing response for task status " + rType, ex);
                throw;
            }
        }
Example #50
0
 /// <summary>
 /// Find elements whose sibling index is greater than the supplied index.
 /// </summary>
 /// <param name="index">0-based index</param>
 /// <returns>elements greater than index</returns>
 public Elements GetElementsByIndexGreaterThan(int index)
 {
     return(Collector.Collect(new Evaluator.IndexGreaterThan(index), this));
 }
Example #51
0
 public void Test_ErrorCreateCollector()
 {
     Collector collector = new Collector(null);
 }
Example #52
0
 /// <summary>
 /// Find elements that have attributes whose values match the supplied regular expression.
 /// </summary>
 /// <param name="key">name of the attribute</param>
 /// <param name="pattern">regular expression to match against attribute values</param>
 /// <returns>elements that have attributes matching this regular expression</returns>
 public Elements GetElementsByAttributeValueMatching(string key, Regex pattern)
 {
     return(Collector.Collect(new Evaluator.AttributeWithValueMatching(key, pattern), this));
 }
Example #53
0
        public void Can_collect_exact_phrase_joined_by_or()
        {
            var dir = Path.Combine(Dir, "Can_collect_exact_phrase_joined_by_or");

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

            var docs = new List <List <Field> >
            {
                new List <Field> {
                    new Field("_id", "0"), new Field("title", "rambo first blood")
                },
                new List <Field> {
                    new Field("_id", "1"), new Field("title", "rambo 2")
                },
                new List <Field> {
                    new Field("_id", "2"), new Field("title", "rocky 2")
                },
                new List <Field> {
                    new Field("_id", "3"), new Field("title", "raiders of the lost ark")
                },
                new List <Field> {
                    new Field("_id", "4"), new Field("title", "the rain man")
                },
                new List <Field> {
                    new Field("_id", "5"), new Field("title", "the good, the bad and the ugly")
                }
            };

            var  writer    = new DocumentUpsertOperation(dir, new Analyzer(), compression: Compression.QuickLz, primaryKey: "_id", documents: docs);
            long indexName = writer.Commit();

            var query = new QueryParser(new Analyzer()).Parse("+title:rocky");

            using (var collector = new Collector(dir, IxInfo.Load(Path.Combine(dir, indexName + ".ix")), new Tfidf()))
            {
                var scores = collector.Collect(query).ToList();

                Assert.AreEqual(1, scores.Count);
                Assert.IsTrue(scores.Any(d => d.DocumentId == 2));
            }

            query = new QueryParser(new Analyzer()).Parse("+title:rambo");

            using (var collector = new Collector(dir, IxInfo.Load(Path.Combine(dir, indexName + ".ix")), new Tfidf()))
            {
                var scores = collector.Collect(query).ToList();

                Assert.AreEqual(2, scores.Count);
                Assert.IsTrue(scores.Any(d => d.DocumentId == 0));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 1));
            }

            query = new QueryParser(new Analyzer()).Parse("+title:rocky title:rambo");

            using (var collector = new Collector(dir, IxInfo.Load(Path.Combine(dir, indexName + ".ix")), new Tfidf()))
            {
                var scores = collector.Collect(query).ToList();

                Assert.AreEqual(3, scores.Count);
                Assert.IsTrue(scores.Any(d => d.DocumentId == 0));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 1));
                Assert.IsTrue(scores.Any(d => d.DocumentId == 2));
            }
        }
Example #54
0
 /// <summary>
 /// Find elements whose own text matches the supplied regular expression.
 /// </summary>
 /// <param name="pattern">regular expression to match text against</param>
 /// <returns>elements matching the supplied regular expression.</returns>
 /// <see cref="Element.OwnText()"/>
 public Elements GetElementsMatchingOwnText(Regex pattern)
 {
     return(Collector.Collect(new Evaluator.MatchesOwn(pattern), this));
 }
Example #55
0
 /// <summary>
 /// Find elements whose sibling index is equal to the supplied index.
 /// </summary>
 /// <param name="index">0-based index</param>
 /// <returns>elements equal to index</returns>
 public Elements GetElementsByIndexEquals(int index)
 {
     return(Collector.Collect(new Evaluator.IndexEquals(index), this));
 }
Example #56
0
        public static async Task <ObservableCollection <Submission> > GetSubmissionsForCollector(Material material, Collector collector)
        {
            try
            {
                var submissions = await GetAllSubmissions();

                ObservableCollection <Submission> submissionsList = new ObservableCollection <Submission>();
                if (submissions != null)
                {
                    foreach (Submission submission in submissions)
                    {
                        if (submission.Collector == collector.Username && submission.Material == material.MaterialID)
                        {
                            submissionsList.Add(submission);
                        }
                    }
                    return(submissionsList);
                }
                return(null);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Firebase Exception SDA7", ex.Message, "OK");

                return(null);
            }
        }
Example #57
0
        public static async Task <ObservableCollection <Submission> > GetProposedSubmissionsByCollector(Collector collector)
        {
            try
            {
                var submissions = await GetAllSubmissions();

                ObservableCollection <Submission> submissionsList = new ObservableCollection <Submission>();
                if (submissions != null)
                {
                    foreach (Submission submission in submissions)
                    {
                        if (submission.Collector == collector.Username && submission.Status == SubmissionViewModel.StatusProposed)
                        {
                            submissionsList.Add(submission);
                        }
                    }
                    return(submissionsList);
                }
                return(null);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Firebase Exception SDA4", ex.Message, "OK");

                return(null);
            }
        }
Example #58
0
 public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID)
 {
     return(scorer.Score(collector, max, firstDocID));
 }
    public override bool checkProceduralPrecondition(GameObject agent)
    {
        // Find bush
        float localRadius = (numTry / 2) + radius;

        numTry++;
        Collider2D[] colliders       = Physics2D.OverlapCircleAll(agent.transform.position, localRadius);
        Collider2D   closestCollider = null;
        float        closestDist     = 0;

        if (colliders == null)
        {
            return(false);
        }
        foreach (Collider2D hit in colliders)
        {
            if (hit.tag != "Bush")
            {
                continue;
            }

            BushEntity bush = (BushEntity)hit.gameObject.GetComponent(typeof(BushEntity));
            if (bush.empty || bush.viewed)
            {
                continue;
            }
            if (closestCollider == null)
            {
                closestCollider = hit;
                closestDist     = (closestCollider.gameObject.transform.position - agent.transform.position).magnitude;
            }
            else
            {
                float dist = (hit.gameObject.transform.position - agent.transform.position).magnitude;
                if (dist < closestDist)
                {
                    // we found a closer one, use it
                    closestCollider = hit;
                    closestDist     = dist;
                }
            }
            Debug.DrawLine(closestCollider.gameObject.transform.position, agent.transform.position, Color.red, 3, false);
        }

        bool isClosest = closestCollider != null;

        if (isClosest)
        {
            targetBush = (BushEntity)closestCollider.gameObject.GetComponent(typeof(BushEntity));
            target     = targetBush.gameObject;
            numTry     = 1;
        }
        // Bush too far
        if (numTry > 10)
        {
            // Evolution process
            Collector collector = (Collector)agent.GetComponent(typeof(Collector));
            if (collector.center.needCarriers())
            {
                collector.instanciateSuccessor("Carrier");
                return(false);
            }

            if (collector.center.needHunters())
            {
                collector.instanciateSuccessor("Hunter");
                return(false);
            }

            if (collector.center.needFishers())
            {
                collector.instanciateSuccessor("Fisher");
                return(false);
            }

            collector.instanciateSuccessor("Farmer");
            return(false);
        }
        return(isClosest);
    }
Example #60
0
 /// <summary>
 /// Find all elements under this element (including self, and children of children).
 /// </summary>
 /// <returns>all elements</returns>
 public Elements GetAllElements()
 {
     return(Collector.Collect(new Evaluator.AllElements(), this));
 }