Circuit-Breaker Actor
This is an alternative implementation of the Akka Circuit Breaker Pattern. The main difference is that it is intended to be used only for request-reply interactions with an actor using the Circuit-Breaker as a proxy of the target one in order to provide the same failfast functionalities and a protocol similar to the circuit-breaker implementation in Akka.
### Usage
Let's assume we have an actor wrapping a back-end service and able to respond to Request calls with a Response object containing an Either[String, String] to map successful and failed responses. The service is also potentially slowing down because of the workload.
A simple implementation can be given by this class
object SimpleService {
case class Request(content: String)
case class Response(content: Either[String, String])
case object ResetCount
}
/**
* This is a simple actor simulating a service
* - Becoming slower with the increase of frequency of input requests
* - Failing around 30% of the requests
*/
class SimpleService extends Actor with ActorLogging {
import SimpleService._
var messageCount = 0
import context.dispatcher
context.system.scheduler.schedule(1.second, 1.second, self, ResetCount)
override def receive = {
case ResetCount ⇒
messageCount = 0
case Request(content) ⇒
messageCount += 1
// simulate workload
Thread.sleep(100 * messageCount)
// Fails around 30% of the times
if (Random.nextInt(100) < 70) {
sender ! Response(Right(s"Successfully processed $content"))
} else {
sender ! Response(Left(s"Failure processing $content"))
}
}
}
If we want to interface with this service using the Circuit Breaker we can use two approaches:
Using a non-conversational approach:
class CircuitBreaker(potentiallyFailingService: ActorRef) extends Actor with ActorLogging {
import SimpleService._
val serviceCircuitBreaker =
context.actorOf(
CircuitBreakerPropsBuilder(maxFailures = 3, callTimeout = 2.seconds, resetTimeout = 30.seconds)
.copy(
failureDetector = {
_ match {
case Response(Left(_)) ⇒ true
case _ ⇒ false
}
})
.props(potentiallyFailingService),
"serviceCircuitBreaker")
override def receive: Receive = {
case AskFor(requestToForward) ⇒
serviceCircuitBreaker ! Request(requestToForward)
case Right(Response(content)) ⇒
//handle response
log.info("Got successful response {}", content)
case Response(Right(content)) ⇒
//handle response
log.info("Got successful response {}", content)
case Response(Left(content)) ⇒
//handle response
log.info("Got failed response {}", content)
case CircuitOpenFailure(failedMsg) ⇒
log.warning("Unable to send message {}", failedMsg)
}
}
Using the ask pattern, in this case it is useful to be able to map circuit open failures to the same type of failures returned by the service (a Left[String] in our case):
class CircuitBreakerAsk(potentiallyFailingService: ActorRef) extends Actor with ActorLogging {
import SimpleService._
import akka.pattern._
implicit val askTimeout: Timeout = 2.seconds
val serviceCircuitBreaker =
context.actorOf(
CircuitBreakerPropsBuilder(maxFailures = 3, callTimeout = askTimeout, resetTimeout = 30.seconds)
.copy(
failureDetector = {
_ match {
case Response(Left(_)) ⇒ true
case _ ⇒ false
}
})
.copy(
openCircuitFailureConverter = { failure ⇒
Left(s"Circuit open when processing ${failure.failedMsg}")
})
.props(potentiallyFailingService),
"serviceCircuitBreaker")
import context.dispatcher
override def receive: Receive = {
case AskFor(requestToForward) ⇒
(serviceCircuitBreaker ? Request(requestToForward)).mapTo[Either[String, String]].onComplete {
case Success(Right(successResponse)) ⇒
//handle response
log.info("Got successful response {}", successResponse)
case Success(Left(failureResponse)) ⇒
//handle response
log.info("Got successful response {}", failureResponse)
case Failure(exception) ⇒
//handle response
log.info("Got successful response {}", exception)
}
}
}
If it is not possible to define define a specific error response, you can map the Open Circuit notification to a failure. That also means that your CircuitBreakerActor will be useful to protect you from time out for extra workload or temporary failures in the target actor. You can decide to do that in two ways:
The first is to use the askWithCircuitBreaker method on the ActorRef or ActorSelection instance pointing to your circuit breaker proxy (enabled by importing import akka.contrib.circuitbreaker.Implicits.askWithCircuitBreaker)
class CircuitBreakerAskWithCircuitBreaker(potentiallyFailingService: ActorRef) extends Actor with ActorLogging {
import SimpleService._
import akka.contrib.circuitbreaker.Implicits.askWithCircuitBreaker
implicit val askTimeout: Timeout = 2.seconds
val serviceCircuitBreaker =
context.actorOf(
CircuitBreakerPropsBuilder(maxFailures = 3, callTimeout = askTimeout, resetTimeout = 30.seconds)
.props(target = potentiallyFailingService),
"serviceCircuitBreaker")
import context.dispatcher
override def receive: Receive = {
case AskFor(requestToForward) ⇒
serviceCircuitBreaker.askWithCircuitBreaker(Request(requestToForward)).mapTo[String].onComplete {
case Success(successResponse) ⇒
//handle response
log.info("Got successful response {}", successResponse)
case Failure(exception) ⇒
//handle response
log.info("Got successful response {}", exception)
}
}
}
The second is to map the future response of your ask pattern application with the failForOpenCircuit enabled by importing import akka.contrib.circuitbreaker.Implicits.futureExtensions
class CircuitBreakerAskWithFailure(potentiallyFailingService: ActorRef) extends Actor with ActorLogging {
import SimpleService._
import akka.pattern._
import akka.contrib.circuitbreaker.Implicits.futureExtensions
implicit val askTimeout: Timeout = 2.seconds
val serviceCircuitBreaker =
context.actorOf(
CircuitBreakerPropsBuilder(maxFailures = 3, callTimeout = askTimeout, resetTimeout = 30.seconds)
.props(target = potentiallyFailingService),
"serviceCircuitBreaker")
import context.dispatcher
override def receive: Receive = {
case AskFor(requestToForward) ⇒
(serviceCircuitBreaker ? Request(requestToForward)).failForOpenCircuit.mapTo[String].onComplete {
case Success(successResponse) ⇒
//handle response
log.info("Got successful response {}", successResponse)
case Failure(exception) ⇒
//handle response
log.info("Got successful response {}", exception)
}
}
}
#### Direct Communication With The Target Actor
To send messages to the target actor without expecting any response you can wrap your message in a TellOnly or a Passthrough envelope. The difference between the two is that TellOnly will forward the message only when in closed mode and Passthrough will do it in any state. You can for example use the Passthrough envelope to wrap a PoisonPill message to terminate the target actor. That will cause the circuit breaker proxy to be terminated too
Contents


--- layout: default title: About ---
Hi! My name's Kim, I'm in my early 30's, and obviously I'm amazing at writing 'about me' pages ;)
I was born and raised in the Bay Area. I attended UC Santa Cruz, where I obtained my bachelor's degree in Environmental Studies in 2015. Since then, I've worked in education administration, but I am currently pursuing a career in Environmental Planning.
I'm also very interested in web development and I'm trying to teach myself JavaScript, JQuery, REACT, and Rails. There's definitely a lot to learn!


GIS DATA: nlftp.mlit.go.jp
NOTE: Isolated islands of Tokyo Metropolis don't show up on the window above.


Client Library built on the TON OS API
for Web, Node.js and React Native platforms
Have a question? Get quick help in our channel:
This SDK is distributed via npm packages:
You can find their source code in this repository.
Package probably works OK on other Node.js versions, but we use 14 version in our testing pipelines so we quarantee its stable work only on 14 version.
npm i --save @tonclient/core
The bridge package will download precompiled binaries from TON Labs cloud storage. If you want to rebuild binary from sources see [build binaries](#build binaries) section.
npm i --save @tonclient/lib-node
npm i --save @tonclient/lib-web
Important! Each time you run npm install
the new version of the tonclient.wasm
and index.js
is downloaded. So you have to always update the tonclient.wasm
inside your web package before publishing (starting local web server, creating web bundle etc.). If you use Webpack the best way is to use CopyPlugin.
npm i --save @tonclient/lib-react-native
You must initialize the library before the first use. The best place to do it is an initialization code of your application.
You need to attach the chosen binary module to the TonClient
class.
NodeJs:
const {TonClient} = require("@tonclient/core");
const {libNode} = require("@tonclient/lib-node");
// Application initialization
TonClient.useBinaryLibrary(libNode)
Web:
import {TonClient} from "@tonclient/core";
import {libWeb} from "@tonclient/lib-web";
// Application initialization
TonClient.useBinaryLibrary(libWeb);
By default the library loads wasm module from relative URL /tonclient.wasm
.
You can specify alternative URL if you want to place (or rename) wasm module.
import {TonClient} from "@tonclient/core";
import {libWeb, libWebSetup} from "@tonclient/lib-web";
// Application initialization
libWebSetup({
binaryURL: "/assets/tonclient_1_2_3.wasm",
});
TonClient.useBinaryLibrary(libWeb);
React Native:
import {TonClient} from "@tonclient/core";
import {libReactNative} from "@tonclient/lib-react-native";
// Application initialization
TonClient.useBinaryLibrary(libReactNative);
All library functions are incorporated into TonClient
class. Each client module is represented as a
property of the TonClient
object.
To start use library you must create an instance of the TonClient
class:
const client = new TonClient();
const keys = await client.crypto.generate_random_sign_keys();
You can pass a configuration object in TonClient
constructor:
const client = new TonClient({
network: {
endpoints: ['net.ton.dev']
}
});
In the end, close client to close all the sockets related to it:
client.close();
You can find reference guide to TonClient
here: TON-SDK API Documentation
You can build binaries from sources.
If you install a bridge package from the npmjs
you can build it with the following commands (e.g. for nodejs):
cd node_modules/@tonclient/lib-node/build
cargo run
If you checkout this repository you can build binaries for all bridges.
cd packages/lib-node/build
cargo run
cd ../../../lib-web/build
cargo run
cd ../../../lib-react-native/android/build
cargo run
cd ../../ios/build
cargo run
Also the archives will be created to be published on the TON Labs cloud storage. Archives will be placed into the following folders:
packages/lib-node/publish
packages/lib-web/publish
packages/lib-react-native/ios/publish
packages/lib-react-native/android/publish
This suite has test packages:
tests
– common test package containing all unit tests for a library.tests-node
– tests runner on node js.tests-web
– tests runner on web browser.tests-react-native
– tests runner on react native platform.cd packages/core
npm i
npx tsc
cd packages/tests
npm i
npx tsc
cd packages/tests-node
npm i
node run
cd packages/tests-web
npm i
node run
cd packages/tests-react-native
npm i
node run ios
node run android
TON_USE_SE=true TON_NETWORK_ADDRESS=http://localhost node run
Instead of building library yourself, you can download the latest precompiled binaries from TON Labs SDK Binaries Store.
| Binary | Target | Major | Download links |
|---|---|---|---|
| Node.js AddOn | Win32 | 1 | tonclient.node |
| macOS | 1 | tonclient.node |
|
| Linux | 1 | tonclient.node |
|
| React Native Module | Android x86_64 | 1 | libtonclient.so |
| Android i686 | 1 | libtonclient.so |
|
| Android armv7 | 1 | libtonclient.so |
|
| Android aarch64 | 1 | libtonclient.so |
|
| iOS | 1 | libtonclient.a |
|
| WASM Module | Browser | 1 | tonclient.wasm , index.js |
Downloaded archive is gzipped file
Copyright 2018-2020 TON DEV SOLUTIONS LTD.
Generated using TypeDoc


| Name | Description |
| antiAffin |
Fulfill anti-affinity rule.
|
| balanceDatastoreIOLoad |
Balance datastore I/O workload.
Since vSphere API 5.0
|
| balanceDatastoreIOPSReservation |
Balance datastore IOPS reservation
Since vSphere API 6.0
|
| balanceDatastoreSpaceUsage |
Balance datastore space usage.
Since vSphere API 5.0
|
| checkResource |
Sanity-check resource pool hierarchy
Since vSphere API 4.0
|
| datastoreMaint |
Datastore entering maintenance mode.
Since vSphere API 5.0
|
| datastoreSpaceOutage |
Fix the issue that a datastore run out of space.
Since vSphere API 5.0
|
| enterStandby |
Host entering standby mode.
|
| fairnessCpuAvg |
Balance average CPU utilization.
|
| fairnessMemAvg |
Balance average memory utilization.
|
| ftConstraints |
Fix ft maxVMs and maxVcpus constraint violations
Since vSphere API 6.5
|
| hostExitDegradation |
Host is not degraded.
Since vSphere API 6.5
|
| hostInDegradation |
Host is partially degraded.
Since vSphere API 6.5
|
| hostMaint |
Host entering maintenance mode.
|
| increaseCapacity |
Power on host to increase cluster capacity
|
| iolbDisabledInternal |
IO load balancing was disabled internally.
Since vSphere API 5.0
|
| jointAffin |
Fulfill affinity rule.
|
| maxVmsConstraint |
Fix maxVms constraint violation
Since vSphere API 6.5
|
| networkBandwidthReservation |
Fix network bandwidth reservation violation
Since vSphere API 6.0
|
| powerOnVm |
Power on virtual machine
|
| powerSaving |
Power off host for power savings
|
| reservationCpu |
balance CPU reservations
|
| reservationMem |
balance memory reservations
|
| storagePlacement |
Satisfy storage initial placement requests.
Since vSphere API 5.0
|
| unreservedCapacity |
Maintain unreserved capacity
Since vSphere API 4.0
|
| virtualDiskAntiAffin |
Fix virtual disk anti-affinity rule violation.
Since vSphere API 5.0
|
| virtualDiskJointAffin |
Fix virtual disk affinity rule violation.
Since vSphere API 5.0
|
| vmHostHardAffinity |
Fix hard VM/host affinity rule violation
Since vSphere API 4.1
|
| vmHostSoftAffinity |
Fix soft VM/host affinity rule violation
Since vSphere API 4.1
|
| xvmotionPlacement |
Satisfy unified vmotion placement requests.
Since vSphere API 6.0
|


MENU
HOME
PORTFOLIO
ABOUT
CONTACT
Frederic Davidsen
Founder of
FD Code Studio
Web Developer | Data Scientist
Latest Projects
FD Code Studio
Evelyn Belinda Photography
Birthday Page
Album of High School Memories
Personal Data Science Projects
Current Weather
View all projects


--- title: Increase your Productivity keywords: fastai sidebar: home_sidebar nb_path: "00_core.ipynb" ---
I want to share some shortcuts and tips that have increased my productivity on ML problems. Over the years, I find myself going back to looking up the same commands on Stack Overflow. I want to share commonly used commands with you. The topics that we will focus on are:


Are you still using FTP to deploy your code? Are you still manually performing the same steps of deploying a feature, again and again? How many hours have you spent on ssh-ing into the server, pulling the repo, migrating the database, reloading the web server and so on, for each deployment?? Ever wondered if there is a process as simple as a single click to perform all these steps for you?
Automated Deployment does exactly these things for you. It takes the burden of remembering all the steps required in each deployment process and execute it smoothly.
You don’t need to know the rocket sicence to conclude that machine is reliable, efficient and faster than humans. In context to the software development, be it writing your code, testing your code and deploying your code, it is not a different story. You need to leverage the tools and technologies available, if you want to be a better software engineer. If the tools are free that is even better.
In regard to software deployment, just try to count the number of times you deploy your software to staging, testing or production server, during its life cycle. I am pretty sure you don’t have an exact number, or if you have, it is no less than hundreds. In each deployment you execute, it involves numerous steps; be it running some package installer scripts/commands, migrating your databases, notifying the clients about the deployment, and so on, which you will repeat again and again. You have no guarantee either, that the deployment will be successful each and everytime because YOU, a human, are deploying. Since you are deploying, it is more likely to be error prone than it would have been, had it been automated.
I am going to deliver a presentation in the PHP Dev Meetup #14 on the very topic and below are the slides for that presentation. You can have a look at it and decide for yourself, whether you wanna keep getting stuck to the old fashioned and unreliable deployment process or or you want to follow modern deployment paradigm.
Slides
You can also view the slides in browser from here
There is a part-2 to this blog, in which I have written in detail, on how you can setup and deploy a Laravel 5 project using Capistrano 3. So do check it out.
Happy Deploying!! :)


Before Change
def calc_stable_idx(aeb_df):
"""Calculate the index (epi) when strength first becomes stable (using moving mean and working backward)"""
// interpolate linearly by strength to account for failure to solve
interp_strength = min(1, aeb_df["strength_ma"].max())
std_strength_ra_idx = (aeb_df["strength_ma"] == interp_strength).idxmax()
// index when it first achieved stable std_strength
stable_idx = std_strength_ra_idx - (MA_WINDOW - 1)
After Change
"""Calculate the index (epi) when strength first becomes stable (using moving mean and working backward)"""
std_strength = 1
above_std_strength_sr = (aeb_df["strength_ma"] >= std_strength)
if above_std_strength_sr.any():
// if it achieved stable (ma) std_strength at some point, the index when
std_strength_ra_idx = above_std_strength_sr.idxmax()
stable_idx = std_strength_ra_idx - (MA_WINDOW - 1)
else:
stable_idx = np.nan
return stable_idx


{% verbatim %}
We are planning to build Deep Speech 2 (DS2) [1], a powerful Automatic Speech Recognition (ASR) engine, on PaddlePaddle. For the first-stage plan, we have the following short-term goals:
Intensive system optimization and low-latency inference library (details in [1]) are not yet covered in this first-stage plan.
We roughly break down the project into 14 tasks:
DenseScanner
in dataprovider_converter.py
, etc.ctc_error_evaluator
(CER) to support WER.Tasks parallelizable within phases:
| Roadmap | Description | Parallelizable Tasks |
|---|---|---|
| Phase I | Simplified model & components | Task 1 ~ Task 8 |
| Phase II | Standard model & benchmarking & profiling | Task 9 ~ Task 12 |
| Phase III | Documentations | Task13 ~ Task14 |
Issue for each task will be created later. Contributions, discussions and comments are all highly appreciated and welcomed!
Traditional ASR (Automatic Speech Recognition) pipelines require great human efforts devoted to elaborately tuning multiple hand-engineered components (e.g. audio feature design, accoustic model, pronuncation model and language model etc.). Deep Speech 2 (DS2) [1], however, trains such ASR models in an end-to-end manner, replacing most intermediate modules with only a single deep network architecture. With scaling up both the data and model sizes, DS2 achieves a very significant performance boost.
Please read Deep Speech 2 [1,2] paper for more background knowledge.
The classical DS2 network contains 15 layers (from bottom to top):
We don't have to persist on this 2-3-7-1-1-1 depth [2]. Similar networks with different depths might also work well. As in [1], authors use a different depth (e.g. 2-2-3-1-1-1) for final experiments.
Key ingredients about the layers:
| Required Components | PaddlePaddle Support | Need to Develop |
|---|---|---|
| Data Layer I (Spectrogram) | Not supported yet. | TBD (Task 3) |
| Data Layer II (Transcription) | paddle.data_type.integer_value_sequence | - |
| 2D Convolution Layer | paddle.layer.image_conv_layer | - |
| DataType Converter (vec2seq) | paddle.layer.block_expand | - |
| Bi-/Uni-directional RNNs | paddle.layer.recurrent_group | - |
| Row Convolution Layer | Not supported yet. | TBD (Task 4) |
| CTC-loss Layer | paddle.layer.warp_ctc | - |
| Batch Normalization Layer | paddle.layer.batch_norm | - |
| CTC-Beam search | Not supported yet. | TBD (Task 6) |
TODO by Assignees
if l^+ not in A_prev then
after probabilities' computation is deprecated for it is hard to understand and seems unnecessary.


Fall 2018
Spring 2018
Fall 2017
Spring 2017
Fall 2016
CSCI 561: Foundations of Artifical Intelligence
EE 512: Stochastic Processes
ISE 538: Stochastic Processes
BISC 104: How the body works
Summer 2016
Spring 2016
Fall 2015
Summer 2015
Spring 2015
Fall 2014


overview |
Smisk is basically comprised of three modules:
|
smisk.core |
|
smisk.mvc |
|
smisk.wsgi |
|
title: examples auto-linebreaks: no
overview |
Smisk is basically comprised of three modules:
|
smisk.core |
|
smisk.mvc |
|
smisk.wsgi |
|


Atlas Shrugged: Part I
Atlas Shrugged: Part I is a movie starring Taylor Schilling, Grant Bowler, and Matthew Marsden. Railroad executive Dagny Taggart and steel mogul Henry Rearden form an alliance to fight the increasingly authoritarian government of...


Class: Mocha::Mock
- Inherits:
-
Object
- Object
- Mocha::Mock
- Defined in:
- lib/mocha/mock.rb
Overview
Traditional mock object.
#expects and #stubs return an Expectation which can be further modified by methods on Expectation.
#responds_like and #responds_like_instance_of both return a Mock, and can therefore, be chained to the original creation methods in API. They force the mock to indicate what it is supposed to be mocking, thus making it a safer verifying mock. They check that the underlying responder
will actually respond to the methods being stubbed, throwing a NoMethodError
upon invocation otherwise.
Stubs and expectations are basically the same thing. A stub is just an expectation of zero or more invocations. The #stubs method is syntactic sugar to make the intent of the test more explicit.
When a method is invoked on a mock object, the mock object searches through its expectations from newest to oldest to find one that matches the invocation. After the invocation, the matching expectation might stop matching further invocations. For example, an expects(:foo).once expectation only matches once and will be ignored on future invocations while an expects(:foo).at_least_once expectation will always be matched against invocations.
This scheme allows you to:
-
Set up default stubs in your the
setup
method of your test class and override some of those stubs in individual tests. -
Set up different
once
expectations for the same method with different action per invocation. However, it’s better to use the Expectation#returns method with multiple arguments to do this, as described below.
However, there are some possible “gotchas” caused by this scheme:
-
if you create an expectation and then a stub for the same method, the stub will always override the expectation and the expectation will never be met.
-
if you create a stub and then an expectation for the same method, the expectation will match, and when it stops matching the stub will be used instead, possibly masking test failures.
-
if you create different expectations for the same method, they will be invoked in the opposite order than that in which they were specified, rather than the same order.
The best thing to do is not set up multiple expectations and stubs for the same method with exactly the same matchers. Instead, use the Expectation#returns method with multiple arguments to create multiple actions for a method. You can also chain multiple calls to Expectation#returns and Expectation#raises (along with syntactic sugar Expectation#then if desired).
If you want to specify more complex ordering or order invocations across different mock objects, use the Expectation#in_sequence method to explicitly define a total or partial ordering of invocations.
Instance Method Summary collapse
-
#expects(method_name_or_hash, backtrace = nil) ⇒ Expectation
(also: #__expects__)
Adds an expectation that the specified method must be called exactly once with any parameters.
-
#responds_like(responder) ⇒ Mock
(also: #quacks_like)
Constrains the Mock instance so that it can only expect or stub methods to which
responder
responds publicly. -
#responds_like_instance_of(responder_class) ⇒ Mock
(also: #quacks_like_instance_of)
Constrains the Mock instance so that it can only expect or stub methods to which an instance of the
responder_class
responds publicly. -
#stubs(method_name_or_hash, backtrace = nil) ⇒ Expectation
(also: #__stubs__)
Adds an expectation that the specified method may be called any number of times with any parameters.
- #unstub(*method_names) ⇒ Object
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(symbol, *arguments, &block) ⇒ Object
rubocop:disable Style/MethodMissingSuper
313 314 315 |
# File 'lib/mocha/mock.rb', line 313 def method_missing(symbol, *arguments, &block) handle_method_call(symbol, arguments, block) end |
Instance Method Details
#expects(method_name) ⇒ Expectation #expects(expected_methods_vs_return_values) ⇒ Expectation Also known as: __expects__
Adds an expectation that the specified method must be called exactly once with any parameters.
110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/mocha/mock.rb', line 110 def expects(method_name_or_hash, backtrace = nil) expectation = nil iterator = ArgumentIterator.new(method_name_or_hash) iterator.each do |*args| method_name = args.shift ensure_method_not_already_defined(method_name) expectation = Expectation.new(self, method_name, backtrace) expectation.returns(args.shift) unless args.empty? @expectations.add(expectation) end expectation end |
#responds_like(responder) ⇒ Mock Also known as: quacks_like
Constrains the Mocha::Mock instance so that it can only expect or stub methods to which responder
responds publicly. The constraint is only applied at method invocation time.
A NoMethodError
will be raised if the responder
does not publicly #respond_to?
the invoked method (even if the method has been expected or stubbed).
The Mocha::Mock instance will delegate its #respond_to?
method to the responder
. However, the include_all
parameter is not passed through, so only public methods on the responder
will be considered.
Note that the methods on responder
are never actually invoked.
235 236 237 238 |
# File 'lib/mocha/mock.rb', line 235 def responds_like(responder) @responder = responder self end |
#responds_like_instance_of(responder_class) ⇒ Mock Also known as: quacks_like_instance_of
Constrains the Mocha::Mock instance so that it can only expect or stub methods to which an instance of the responder_class
responds publicly. The constraint is only applied at method invocation time. Note that the responder instance is instantiated using Class#allocate.
A NoMethodError
will be raised if the responder instance does not publicly #respond_to?
the invoked method (even if the method has been expected or stubbed).
The Mocha::Mock instance will delegate its #respond_to?
method to the responder instance. However, the include_all
parameter is not passed through, so only public methods on the responder
will be considered.
Note that the methods on the responder instance are never actually invoked.
268 269 270 |
# File 'lib/mocha/mock.rb', line 268 def responds_like_instance_of(responder_class) responds_like(responder_class.allocate) end |
#stubs(method_name) ⇒ Expectation #stubs(stubbed_methods_vs_return_values) ⇒ Expectation Also known as: __stubs__
Adds an expectation that the specified method may be called any number of times with any parameters.
148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/mocha/mock.rb', line 148 def stubs(method_name_or_hash, backtrace = nil) expectation = nil iterator = ArgumentIterator.new(method_name_or_hash) iterator.each do |*args| method_name = args.shift ensure_method_not_already_defined(method_name) expectation = Expectation.new(self, method_name, backtrace) expectation.at_least(0) expectation.returns(args.shift) unless args.empty? @expectations.add(expectation) end expectation end |
#unstub(*method_names) ⇒ Object
180 181 182 183 184 |
# File 'lib/mocha/mock.rb', line 180 def unstub(*method_names) method_names.each do |method_name| @expectations.remove_all_matching_method(method_name) end end |


Vinicius Freitas
Last updated June 5th, 2018
Recent Work:
Topics of Interest:
- High Performance Computing (HPC)
- Load Balancing
- Scheduling and Global Scheduling
- Supercomputing Applications
- Parallel and Distributed Programming
- Design Patterns applied to HPC
- Parallel and Distributed Algorithms
- OpenMP, MPI, Charm++, OMPSS
Current Work:
2018-06-05


DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.
Debugging Rails Applications
This guide introduces techniques for debugging Ruby on Rails
applications.
After reading this guide, you will know:
- The purpose of debugging.
- How to track down problems and issues in your application that your tests aren't identifying.
- The different ways of debugging.
- How to analyze the stack trace.
View Helpers for Debugging
One common task is to inspect the contents of a variable. Rails
provides three different ways to do this:
debug
to_yaml
inspect
debug
The debug
helper will return a
 tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
<%= debug @article %>

Title:
<%= @article.title %>

You'll see something like this:
--- !ruby/object Article
attributes:
updated_at: 2008-09-05 22:55:47
body: It's a very helpful guide for debugging your Rails app.
title: Rails debugging guide
published: t
id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}
Title: Rails debugging guide
to_yaml
Alternatively, calling to_yaml
on any object converts it to YAML. You can pass this converted object into the simple_format
helper method to format the output. This is how debug
does its magic.
<%= simple_format @article.to_yaml %>

Title:
<%= @article.title %>

The above code will render something like this:
--- !ruby/object Article
attributes:
updated_at: 2008-09-05 22:55:47
body: It's a very helpful guide for debugging your Rails app.
title: Rails debugging guide
published: t
id: "1"
created_at: 2008-09-05 22:55:47
attributes_cache: {}
Title: Rails debugging guide
inspect
Another useful method for displaying object values is inspect
, especially when working with arrays or hashes. This will print the object value as a string. For example:
<%= [1, 2, 3, 4, 5].inspect %>

Title:
<%= @article.title %>

Will render:
[1, 2, 3, 4, 5]
Title: Rails debugging guide
The Logger
It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
What is the Logger?
Rails makes use of the ::ActiveSupport::Logger
class to write log information. Other loggers, such as Log4r
, may also be substituted.
You can specify an alternative logger in config/application.rb
or any other environment file, for example:
config.logger = Logger.new(STDOUT)
config.logger = Log4r::Logger.new("Application Log")
Or in the Initializer
section, add any of the following
Rails.logger = Logger.new(STDOUT)
Rails.logger = Log4r::Logger.new("Application Log")
TIP: By default, each log is created under Rails.root/log/
and the log file is named after the environment in which the application is running.
Log Levels
When something is logged, it's printed into the corresponding log if the log
level of the message is equal to or higher than the configured log level. If you
want to know the current log level, you can call the Rails.logger.level
method.
The available log levels are: :debug
, :info
, :warn
, :error
, :fatal
,
and :unknown
, corresponding to the log level numbers from 0 up to 5,
respectively. To change the default log level, use
config.log_level = :warn # In any environment initializer, or
Rails.logger.level = 0 # at any time
This is useful when you want to log under development or staging without flooding your production log with unnecessary information.
TIP: The default Rails log level is debug
in all environments.
Sending Messages
To write in the current log use the logger.(debug|info|warn|error|fatal|unknown)
method from within a controller, model, or mailer:
logger.debug "Person attributes hash<EMAIL_ADDRESS>logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"
Here's an example of a method instrumented with extra logging:
class ArticlesController < ApplicationController
# ...
def create
@article = Article.new(article_params)
logger.debug "New article<EMAIL_ADDRESS>logger.debug "Article should be valid: #{@article.valid?}"
if @article.save
logger.debug "The article was saved and now the user is going to be redirected..."
redirect_to @article, notice: 'Article was successfully created.'
else
render :new, status: :unprocessable_entity
end
end
# ...
private
def article_params
params.require(:article).permit(:title, :body, :published)
end
end
Here's an example of the log generated when this controller action is executed:
Started POST "/articles" for <IP_ADDRESS> at 2018-10-18 20:09:23 -0400
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XLveDrKzF1SwaiNRPTaMtkrsTzedtebPPkmxEFIU0ordLjICSnXsSNfrdMa4ccyBjuGwnnEiQhEoMN6H1Gtz3A==", "article"=>{"title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs.", "published"=>"0"}, "commit"=>"Create Article"}
New article: {"id"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs.", "published"=>false, "created_at"=>nil, "updated_at"=>nil}
Article should be valid: true
(0.0ms) begin transaction
↳ app/controllers/articles_controller.rb:31
Article Create (0.5ms) INSERT INTO "articles" ("title", "body", "published", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["title", "Debugging Rails"], ["body", "I'm learning how to print in logs."], ["published", 0], ["created_at", "2018-10-19 00:09:23.216549"], ["updated_at", "2018-10-19 00:09:23.216549"]]
↳ app/controllers/articles_controller.rb:31
(2.3ms) commit transaction
↳ app/controllers/articles_controller.rb:31
The article was saved and now the user is going to be redirected...
Redirected to http://localhost:3000/articles/1
Completed 302 Found in 4ms (ActiveRecord: 0.8ms)
Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels to avoid filling your production logs with useless trivia.
Verbose Query Logs
When looking at database query output in logs, it may not be immediately clear why multiple database queries are triggered when a single method is called:
irb(main):001:0> Article.pamplemousse
Article Load (0.4ms) SELECT "articles".* FROM "articles"
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 1]]
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 2]]
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 3]]
#=> #<Comment id: 2, author: "1", body: "Well, actually...", article_id: 1, created_at: "2018-10-19 00:56:10", updated_at: "2018-10-19 00:56:10">
After running ActiveRecord.verbose_query_logs = true
in the bin/rails console
session to enable verbose query logs and running the method again, it becomes obvious what single line of code is generating all these discrete database calls:
irb(main):003:0> Article.pamplemousse
Article Load (0.2ms) SELECT "articles".* FROM "articles"
↳ app/models/article.rb:5
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 1]]
↳ app/models/article.rb:6
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 2]]
↳ app/models/article.rb:6
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."article_id" = ? [["article_id", 3]]
↳ app/models/article.rb:6
#=> #<Comment id: 2, author: "1", body: "Well, actually...", article_id: 1, created_at: "2018-10-19 00:56:10", updated_at: "2018-10-19 00:56:10">
Below each database statement you can see arrows pointing to the specific source filename (and line number) of the method that resulted in a database call. This can help you identify and address performance problems caused by N+1 queries: single database queries that generates multiple additional queries.
Verbose query logs are enabled by default in the development environment logs after Rails 5.2.
WARNING: We recommend against using this setting in production environments. It relies on Ruby's Kernel#caller
method which tends to allocate a lot of memory in order to generate stacktraces of method calls.
Tagged Logging
When running multi-user, multi-account applications, it's often useful
to be able to filter the logs using some custom rules. TaggedLogging
in Active Support helps you do exactly that by stamping log lines with subdomains, request ids, and anything else to aid debugging such applications.
logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
logger.tagged("BCX") { logger.info "Stuff" } # Logs "[BCX] Stuff"
logger.tagged("BCX", "Jason") { logger.info "Stuff" } # Logs "[BCX] [Jason] Stuff"
logger.tagged("BCX") { logger.tagged("Jason") { logger.info "Stuff" } } # Logs "[BCX] [Jason] Stuff"
Impact of Logs on Performance
Logging will always have a small impact on the performance of your Rails app, particularly when logging to disk. Additionally, there are a few subtleties:
Using the :debug
level will have a greater performance penalty than :fatal
,
as a far greater number of strings are being evaluated and written to the
log output (e.g. disk).
Another potential pitfall is too many calls to Logger
in your code:
logger.debug "Person attributes hash<EMAIL_ADDRESS>In the above example, there will be a performance impact even if the allowed
output level doesn't include debug. The reason is that Ruby has to evaluate
these strings, which includes instantiating the somewhat heavy String
object
and interpolating the variables.
Therefore, it's recommended to pass blocks to the logger methods, as these are only evaluated if the output level is the same as — or included in — the allowed level (i.e. lazy loading). The same code rewritten would be:
logger.debug {"Person attributes hash<EMAIL_ADDRESS>The contents of the block, and therefore the string interpolation, are only evaluated if debug is enabled. This performance savings are only really noticeable with large amounts of logging, but it's a good practice to employ.
INFO: This section was written by Jon Cairns at a Stack Overflow answer and it is licensed under cc by-sa 4.0.
Debugging with the debug
Gem
When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.
The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written into the underlying Rails code.
Rails 7 includes the debug
gem in the Gemfile
of new applications generated
by CRuby. By default, it is ready in the development
and test
environments.
Please check its documentation for usage.
Entering a Debugging Session
By default, a debugging session will start after the debug
library is required, which happens when your app boots. But don't worry, the session won't interfere your program.
To enter the debugging session, you can use binding.break
and its aliases: binding.b
and debugger
. The following examples will use debugger
:
class PostsController < ApplicationController
before_action :set_post, only: %i[ show edit update destroy ]
# GET /posts or /posts.json
def index
@posts = Post.all
debugger
end
# ...
end
Once your app evaluates the debugging statement, it'll enter the debugging session:
Processing by PostsController#index as HTML
[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
2| before_action :set_post, only: %i[ show edit update destroy ]
3|
4| # GET /posts or /posts.json
5| def index
6| @posts = Post.all
=> 7| debugger
8| end
9|
10| # GET /posts/1 or /posts/1.json
11| def show
=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
#1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg)
You can exit the debugging session at any time and continue your application execution with the continue
(or c
) command. Or, to exit both the debugging session and your application, use the quit
(or q
) command.
The Context
After entering the debugging session, you can type in Ruby code as you're in a Rails console or IRB.
(rdbg) @posts # ruby
[]
(rdbg) self
#<PostsController:0x0000000000aeb0>
(rdbg)
You can also use p
or pp
command to evaluate Ruby expressions (e.g. when a variable name conflicts with a debugger command).
(rdbg) p headers # command
=> {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Download-Options"=>"noopen", "X-Permitted-Cross-Domain-Policies"=>"none", "Referrer-Policy"=>"strict-origin-when-cross-origin"}
(rdbg) pp headers # command
{"X-Frame-Options"=>"SAMEORIGIN",
"X-XSS-Protection"=>"1; mode=block",
"X-Content-Type-Options"=>"nosniff",
"X-Download-Options"=>"noopen",
"X-Permitted-Cross-Domain-Policies"=>"none",
"Referrer-Policy"=>"strict-origin-when-cross-origin"}
(rdbg)
Besides direct evaluation, debugger also helps you collect rich amount of information through different commands. Just to name a few here:
info
(ori
) - Information about current frame.backtrace
(orbt
) - Backtrace (with additional information).outline
(oro
,ls
) - Available methods, constants, local variables, and instance variables in the current scope.
The info
Command
It'll give you an overview of the values of local and instance variables that are visible from the current frame.
(rdbg) info # command
%self = #<PostsController:0x0000000000af78>
@_action_has_layout = true
@_action_name = "index"
@_config = {}
@_lookup_context = #<ActionView::LookupContext:0x00007fd91a037e38 @details_key=nil, @digest_cache=...
@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for <IP_ADDRESS>>
@_response = #<ActionDispatch::Response:0x00007fd91a03ea08 @mon_data=#<Monitor:0x00007fd91a03e8c8>...
@_response_body = nil
@_routes = nil
@marked_for_same_origin_verification = true
@posts = []
@rendered_format = nil
The backtrace
Command
When used without any options, it lists all the frames on the stack:
=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
#1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
#2 AbstractController::Base#process_action(method_name="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/abstract_controller/base.rb:214
#3 ActionController::Rendering#process_action(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/rendering.rb:53
#4 block in process_action at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/abstract_controller/callbacks.rb:221
#5 block in run_callbacks at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-7.0.0.alpha2/lib/active_support/callbacks.rb:118
#6 ActionText::Rendering::ClassMethods#with_renderer(renderer=#<PostsController:0x0000000000af78>) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-7.0.0.alpha2/lib/action_text/rendering.rb:20
#7 block {|controller=#<PostsController:0x0000000000af78>, action=#<Proc:0x00007fd91985f1c0 /Users/st0012/...|} in <class:Engine> (4 levels) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actiontext-7.0.0.alpha2/lib/action_text/engine.rb:69
#8 [C] BasicObject#instance_exec at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activesupport-7.0.0.alpha2/lib/active_support/callbacks.rb:127
..... and more
Every frame comes with:
- Frame identifier
- Call location
- Additional information (e.g. block or method arguments)
This will give you a great sense about what's happening in your app. However, you probably will notice that:
- There are too many frames (usually 50+ in a Rails app).
- Most of the frames are from Rails or other libraries you use.
Don't worry, the backtrace
command provides 2 options to help you filter frames:
backtrace [num]
- only shownum
numbers of frames, e.g.backtrace 10
.backtrace /pattern/
- only show frames with identifier or location that matches the pattern, e.g.backtrace /MyModel/
.
It's also possible to use these options together: backtrace [num] /pattern/
.
The outline
Command
This command is similar to pry
and irb
's ls
command. It will show you what's accessible from the current scope, including:
- Local variables
- Instance variables
- Class variables
- Methods & their sources
ActiveSupport::Configurable#methods: config
AbstractController::Base#methods:
action_methods action_name action_name= available_action? controller_path inspect
response_body
ActionController::Metal#methods:
content_type content_type= controller_name dispatch headers
location location= media_type middleware_stack middleware_stack=
middleware_stack? performed? request request= reset_session
response response= response_body= response_code session
set_request! set_response! status status= to_a
ActionView::ViewPaths#methods:
_prefixes any_templates? append_view_path details_for_lookup formats formats= locale
locale= lookup_context prepend_view_path template_exists? view_paths
AbstractController::Rendering#methods: view_assigns
# .....
PostsController#methods: create destroy edit index new show update
instance variables:
@_action_has_layout @_action_name @_config @_lookup_context @_request
@_response @_response_body @_routes @marked_for_same_origin_verification @posts
@rendered_format
class variables: @@raise_on_missing_translations @@raise_on_open_redirects
Breakpoints
There are many ways to insert and trigger a breakpoint in the debugger. In addition to adding debugging statements (e.g. debugger
) directly in your code, you can also insert breakpoints with commands:
break
(orb
)break
- list all breakpointsbreak <num>
- set a breakpoint on thenum
line of the current filebreak <file:num>
- set a breakpoint on thenum
line offile
break <Class#method>
orbreak <Class.method>
- set a breakpoint onClass#method
orClass.method
break <expr>.<method>
- sets a breakpoint on<expr>
result's<method>
method.
catch <Exception>
- set a breakpoint that'll stop whenException
is raisedwatch <@ivar>
- set a breakpoint that'll stop when the result of current object's@ivar
is changed (this is slow)
And to remove them, you can use:
delete
(ordel
)delete
- delete all breakpointsdelete <num>
- delete the breakpoint with idnum
The break
Command
Set a breakpoint on a specified line number - e.g. b 28
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
20| end
21|
22| # POST /posts or /posts.json
23| def create
24| @post = Post.new(post_params)
=> 25| debugger
26|
27| respond_to do |format|
28| if @post.save
29| format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
#1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg) b 28 # break command
#0 BP - Line /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line)
(rdbg) c # continue command
[23, 32] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
23| def create
24| @post = Post.new(post_params)
25| debugger
26|
27| respond_to do |format|
=> 28| if @post.save
29| format.html { redirect_to @post, notice: "Post was successfully created." }
30| format.json { render :show, status: :created, location: @post }
31| else
32| format.html { render :new, status: :unprocessable_entity }
=>#0 block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28
#1 ActionController::MimeResponds#respond_to(mimes=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/mime_responds.rb:205
# and 74 frames (use `bt' command for all frames)
Stop by #0 BP - Line /Users/st0012/projects/rails-guide-example/app/controllers/posts_controller.rb:28 (line)
Set a breakpoint on a given method call - e.g. b @post.save
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
20| end
21|
22| # POST /posts or /posts.json
23| def create
24| @post = Post.new(post_params)
=> 25| debugger
26|
27| respond_to do |format|
28| if @post.save
29| format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
#1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg) b @post.save # break command
#0 BP - Method @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43
(rdbg) c # continue command
[39, 48] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb
39| SuppressorRegistry.suppressed[name] = previous_state
40| end
41| end
42|
43| def save(**) # :nodoc:
=> 44| SuppressorRegistry.suppressed[self.class.name] ? true : super
45| end
46|
47| def save!(**) # :nodoc:
48| SuppressorRegistry.suppressed[self.class.name] ? true : super
=>#0 ActiveRecord::Suppressor#save(#arg_rest=nil) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:44
#1 block {|format=#<ActionController::MimeResponds::Collec...|} in create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:28
# and 75 frames (use `bt' command for all frames)
Stop by #0 BP - Method @post.save at /Users/st0012/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/suppressor.rb:43
The catch
Command
Stop when an exception is raised - e.g. catch ActiveRecord::RecordInvalid
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
20| end
21|
22| # POST /posts or /posts.json
23| def create
24| @post = Post.new(post_params)
=> 25| debugger
26|
27| respond_to do |format|
28| if @post.save!
29| format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
#1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg) catch ActiveRecord::RecordInvalid # command
#1 BP - Catch "ActiveRecord::RecordInvalid"
(rdbg) c # continue command
[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb
75| def default_validation_context
76| new_record? ? :create : :update
77| end
78|
79| def raise_validation_error
=> 80| raise(RecordInvalid.new(self))
81| end
82|
83| def perform_validations(options = {})
84| options[:validate] == false || valid?(options[:context])
=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
#1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
# and 88 frames (use `bt' command for all frames)
Stop by #1 BP - Catch "ActiveRecord::RecordInvalid"
The watch
Command
Stop when the instance variable is changed - e.g. watch @_response_body
[20, 29] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
20| end
21|
22| # POST /posts or /posts.json
23| def create
24| @post = Post.new(post_params)
=> 25| debugger
26|
27| respond_to do |format|
28| if @post.save!
29| format.html { redirect_to @post, notice: "Post was successfully created." }
=>#0 PostsController#create at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:25
#1 ActionController::BasicImplicitRender#send_action(method="create", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg) watch @_response_body # command
#0 BP - Watch #<PostsController:0x00007fce69ca5320> @_response_body =
(rdbg) c # continue command
[173, 182] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal.rb
173| body = [body] unless body.nil? || body.respond_to?(:each)
174| response.reset_body!
175| return unless body
176| response.body = body
177| super
=> 178| end
179|
180| # Tests if render or redirect has already happened.
181| def performed?
182| response_body || response.committed?
=>#0 ActionController::Metal#response_body=(body=["You are being  ["You are being <a href=\"ht...
#1 ActionController::Redirecting#redirect_to(options=#<Post id: 13, title: "qweqwe", content:..., response_options={:allow_other_host=>false}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/redirecting.rb:74
# and 82 frames (use `bt' command for all frames)
Stop by #0 BP - Watch #<PostsController:0x00007fce69ca5320> @_response_body = -> ["You are being redirected."]
(rdbg)
Breakpoint Options
In addition to different types of breakpoints, you can also specify options to achieve more advanced debugging workflow. Currently, the debugger supports 4 options:
do: <cmd or expr>
- when the breakpoint is triggered, execute the given command/expression and continue the program:break Foo#bar do: bt
- whenFoo#bar
is called, print the stack frames
pre: <cmd or expr>
- when the breakpoint is triggered, execute the given command/expression before stopping:break Foo#bar pre: info
- whenFoo#bar
is called, print its surrounding variables before stopping.
if: <expr>
- the breakpoint only stops if the result of<expr
> is true:break Post#save if: params[:debug]
- stops atPost#save
ifparams[:debug]
is also true
path: <path_regexp>
- the breakpoint only stops if the event that triggers it (e.g. a method call) happens from the given path:break Post#save if: app/services/a_service
- stops atPost#save
if the method call happens at a method matches Ruby regexp/app\/services\/a_service/
.
Please also note that the first 3 options: do:
, pre:
and if:
are also available for the debug statements we mentioned earlier. For example:
[2, 11] in ~/projects/rails-guide-example/app/controllers/posts_controller.rb
2| before_action :set_post, only: %i[ show edit update destroy ]
3|
4| # GET /posts or /posts.json
5| def index
6| @posts = Post.all
=> 7| debugger(do: "info")
8| end
9|
10| # GET /posts/1 or /posts/1.json
11| def show
=>#0 PostsController#index at ~/projects/rails-guide-example/app/controllers/posts_controller.rb:7
#1 ActionController::BasicImplicitRender#send_action(method="index", args=[]) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/actionpack-7.0.0.alpha2/lib/action_controller/metal/basic_implicit_render.rb:6
# and 72 frames (use `bt' command for all frames)
(rdbg:binding.break) info
%self = #<PostsController:0x00000000017480>
@_action_has_layout = true
@_action_name = "index"
@_config = {}
@_lookup_context = #<ActionView::LookupContext:0x00007fce3ad336b8 @details_key=nil, @digest_cache=...
@_request = #<ActionDispatch::Request GET "http://localhost:3000/posts" for <IP_ADDRESS>>
@_response = #<ActionDispatch::Response:0x00007fce3ad397e8 @mon_data=#<Monitor:0x00007fce3ad396a8>...
@_response_body = nil
@_routes = nil
@marked_for_same_origin_verification = true
@posts = #<ActiveRecord::Relation [#<Post id: 2, title: "qweqwe", content: "qweqwe", created_at: "...
@rendered_format = nil
Program Your Debugging Workflow
With those options, you can script your debugging workflow in one line like:
def create
debugger(do: "catch ActiveRecord::RecordInvalid do: bt 10")
# ...
end
And then the debugger will run the scripted command and insert the catch breakpoint
(rdbg:binding.break) catch ActiveRecord::RecordInvalid do: bt 10
#0 BP - Catch "ActiveRecord::RecordInvalid"
[75, 84] in ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb
75| def default_validation_context
76| new_record? ? :create : :update
77| end
78|
79| def raise_validation_error
=> 80| raise(RecordInvalid.new(self))
81| end
82|
83| def perform_validations(options = {})
84| options[:validate] == false || valid?(options[:context])
=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
#1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
# and 88 frames (use `bt' command for all frames)
Once the catch breakpoint is triggered, it'll print the stack frames
Stop by #0 BP - Catch "ActiveRecord::RecordInvalid"
(rdbg:catch) bt 10
=>#0 ActiveRecord::Validations#raise_validation_error at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:80
#1 ActiveRecord::Validations#save!(options={}) at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/validations.rb:53
#2 block in save! at ~/.rbenv/versions/3.0.1/lib/ruby/gems/3.0.0/gems/activerecord-7.0.0.alpha2/lib/active_record/transactions.rb:302
This technique can save you from repeated manual input and make the debugging experience smoother.
You can find more commands and configuration options from its documentation.
Autoloading Caveat
Debugging with debug
works fine most of the time, but there's an edge case: If you evaluate an expression in the console that autoloads a namespace defined in a file, constants in that namespace won't be found.
For example, if the application has these two files:
# hotel.rb
class Hotel
end
# hotel/pricing.rb
module Hotel::Pricing
end
and Hotel
is not yet loaded, then
(rdbg) p Hotel::Pricing
will raise a NameError
. In some cases, Ruby will be able to resolve an unintended constant in a different scope.
If you hit this, please restart your debugging session with eager loading enabled (config.eager_load = true
).
Stepping commands line next
, continue
, etc., do not present this issue. Namespaces defined implicitly only by
subdirectories are not subject to this issue either.
See ruby/debug#408 for details.
Debugging with the web-console
Gem
Web Console is a bit like debug
, but it runs in the browser. You can request a console in the context of a view or a controller on any page. The console would be rendered next to your HTML content.
Console
Inside any controller action or view, you can invoke the console by
calling the console
method.
For example, in a controller:
class PostsController < ApplicationController
def new
console
@post = Post.new
end
end
Or in a view:
<% console %>

New Post

This will render a console inside your view. You don't need to care about the
location of the console
call; it won't be rendered on the spot of its
invocation but next to your HTML content.
The console executes pure Ruby code: You can define and instantiate custom classes, create new models, and inspect variables.
NOTE: Only one console can be rendered per request. Otherwise web-console
will raise an error on the second console
invocation.
Inspecting Variables
You can invoke instance_variables
to list all the instance variables
available in your context. If you want to list all the local variables, you can
do that with local_variables
.
Settings
config.web_console.allowed_ips
: Authorized list of IPv4 or IPv6 addresses and networks (defaults:<IP_ADDRESS>/8, ::1
).config.web_console.whiny_requests
: Log a message when a console rendering is prevented (defaults:true
).
Since web-console
evaluates plain Ruby code remotely on the server, don't try
to use it in production.
Debugging Memory Leaks
A Ruby application (on Rails or not), can leak memory — either in the Ruby code or at the C code level.
In this section, you will learn how to find and fix such leaks by using tools such as Valgrind.
Valgrind
Valgrind is an application for detecting C-based memory leaks and race conditions.
There are Valgrind tools that can automatically detect many memory management
and threading bugs, and profile your programs in detail. For example, if a C
extension in the interpreter calls malloc()
but doesn't properly call
free()
, this memory won't be available until the app terminates.
For further information on how to install Valgrind and use with Ruby, refer to Valgrind and Ruby by Evan Weaver.
Find a Memory Leak
There is an excellent article about detecting and fixing memory leaks at Derailed, which you can read here.
Plugins for Debugging
There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
- Query Trace Adds query origin tracing to your logs.
- Exception Notifier Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
- Better Errors Replaces the standard Rails error page with a new one containing more contextual information, like source code and variable inspection.
- RailsPanel Chrome extension for Rails development that will end your tailing of development.log. Have all information about your Rails app requests in the browser — in the Developer Tools panel. Provides insight to db/rendering/total times, parameter list, rendered views and more.
- Pry An IRB alternative and runtime developer console.


Ebola border health economic community research trust context political response work livelihood Uganda {border-style Health Uganda. px;} #ffffff;} District []. local cross informal Social fishing study ;():–. cross-border strategies workers dynamics DRC Sciences Virus economy epidemic information mistrust movement porous reported (mis)trust Congolese Participants [,]. [], areas communities control crossing described government leaders members risk Uganda, conducted high individuals low preparedness public structural Disease Hemorrhagic authorities authorities. boda borderlands colonial communities, cultural districts high-risk participants px; social uptake violence water {font-family EVD FGD Fever Research access activities anthropological authority care engage font-size need participant, people points prevention review Available Community Ebola, NGO National Pathogens Trust Ugandan Ugandans Uganda’s Viral additional border. borderland broader consider double; drivers efforts efforts. engagement ethnic formal from: historical implications included individual key livelihoods make outbreak seeking ways (e.g. British Congo DRC, DRC. Kasese Medicine Ministry Uganda: Western anthropology border, border-color border-width borderlands, borders borders. crossed data demonstrates especially findings group importance important limited literature market official ones opportunities particularly policies role rumors rural shape solid; source spread state team understanding {font-style {font-weight Additionally, Arua Biology Cultural Diseases District, Force Kagadi Kampala, Livelihood Local Meanwhile, Platform Red Republic Response Science Study Task University Viruses: World activities. analysis behavior bold borderlands. came case central codes contemporary courier; daily demonstrate disease district em; existing focus given goods help implication including interviews issues level marginalized ongoing participant pay perceived perceptions policy political-economic practices, private pt;} reasons regions religious seek service small strategies, time trusted use using workers,


LEGO® and MINDSTORMS® are trademarks of The LEGO Group of companies which does not sponsor, authorize or endorse this site.


Introduction
Vortex OpenSplice is the leading (commercial and Open Source) implementation of the
Object Management Group's (OMG) Data Distribution Service (DDS) for Real-Time
Systems messaging middleware standard. Vortex OpenSplice is an advanced and
proven data-centric solution that enables seamless, timely, scalable and
dependable distributed data sharing from Embedded and Mobile Devices to the
Enterprise and the Cloud. Vortex OpenSplice delivers the right data, in the right
place, at the right time, every time ; even in the largest-scale mission and
business critical systems.
Key Features:
- Deployed in the most challenging business and mission critical systems
- Seamless Integration with 80+ middleware technologies
- Largest ecosystem of plug-ins and tools for modeling, deployment and testing
- Supported by world-renowned professional services expertise from the developers of the DDS standard
- Genuinely the fastest, most scalable and most reliable Open Source integration technology
- Genuine Open Source LGPLv3 licensing for both its Community and Commercial editions
- Field-proven Interoperability with other DDS Implementations
- Richest set of QoS policies for controlling efficiency, determinism and fault-tolerance
- Runtime choice between simple/standalone and high-performance/federated deployment
- Optional interaction-patterns, implemented on top of DDS: Remote Method invocation (RMI) and transparent batching (STREAMS)
The Vortex OpenSplice components are located in the following sub-directories
of the installation:
-
bin - contains Vortex OpenSplice executables.
-
custom_lib - contains source code of the C++, ISO C++ and Java
language binding, for the customer to re-build to
ensure compliance with platform/compiler.
-
demos - contains demos for Vortex OpenSplice.
-
docs - contains the documentation set and release notes for
Vortex OpenSplice.
-
etc - the default location for the license file and
configuration file(s). In case of the HDE, the
templates for code generation are also located in this
directory.
-
examples - contains code examples (for all supported DDS
languages) demonstrating the use of Vortex OpenSplice.
-
include - contains all Vortex OpenSplice header files.
-
jar - contains all JAVA archives for Vortex OpenSplice API's and
Vortex OpenSplice tools.
-
lib - contains all Vortex OpenSplice library files.
-
redist - depending on the platform this directory contains
redistributable packages needed by Vortex OpenSplice. These
packages are automatically installed.
-
src - contains the source code for the open source components of
Vortex OpenSplice that was used to build the Vortex OpenSplice libraries,
jars, executables, etc of the installed version.
-
tools - contains useful tools/utilities for use with Vortex OpenSplice.
-
release.xxx - running this script in your current shell will
setup the Vortex OpenSplice environment, where
.xxx = .com for Unix and .bat for Windows.
Important Notice
The following rights apply to ADLINK Technology Inc. proprietary software contained in this distribution:
The Software and documentation are Copyright 2006 to TO_YEAR ADLINK Technology Inc. All rights reserved.
The Software and documentation included herein are commercial items.
If the Licensee is the U.S. Government or any agency or department thereof, the Software is
licensed hereunder only as a commercial item subject to Restricted Rights and unless otherwise
expressly agreed in the purchase contract, with only those rights as are granted to all
other end users pursuant to the terms and conditions of ADLINK's Software License Agreement.


A command line parser to be used with Rscript to write "#!" shebang scripts that gracefully accept positional and optional arguments and automatically generate usage.
| Version: | 2.0.0 |
| Imports: | R6, findpython, getopt (≥ 1.19), jsonlite |
| Suggests: | knitr (≥ 1.15.19), testthat |
| Published: | 2018-11-30 |
| Author: | Trevor L Davis [aut, cre], Allen Day [ctb] (Some documentation and examples ported from the getopt package.), Python Software Foundation [ctb] (Some documentation from the optparse Python module.), Paul Newell [ctb] |
| Maintainer: | Trevor L Davis <trevor.l.davis at gmail.com> |
| BugReports: | https://github.com/trevorld/r-argparse/issues |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| Copyright: | See file (inst/)COPYRIGHTS. argparse copyright details |
| URL: | https://github.com/trevorld/r-argparse |
| NeedsCompilation: | no |
| SystemRequirements: | python (>= 3.2) |
| Materials: | README NEWS INSTALL |
| CRAN checks: | argparse results |
| Reference manual: | argparse.pdf |
| Vignettes: |
argparse Command Line Argument Parsing |
| Package source: | argparse_2.0.0.tar.gz |
| Windows binaries: | r-devel: argparse_2.0.0.zip, r-release: argparse_2.0.0.zip, r-oldrel: argparse_2.0.0.zip |
| OS X binaries: | r-release: argparse_2.0.0.tgz, r-oldrel: argparse_2.0.0.tgz |
| Old sources: | argparse archive |
Please use the canonical form https://CRAN.R-project.org/package=argparse to link to this page.


Tennis: Sinner beats De Minaur to win Next Gen ATP Finals
MILAN: Italian teenager Jannik Sinner downed top-seed Australian Alex de Minaur in straight sets to win the Next Gen ATP Finals on home soil in Milan on Saturday (Nov 9).
The 18-year-old Sinner, an eighth-seeded wildcard, saved nine break points to win 4-2, 4-1, 4-2 in just over an hour against 18th-ranked De Minaur, who also lost last year's final to Stefanos Tsitsipas.
The tournament, which began in 2017, features the eight best players aged 21-and-under on the ATP Tour.
The top two players in the category are absent, with Greece's Tsitsipas playing the ATP Tour Finals in London next week, while world number 15 Denis Shapovalov withdrew from Milan after reaching last weekend's Paris Masters final.
It was the first meeting between De Minaur and Sinner, ranked 95.
But the Italian, the youngest competitor in this year's tournament, brushed aside his Australian rival dubbed 'Speed Demon'.
Sinner broke to love in the sixth game of the first set and staved off break points on his serve in the first game of the second set.
Hitting two aces he converted three of his eight break point chances to wrap up the match to love when De Minaur hit a return of serve into the net.
After starting the year ranked at 551, the player from northern Italy, has broken into the top 100.
He also beat another top 20 ranked player France's Gael Monfils last month en route to the semi-finals in Antwerp.
Sinner's winnings for the week over $372,000 overtake his career earnings of $274,470 so far.
The Next Gen tournament also offers a chance to test new innovations. Matches are played in three winning sets with four games, and at tie-break at 3-3.
Coaching is allowed using headphones with hawk-eye replacing line judges.
The let returned this year having being eliminated in the two previous editions.


Source code for src.forms
"""This module contains all forms used by the Observer-Hive frontend.
"""
import os
import json
import logging
from bcrypt import checkpw
from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, EqualTo, Length
logger = logging.getLogger('src')
[docs]def get_users():
"""Retrieve all users and their passwords.
:return: dictionary with all users and passwords
"""
cwd = os.path.dirname(os.path.abspath(__file__))
with open(cwd + '/users.json') as registered_users:
users = json.load(registered_users)
return users
[docs]class LoginForm(FlaskForm):
"""This class defines the login form.
The form provides two entry fields for the user's
credentials: username and password.
"""
username = StringField('username',
validators=[InputRequired(
message="Please enter a Username.")])
password = PasswordField('password',
validators=[InputRequired(
message="Please enter your Password.")])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
[docs] def validate(self):
"""Custom validator for the login form.
Checks if username is known to the app and compares the
entered password to the stored one.
:return: True if all checks have been passed
"""
rv = FlaskForm.validate(self)
if not rv:
return False
users = get_users()
username = self.username.data
if username not in users:
self.username.errors.append('Unknown username')
logger.info(username + ' unknown.')
return False
if not checkpw(self.password.data.encode('utf-8'),
users[username].encode('utf-8')):
self.password.errors.append('Invalid password')
logger.info('Denied access to '
+ username
+ ' due to wrong password.')
return False
return True
[docs]class ChangeCredentialsForm(FlaskForm):
"""This class defines the form to change an existing users password.
The form provides one entry fields for the current password and two
entry fields for new password, the second one being used for verification.
"""
username = StringField('username',
validators=[InputRequired(
message="Please enter a Username.")])
currentPassword = PasswordField('currentPassword',
validators=[
InputRequired(
message="Please enter your current Password.")])
newPassword1 = PasswordField('newPassword1',
validators=[
InputRequired(
message="Please enter your new Password."),
Length(min=4,
message="Your password must contain at least 4 characters.")])
newPassword2 = PasswordField('newPassword2',
validators=[
InputRequired(message=
"Please enter your new Password again."),
EqualTo('newPassword1',
message=
'Passwords must match')])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
[docs] def validate(self):
"""Custom validator to change credentials.
Checks if user provided the correct password currently in use and
changes it if user has entered a new password which has been
verified by entering it a second time.
:return: True if all checks have been passed.
"""
rv = FlaskForm.validate(self)
if not rv:
return False
users = get_users()
if not checkpw(self.currentPassword.data.encode('utf-8'),
users[current_user.id].encode('utf-8')):
self.currentPassword.errors.append('Invalid password')
logger.info('Attempt to change password of '
+ current_user.id
+ ' failed due to wrong current password.')
return False
return True
[docs]class RegisterForm(FlaskForm):
"""This class defines part the registration form.
The form provides entry fields for the chosen username and
two entry fields for a password, the second one being used for verification.
"""
username = StringField('username',
validators=[InputRequired(
message="Please enter a Username.")])
password1 = PasswordField('password1',
validators=[
InputRequired(
message="Please enter your new Password."),
Length(min=4,
message="Your password must contain at least 4 characters.")])
password2 = PasswordField('password2',
validators=[
InputRequired(message=
"Please enter your new Password again."),
EqualTo('password1',
message=
'Passwords must match')])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
[docs] def validate(self):
"""Custom validator for new user registrations.
Checks if password is at least 4 characters long and verifies the
correct entry by comparing it to the second input of password.
:return: True if all checks have been passed.
"""
rv = FlaskForm.validate(self)
if not rv:
return False
return True


Hi welcome to my portfolio. This site will showcase any work past and present work I've done either solo or as a team. I'm in the process of learning HTML, CSS, Ruby etc. That is why my site looks so empty with zero-style and also why I'm currently enrolled at Dev Bootcamp.
Next step CSS!
| Interests | |
|---|---|
|
|
| Basically the arts are my interest |
| Phobias | |
|---|---|
| Falling |
Note: Made table the color red with the bgcolor attribute for the table element.


--- layout: post title: '' date: '2008-07-01T23:21:31-07:00' tags: tumblr_url: http://alexhwilliams.tumblr.com/post/40649469/iterasi-now-has-rss-and-widgets-please-susbcribe ---
iterasi now has RSS and widgets. Please susbcribe to my feed. :-)


Content Editable is a JS library useful to interact and update your content in live. Check out the source code on Github!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aperiam at consequuntur corporis distinctio dolores earum eius eos, explicabo.
| Monday to Friday | 8am to 8pm |
| Saturday | 10am to 7pm |


Return to Paradise is Anything ButBy Michael Asimow, UCLA Law School and Stan Ross, University of New South Wales School of Law (September 1998) The new film Return to Paradise raises profound questions about the gulf between law and justice and about personal moral responsibility. We think every lawyer should see it. Three young Americans meet in Malaysia and enjoy the tourist attractions, including lots of cheap hashish. Tony and Sheriff return to the states, leaving Lewis behind with the hash stash. Hes busted for drugs. Two years later, Tony and Sheriff are getting on with their lives in New York when they are contacted by Beth, Lewis lawyer (outstandingly played by Anne Heche). They learn that Lewis has been convicted and sentenced to death. The sentence will be carried out in eight days. Beth explains that she has struck an unwritten deal with the Attorney General of Malaysia. If Tony and Sheriff return to Malaysia, Lewis life will be spared. If both Tony and Sheriff return, each must serve three years in prison. If only one returns, he must serve six years. Its a classic and quite literal version of the prisoners dilemma. Beth is incredibly persistent in trying to persuade them to go, but she is far from candid in her dealings with them. And she begins a passionate affair with Sheriff. We wont disclose any more of the plot, but consider the issues raised just by this brief summary. The Malaysian drug law imposes an incredibly harsh and unjust penaltya mandatory death sentence for possession of drugs for personal use. This occurs because the law irrebuttably presumes that possession of more than a minimum amount of the drug (200 grams of cannabis, a figure which the film reduces to 100) is trafficking. About 150 people have been executed under this law, including a number of foreigners. Are we being ethnocentric here? At the clemency hearing that occurs near the end of the film, the Malaysian Chief Justice says that Americans dont understand the harshness of Malaysias drug laws. But he observes that Malaysians dont understand the American tolerance toward drugs and the tremendous damage theyve done to our society. Many of the best films about law have dramatized the gulf between law and justice. Recall To Kill a Mockingbird, when an obviously innocent black man is convicted of rape, or Billy Budd, which involved a mandatory death penalty for striking an officer. Or Paths of Glory in which soldiers are selected by lot to be shot because an entire army unit failed to capture an enemy position. I believe Return to Paradise deserves a place alongside these great films. And it may even cause us to question our own incredibly severe minimum penalties for drug offenses, especially for possession of crack cocaine. The reality, however, is that it is extremely unlikely that Lewis would be executed for this offense. According to Professor Sid Harring, only the very worst traffickers or the very most unlucky people are actually executed. There are about ten executions a year but there are probably at least 1000 people who are caught by the police and could potentially get the death penalty. Harring observes that the police drop a large number of cases that might be prosecuted. He also points out that the judiciary manipulates the drug law to acquit a large number of people who are probably guilty. This is to be expected when the penalty is so out of proportion to the gravity of the offense. Thus a large number of defendants are acquitted because they sustain the burden of showing that they lacked "knowledge" of the presence of drugs in their bags or rooms (for example, because there were multiple occupants of the room). Other decisions have allowed defendants to rebut the presumption that possession of specified amounts automatically shows trafficking (though this seems to contravene the statute). Finally, a good many defendants win on appeal or receive clemency. The clemency hearing that occurs in the film is quite inaccurate. The Chief Justice would not preside over such a hearing. Harring says he pointed this out to the filmmakers but they felt that they needed the drama of a judicialized hearing. Instead, the clemency hearing would be provided by an administrative pardons board. The Attorney General would take part in this proceeding and probably could control the outcome. Therefore, it is possible (though unlikely) that the Attorney General would have struck the deal described in the film. It would not have been a plea bargain but instead an agreement by the Attorney General to recommend clemency for Lewis to the pardons board. It is not clear how the AG could have guaranteed to Tony and Sheriff that they would receive three or six year terms since plea bargaining as such does not exist in Malaysia. This film also raises troubling questions of personal responsibility. What is the moral obligation of Tony and Sheriff to return to Malaysia to serve three or six years in prison? Would you go? Lewis was only a casual acquaintance, not a lifelong friend. Even if the AG honors his promise and they have to serve only three or six years, they will do so in a very unpleasant, very dangerous third-world prison. Their lives and relationships will be left in shambles. Yet if they dont go and Lewis is hanged, they may feel remorse for the rest of their lives. Return to Paradise also raises thorny questions of legal ethics. What, for example, is the ethical duty of a lawyer, who is representing a client sentenced to death, in trying to persuade non-clients to return to Malaysia? Certainly, Beth meets and exceeds the standard for zealous representation of her client. But in her dealings with Tony and Sheriff, Beth is less than candid (were not disclosing here in what respect Beth misled Tony and Sheriff). Model Rule 4.1 states that in the course of representing a client a lawyer shall not "knowingly make a false statement of material fact or law to a third person." The comment to Rule 4.1 explains that the lawyer has no affirmative duty to inform an opposing party of relevant facts. Did Beth make false statements or tell half-truths? Or merely fail to inform Tony and Sheriff of relevant facts? And if she was untruthful, could her actions be justified by her clients horrible situation? Did Beth act unethically in starting an affair with Sheriff? Lawyer-client sex is highly frowned on today. Some states have banned it entirely, even if it is entirely consensual. Other states prohibit sexual relations if the client is abused or if the relationship would adversely affect the lawyers ability to represent the client. But here Sheriff is not Beths client, and the affair may well be in Lewis best interests. So maybe starting the affair was a smart and ethical strategic move. In addition to many other issues, Return to Paradise contains troubling material on the irresponsibility of the press. An ambitious American journalist gets wind of the story. Beth pleads with the journalist not to report it because any press disclosure will infuriate the Malaysians and torpedo the deal. Apparently hostile foreign press coverage hastened the execution of two Australians (Barlow and Chalmers). We wont tell you what happens, but lets just say that the story doesnt reflect well on the press. Like many works of popular culture about law, Return to Paradise raises all of these issues and more. It has haunted us and our families. See it if you get the chance. The authors gratefully acknowledge the help of Professor Sid Harring of CUNY Law School and Professor Jesse Wu of the Faculty of Law, Northern Territory University, Australia. We referred extensively to Harrings article, Death, Drugs and Development: Malaysias Mandatory Death Penalty for Traffickers and the International War on Drugs, 29 Colum. J. Transn. Law 365 (1991).
|


CODE A DIFFERENCE: Nutz' deine Fähigkeiten, um deine Stadt zu verbessern!
Many origins
- E-Democracy
- Gov 2.0
- Open Source Govtech
Fueled by
- Open Data
- Open Gov
- Open Source
People/Stakeholders involved
- People inside of governments
- People outside of governments
- YOU!!!
Foundations of a Civic Application
- Open Data or User Driven Data
- Website or Mapping Interface
- Text Messages or Mobile Interface
- Social (in some aspect)
- May use an API (Application Programming Interface)
Useful skills/roles for civic hacking
- The Investigator
- The Communicator
- The Researcher/Data Gatherer
- The Designer
- The Software Developer
- The Project Manager


Version 0.7 Author Michael Schmoock Supports Bitcoin.de, Bitwala, Xapo, Kraken, Otc Currencies Currently only BTC and Eur Sources GitHub sources Disclaimer Use at own risk!


Coding Quiz Challenge
Try to answer the following code-related questions within the time limit. Keep in mind that incorrect answers will penalize your score/time by ten seconds.
Time: 60
Try to answer the following code-related questions within the time limit. Keep in mind that incorrect answers will penalize your score/time by ten seconds.


---
layout: post
title: Virtual chessboard
date: '2013-04-04T18:43:00+02:00'
categories:
- Storyboards
- Atoleiros Battle
picture_url: https://film-Storyboards.tumblr.com/post/47146093444/virtual-chessboard
---
Virtuimagesd animatic frame - second rough, often the best.
The demise of queen Leonor.
D. Juan, King of Castile leave Lisbon promising for vengeance.
Animatic series of drawings done for a cross media project on display at the Battle of Atoleiros Interpretation Centre, Fronteira, Portugal, a project by Maverick ICS
In order to explain visually a complex story of royal intrigue and betrayal, we imagined a virtual chessboard set where each character’s role is crystallised like on a theatre scene. I built a mock up of the room to capture perspective from different angles.


Register Application
Firstname
Lastname
Position
iOS Developer
Ruby on Rails Backend Developer
Android Developer
Frontend Developer
Experience Level
Junior
Intermediate
Senior
Job Type:
Full-Time
Part-Time
Contract
Employment Status:
Employed
Unemployed
Student
Additional Comments


Tell us about your preferred film genres!
Do you consider yourself a cinephile?
What film genres do you like?
Tell me about what you like in a movie:


hAPPy E-Mail Verification
SUCCESSFUL VERIFICATION
Hi ${name},
You successfully verificated your account. Have fun!
Thanks,
The hAPPy Team


Specifying Textures
Now that a texture object has been created on the GPU and it's associated handle has been bound as the active texture, it's time to actually fill that texture object with data.
It's important to make the distinction between GPU memory and CPU memory. You have control of CPU memory, but not GPU memory. Rendering is done mostly using GPU memory. Therefore, to render a texture, you must upload it to GPU memory.
The process of getting a texture into GPU memory is fairly straight forward.
- First, you must have the texture object you want to fill with data bound.
- Read the texture data into CPU memory.
- Upload to the GPU with
GL.TexImage2D
- At this point, you can manually delete CPU memory
- Or let the garbage collector do it, depends on how you loaded the texture
The GL.TexImage2D
function is fairly straight forward, but it does have a lot of arguments
GL.TexImage2D(TextureTarget target, int level, PixelInternalFormat internalFormat, int width, int height, int border, PixelFormat sourceFormat, PixelType sourceType, IntPtr data)
Let's break each argument down
- TextureTarget target
- Which texture are we loading data into? Texture1D, Texture2D, etc..
- Most often (99% of the time) this will be
TextureTarget.Texture2D
- int level
- Specifies how many levels of detail the image has.
- Level 0 is the base, each additional level is a new mip-map
- We will cover mip-maps later. For now, keep this at 0
- PixelInternalFormat internalFormat
- Specifies what the image is formatted for, Color, Light, etc..
- 99% of the time you will use:
PixelInternalFormat.Rgba
- The other two that we use are:
PixelInternalFormat.Rgb
PixelInternalFormat.Alpha
- There are other options, but they are not useful for games.
- int width
- Specifies the width of the texture being loaded
- Remember, you should be using a power of 2!
- int height
- Specifies the height of the texture being loaded
- Remember, you should be using a power of 2!
- int border
- Specifies a memory border, NOT a pixel border
- When written to OpenGL throws an error
- THIS MUST BE 0 (I don't know why they included this paramater)
- PixelFormat sourceFormat
- Spefifies how the source data is laid out
- Values are Argb, Bgra, Rgb, Alpha, etc...
- PixelType sourceType
- Specifies what data type we are storing the source as
- Most often this will be an unsigned byte, values are:
- PixelType.UnsignedByte
- PixelType.Short
- PixelType.Int
- There are more types, but those are the 3 you will most often use
- IntPtr data
- An IntPtr is an unsafe data type
- It can point to any array of numeric data (int[], byte[], etc...)
- This is a long, single dimensional array containing the pixels to upload to the GPU
The function looks complicated, but you only have to really write it once in a friendly wrapper. After calling this function, you can discard the pixel data you are holding onto on the CPU, as the function will have uploaded it to the GPU
Decoder
So, how do we get that array of bytes that represents the texture? We have to decode a texture from it's source format (png, jpg, tga, etc...) into an array of bytes. We're going to use built-in windows functions to do this.
In order to use windows to decode, you must include a reference to System.Drawing, as it contains the Bitmap
class that we will use to decode the texture. The following block of code is commented to explain what is involved in devoding a texture.
private int LoadGLTexture(string filename, out int width, out int height) {
if (string.IsNullOrEmpty(filename)) {
Error("Load texture file path was null");
throw new ArgumentException(filename);
}
// Generate a handle on the GPU
int id = GL.GenTexture();
// Bind the handle to the be the active texture.
GL.BindTexture(TextureTarget.Texture2D, id);
/* TODO:
* Set appropriate min and mag filters
* we will talk about these in the next section
*/
// Allocate CPU system memory for the image
// This will load the encoded texture into CPU memory
Bitmap bmp = new Bitmap(filename);
// Decode the image data and store the byte array into CPU memory
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
/* TODO:
* Check bmp.Width and bmp.Height, if they are not a power
* of two, throw an error
*/
// Upload the image data to the GPU
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
// Mark CPU memory eligable for GC, disposing it
bmp.UnlockBits(bmp_data);
bmp.Dispose();
// Return the textures width, height and GPU ID
width = bmp.Width;
height = bmp.Height;
return id;
}
Using this function is pretty easy. It returns the texture handle and gives you the width & height of the loaded texture as out paramaters:
int texWidth = -1;
int texHeight = -1;
int texHandle = LoadGLTexture("File.png", out texWidth, out texHeight);
So far
Reading the above code, you will notice that we've wrapped not only GL.TexImage2D
, but also GL.GenTexture
and GL.BindTexture
into the LoadGLTexture
helper function. So, our code to load (and eventually display) a texture becomes:
// Enable Texturing
GL.Enable(EnableCap.Texture2D);
// Generate a texture handle, bind it and load it with data
int width = -1;
int height = -1;
int handle = LoadGLTexture(file.png, out width, out height);
Width & Height
By far the easyest way to obtain the width and height of a texture is to store it at the time of loading that texture. However, you don't HAVE to do it this way. You can get the width or height of a texture anytime with the
function.
int GetWidth(int textureId) {
GL.BindTexture(TextureTarget.Texture2D, textureId);
int result = 0;
GL.GetTexLevelParameter(TextureTarget.Texture2D, 0, GetTextureParameter.TextureWidth, out result);
return result;
}
But just storing the width / height at load time is much easyer and much more performant!
Other loading methods
The method we used to load textures here is by far the simplest. It relies on Windows to decode texture files for us. Sometimes, this isn't an option tough. For example, on an iPhone. So, how can we decode textures on non-windows platforms?
A common method is to use stb_image or LodePng. Both are C libraries that you have to compile into a .dll file and link against. Once compiled, you can use C#'s interop features to access the C functions.
If that sounds like a lot of work just to load a texture, well that's because it is! Another way to get texture loading to work is to browse NuGet for a png or jpg decoder package. NuGet is the Visual Studio package manager we used to link against OpenGL (In the form of OpenTK) and NAudio.
We actually use NAudio that we got trough NuGet to decode mp3 files in the OpenTK framework. You can find LodePNG on NuGet if you want to play around with a third party decoder. LodePNG is actually faster than the built in Windows decoder.


public class IntersectionReport
extends java.lang.Object
NamedQuery
objects. The value reported in a given cell is calculated by first AND'ing together
the relevant row and column criterion. In turn the AND'ed expression is provided to a ColumnValueGenerator
which can make use of the query
provided to calculate its particular value. Examples might be running Case.count(query) to get a responsive item count or running Case.search(query)
and tweaking the results to include families or calling methods on CaseStatistics such as getAuditSize(query) to report responsive items total audited size.
This class takes care of iteratively running these things and providing formatting as they are written into an XLSX Excel spreadsheet. If a scope query
is provided via the method IntersectionReportSheetConfiguration.setScopeQuery(String)
, the provided query will be AND'ed together as well with each row/col criteria combination, allowing
you to further scope the overall report to things like particular evidence, item types, tags, etc.| Constructor and Description |
|---|
IntersectionReport(java.lang.String file)
Creates a new instance
|
| Modifier and Type | Method and Description |
|---|---|
void |
generate(nuix.Case nuixCase,
java.lang.String sheetName,
IntersectionReportSheetConfiguration sheetConfig)
Generates a new report sheet using the row criteria, column criteria and value generators currently assigned to this instance
|
ColorRing |
getColCategoryColorRing() |
void |
setColCategoryColorRing(ColorRing colCategoryColorRing) |
void |
whenMessageGenerated(java.util.function.Consumer<java.lang.String> callback) |
void |
whenProgressUpdated(IntersectionReportProgressCallback callback) |
public IntersectionReport(java.lang.String file) throws java.lang.Exception
file
- File path of existing XLSX if you wish to add to an existing workbook, can be nulljava.lang.Exception
- Thrown if there are errorspublic void whenProgressUpdated(IntersectionReportProgressCallback callback)
public void whenMessageGenerated(java.util.function.Consumer<java.lang.String> callback)
public void generate(nuix.Case nuixCase, java.lang.String sheetName, IntersectionReportSheetConfiguration sheetConfig) throws java.lang.Exception
nuixCase
- The Nuix case report data is collected againstsheetName
- The name of the excel worksheet to createsheetConfig
- Configuration details regarding how this sheet should be generatedjava.lang.Exception
- Thrown if there are errorspublic ColorRing getColCategoryColorRing()
public void setColCategoryColorRing(ColorRing colCategoryColorRing)


Welcome to Brit Library
A service dedicated to students of London Metropolitan University. We provide online resources, professional support and guidance to all our students whenever, and from wherever they have chosen to study.
Brit Library currently has over 97 million e-journal titles and a growing collection of e-books. We provide many of the essential reading articles for your course.
Your access
You can access Brit Library 24/7.
View Details
A service dedicated to students of London Metropolitan University. We provide online resources, professional support and guidance to all our students whenever, and from wherever they have chosen to study.
Brit Library currently has over 97 million e-journal titles and a growing collection of e-books. We provide many of the essential reading articles for your course.
Your access
You can access Brit Library 24/7.
View Details
Opening hours
Monday-Friday: 9: 00 - 21: 45
Saturday: 9: 00 - 18: 15
Sunday: 13: 30 - 18: 15
Closed on public holidays
View Details
Monday-Friday: 9: 00 - 21: 45
Saturday: 9: 00 - 18: 15
Sunday: 13: 30 - 18: 15
Closed on public holidays
View Details


WASSCE
Fill in the details of your WASSCE grades.
| Subject | Grade |
|---|
IGSCE
Fill in the details of your IGSCE grades.
| Subject | Grade |
|---|
SAT
Fill in the details of your SAT grades
| Critical Reading | Writing | Maths |
|---|
TOEFL
Fill in the details of your TOEFL grades.
| Writing | Reading | Listening | Speaking |
|---|
OTHER
Fill in the details of other exam you wish to apply with.
| Subject | Grade |
|---|