Search Results

Search found 237 results on 10 pages for 'observer'.

Page 4/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Is it worthwhile to implement observer pattern in PHP?

    - by Extrakun
    I have been meaning to make use of design pattern in PHP, such as the observer pattern, but that I have to recreate the observers' relationship each time the page is loaded pains me. As references are saved as a new concrete objects in session, there is no way to preserve relationships between subscribers and their observers unless you use a GUID or some other properties to form a lookup, and store that property instead. With the cost of recreating the relationships each time a page is loaded, is it worthwhile to use design patterns such as observers in PHP, compared to having a clean design? Any real-world experience to share?

    Read the article

  • C#.NET: How to update multiple .NET pages when a particular event occurs in one .Net page? In another words how to use Observer pattern(Publish and subscribe to events)

    Problem: Suppose you have a scenario in which you have to update multiple pages when an event occurs in main page. For example imagine you have a main page where you are dispalying a tab control. This tab control has 3 tab pages where you are loading 3 different user controls. On click of an update button in main page imagine if you have do something in all the 3 tab panels. In other words an event in main page has to be handled in many other pages. An event in main page which contains the tab control has to be handled in all the tab panels(user controls) Answer: Use Observer pattern Define a base page for the page that contains the tab control. Main page which contains the tab: Baseline_Baseline Basepage for the above main page: BaselineBasePage User control that has to be udpated for an event in main page: Baseline_PriorNonDeloitte Source Code: public class BaselineBasePage : System.Web.UI.Page { IList lstControls = new List(); public void Add(IObserver userControl) { lstControls.Add(userControl); } public void Remove(IObserver userControl) { lstControls.Remove(userControl); } public void RemoveAllUserControls() { lstControls.Clear(); } public void Update(SaveEventArgs e) { foreach (IObserver LobjControl in lstControls) { LobjControl.Save(e); } } } public interface IObserver { void Update(SaveEventArgs e); } public partial class Baseline_Baseline : BaselineBasePage { . . . this.Add(_ucPI); this.Add(_ucPI1); protected void abActionBar_saveClicked(object sender, EventArgs e) { SaveEventArgs se = new SaveEventArgs(); se.TabType = (BaselineTabType)tcBaseline.ActiveTabIndex; this.Update(se); } } Public class Baseline_PriorNonDeloitte : System.Web.UI.UserControl,IObserver { public void Update(SaveEventArgs e) { } } More info at: http://www.dofactory.com/Patterns/PatternObserver.aspx span.fullpost {display:none;}

    Read the article

  • C#.NET: How to update multiple .NET pages when a particular event occurs in one .Net page? In another words how to use Observer pattern(Publish and subscribe to events)

    Problem: Suppose you have a scenario in which you have to update multiple pages when an event occurs in main page. For example imagine you have a main page where you are dispalying a tab control. This tab control has 3 tab pages where you are loading 3 different user controls. On click of an update button in main page imagine if you have do something in all the 3 tab panels. In other words an event in main page has to be handled in many other pages. An event in main page which contains the tab control has to be handled in all the tab panels(user controls) Answer: Use Observer pattern Define a base page for the page that contains the tab control. Main page which contains the tab: Baseline_Baseline Basepage for the above main page: BaselineBasePage User control that has to be udpated for an event in main page: Baseline_PriorNonDeloitte Source Code: public class BaselineBasePage : System.Web.UI.Page { IList lstControls = new List(); public void Add(IObserver userControl) { lstControls.Add(userControl); } public void Remove(IObserver userControl) { lstControls.Remove(userControl); } public void RemoveAllUserControls() { lstControls.Clear(); } public void Update(SaveEventArgs e) { foreach (IObserver LobjControl in lstControls) { LobjControl.Save(e); } } } public interface IObserver { void Update(SaveEventArgs e); } public partial class Baseline_Baseline : BaselineBasePage { . . . this.Add(_ucPI); this.Add(_ucPI1); protected void abActionBar_saveClicked(object sender, EventArgs e) { SaveEventArgs se = new SaveEventArgs(); se.TabType = (BaselineTabType)tcBaseline.ActiveTabIndex; this.Update(se); } } Public class Baseline_PriorNonDeloitte : System.Web.UI.UserControl,IObserver { public void Update(SaveEventArgs e) { } } More info at: http://www.dofactory.com/Patterns/PatternObserver.aspx span.fullpost {display:none;}

    Read the article

  • Where is the error in this code.

    - by basit74
    Hello, Here is my code snippt. But the code is breaking after inner for loop. But getting no error message. Any idea? Thanks. var lastnames = document.getElementsByClassName('box_nachname'); var firstnames = document.getElementsByClassName('box_vorname'); var teilnehmer = document.getElementsByClassName('select'); observers = []; // iterate over nachname array. for (var i = 0; i < lastnames.length; i++) { // Create an observer instance. observers[i] = new Observer(); // Subscribe oberser object. for(idx in teilnehmer) { if(teilnehmer[idx].id.split("_")[0].toLowerCase() !== "zl") { var anynum = function(element) { observers[i].subscribe(element, updateTeilnehmerSelectbox); }(teilnehmer[idx]); } } //on blur the Observer fire the updated info to all the subscribers. var anynumNachname = function(j, element, value, observer) { cic.addEvent(lastnames[j], 'blur', observer.fire(element, value)); } (i, lastnames[i], lastnames[i].value, observers[i]); cic.addEvent(firstnames[i], 'blur', function(element, value, observer) {observer.fire(element, value)}(lastnames[i], lastnames[i].value, observers[i])); }

    Read the article

  • Can LINQ expression classes implement the observer pattern instead of deferred execution?

    - by Tormod
    Hi. We have issues within an application using a state machine. The application is implemented as a windows service and is iteration based (it "foreaches" itself through everything) and there are myriads of instances being processed by the state machine. As I'm reading the MEAP version of Jon Skeets book "C# in Depth, 2nd ed", I'm wondering if I can change the whole thing to use linq expression instances so that guards and conditions are represented using expression trees. We are building many applications on this state machine engine and would probably greatly benefit from the new Expression tree visualizer in VS 2010 Now, simple example. If I have an expression tree where there is an OR Expression condition with two sub nodes, is there any way that these can implement the observer pattern so that the expression tree becomes event driven? If a condition change, it should notify its parent node (the OR node). Since the OR node then changes from "false" to "true", then it should notify ITS parent and so on. I love the declarative model of expression trees, but the deferred execution model works in opposite direction of the control flow if you want event based "live" conditions. Am I off on a wild goose chase here? Or is there some concept in the BCL that may help me achieve this?

    Read the article

  • Android Persistent ContentObserver

    - by Lucas Stark
    Are content observers persistent in Android? If I create a content observer in an activity, will that observer continue to run until I remove the observer. Basically I am creating a service for SMS, where on receive and on send I post the SMS out to a web service, so I can check my messages with out having my phone. If the content observer is tied to the Activity's life, how can I create a ContentObserver that will always receive notifications on content:/sms/

    Read the article

  • Type problem with Observable.Create from Boo

    - by Tristan
    I'm trying to use Reactive Extensions from Boo and am running into type problems. Here's the basic example: def OnSubscribe(observer as IObservable[of string]) as callable: print "subscribing" def Dispose(): print "disposing" return Dispose observable = System.Linq.Observable.Create[of string](OnSubscribe) observer = System.Linq.Observer.Create[of string]({x as string | print x}) observable.Subscribe(observer) The Subscribe here gives a System.InvalidCastException: Cannot cast from source type to destination type. The issue appears to be with how I'm creating the observable, but I've struggled to see where the type problem arises from. Ideas?

    Read the article

  • Java Synchronized List Deadlock

    - by portoalet
    From Effective Java 2nd edition item 67 page 266-268: The background thread calls s.removeObserver, which attempts to lock observers, but it can’t acquire the lock, because the main thread already has the lock. All the while, the main thread is waiting for the background thread to finish removing the observer, which explains the deadlock. I am trying to find out which threads deadlock in the main method by using ThreadMXBean (http://stackoverflow.com/questions/1102359/programmatic-deadlock-detection-in-java) , but why does it not return the deadlocked threads? I used a new Thread to run the ThreadMXBean detection. public class ObservableSet<E> extends ForwardingSet<E> { public ObservableSet(Set<E> set) { super(set); } private final List<SetObserver<E>> observers = new ArrayList<SetObserver<E>>(); public void addObserver(SetObserver<E> observer) { synchronized(observers) { observers.add(observer); } } public boolean removeObserver(SetObserver<E> observer) { synchronized(observers) { return observers.remove(observer); } } private void notifyElementAdded(E element) { synchronized(observers) { for (SetObserver<E> observer : observers) observer.added(this, element); } } @Override public boolean add(E element) { boolean added = super.add(element); if (added) notifyElementAdded(element); return added; } @Override public boolean addAll(Collection<? extends E> c) { boolean result = false; for (E element : c) result|=add(element); //callsnotifyElementAdded return result; } public static void main(String[] args) { ObservableSet<Integer> set = new ObservableSet<Integer>(new HashSet<Integer>()); final ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); Thread t = new Thread(new Runnable() { @Override public void run() { while( true ) { long [] threadIds = threadMxBean.findDeadlockedThreads(); if( threadIds != null) { ThreadInfo[] infos = threadMxBean.getThreadInfo(threadIds); for( ThreadInfo threadInfo : infos) { StackTraceElement[] stacks = threadInfo.getStackTrace(); for( StackTraceElement stack : stacks ) { System.out.println(stack.toString()); } } } try { System.out.println("Sleeping.."); TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); t.start(); set.addObserver(new SetObserver<Integer>() { public void added(ObservableSet<Integer> s, Integer e) { ExecutorService executor = Executors.newSingleThreadExecutor(); final SetObserver<Integer> observer = this; try { executor.submit(new Runnable() { public void run() { s.removeObserver(observer); } }).get(); } catch (ExecutionException ex) { throw new AssertionError(ex.getCause()); } catch (InterruptedException ex) { throw new AssertionError(ex.getCause()); } finally { executor.shutdown(); } } }); for (int i = 0; i < 100; i++) set.add(i); } } public interface SetObserver<E> { // Invoked when an element is added to the observable set void added(ObservableSet<E> set, E element); } // ForwardingSet<E> simply wraps another Set and forwards all operations to it.

    Read the article

  • Designing for an algorithm that reports progress

    - by Stefano Borini
    I have an iterative algorithm and I want to print the progress. However, I may also want it not to print any information, or to print it in a different way, or do other logic. In an object oriented language, I would perform the following solutions: Solution 1: virtual method have the algorithm class MyAlgoClass which implements the algo. The class also implements a virtual reportIteration(iterInfo) method which is empty and can be reimplemented. Subclass the MyAlgoClass and override reportIteration so that it does what it needs to do. This solution allows you to carry additional information (for example, the file unit) in the reimplemented class. I don't like this method because it clumps together two functionalities that may be unrelated, but in GUI apps it may be ok. Solution 2: observer pattern the algorithm class has a register(Observer) method, keeps a list of the registered observers and takes care of calling notify() on each of them. Observer::notify() needs a way to get the information from the Subject, so it either has two parameters, one with the Subject and the other with the data the Subject may pass, or just the Subject and the Observer is now in charge of querying it to fetch the relevant information. Solution 3: callbacks I tend to see the callback method as a lightweight observer. Instead of passing an object, you pass a callback, which may be a plain function, but also an instance method in those languages that allow it (for example, in python you can because passing an instance method will remain bound to the instance). C++ however does not allow it, because if you pass a pointer to an instance method, this will not be defined. Please correct me on this regard, my C++ is quite old. The problem with callbacks is that generally you have to pass them together with the data you want the callback to be invoked with. Callbacks don't store state, so you have to pass both the callback and the state to the Subject in order to find it at callback execution, together with any additional data the Subject may provide about the event is reporting. Question My question is relative to the fact that I need to implement the opening problem in a language that is not object oriented, namely Fortran 95, and I am fighting with my usual reasoning which is based on python assumptions and style. I think that in Fortran the concept is similar to C, with the additional trouble that in C you can store a function pointer, while in Fortran 95 you can only pass it around. Do you have any comments, suggestions, tips, and quirks on this regard (in C, C++, Fortran and python, but also in any other language, so to have a comparison of language features that can be exploited on this regard) on how to design for an algorithm that must report progress to some external entity, using state from both the algorithm and the external entity ?

    Read the article

  • Observer not clearing cache in Rails 2.3.2 - please help.

    - by Jason
    Hi, We are using Rails 2.3.2, Ruby 1.8 & memcache. In my Posts controller I have: cache_sweeper Company::Caching::Sweepers::PostSweeper, :only => [:save_post] I have created the following module: module Company module Caching module Sweepers class PostSweeper < ActionController::Caching::Sweeper observe Post def after_save(post) Rails.cache.delete("post_" + post.permalink) end end end end end but when the save_post method is invoked, the cache is never deleted. Just hoping someone can see what I am doing wrong here. Thanks.

    Read the article

  • Where do I attach the StoreKit delegate and observer in a Cocos2d App?

    - by Jeff B
    I have figured out how all of the StoreKit stuff works and have actually tested working code... however, I have a problem. I made my "store" layer/scene the SKProductsRequestDelegate. Is this the correct thing to do? I get the initial product info like so: SKProductsRequest *productRequest = [[SKProductsRequest alloc] initWithProductIdentifiers: productIDs]; [productRequest setDelegate: self]; [productRequest start]; The problem is that if I transition to a new scene when a request is in progress, the current layer is retained by the productRequest. This means that touches on my new scene/layer are handled by both the new layer and the old layer. I could cancel the productRequest when leaving the scene, but: I do not know if it is in progress at that point. I cannot release it because it may or may not have been released by the request delegates. There has got to be a better way to do this. I could make the delegate a class external to the current layer, but then I do not know how to easily update the layer with the product information when the handler is called.

    Read the article

  • Would Python's Twisted library be the best case for an observer type pattern?

    - by beagleguy
    hi all, I'm developing a system where a queue will be filled with millions of items I need a process that reads items from the queue constantly and then sends those items out to registered clients. I'm thinking about using twisted for this, having the queue reader be a twisted server listening on a tcp port then clients can connect on that port and when an item is pulled from the queue the server writes it out to all the clients. Does that sound like something that twisted would be ideal for? Does anyone know of any sample code out there that may do something similar? thanks

    Read the article

  • How to initiate chatting between two clients and two clients only, using applets and servlets?

    - by mithun1538
    Hello everyone, I first need to apologize for my earlier questions. (You can check my profile for them)They seemed to ask more questions than give answers. Hence, I am laying down the actual question that started all them absurd questions. I am trying to design a chat applet. Till now, I have coded the applet, servlet and communication between the applet and the servlet. The code in the servlet side is such that I was able to establish chatting between clients using the applets, but the code was more like a broadcast all feature, i.e. all clients would be chatting with each other. That was my first objective when I started designing the chat applet. The second step is chatting between only two specific users, much like any other chat application we have. So this was my idea for it: I create an instance of the servlet that has the 'broadcast-all' code. I then pass the address of this instance to the respective clients. 2 client applets use the address to then chat. Technically the code is 'broadcast-all', but since only 2 clients are connected to it, it gives the chatting between two clients feature. Thus, groups of 2 clients have different instances of the same servlet, and each instance handles chatting between two clients at a max. However, as predicted, the idea didn't materialize! I tried to create an instance of the servlet but the only solution for that was using sessions on the servlet side, and I don't know how to use this session for later communications. I then tried to modify my broadcast-all code. In that code, I was using classes that implemented Observer and Observable interfaces. So the next idea that I got was: Create a new object of the Observable class(say class_1). This object be common to 2 clients. 2 clients that wish to chat will use same object of the class_1. 2 other clients will use a different object of class_1. But the problem here lies with the class that implements the Observer interface(say class_2). Since this has observers monitoring the same type of class, namely class_1, how do I establish an observer monitoring one object of class_1 and another observer monitoring another object of the same class class_1 (Because notifyObservers() would notify all the observers and I can't assign a particular observer to a particular object)? I first decided to ask individual problems, like how to create instances of servlets, using objects of observable and observer and so on in stackoverflow... but I got confused even more. Can anyone give me an idea how to establish chatting between two clients only?(I am using Http and not sockets or RMI). Regards, Mithun. P.S. Thanks to all who replied to my previous (absurd) queries. I should have stated the purpose earlier so that you guys could help me better.

    Read the article

  • How should I structure my turn based engine to allow flexibility for players/AI and observation?

    - by Reefpirate
    I've just started making a Turn Based Strategy engine in GameMaker's GML language... And I was cruising along nicely until it came time to handle the turn cycle, and determining who is controlling what player, and also how to handle the camera and what is displayed on screen. Here's an outline of the main switch happening in my main game loop at the moment: switch (GameState) { case BEGIN_TURN: // Start of turn operations/routines break; case MID_TURN: switch (PControlledBy[Turn]) { case HUMAN: switch (MidTurnState) { case MT_SELECT: // No units selected, 'idle' UI state break; case MT_MOVE: // Unit selected and attempting to move break; case MT_ATTACK: break; } break; case COMPUTER: // AI ROUTINES GO HERE break; case OBSERVER: // OBSERVER ROUTINES GO HERE break; } break; case END_TURN: // End of turn routines/operations, and move Turn to next player break; } Now, I can see a couple of problems with this set-up already... But I don't have any idea how to go about making it 'right'. Turn is a global variable that stores which player's turn it is, and the BEGIN_TURN and END_TURN states make perfect sense to me... But the MID_TURN state is baffling me because of the things I want to happen here: If there are players controlled by humans, I want the AI to do it's thing on its turn here, but I want to be able to have the camera follow the AI as it makes moves in the human player's vision. If there are no human controlled player's, I'd like to be able to watch two or more AI's battle it out on the map with god-like 'observer' vision. So basically I'm wondering if there are any resources for how to structure a Turn Based Strategy engine? I've found lots of writing about pathfinding and AI, and those are all great... But when it comes to handling the turn structure and the game states I am having trouble finding any resources at all. How should the states be divided to allow flexibility between the players and the controllers (HUMAN, COMPUTER, OBSERVER)? Also, maybe if I'm on the right track I just need some reassurance before I lay down another few hundred lines of code...

    Read the article

  • To SYNC or not to SYNC – Part 4

    - by AshishRay
    This is Part 4 of a multi-part blog article where we are discussing various aspects of setting up Data Guard synchronous redo transport (SYNC). In Part 1 of this article, I debunked the myth that Data Guard SYNC is similar to a two-phase commit operation. In Part 2, I discussed the various ways that network latency may or may not impact a Data Guard SYNC configuration. In Part 3, I talked in details regarding why Data Guard SYNC is a good thing, and the distance implications you have to keep in mind. In this final article of the series, I will talk about how you can nicely complement Data Guard SYNC with the ability to failover in seconds. Wait - Did I Say “Seconds”? Did I just say that some customers do Data Guard failover in seconds? Yes, Virginia, there is a Santa Claus. Data Guard has an automatic failover capability, aptly called Fast-Start Failover. Initially available with Oracle Database 10g Release 2 for Data Guard SYNC transport mode (and enhanced in Oracle Database 11g to support Data Guard ASYNC transport mode), this capability, managed by Data Guard Broker, lets your Data Guard configuration automatically failover to a designated standby database. Yes, this means no human intervention is required to do the failover. This process is controlled by a low footprint Data Guard Broker client called Observer, which makes sure that the primary database and the designated standby database are behaving like good kids. If something bad were to happen to the primary database, the Observer, after a configurable threshold period, tells that standby, “Your time has come, you are the chosen one!” The standby dutifully follows the Observer directives by assuming the role of the new primary database. The DBA or the Sys Admin doesn’t need to be involved. And - in case you are following this discussion very closely, and are wondering … “Hmmm … what if the old primary is not really dead, but just network isolated from the Observer or the standby - won’t this lead to a split-brain situation?” The answer is No - It Doesn’t. With respect to why-it-doesn’t, I am sure there are some smart DBAs in the audience who can explain the technical reasons. Otherwise - that will be the material for a future blog post. So - this combination of SYNC and Fast-Start Failover is the nirvana of lights-out, integrated HA and DR, as practiced by some of our advanced customers. They have observed failover times (with no data loss) ranging from single-digit seconds to tens of seconds. With this, they support operations in industry verticals such as manufacturing, retail, telecom, Internet, etc. that have the most demanding availability requirements. One of our leading customers with massive cloud deployment initiatives tells us that they know about server failures only after Data Guard has automatically completed the failover process and the app is back up and running! Needless to mention, Data Guard Broker has the integration hooks for interfaces such as JDBC and OCI, or even for custom apps, to ensure the application gets automatically rerouted to the new primary database after the database level failover completes. Net Net? To sum up this multi-part blog article, Data Guard with SYNC redo transport mode, plus Fast-Start Failover, gives you the ideal triple-combo - that is, it gives you the assurance that for critical outages, you can failover your Oracle databases: very fast without human intervention, and without losing any data. In short, it takes the element of risk out of critical IT operations. It does require you to be more careful with your network and systems planning, but as far as HA is concerned, the benefits outweigh the investment costs. So, this is what we in the MAA Development Team believe in. What do you think? How has your deployment experience been? We look forward to hearing from you!

    Read the article

  • When should I observe javascript events on window vs. document vs. document.body?

    - by brahn
    I'm using prototype.js for my web app, and I have everything running on chrome, safari, and firefox. I am now working on IE8 compatibility. As I've been debugging in IE, I've noticed that there are javascript events for which I have previously set an observer on the window, e.g. Event.observe(window, eventType, function () {...}); (where eventType might be "dom:loaded", "keypress", etc.) and it works just fine in Chrome/Safari/Firefox. However, in IE the observer never fires. In at least some cases I could get this to work on IE by instead placing the observer on something other than window, e.g. document (in the case of "dom:loaded") or document.body (in the case of "keypress"). However, this is all trial-and-error. Is there some more systematic way to determine where to place these observers such that the results will be cross-browser compatible? Thanks!

    Read the article

  • Accessing rails flash[:notice] in a model

    - by titaniumdecoy
    I am trying to assign a message to flash[:notice] in a model observer. This question has already been asked: Ruby on Rails: Observers and flash[:notice] messages? However, I get the following error message when I try to access it in my model: undefined local variable or method `flash' for #<ModelObserver:0x2c1742c> Here is my code: class ModelObserver < ActiveRecord::Observer observe A, B, C def after_save(model) puts "Model saved" flash[:notice] = "Model saved" end end I know the method is being called because "Model saved" is printed to the terminal. Is it possible to access the flash inside an observer, and if so, how?

    Read the article

  • Listening to another window resize events in C#

    - by Steve
    Hi all I am implementing a small application (observer) that needs to "attach" itself to the bottom of another window (observed). The latter is not a window inside the application. At this moment I solved by getting the hWnd of the window and querying periodically in a thread the location of the observed window, moving the observer window accordingly. However this is a very inelegant solution. What I would like to do is to listen to the resize event of the observed window so that the observer will react only when necessary. I assume I should use a hook, and I found plenty of ways of doing it, but my lack of knowledge of the C WinAPI is blocking me in understanding which hook I need to create and how (pinvoke/parameters/etc). I'm pretty sure this is quite trivial, and some of you familiar with C/C++ and WinAPI will have the answer ready at hand ;) Thanks

    Read the article

  • java.util.Observable, will clients complete executing their update() before continuing

    - by jax
    When I call: setChanged(); notifyObservers() on a java.until.Observable class, will all the listening Observer objects complete execution of their udpate() methods - assuming we are running in the same Thread - before the java.until.Observable class continues running? This is important because I will be sending a few messages through the notifyObservers(Object o) method in quick concession, it is important that each Observer class has finished its method before the new one though. I understand that the order of execution for each Observer class may vary when we call notifyObservers() - it is just important that the order of method execution for each individual instance is in order.

    Read the article

  • Using Subjects to Deploy Queries Dynamically

    - by Roman Schindlauer
    In the previous blog posting, we showed how to construct and deploy query fragments to a StreamInsight server, and how to re-use them later. In today’s posting we’ll integrate this pattern into a method of dynamically composing a new query with an existing one. The construct that enables this scenario in StreamInsight V2.1 is a Subject. A Subject lets me create a junction element in an existing query that I can tap into while the query is running. To set this up as an end-to-end example, let’s first define a stream simulator as our data source: var generator = myApp.DefineObservable(     (TimeSpan t) => Observable.Interval(t).Select(_ => new SourcePayload())); This ‘generator’ produces a new instance of SourcePayload with a period of t (system time) as an IObservable. SourcePayload happens to have a property of type double as its payload data. Let’s also define a sink for our example—an IObserver of double values that writes to the console: var console = myApp.DefineObserver(     (string label) => Observer.Create<double>(e => Console.WriteLine("{0}: {1}", label, e)))     .Deploy("ConsoleSink"); The observer takes a string as parameter which is used as a label on the console, so that we can distinguish the output of different sink instances. Note that we also deploy this observer, so that we can retrieve it later from the server from a different process. Remember how we defined the aggregation as an IQStreamable function in the previous article? We will use that as well: var avg = myApp     .DefineStreamable((IQStreamable<SourcePayload> s, TimeSpan w) =>         from win in s.TumblingWindow(w)         select win.Avg(e => e.Value))     .Deploy("AverageQuery"); Then we define the Subject, which acts as an observable sequence as well as an observer. Thus, we can feed a single source into the Subject and have multiple consumers—that can come and go at runtime—on the other side: var subject = myApp.CreateSubject("Subject", () => new Subject<SourcePayload>()); Subject are always deployed automatically. Their name is used to retrieve them from a (potentially) different process (see below). Note that the Subject as we defined it here doesn’t know anything about temporal streams. It is merely a sequence of SourcePayloads, without any notion of StreamInsight point events or CTIs. So in order to compose a temporal query on top of the Subject, we need to 'promote' the sequence of SourcePayloads into an IQStreamable of point events, including CTIs: var stream = subject.ToPointStreamable(     e => PointEvent.CreateInsert<SourcePayload>(e.Timestamp, e),     AdvanceTimeSettings.StrictlyIncreasingStartTime); In a later posting we will show how to use Subjects that have more awareness of time and can be used as a junction between QStreamables instead of IQbservables. Having turned the Subject into a temporal stream, we can now define the aggregate on this stream. We will use the IQStreamable entity avg that we defined above: var longAverages = avg(stream, TimeSpan.FromSeconds(5)); In order to run the query, we need to bind it to a sink, and bind the subject to the source: var standardQuery = longAverages     .Bind(console("5sec average"))     .With(generator(TimeSpan.FromMilliseconds(300)).Bind(subject)); Lastly, we start the process: standardQuery.Run("StandardProcess"); Now we have a simple query running end-to-end, producing results. What follows next is the crucial part of tapping into the Subject and adding another query that runs in parallel, using the same query definition (the “AverageQuery”) but with a different window length. We are assuming that we connected to the same StreamInsight server from a different process or even client, and thus have to retrieve the previously deployed entities through their names: // simulate the addition of a 'fast' query from a separate server connection, // by retrieving the aggregation query fragment // (instead of simply using the 'avg' object) var averageQuery = myApp     .GetStreamable<IQStreamable<SourcePayload>, TimeSpan, double>("AverageQuery"); // retrieve the input sequence as a subject var inputSequence = myApp     .GetSubject<SourcePayload, SourcePayload>("Subject"); // retrieve the registered sink var sink = myApp.GetObserver<string, double>("ConsoleSink"); // turn the sequence into a temporal stream var stream2 = inputSequence.ToPointStreamable(     e => PointEvent.CreateInsert<SourcePayload>(e.Timestamp, e),     AdvanceTimeSettings.StrictlyIncreasingStartTime); // apply the query, now with a different window length var shortAverages = averageQuery(stream2, TimeSpan.FromSeconds(1)); // bind new sink to query and run it var fastQuery = shortAverages     .Bind(sink("1sec average"))     .Run("FastProcess"); The attached solution demonstrates the sample end-to-end. Regards, The StreamInsight Team

    Read the article

  • Rails - asynchronous tasks, forked processes, best practices

    - by LisaPatton
    I'm using a Observer on my classes. When one of the records is created/updated I need to notfify another service (via a URL call). What is the best way to do this to avoid slowing down my class? Would using a gem liked delayed_job be overkill? In my Observer's after_update() / after_create() I just want to launch a thread that calls the URL...

    Read the article

  • Flex: Constant strings in metadata

    - by Daniel Engmann
    I have something like public class Controller { [Observer("fetchEmployeesEvent")] public function fetchEmployees() : void { //doSomething } } and I want something like public class Controller { public static const FETCH_EMPLOYEES_EVENT : String = "fetchEmployeesEvent"; [Observer(FETCH_EMPLOYEES_EVENT)] public function fetchEmployees() : void { //doSomething } } My problem is that only the first code snippet works. Flex seems to ignore the constant FETCH_EMPLOYEES_EVENT in the metadata-tag. My question is: Is it somehow possible to use constant strings in metadata?

    Read the article

  • Strategies for testing reactive, asynchronous code

    - by Arne
    I am developing a data-flow oriented domain-specific language. To simplify, let's just look at Operations. Operations have a number of named parameters and can be asked to compute their result using their current state. To decide when an Operation should produce a result, it gets a Decision that is sensitive to which parameter got a value from who. When this Decision decides that it is fulfilled, it emits a Signal using an Observer. An Accessor listens for this Signal and in turn calls the Result method of the Operation in order to multiplex it to the parameters of other Operations. So far, so good, nicely decoupled design, composable and reusable and, depending on the specific Observer used, as asynchronous as you want it to be. Now here's my problem: I would love to start coding actual Tests against this design. But with an asynchronous Observer... how should I know that the whole signal-and-parameters-plumbing worked? Do I need to use time outs while waiting for a Signal in order to say that it was emitted successfully or not? How can I be, formally, sure that the Signal will not be emitted if I just wait a little longer (halting problem? ;-)) And, how can I be sure that the Signal was emitted because it was me who set a parameter, and not another Operation? It might well be that my test comes to early and sees a Signal that was emitted way before my setting a parameter caused a Decision to emit it. Currently, I guess the trivial cases are easy to test, but as soon as I want to test complex many-to-many - situations between operations I must resort to hoping that the design Just Works (tm)...

    Read the article

  • PHP Aspect Oriented Design

    - by Devin Dixon
    This is a continuation of this Code Review question. What was taken away from that post, and other aspect oriented design is it is hard to debug. To counter that, I implemented the ability to turn tracing of the design patterns on. Turning trace on works like: //This can be added anywhere in the code Run::setAdapterTrace(true); Run::setFilterTrace(true); Run::setObserverTrace(true); //Execute the functon echo Run::goForARun(8); In the actual log with the trace turned on, it outputs like so: adapter 2012-02-12 21:46:19 {"type":"closure","object":"static","call_class":"\/public_html\/examples\/design\/ClosureDesigns.php","class":"Run","method":"goForARun","call_method":"goForARun","trace":"Run::goForARun","start_line":68,"end_line":70} filter 2012-02-12 22:05:15 {"type":"closure","event":"return","object":"static","class":"run_filter","method":"\/home\/prodigyview\/public_html\/examples\/design\/ClosureDesigns.php","trace":"Run::goForARun","start_line":51,"end_line":58} observer 2012-02-12 22:05:15 {"type":"closure","object":"static","class":"run_observer","method":"\/home\/prodigyview\/public_html\/public\/examples\/design\/ClosureDesigns.php","trace":"Run::goForARun","start_line":61,"end_line":63} When the information is broken down, the data translates to: Called by an adapter or filter or observer The function called was a closure The location of the closure Class:method the adapter was implemented on The Trace of where the method was called from Start Line and End Line The code has been proven to work in production environments and features various examples of to implement, so the proof of concept is there. It is not DI and accomplishes things that DI cannot. I wouldn't call the code boilerplate but I would call it bloated. In summary, the weaknesses are bloated code and a learning curve in exchange for aspect oriented functionality. Beyond the normal fear of something new and different, what are other weakness in this implementation of aspect oriented design, if any? PS: More examples of AOP here: https://github.com/ProdigyView/ProdigyView/tree/master/examples/design

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >