There’s a lot of confusion about how asynchronous communication works in RIA’s
such as Silverlight, GWT and Javascript. When I start talking about the problems of
concurrency control, many people tell me that there aren’t any concurrency problems
since everything runs in a single thread. [1]
It’s important to understand the basics of what is going on when you’re writing
asynchronous code, so I’ve put together a simple example to show how execution
works in RIA’s and how race conditions are possible. This example applies to
Javascript, Silverlight, GWT and Flex, as well as a number of other environments
based on Javascript. This example doesn’t represent best practices, but rather what
can happen when you’re not using a proactive strategy that eliminates concurrency problems
The document discusses using Hibernate for database persistence in layered Java applications. It describes using Hibernate with servlet engines and the thread-local session pattern to share a single database session across request processing. It also discusses implementing data access with DAOs and a session facade pattern to provide coarse-grained services. Finally, it briefly mentions implementing audit logging for persistent objects by marking classes, defining log fields, and using a Hibernate interceptor.
The document provides an introduction to asynchronous JavaScript. It discusses callbacks and their disadvantages like callback hell. Promises are introduced as a better way to handle asynchronous code by making it easier to write and chain asynchronous operations. Async/await is described as syntactic sugar that allows asynchronous code to be written more readably in a synchronous style using await and try/catch. Key aspects like the event loop, microtask queue, and Promise methods like all and race are explained. Overall the document aims to help understand what makes asynchronous code different and newer methods like promises and async/await that improve handling asynchronous operations in JavaScript.
This document provides an overview of RxAndroid and RxJava. It discusses key concepts like Observables that emit items, Subscribers that receive emitted items and complete/error notifications, and Operators like map that transform Observables. It shows how to create a simple Observable, subscribe to it, and use operators like map. It also demonstrates integrating Rx with Android by observing button clicks and updating UI, merging multiple Observables, and using scan to increment a counter and calculate a running sum from emitted values.
This talk was delivered at JavaOne 2013, together with Andrzej Grzesik. We mention the new Date APIs, changes to Collections as well as Streams APIs and of course... Lambdas!
ReactiveCocoa is a framework for building reactive applications using signals that emit events. It allows defining data flows where events are propagated through operations like map, filter, and flatten. Signals can represent UI controls, network requests, or other asynchronous events. This allows building reactive user interfaces where UI is updated automatically in response to data changes. Operations are chained fluently on signals to transform and combine events.
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
This presentation is about JavaScript Promise. Topics covered in this session are:
1. Asynchronous processing in JavaScript
2. Callbacks and Callback hell
3. Promises arrive in JavaScript!
4. Constructing a Promise
5. Promise states
6. Promises chaining and transformation
7. Error handling
8. Promise.all() and Promise.race()
The document provides examples of how to perform various actions in QuickTest Professional (QTP) such as selecting items from a web list, setting values in a web edit, reading and writing data to text files, and using descriptive programming. Key examples include selecting the third item from a web list, setting the pincode value to "23" in a web edit, reading lines from one text file and writing them to another file, and setting the value "oshoworld" in the first web edit on a page using a descriptive program.
The document discusses Reactive programming concepts using RxJava. It defines key RxJava terms like Observable and Observer. An Observable is the source of events, while an Observer handles incoming events. It also covers how to create Observables from sources like arrays, intervals, and network calls. Operators like filter, map, take, and defaultIfEmpty are demonstrated for transforming Observables.
The document discusses using Hibernate for database persistence in layered Java applications. It describes using Hibernate with servlet engines and the thread-local session pattern to share a single database session across request processing. It also discusses implementing data access with DAOs and a session facade pattern to provide coarse-grained services. Finally, it briefly mentions implementing audit logging for persistent objects by marking classes, defining log fields, and using a Hibernate interceptor.
The document provides an introduction to asynchronous JavaScript. It discusses callbacks and their disadvantages like callback hell. Promises are introduced as a better way to handle asynchronous code by making it easier to write and chain asynchronous operations. Async/await is described as syntactic sugar that allows asynchronous code to be written more readably in a synchronous style using await and try/catch. Key aspects like the event loop, microtask queue, and Promise methods like all and race are explained. Overall the document aims to help understand what makes asynchronous code different and newer methods like promises and async/await that improve handling asynchronous operations in JavaScript.
This document provides an overview of RxAndroid and RxJava. It discusses key concepts like Observables that emit items, Subscribers that receive emitted items and complete/error notifications, and Operators like map that transform Observables. It shows how to create a simple Observable, subscribe to it, and use operators like map. It also demonstrates integrating Rx with Android by observing button clicks and updating UI, merging multiple Observables, and using scan to increment a counter and calculate a running sum from emitted values.
This talk was delivered at JavaOne 2013, together with Andrzej Grzesik. We mention the new Date APIs, changes to Collections as well as Streams APIs and of course... Lambdas!
ReactiveCocoa is a framework for building reactive applications using signals that emit events. It allows defining data flows where events are propagated through operations like map, filter, and flatten. Signals can represent UI controls, network requests, or other asynchronous events. This allows building reactive user interfaces where UI is updated automatically in response to data changes. Operations are chained fluently on signals to transform and combine events.
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
This presentation is about JavaScript Promise. Topics covered in this session are:
1. Asynchronous processing in JavaScript
2. Callbacks and Callback hell
3. Promises arrive in JavaScript!
4. Constructing a Promise
5. Promise states
6. Promises chaining and transformation
7. Error handling
8. Promise.all() and Promise.race()
The document provides examples of how to perform various actions in QuickTest Professional (QTP) such as selecting items from a web list, setting values in a web edit, reading and writing data to text files, and using descriptive programming. Key examples include selecting the third item from a web list, setting the pincode value to "23" in a web edit, reading lines from one text file and writing them to another file, and setting the value "oshoworld" in the first web edit on a page using a descriptive program.
The document discusses Reactive programming concepts using RxJava. It defines key RxJava terms like Observable and Observer. An Observable is the source of events, while an Observer handles incoming events. It also covers how to create Observables from sources like arrays, intervals, and network calls. Operators like filter, map, take, and defaultIfEmpty are demonstrated for transforming Observables.
Learn You a ReactiveCocoa for Great GoodJason Larsen
This document provides an overview of ReactiveCocoa, a framework for working with asynchronous data streams in a reactive and declarative way. It discusses key concepts in reactive and functional programming like streams, signals, sequences, and transformations like map, filter, and fold. It shows how to combine streams, inject side effects safely, and work with subjects. It recommends resources for learning more about ReactiveCocoa and reactive programming best practices.
This is my talk on ReactiveCocoa at @cocoaheads_at in Vienna. I gave an introduction to reactive programming with RAC and an overview of signals and subscribers, and how they can be used to create useful patterns.
Presented at YOW! Connected 2015 (Melbourne) by Jeames Bone & Mark Corbyn:
"There are many great resources for getting started with Functional Reactive Programming and ReactiveCocoa, but what’s the next step? ReactiveCocoa is not just a nice wrapper for KVO, Signals can be used to model many common problems in Cocoa including managing the state of your UI, notifications and even business logic. Adopting ReactiveCocoa can make for more modular, self-documenting code — while still integrating easily with other APIs and your existing code. We would like to share with you some interesting, practical examples where we’ve used ReactiveCocoa to solve problems in our app. Our goal is to inspire you to consider how ReactiveCocoa can be applied in your own apps."
This document introduces Reactive Cocoa, a framework for Functional Reactive Programming in Objective-C. It describes Reactive Programming as a paradigm oriented around data flows and propagation of change. It explains the key concepts in Reactive Cocoa including streams (signals and sequences), how they allow declarative data transformations, and examples of using signals to react to user interface changes.
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
Introduction to RxJava for reactive programming and how to use RxAndroid to do reactive programming on Android.
There is a sample android app to go with the slides that has all the source shown in the project.
For most of us, Reactive Android means using RxJava. In this presentation, I try to borrow a few ideas from the backend world and enrich the concept of Reactive in Android.
My study notes on the Google Percolator paper, available on the Google Research website (USENIX2010). The paper talks about an incremental processing system for large-scale data.
The document discusses the evolution of asynchronous programming in Java. It covers early approaches using threads and executors, and the introduction of futures in Java 5 to simplify asynchronous programming. However, futures had limitations as their methods were blocking. The document discusses how other languages addressed this using callbacks and promises for non-blocking asynchronous code. It highlights how Java 8 introduced completable futures to provide a similar promise-based approach.
Here I discuss about reactive programming, observable, observer and difference between observable and promise.
Also discuss some of important operators like forkJoin, switchMap, from, deboucneTime, discardUntilChanged, mergeMap. I discuss some of observable creation function.
This document discusses callback functions in JavaScript. A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Callback functions allow asynchronous code execution in JavaScript by performing tasks without blocking subsequent code from running. Common examples of callbacks include functions used in event handling and asynchronous operations like AJAX requests.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
ReactiveCocoa provides a common interface for handling asynchronous events from different sources like UI controls, network requests, and notifications. It uses signals that emit events to represent asynchronous data over time. Operations like filtering, mapping, and combining signals allow defining reactive workflows. Swift's support for functional programming makes it a good fit for the declarative style of ReactiveCocoa.
This document provides an introduction to ReactiveCocoa, a framework for building reactive and functional iOS and macOS applications. It discusses key ReactiveCocoa concepts like signals, subscriptions, and operators. It also provides an example of how SmartThings adopted ReactiveCocoa to make their iOS app more reactive and functional. Key benefits included cleaner asynchronous code, easier adoption of MVVM, and ability to chain operations together.
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
This document introduces Reactive Programming with RxJava and how it can be used to create non-blocking applications. It discusses the limitations of blocking code and how RxJava uses Observables and Subscribers to implement reactive and asynchronous operations. It provides examples of converting blocking servlets and HTTP calls to non-blocking using RxJava. While non-blocking code is not always faster, it allows asynchronous operations to utilize threads more efficiently.
arataga. SObjectizer and RESTinio in action: a real-world exampleYauheni Akhotnikau
Slides about the usage of SObjectizer and RESTinio in implementation of performant socks5/http1.1 proxy server that has to deal with thousands of entry points.
Functional programming is a paradigm which concentrates on computing results rather than on performing actions. That is, when you call a function, the only significant effect that the function has is usually to compute a value and return it.
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
Comparing different concurrency models on the JVMMario Fusco
This document compares different concurrency models on the JVM, including the native Java concurrency model based on threads, semaphores, and locks. It discusses the pros and cons of threads and locks, including issues around non-determinism from shared mutable state. Functional programming with immutable data and internal iteration is presented as an alternative that allows for free parallelism. The document also covers actors and their message passing approach, as well as software transactional memory.
The document outlines an approach to scalable network services in Java using event-driven and non-blocking I/O. It discusses using the reactor pattern to handle I/O events asynchronously by dispatching tasks to handlers. This allows for high performance by reducing blocking and leveraging available resources like CPUs. It provides examples of how this can be implemented using Java's NIO APIs including channels, buffers, selectors and selection keys.
Taming Core Data by Arek Holko, MacoscopeMacoscope
The document discusses best practices for working with Core Data in iOS applications. It covers 9 steps: 1) setting up Core Data, 2) accessing the managed object context, 3) creating NSManagedObject subclasses, 4) creating fetch requests, 5) integrating networking, 6) using NSFetchedResultsController, 7) protocolizing models, 8) using immutable models, and 9) modularizing the code. The overall message is that Core Data code should be organized cleanly using small, single-purpose classes and protocols to improve testability, separation of concerns, and code reuse.
The document describes various objects and methods in Prototype for performing AJAX requests and handling responses. It discusses Ajax.Request for making requests, Ajax.Responders for registering global listeners, Ajax.Updater for updating DOM elements with responses, and common options and callbacks that are shared across objects.
Learn You a ReactiveCocoa for Great GoodJason Larsen
This document provides an overview of ReactiveCocoa, a framework for working with asynchronous data streams in a reactive and declarative way. It discusses key concepts in reactive and functional programming like streams, signals, sequences, and transformations like map, filter, and fold. It shows how to combine streams, inject side effects safely, and work with subjects. It recommends resources for learning more about ReactiveCocoa and reactive programming best practices.
This is my talk on ReactiveCocoa at @cocoaheads_at in Vienna. I gave an introduction to reactive programming with RAC and an overview of signals and subscribers, and how they can be used to create useful patterns.
Presented at YOW! Connected 2015 (Melbourne) by Jeames Bone & Mark Corbyn:
"There are many great resources for getting started with Functional Reactive Programming and ReactiveCocoa, but what’s the next step? ReactiveCocoa is not just a nice wrapper for KVO, Signals can be used to model many common problems in Cocoa including managing the state of your UI, notifications and even business logic. Adopting ReactiveCocoa can make for more modular, self-documenting code — while still integrating easily with other APIs and your existing code. We would like to share with you some interesting, practical examples where we’ve used ReactiveCocoa to solve problems in our app. Our goal is to inspire you to consider how ReactiveCocoa can be applied in your own apps."
This document introduces Reactive Cocoa, a framework for Functional Reactive Programming in Objective-C. It describes Reactive Programming as a paradigm oriented around data flows and propagation of change. It explains the key concepts in Reactive Cocoa including streams (signals and sequences), how they allow declarative data transformations, and examples of using signals to react to user interface changes.
Reactive Programming on Android - RxAndroid - RxJavaAli Muzaffar
Introduction to RxJava for reactive programming and how to use RxAndroid to do reactive programming on Android.
There is a sample android app to go with the slides that has all the source shown in the project.
For most of us, Reactive Android means using RxJava. In this presentation, I try to borrow a few ideas from the backend world and enrich the concept of Reactive in Android.
My study notes on the Google Percolator paper, available on the Google Research website (USENIX2010). The paper talks about an incremental processing system for large-scale data.
The document discusses the evolution of asynchronous programming in Java. It covers early approaches using threads and executors, and the introduction of futures in Java 5 to simplify asynchronous programming. However, futures had limitations as their methods were blocking. The document discusses how other languages addressed this using callbacks and promises for non-blocking asynchronous code. It highlights how Java 8 introduced completable futures to provide a similar promise-based approach.
Here I discuss about reactive programming, observable, observer and difference between observable and promise.
Also discuss some of important operators like forkJoin, switchMap, from, deboucneTime, discardUntilChanged, mergeMap. I discuss some of observable creation function.
This document discusses callback functions in JavaScript. A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. Callback functions allow asynchronous code execution in JavaScript by performing tasks without blocking subsequent code from running. Common examples of callbacks include functions used in event handling and asynchronous operations like AJAX requests.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
ReactiveCocoa provides a common interface for handling asynchronous events from different sources like UI controls, network requests, and notifications. It uses signals that emit events to represent asynchronous data over time. Operations like filtering, mapping, and combining signals allow defining reactive workflows. Swift's support for functional programming makes it a good fit for the declarative style of ReactiveCocoa.
This document provides an introduction to ReactiveCocoa, a framework for building reactive and functional iOS and macOS applications. It discusses key ReactiveCocoa concepts like signals, subscriptions, and operators. It also provides an example of how SmartThings adopted ReactiveCocoa to make their iOS app more reactive and functional. Key benefits included cleaner asynchronous code, easier adoption of MVVM, and ability to chain operations together.
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
This document introduces Reactive Programming with RxJava and how it can be used to create non-blocking applications. It discusses the limitations of blocking code and how RxJava uses Observables and Subscribers to implement reactive and asynchronous operations. It provides examples of converting blocking servlets and HTTP calls to non-blocking using RxJava. While non-blocking code is not always faster, it allows asynchronous operations to utilize threads more efficiently.
arataga. SObjectizer and RESTinio in action: a real-world exampleYauheni Akhotnikau
Slides about the usage of SObjectizer and RESTinio in implementation of performant socks5/http1.1 proxy server that has to deal with thousands of entry points.
Functional programming is a paradigm which concentrates on computing results rather than on performing actions. That is, when you call a function, the only significant effect that the function has is usually to compute a value and return it.
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
Comparing different concurrency models on the JVMMario Fusco
This document compares different concurrency models on the JVM, including the native Java concurrency model based on threads, semaphores, and locks. It discusses the pros and cons of threads and locks, including issues around non-determinism from shared mutable state. Functional programming with immutable data and internal iteration is presented as an alternative that allows for free parallelism. The document also covers actors and their message passing approach, as well as software transactional memory.
The document outlines an approach to scalable network services in Java using event-driven and non-blocking I/O. It discusses using the reactor pattern to handle I/O events asynchronously by dispatching tasks to handlers. This allows for high performance by reducing blocking and leveraging available resources like CPUs. It provides examples of how this can be implemented using Java's NIO APIs including channels, buffers, selectors and selection keys.
Taming Core Data by Arek Holko, MacoscopeMacoscope
The document discusses best practices for working with Core Data in iOS applications. It covers 9 steps: 1) setting up Core Data, 2) accessing the managed object context, 3) creating NSManagedObject subclasses, 4) creating fetch requests, 5) integrating networking, 6) using NSFetchedResultsController, 7) protocolizing models, 8) using immutable models, and 9) modularizing the code. The overall message is that Core Data code should be organized cleanly using small, single-purpose classes and protocols to improve testability, separation of concerns, and code reuse.
The document describes various objects and methods in Prototype for performing AJAX requests and handling responses. It discusses Ajax.Request for making requests, Ajax.Responders for registering global listeners, Ajax.Updater for updating DOM elements with responses, and common options and callbacks that are shared across objects.
Ajax allows for asynchronous retrieval of data from a server in the background without reloading the page. It uses a combination of technologies like XMLHttpRequest, JavaScript, and DOM to make asynchronous calls to a server and update portions of a page without reloading. The document then provides an example of how an Ajax interaction works, from making an asynchronous request to a server to processing the response and updating the HTML DOM.
Ajax allows for asynchronous retrieval of data from a server in the background without reloading the page. It uses a combination of technologies like XMLHttpRequest, JavaScript, and DOM to make asynchronous calls to a server and update portions of a page without reloading. The document then provides an example of how an Ajax interaction works, from making an asynchronous request to a server to processing the response and updating the HTML DOM.
The document discusses asynchronous programming in .NET 4.5 using tasks and async/await. Key points include:
- Tasks and Task<T> represent asynchronous operations and let you specify continuations using ContinueWith.
- The async modifier indicates an asynchronous method, which returns a task. Await pauses execution until the awaited task completes.
- Async methods make long-running work non-blocking. The caller resumes without waiting for the async method to finish.
- Async and await simplify asynchronous code by turning callbacks into synchronous-looking code.
This document discusses client-server connections for a library application. It provides code for a CustomHttpClient class that defines methods for performing HTTP GET and POST requests. This includes setting connection timeout parameters. It also provides code for connecting to a MySQL database and inserting login credentials and book borrowing history. The code samples show how to connect between the client and server and interface with the backend database.
Top questions with answers and code examples for JavaScript
JavaScript interview questions with answers:
What is closure in JavaScript and how does it work?
Answer: Closure is a feature in JavaScript where a function has access to its outer scope even after the outer function has returned. It is created when a function is defined inside another function, and the inner function retains access to the variables in the outer function’s scope. How do you declare a variable in JavaScript?
Answer: Variables in JavaScript can be declared using the “var”, “let” or “const” keywords. The “var” keyword is used to declare a variable with function scope, while “let” and “const” are used to declare variables with block scope.
Slides from the NestJS MasterClass.
We learned how to build JavaScript server-side applications with NestJS - A progressive NodeJS framework built with TypeScript.
You can find the code on GitHub:
https://github.com/nirkaufman/task-manager
Building Scalable Stateless Applications with RxJavaRick Warren
RxJava is a lightweight open-source library, originally from Netflix, that makes it easy to compose asynchronous data sources and operations. This presentation is a high-level intro to this library and how it can fit into your application.
The document provides information about communicating with servers in GWT (Google Web Toolkit), including asynchronous HTTP requests, submitting form data using traditional and GWT methods, and using GWT RPC (Remote Procedure Calls). It discusses creating asynchronous GET and POST requests, submitting form data by constructing requests manually and using FormPanel, and implementing GWT RPC through creating client and server interfaces, making the remote call, and handling responses.
Sample JavaScript Code Laurence Svekis
JavaScript Closure
A closure in JavaScript is a function that has access to the variables in its parent scope, even after the parent function has completed execution. This allows for data to be “closed over” or remembered by the inner function, even after the outer function has returned.
Here, the makeCounter function returns an inner function that has access to the count variable declared in its parent scope, and can “remember” the current count value even after the makeCounter function has completed execution. Each time the inner function is called, it returns the current value of count and increments it by 1.
JavaScript Closure Advanced
In this example, the makeAdder function takes in a single argument x and returns an inner function that takes in a second argument y. The inner function has access to the x variable declared in the parent scope and uses it to add x and y together and return the result.
We can see here that the outer function makeAdder has been executed twice and it returns two different inner functions which are assigned to different variables add5 and add10 and these inner functions are able to remember their respective parent scope values of x.
This document provides instructions for setting up and running a bot project using the Bot Builder SDK v4. It discusses downloading necessary software, creating a project in Visual Studio, implementing a welcome message, and managing state using user profiles and state accessors. The document contains code samples for creating a SampleBot class that inherits from IBot and uses state accessors and user profiles to save and retrieve a user's handle name.
This document provides an overview of AJAX (Asynchronous JavaScript and XML), including its history, how it works, examples of request and response phases, and advantages and disadvantages. AJAX allows for asynchronous updating of parts of a web page without reloading the entire page. It uses technologies like JavaScript, XML, DOM, and CSS to speed up interactions and provide a more responsive user experience similar to desktop applications.
This is my presentation from TechBeats #3 hosted by Applause about Server-Side Swift framework called Vapor.
Swift is a great language and possibility of using it also in backend is a huge benefit for any iOS developer out there. Using Vapor is a seamless experience. With this framework creating advance APIs by iOS developer is as easy as writing simple iOS app.
https://www.meetup.com/TechBeats-hosted-by-Applause/events/254910023/
Asynchronous programming in .net 4.5 with c#Binu Bhasuran
The document discusses various asynchronous programming models in .NET, including the Asynchronous Programming Model (APM), Event-Based Asynchronous Pattern (EAP), and Task-Based Asynchronous Pattern (TAP). It provides details on how each model handles asynchronous operations and completion. It also describes how asynchronous implementations can be converted between the different patterns, such as wrapping an APM implementation in a TAP or vice versa.
This document discusses using web services in Android development. It covers making HTTP requests to web services, parsing the response, and creating your own basic web service using PHP. Key points include constructing the URL, executing asynchronous HTTP requests, checking response codes, and parsing XML or JSON responses. The document provides code samples for making a request and handling the response. It also discusses possible issues like blocking the UI thread during the request and suggests using threads to avoid this. Finally, it proposes an exercise to build an accessible application using a web service and GPS.
JavaScript Multithread or Single Thread.pptxRAHITNATH
The document discusses how JavaScript works and whether it is single-threaded or multi-threaded. It explains that JavaScript is single-threaded, with a single call stack that executes code line by line. Asynchronous functions use callbacks and a callback queue to avoid blocking the main thread. The event loop monitors the call stack and callback queue, executing callbacks when the call stack is empty. This allows for non-blocking behavior through asynchronous functions and Web APIs, even though JavaScript remains a single-threaded language.
AJAX allows for asynchronous data retrieval and updating of parts of a web page without reloading the entire page. It uses a combination of technologies including XML, JavaScript, CSS, HTML and the XMLHttpRequest object. The XMLHttpRequest object makes asynchronous HTTP requests to the server in the background and retrieves data from the server. This allows updating parts of the web page without interrupting the user's operation.
Have you ever wondered how Ajax requests fit in with WebObject's Request-Response loop? Have you ever wanted to make a new Ajax component or debug a problem in an existing one? Do you want to use a different JavaScript library with WebObjects? This session will look at what was done to make Ajax work in a component action world, looking at changes to the Request-Response loop and the page cache. You will learn how to use AjaxComponent, AjaxDynamicElement, and the other classes that are used to create WebObjects Ajax components.
Similar to Keeping track of state in asynchronous callbacks (20)
Chatbots are growing in popularity as developers face the
limitations of the mobile app. User interfaces that simulate a human
conversation, the history of chatbots goes back to the late 18th
century. I'll take you on a tour of that history with an eye on finding
insights on what is possible today and in the near future with chatbots.
Issues Covered: Amazon Alexa, Facebook Messenger Chatbots, Alan
Turing, and much more.
Estimating the Software Product Value during the Development ProcessPaul Houle
Nowadays software companies are facing a fierce competition
to deliver better products but offering a higher value to the customer.
In this context, software product value has becoming a major concern
in software industry, leading for improving the knowledge and better
understanding about how to estimate the software value in early development
phases. Other way, software companies encounter problems such
as releasing products that were developed with high expectations, but
they gradually fall into the category of a mediocre product when they
are released to the market. These high expectations are tightly related
to the expected and offered software value to the customer. This paper
presents an approach for estimating the software product value, focusing
on the development phases. We propose a value indicators approach to
quantify the real value of the development products. The aim is early
identifying potential deviations in the real software value, by comparing
the estimated versus the expected. We present an internal validation
to show the feasibility of this approach to produce benefits in industry
projects.
Universal Standards for LEI and other Corporate Reference Data: Enabling risk...Paul Houle
Individual Records are supposed be updated yearly, but more than 25% of records have lapsed
LEI records must be updated sooner in response to corporate actions if the GLEIS is to be useful as golden copy reference data inside financial institutions
Needed: real-time, streaming analytics to monitor SIFI, trading and the buildup of systemic risk
LOUs publish records daily, which are concatenated by the LOUS: however, the data on organization types (Corporation, Fund, Trust, etc.), Geographic Regions, Business Registry Numbers, Hierarchy and other fields are often missing or inconsistently represented
Implementing Reference Dataand Corporate Actions in a Blockchain
Fixing a leaky bucket; Observations on the Global LEI SystemPaul Houle
We apply bitemporal analysis to more than 500 daily data files supplied by the Global Legal Entity Identifier Foundation to show that churn dominates the dynamics of growth, such that the number of paid up records in full standing has been flat over the last year. Our analysis reveals occasional daily glitches in the past that affected thousands of records. These appear to be in better control now, but a high lapse rate is the primary challenge to the Global LEI System right now
Although animals do not use language, they are capable of many of the same kinds of cognition as us; much of our experience is at a non-verbal level.
Semantics is the bridge between surface forms used in language and what we do and experience.
Language understanding depends on world knowledge (i.e. “the pig is in the pen” vs. “the ink is in the pen”)
We might not be ready for executives to specify policies themselves, but we can make the process from specification to behavior more automated, linked to precise vocabulary, and more traceable.
Advances such as SVBR and an English serialization for ISO Common Logic means that executives and line workers can understand why the system does certain things, or verify that policies and regulations are implemented
The Ontology2 platform squares the circle between big data, low latency, and semantics by combining expressive reasoning, information retrieval and machine learning with Hadoop, Apache Spark and Solid State Drive backed cloud .
Types in Freebase typically mean that something plays a role. For instance, superman is a :film.film_subject because he the subject of a film. He is an :amusement_parks.ride_theme because amusement parks have been made about him. There's nothing contradictory about this, at least to first order, because these types don't fit into a hierarchy.
Today's Enterprise Search products have effective answers for content ingestion and and query performance.
Any product that is successful at all has an answer for content ingestion. It's a complex problem because you need to interact with many kinds of system, but it's a solved problem: a vendor who hasn't solved this problem would not be successful at all.
This graph compares two importance scores for DBpedia concepts.
x-axis (left) is a usage-based importance score (based on which pages people view) and y-axis (up) is the PageRank score published by ath representing the strength of links to a concept. Correlation coefficients via kendal, spearman and pearson are in the 0.35-0.5 range.
Be warned that this system does not have a sense of "respectability" so you be offended by many of its opinions and we apologize for it.
Extension methods, nulls, namespaces and precedence in c#Paul Houle
Extension methods are the most controversial feature that Microsoft has introduced in
C# 3.0. Introduced to support the LINQ query framework, extension methods make
it possible to define new methods for existing classes.
Although extension methods can greatly simplify code that uses them, many are
concerned that they could transform C# into something that programmers find
unrecognizable, or that C#’s namespace mechanisms are inadequate for managing
large systems that use extension methods. Adoption of the LINQ framework,
however, means that extension methods are here to stay, and that .net
programmers need to understand how to use them effectively, and, in particular,
how extension methods are different from regular methods.
This article discusses three ways in which extension methods differ from regular
methods:
1. Extension methods can be called on null objects without throwing an exception
2. Extension methods cannot be called inside of a subclass
Dropping unique constraints in sql serverPaul Houle
I got started with relational databases with mysql, so I’m in the habit of making
database changes with SQL scripts, rather than using a GUI. Microsoft SQL Server
requires that we specify the name of a unique constraint when we want to drop it. If
you’re thinking ahead, you can specify a name when you create the constraint; if
you don’t, SQL Server will make up an unpredictable name, so you can’t write a
simple script to drop the constraint.
This is a story of two types: GenericType and SpecificType, where GenericType is a
superclass of SpecificType. There are two types of explicit cast in C#:
The Prefix cast:
[01] GenericType g=...;
[02] SpecificType t=(SpecificType) g;
The as cast:
[03] GenericType g=...;
[04] SpecificType t=g as SpecificType;
Most programmers have a habit of using one or the other — this isn’t usually a
conscious decision, but more of a function of which form a programmer saw first. I,
for instance, programmed in Java before I learned C#, so I was already in the prefix
cast habit. People with a Visual Basic background often do the opposite. There are
real differences between the two casting operators
I'm an expert on building commerical large scale systems based on Linked Data sources such as Freebase and DBpedia. I'm the creator of :BaseKB, which was the first correct conversion of Freebase to RDF and of Infovore, the open source
I do consulting on the following areas:
* Data processing with Hadoop and the design and construction of systems using Amazon Web Services
* Architecture and construction of systems that consume and produce Linked Data
* Construction and evaluation of intelligent systems that make subjective decisions (text search, text classification, machine learning, etc.)
I'm not at all interested in doing maintenance work on other people's code, but I am interested in helping you align your process, structure, and tools to speed up your development cycle, improve your products, and prevent developer burnout. I am not free to relocate at this time, but I collaborate all of the time with workers around the world and I can travel to your location, understand your needs and transfer skills to your workforce.
Mat Byrne recently posted source code for a dynamic domain object in PHP which
takes advantage of the dynamic nature of PHP. It’s a good example of how
programmers can take advantage of the unique characteristics of a programming
language.
Statically typed languages such as C# and Java have some advantages: they run
faster and IDE’s can understand the code enough to save typing (with your fingers),
help you refactor your code, and help you fix errors. Although there’s a lot of things I
like symfony, it feels like a Java framework that’s invaded the PHP world. Eclipse
would help you deal with the endless getters and setters and domain object methods
with 40-character names in Java, Eclipse.
The limits of polymorphism are a serious weakness of today’s statically typed
languages. C# and Java apps that I work with are filled with if-then-else or case
ladders when they need to initialize a dynamically chosen instance of one of a set of
classes that subclass a particular base class or that implement a particular interface.
Sure, you can make a HashMap or Dictionary that’s filled with Factory objects, but
any answer for that is cumbersome. I
articles on asynchronous communications with a focus on Javascript.
Minimizing Code Paths In Asynchronous Code, a recent post of his, is about a lesson
that I learned the hard way with GWT that applies to all RIA systems that use
asynchronous calls. His example is the same case I encountered, where a function
might return a value from a cache or might query the server to get the value: an
obvious way to do this in psuedocode is:
function getData(...arguments...,callback) {
if (... data in cache...) {
callback(...cached data...);
}
cacheCallback=anonymousFunction(...return value...) {
... store value in cache...
callback(...cached data...);
}
getDataFromServer(...arguments...,cacheCallback)
}
At first glance this code looks innocuous, but there’s a major difference between
what happens in the cached and uncached case. In the cached case, the callback()
function gets called before getData() returns — in the uncached case, the opposite
happens. What happens in this function has a global impact on the execution of the
program, opening up two code paths that complicate concurrency control and
introduce bugs that can be frustrating to debug.
This function can be made more reliable if it schedules callback() to run after the
thread it is running in completes. In Javascript, this can be done with setTimeout().
In Silverlight use System.Windows.Threading.Dispatcher. to schedule the callback
What do you do when you’ve caught an exception?Paul Houle
This article is a follow up to “Don’t Catch Exceptions“, which advocates that
exceptions should (in general) be passed up to a “unit of work”, that is, a fairly
coarse-grained activity which can reasonably be failed, retried or ignored. A unit of
work could be:
an entire program, for a command-line script,
a single web request in a web application,
the delivery of an e-mail message
the handling of a single input record in a batch loading application,
rendering a single frame in a media player or a video game, or
an event handler in a GUI program
The code around the unit of work may look something like
[01] try {
[02] DoUnitOfWork()
[03] } catch(Exception e) {
[04] ... examine exception and decide what to do ...
[05] }
For the most part, the code inside DoUnitOfWork() and the functions it calls tries to
throw exceptions upward rather than catch them.
To handle errors correctly, you need to answer a few questions, such as
Was this error caused by a corrupted application state?
Did this error cause the application state to be corrupted?
Was this error caused by invalid input?
What do we tell the user, the developers and the system administrator?
Could this operation succeed if it was retried?
Is there something else we could do?
Although it’s good to depend on existing exception
Extension methods, nulls, namespaces and precedence in c#Paul Houle
Extension methods allow calling methods on null objects without exceptions and add methods to existing classes without modifying them. However, extension methods have different precedence than regular methods and can cause conflicts if defined in multiple namespaces. To avoid issues, extension methods should be defined carefully, null values should be checked, and namespaces should be managed properly.
ProAlign Web is sold on a “Software as a Service” basis, which eliminates the burden and costs of software installation, maintenance, and any server requirements. Upgrades happen seamlessly without your involvement.
Users have permission levels for manipulating and viewing data — the system will show only those geographic areas authorized for each user.
It's easy to create, share, modify and approve alignments online — visualization tools allow immediate understanding of key account metrics by territory
Built in communication — allows integrated notes, requests and approval processes.
Every installation of ProAlign Web is fully integrated with and includes ProAlign Desktop. Built on ESRI ArcGIS ® mapping technology, the world’s number one mapping software. ProAlign Desktop offers an additional robust portfolio of analytical, database and mapping features for the sales manager or sales operations analyst.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
"Choosing proper type of scaling", Olena SyrotaFwdays
Imagine an IoT processing system that is already quite mature and production-ready and for which client coverage is growing and scaling and performance aspects are life and death questions. The system has Redis, MongoDB, and stream processing based on ksqldb. In this talk, firstly, we will analyze scaling approaches and then select the proper ones for our system.
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...Alex Pruden
Folding is a recent technique for building efficient recursive SNARKs. Several elegant folding protocols have been proposed, such as Nova, Supernova, Hypernova, Protostar, and others. However, all of them rely on an additively homomorphic commitment scheme based on discrete log, and are therefore not post-quantum secure. In this work we present LatticeFold, the first lattice-based folding protocol based on the Module SIS problem. This folding protocol naturally leads to an efficient recursive lattice-based SNARK and an efficient PCD scheme. LatticeFold supports folding low-degree relations, such as R1CS, as well as high-degree relations, such as CCS. The key challenge is to construct a secure folding protocol that works with the Ajtai commitment scheme. The difficulty, is ensuring that extracted witnesses are low norm through many rounds of folding. We present a novel technique using the sumcheck protocol to ensure that extracted witnesses are always low norm no matter how many rounds of folding are used. Our evaluation of the final proof system suggests that it is as performant as Hypernova, while providing post-quantum security.
Paper Link: https://eprint.iacr.org/2024/257
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsDianaGray10
Join us to learn how UiPath Apps can directly and easily interact with prebuilt connectors via Integration Service--including Salesforce, ServiceNow, Open GenAI, and more.
The best part is you can achieve this without building a custom workflow! Say goodbye to the hassle of using separate automations to call APIs. By seamlessly integrating within App Studio, you can now easily streamline your workflow, while gaining direct access to our Connector Catalog of popular applications.
We’ll discuss and demo the benefits of UiPath Apps and connectors including:
Creating a compelling user experience for any software, without the limitations of APIs.
Accelerating the app creation process, saving time and effort
Enjoying high-performance CRUD (create, read, update, delete) operations, for
seamless data management.
Speakers:
Russell Alfeche, Technology Leader, RPA at qBotic and UiPath MVP
Charlie Greenberg, host
Essentials of Automations: Exploring Attributes & Automation ParametersSafe Software
Building automations in FME Flow can save time, money, and help businesses scale by eliminating data silos and providing data to stakeholders in real-time. One essential component to orchestrating complex automations is the use of attributes & automation parameters (both formerly known as “keys”). In fact, it’s unlikely you’ll ever build an Automation without using these components, but what exactly are they?
Attributes & automation parameters enable the automation author to pass data values from one automation component to the next. During this webinar, our FME Flow Specialists will cover leveraging the three types of these output attributes & parameters in FME Flow: Event, Custom, and Automation. As a bonus, they’ll also be making use of the Split-Merge Block functionality.
You’ll leave this webinar with a better understanding of how to maximize the potential of automations by making use of attributes & automation parameters, with the ultimate goal of setting your enterprise integration workflows up on autopilot.
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframePrecisely
Inconsistent user experience and siloed data, high costs, and changing customer expectations – Citizens Bank was experiencing these challenges while it was attempting to deliver a superior digital banking experience for its clients. Its core banking applications run on the mainframe and Citizens was using legacy utilities to get the critical mainframe data to feed customer-facing channels, like call centers, web, and mobile. Ultimately, this led to higher operating costs (MIPS), delayed response times, and longer time to market.
Ever-changing customer expectations demand more modern digital experiences, and the bank needed to find a solution that could provide real-time data to its customer channels with low latency and operating costs. Join this session to learn how Citizens is leveraging Precisely to replicate mainframe data to its customer channels and deliver on their “modern digital bank” experiences.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
How information systems are built or acquired puts information, which is what they should be about, in a secondary place. Our language adapted accordingly, and we no longer talk about information systems but applications. Applications evolved in a way to break data into diverse fragments, tightly coupled with applications and expensive to integrate. The result is technical debt, which is re-paid by taking even bigger "loans", resulting in an ever-increasing technical debt. Software engineering and procurement practices work in sync with market forces to maintain this trend. This talk demonstrates how natural this situation is. The question is: can something be done to reverse the trend?
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyScyllaDB
Freshworks creates AI-boosted business software that helps employees work more efficiently and effectively. Managing data across multiple RDBMS and NoSQL databases was already a challenge at their current scale. To prepare for 10X growth, they knew it was time to rethink their database strategy. Learn how they architected a solution that would simplify scaling while keeping costs under control.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Choosing The Best AWS Service For Your Website + API.pptx
Keeping track of state in asynchronous callbacks
1. Generation 5 » Keeping Track Of State In Asynchronous Callbacks
Subscribe to our RSS Feed | About Us
Keeping Track Of State In Asynchronous Callbacks
When you’re writing applications that use asynchronous callbacks (i.e. Silverlight,
AJAX, or GWT) you’ll eventually run into the problem of keeping track of the context
that a request is being done in. This isn’t a problem in synchronous programming,
because local variables continue to exist after one function calls another function
synchronously:
int AddToCount(int amount,string countId)
int countValue=GetCount(countId);
return countValue+amount;
}
{
This doesn’t work if the GetCount function is asynchronous, where we need to write
something like
int AddToCountBegin(int amount,string countId,CountCallback outerCallback) {
GetCountBegin(countId,AddToCountCallback);
}
void AddToCountCallback(int countValue) {
... some code to get the values of amount and outerCallback ...
outerCallback(countValue+amount);
}
Several things change in this example: (i) the AddToCount function gets broken up
into two functions: one that does the work before the GetCount invocation, and one
that does the work after GetCount completes. (ii) We can’t return a meaningful value
from AddToCountCallback, so it needs to ‘return’ a value via a specified callback
function. (iii) Finally, the values of outerCallback and amount aren’t automatically
shared between the functions, so we need to make sure that they are carried over
somehow.
There are three ways of passing context from a function that calls and asynchronous
function to the callback function:
1. As an argument to the callback function
2. As an instance variable of the class of which the callback function is a class
3. Via a closure
Let’s talk about these alternatives:
1. Argument to the Callback Function
In this case, a context object is passed to the asynchronous function, which passes
the context object to the callback. The advantage here is that there aren’t any
constraints on how the callback function is implemented, other than by accepting the
context object as a callback. In particular, the callback function can be static. A major
disadvantage is that the asynchronous function has to support this: it has to accept a
state object which it later passes to the callback function.
The implementation of HttpWebRequest.BeginGetResponse(AsyncCallback a,Object
state) in the Silverlight libraries is a nice example. If you wish to pass a context object
to the AsyncCallback, you can pass it in the second parameter, state. Your callback
function will implement the AsyncCallback delegate, and will get something that
implements IAsyncResult as a parameter. The state that you passed into
BeginGetResponse will come back in the IAsyncResult.AsyncState property. For
example:
class MyHttpContext {
public HttpWebRequest Request;
public SomeObject FirstContextParameter;
public AnotherObject AnotherContextParameter;
}
protected void myHttpCallback(IAsyncResult abstractResult) {
MyHttpContext context = (MyHttpContext) abstractResult.AsyncState;
HttpWebResponse Response=(HttpWebResponse)
context.Request.EndGetResponse(abstractResult);
}
http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/[1/12/2014 9:30:30 PM]
Search for:
Search
Archives
June 2012 (1)
August 2010 (1)
May 2010 (1)
June 2009 (2)
April 2009 (1)
March 2009 (1)
February 2009 (3)
January 2009 (3)
November 2008 (1)
August 2008 (2)
July 2008 (5)
June 2008 (5)
May 2008 (2)
April 2008 (6)
March 2008 (8)
June 2006 (1)
February 2006 (1)
Categories
AJAX (2)
Asynchronous Communications (16)
Biology (1)
Books (1)
Design (1)
Distributed (1)
Exceptions (2)
Functional Programming (1)
GIS (1)
Ithaca (1)
Japan (1)
Math (1)
Media (3)
Nature (1)
Semantic Web (3)
Tools (28)
CRUD (1)
Dot Net (17)
Freebase (2)
GWT (9)
Java (7)
Linq (2)
PHP (6)
Server Frameworks (1)
Silverlight (12)
SQL (5)
Uncategorized (1)
Web (2)
Analytics (1)
2. Generation 5 » Keeping Track Of State In Asynchronous Callbacks
public doHttpRequest(...) {
...
MyHttpContext context=new MyHttpContext();
context.Request=Request;
context.FirstContextParameter = ... some value ...;
context.AnotherContextParameter = .. another value ...;
Request.BeginGetResponse();
Request.Callback(myHttpCallback,context);
}
Note that, in this API, the Request object needs to be available in myHttpCallback
because myHttpCallbacks get the response by calling the
HttpWebResponse.EndGetResponse() method. We could simply pass the Request
object in the state parameter, but we’re passing an object we defined,
myHttpCallback, because we’d like to carry additional state into myHttpCallback.
Note that the corresponding method for doing XMLHttpRequests in GWT, the use of a
RequestBuilder object doesn’t allow using method (1) to pass context information —
there is no state parameter. in GWT you need to use method (2) or (3) to pass
context at the RequestBuilder or GWT RPC level. You’re free, of course, to use method
(1) when you’re chaining asynchronous callbacks: however, method (2) is more
natural in Java where, instead of a delegate, you need to pass an object reference to
designate a callback function.
2. Instance Variable Of The Callback Function’s Class
Functions (or Methods) are always attached to a class in C# and Java: thus, the state
of a callback function can be kept in either static or instance variables of the
associated class. I don’t advise using static variables for this, because it’s possible for
more than one asynchronous request to be flight at a time: if two request store state
in the same variables, you’ll introduce race conditions that will cause a world of pain.
(see how race conditions arise in asynchronous communications.)
Method 2 is particularly effective when both the calling and the callback functions are
methods of the same class. Using objects whose lifecycle is linked to a single
asynchronous request is an effective way to avoid conflicts between requests (see the
asynchronous command pattern and asynchronous functions.)
Here’s an example, lifted from the asynchronous functions article:
public class HttpGet : IAsyncFunction<String>
{
private Uri Path;
private CallbackFunction<String> OuterCallback;
private HttpWebRequest Request;
public HttpGet(Uri path)
{
Path = path;
}
public void Execute(CallbackFunction<String> outerCallback)
{
OuterCallback = outerCallback;
try
{
Request = (HttpWebRequest)WebRequest.Create(Path);
Request.Method = "GET";
Request.BeginGetRequestStream(InnerCallback,null);
}
catch (Exception ex)
{
OuterCallback(CallbackReturnValue<String>.CreateError(ex));
}
}
public void InnerCallback(IAsyncResult result)
{
try
{
HttpWebResponse response = (HttpWebResponse)
Request.EndGetResponse(result);
TextReader reader = new
StreamReader(response.GetResponseStream());
OuterCallback(CallbackReturnValue<String>.CreateOk(reader.ReadToEnd()));
} catch(Exception ex) {
OuterCallback(CallbackReturnValue<String>.CreateError(ex));
}
}
}
Note that two pieces of context are being passed into the callback function: an
HttpWebRequest object named Request (necessary to get the response) and a
CallbackFunction<String> delegate named OuterCallback that receives the return
value of the asynchronous function.
Unlike Method 1, Method 2 makes it possible to keep an unlimited number of context
variables that are unique to a particular case in a manner that is both typesafe and
http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/[1/12/2014 9:30:30 PM]
3. Generation 5 » Keeping Track Of State In Asynchronous Callbacks
oblivious to the function being called — you don’t need to cast an Object to
something more specific, and you don’t need to create a new class to hold multiple
variables that you’d like to pass into the callback function.
Method 2 comes into it’s own when it’s used together with polymorphism, inheritance
and initialization patterns such as the factory pattern: if the work done by the
requesting and callback methods can be divided into smaller methods, a hierarchy of
asynchronous functions or commands can reuse code efficiently.
3. Closures
In both C# and Java, it’s possible for a method defined inside a method to have
access to variables in the enclosing method. In C# this is a matter of creating an
anonymous delegate, while in Java it’s necessary to create an anonymous class.
Using closures results in the shortest code, if not the most understandable code. In
some cases, execution proceeds in a straight downward line through the code —
much like a synchronous version of the code. However, people sometimes get
confused the indentation, and, more seriously, parameters after the closure definition
and code that runs immediately after the request is fired end up in an awkward place
(after the definition of the callback function.)
public class HttpGet : IAsyncFunction<String>
{
private Uri Path;
public HttpGet(Uri path)
{
Path = path;
}
public void Execute(CallbackFunction<String> outerCallback)
{
OuterCallback = outerCallback;
try
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(Path);
Request.Method = "GET";
Request.BeginGetRequestStream(delegate(IAsyncResult result) {
try {
response = request.EndGetResponse(result);
TextReader reader = new
StreamReader(response.GetResponseStream());
outerCallback(CallbackReturnValue<String>.CreateOk(reader.ReadToEnd()));
} catch(Exception ex) {
outerCallback(CallbackReturnValue<String>.CreateError(ex));
}
},null); // <--- note parameter value after delegate definition
}
catch (Exception ex)
{
outerCallback(CallbackReturnValue<String>.CreateError(ex));
}
}
}
The details are different in C# and Java: anonymous classes in Java can access local,
static and instance variables from the enclosing context that are declared final — this
makes it impossible for variables to be stomped on while an asynchronous request is
in flight. C# closures, on the other hand, can access only local variables: most of the
time this prevents asynchronous requests from interfering with one another, unless a
single method fires multiple asynchronous requests, in which case counter-intuitive
things can happen.
Conclusion
In addition to receiving return value(s), callback functions need to know something
about the context they run in: to write reliable applications, you need to be conscious
of where this information is; better yet, a strategy for where you’re going to put it.
Closures, created with anonymous delegates (C#) or classes (Java) produce the
shortest code, but not necessarily the clearest. Passing context in an argument to the
callback function requires the cooperation of the called function, but it makes few
demands on the calling and callback functions: the calling and callback functions can
both be static. When a single object contains both calling and callback functions,
context can be shared in a straightforward and typesafe manner; and when the calling
and callback functions can be broken into smaller functions, opportunities for efficient
code reuse abound.
http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/[1/12/2014 9:30:30 PM]
4. Generation 5 » Keeping Track Of State In Asynchronous Callbacks
Paul Houle on June 2nd 2008 in Asynchronous Communications, Dot Net, GWT,
Java, Silverlight
Comments (6)
Comments (6)
Login
Sort by: Date Rating Last Activity
Thomas Hansen · 292 weeks ago
+1
Or you could use an Ajax Framework that queues up the requests which is the only sane thing to do
when you have a server/client solution and waits for the previous one to finish before creating a new
one ;)
(Hint; follow my link)
Nice blog though, and VERY important to be aware of, though probably less than 1% of ASP.NET AJAX
developers are... :)
Reply
admin · 292 weeks ago
0
@Thomas, your solution is a correct way to use AJAX and makes a lot of sense.
There is one case where it does make sense to generate concurrent requests, and that's when
information from several requests is going to be combined. Running requests in parallel can greatly
reduce the effects of latency -- in many cases this can make a large difference in performance (much
more than two.)
I think most people doing AJAX in Javascript can get away with being ignorant about concurrency
problems because they're bolting simple behaviors onto an HTML page: when something does go
wrong, the situation is usually recoverable. I know that I programmed a little AJAX here and there for
years and never experienced concurrency problems -- then I built a GWT app!
People working with tools like Silverlight, GWT and Flex (as well as a few brave Javascript Ninjas) are
building larger applications that are going to have more problems. It's time to spread the word about
the problems and the solutions!
Reply
Thomas Hansen · 292 weeks ago
0
@admin
Yes I totally agree, in fact I by "chance" stumbled into the problem when adding up a timer onto my
page and then frenetically clicked a button at the same time and by accident discovered that
sometimes the ViewState went completely *bananas* and the page became in an "undefined state"...
Then I spent more than a WEEK in fact re-creating our core to give support for sequential requests...
I think that yes you are right, there might exist some extreme scenarios where it makes sense to have
more than one running at the same time, though if they're both running towards the same server, you
will get OTHER problems (2 HTTP connections per IP constraint in most browsers)
So I think probably if you are going to use them you would normally have them first of all run towards
different IPs (servers) then also in addition it would be *WISE* to make sure they're not updating the
same parts of the UI...
Though for us (Gaia Ajax Widgets) this is completely abstract and would never happen unless people
completely mis-used our framework in ways it was never intended to be used for...
On the server creating more than one request towards OTHER servers (WebServices and so on)
asynchronously though is a totally different story...
.t
Reply
admin · 292 weeks ago
0
Well, in a perfect world, we'd design the client-server protocol so that all the information that the client
needs to handle a UI event comes in one big batch... Then you don't need to worry about
choreography, error handling and all those hairy issues. See this article.
In the real world we need to talk to server apps that we don't control... So we have to deal with those
issues.
http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/[1/12/2014 9:30:30 PM]