This article is meant to address some of the practical implications of the Chip8 instruction set and how it can be applied to writing games. Examples will be given using Octo assembler, but should be easy to translate into the assembler of your choice or raw Chip8 bytecode.
The Chip8 specification doesn’t say how fast programs should run. Experimentally, you may find that various games seem intended to run at different speeds. Pong.ch8, for example, is pretty playable when the game runs at about 7 chip8 cycles per frame and a framerate of 60fps. Many interpreters make it possible to adjust their speed for each game. This is less than ideal, however, as it requires players to experiment. Let’s consider a very simple program which moves a sprite on the screen at a fixed rate:
: box
0b11110000
0b10010000
0b10010000
0b11110000
: main
i := box
v0 := 10 # x position
v1 := 10 # y position
loop
clear
sprite v0 v1 4
v0 += 1
again
Since we know the delay
timer counts down at 60hz, we can use it to precisely time an interframe delay. Take a look at this modified program and note that animation will run at a consistent speed even if your interpreter is cranked up really fast:
: box
0b11110000
0b10010000
0b10010000
0b11110000
: sync
loop
vf := delay
if vf != 0 then
again
# delay for up to 1/60th of a second
# using the fixed-rate delay timer
vf := 1
delay := vf
;
: main
i := box
v0 := 10 # x position
v1 := 10 # y position
loop
clear
sprite v0 v1 4
v0 += 1
sync
again
Consider making use of a routine like sync
in your own programs to ensure a consistent gameplay experience on different interpreters.
Whether it’s counting down the number of missiles stored in your gigantic mech or telling you how many human skulls you’ve crushed beneath the treads of your tank, video games frequently involve displaying numbers on screen. Fortunately, Chip8 provides some instructions specially for this purpose.
To display a single digit from a register, we can make use of the hex
statement to load the address of a (built-in) hexadecimal character into i
. Then it’s just a matter of using sprite
to display it:
: main
v0 := 7 # some one-digit number
i := hex v0 # load the address of a character
sprite v0 v0 5 # built in characters are 5 pixels tall
There are two caveats here: the number displayed is in hexadecimal and we can only display a single digit. How do we display larger numbers? That’s where bcd
comes in. It’ll take a number in a register, split it into hundreds, tens and ones and then store those into sequential addresses in memory. Then we use load
to scoop those values into the bottom three registers and use hex
like before to display them.
# temporary storage for hundreds, tens and ones:
: digits 0 0 0
: main
v0 := 137 # some number 0-255
i := digits # the destination for bcd
bcd v0 # unpack digits in v0
va := 10 # x position of first digit
vb := 20 # y position of first digit
i := digits
load v2 # load digits into v0-v2
i := hex v0 # hundreds digit
sprite va vb 5
va += 5
i := hex v1 # tens digit
sprite va vb 5
va += 5
i := hex v2 # ones digit
sprite va vb 5
You can also use bcd
as a way of dividing numbers by 10 or 100, but it’s a little fiddly for this purpose.
It’s easy to make objects move in whole numbers of pixels per second- just store a speed in a register and add that speed to the object’s position every time you update the display. What may be less obvious is how you move objects slower than 1 pixel per frame.
One technique for accomplishing this is to use fixed-point arithmetic and the flag (vf
) register. You’ll store a fractional position in one register, accumulating your speed into it and incrementing the real position whenever the result sets the carry register- that is, whenever the result wraps around.
: ball
0b0110000
0b1001000
0b1001000
0b0110000
: main
i := ball
va := 1 # x position of ball 1 (pixels)
vb := 1 # x position of ball 2 (pixels)
v0 := 0 # x position of ball 1 (fractional)
v1 := 0 # x position of ball 2 (fractional)
v2 := 10 # x velocity of ball 1
v3 := 5 # x velocity of ball 2
loop
vc := 4
sprite va vc 4
vc := 12
sprite vb vc 4
v0 += v2
va += vf
v1 += v3
vb += vf
clear
again
Note that immediate adds (adding a constant) do not set vf
on overflow; we must store the velocity of the balls in registers, at least temporarily.
Say you want to make a turn-based game where a player moves an 8x8 tile at a time. We can use key
to wait for key input and then move the player based on the value we get. In this example I will represent the player’s horizontal and vertical position using a single “tile” coordinate system which numbers each 8x8 region on the screen left to right, top to bottom. Later on, this system would make it easy to add obstacles and tiles which do special things when a player walks on them.
: darwinian
0b00000000
0b00010000
0b00010000
0b01111100
0b00010000
0b00111000
0b00101000
0b00101000
: draw-player
va := v0
vc := 0b00111 # low 3 bits of v0 are the x coordinate
va &= vc # mask them off
va <<= va # multiply by 8 to get pixels
va <<= va
va <<= va
vb := v0
vc := 0b11000 # high 2 bits of v0 are the y coordinate
vb &= vc # mask them off
# and they're already in pixels!
i := darwinian
sprite va vb 8
;
: main
v0 := 12 # the player's position in tiles
loop
draw-player
v1 := key # wait for a keypress
draw-player # erase the player before moving
# assuming a default keyboard layout,
# these numbers will map to ASWD:
if v1 == 7 then v0 += -1 # move left
if v1 == 9 then v0 += 1 # move right
if v1 == 5 then v0 += -8 # move up
if v1 == 8 then v0 += 8 # move down
again
Note that since we do no boundary checking the player can wrap around the edges of the screen. You could add additional logic to prevent this, or you could take advantage of it as a game mechanic.
On the other hand, perhaps the tile coordinate system is unnecessary overhead for your game. Here’s a similar program which uses discrete x and y position registers. A jump table based on jump0
(which jumps to an address + the contents of v0
) is used to decode keypresses. The launch
routine is a subroutine so that after the jump0 and second jump into the body of each handler we can return
to the caller of launch
.
Movement is constrained to avoid having the player wrap around the edges of the screen. Finally, we avoid using subtraction instructions when moving the player by using immediate adds which will wrap around to the desired value.
: darwinian
0b00000000
0b00010000
0b00010000
0b01111100
0b00010000
0b00111000
0b00101000
0b00101000
: lf if va != 0 then va += 248 ;
: rt if va != 56 then va += 8 ;
: up if vb != 0 then vb += 248 ;
: dn if vb != 24 then vb += 8 ;
: code return return return return
return jump up return jump lf
jump dn jump rt return return
return return return return
: launch
# launch is a sub so that jump
# entries can return to the caller.
# jump table entries are
# 2 bytes, so double the key code:
v0 <<= v0
jump0 code
: main
va := 16 # x position
vb := 8 # y position
i := darwinian
loop
sprite va vb 8 # draw sprite
v0 := key # wait for key
sprite va vb 8 # erase sprite
launch
again
The jump0
instruction can be very useful for eliminating complex nests of branches and conditionals. Remember that if your jump table entries are 2 bytes long you can only have 128 in a table (such as if they are jump
s) and if they are 4 bytes long you can only have 64 (such as if they are a subroutine call
followed by a return
).
Say you want to make a game that draws a series of “tiles” to fill the screen as in an RPG overworld. We can start by declaring the tile data the rest of our experiments will use.
# 8x8 tiles for a simple RPG-like overworld
: ground 0b11101111 0b10111101 0b11110111 0b11011110
0b11110111 0b10111101 0b11101111 0b01111011
: water 0b00000000 0b00000000 0b11001100 0b00110000
0b00000000 0b10000110 0b00011000 0b00000000
: tree 0b11000011 0b10101001 0b01010101 0b00101010
0b01010100 0b10000001 0b11100111 0b11000011
: house 0b11111111 0b11100111 0b10011001 0b01111110
0b00000000 0b10111101 0b10100101 0b10100101
First, let’s try writing some simple loops that cover the entire display with tree tiles. Since the Chip8 display is 64x32 and our tiles are 8x8 we’ll draw four rows of 8 tiles:
: main
v0 := 0 # x position
v1 := 0 # y position
i := tree
loop
loop
sprite v0 v1 8
v0 += 8
if v0 != 64 then
again
v0 := 0
v1 += 8
if v1 != 32 then
again
Now we want to extend this program to randomly scatter tiles. Let’s generate a tile offset in v2 by using random
and a mask which will select random numbers spaced 8 bytes apart. This process is made very convenient because both the size and number of tiles are powers of two.
: get-tile
v2 := random 0b11000 # { 0, 8, 16, 24 }
i := ground # the base of the tileset
i += v2 # add the tile in
;
: main
v0 := 0 # x position
v1 := 0 # y position
loop
loop
get-tile
sprite v0 v1 8
v0 += 8
if v0 != 64 then
again
v0 := 0
v1 += 8
if v1 != 32 then
again
What if instead of picking tiles randomly we had static data defining a level? There are many ways we might store the level data with varying degrees of compactness. For simplicity and ease of editing, let’s represent each tile in the map with a byte, 0-3. Data will be stored a row at a time to correspond to the way we draw the level. I’ve rearranged our registers a bit because we need low registers free to be able to use load
.
: map
1 1 1 1 1 2 2 2
1 1 1 1 0 0 0 2
2 0 0 0 0 0 2 2
0 3 0 0 0 2 2 2
: get-tile
i := map # load the tile into v0
i += vc
load v0
v0 <<= v0 # multiply v0 by 8
v0 <<= v0
v0 <<= v0
i := ground
i += v0
;
: main
va := 0 # x position
vb := 0 # y position
vc := 0 # tile index
loop
loop
get-tile
sprite va vb 8
va += 8
vc += 1
if va != 64 then
again
va := 0
vb += 8
if vb != 32 then
again
Naturally we could simplify our get-tile
routine a bit if we stored tiles in multiples of 8 to begin with. Perhaps we could use the lower-order bits to store other information and mask them off with a simple and
before using them to index into the tile sheet. This approach can support up to 32 8x8 tiles before v0
will wrap around while computing an offset for i
. If we wanted more tiles, we would need to add to i
in multiple smaller steps.
In everyday programming, it is not unusual to want to dereference more than one pointer in sequence- imagine indexing a “jagged” 2d array or traversing a linked list. Unfortunately, it is difficult to do something like this in the Chip8 instruction set.
We can only load data from memory through the 16-bit i
register, and and we can only load into an 8 bit ordinary register. i
can be initialized to a constant or we can add an 8 bit value to it. How can we load an arbitrary value in normal registers into i
?
One approach would be to use repeated addition into i
:
v0 := 2 # high 4 bits of desired i
v1 := 37 # low 8 bits of desired i
v2 := 128 # constant
i := 0
i += v1
loop
while v0 != 0
i += v2 # we can't add 256 at once,
i += v2 # so we do it in two steps.
v0 += -1 # equivalent to adding 255
again
Another approach would be to use self-modifying code to place an i := NNN
instruction in memory before executing it. This looks like “0xANNN” in memory, so we can or
our high nybble with 0xA0
.
: code
v0 := 2 # high 4 bits of desired i
v1 := 37 # low 8 bits of desired i
v2 := 0xA0 # constant
v0 |= v2 # now v0-v1 contain our instruction
i := trampoline # select destination for instruction
save v1 # write the instruction
: trampoline 0 0 # destination for i := NNN
If you want to generate an i :=
instruction pointing to a label known at assembly time, you can use Octo’s :unpack
statement to achieve the same trick:
: code
:unpack 0xA some-label # store address in v0-v1
i := trampoline # select destination for instruction
save v1 # write the instruction
: trampoline 0 0 # execute our instruction, setting i.
And another approach could be to use a jump table. This doesn’t allow us to store completely arbitrary values into i
, but it does allow us to select an i
based on the contents of a register. Since the jump table entries are 4 bytes each and are indexed by v0
, we can have at most 64 such entries in a table.
: table
i := 0x123 ;
i := 0x456 ;
i := 0x789 ;
i := 0xABC ;
i := 0xDEF ;
: get-i
# assume get-i is called as a subroutine,
# and v0 contains the table index.
v0 <<= v0 # multiply by 4, the table entry size
v0 <<= v0
jump0 table
Basic Chip8 doesn’t have any instructions for scrolling the screen, but since sprites occupy small regions of memory it’s fairly easy to scroll their images directly. We must remain aware that the load
and save
statements both increment i
to the address immediately after the region of memory they operate upon, which unfortunately is not very useful most of the time.
Let’s begin with a byte-wise scroll upwards of an 8 pixel tall sprite:
: letter 0x18 0x18 0x34 0x24 0x7C 0x62 0xC2 0xE7
: main
loop
v1 := 7 # memory offset
i := letter
load v0
v2 := v0 # prime v2 with the first row for wraparound
loop
i := letter
i += v1
load v0 # fetch the current row
v3 := v0 # stash current row in v3
v0 := v2
i := letter
i += v1
save v0 # write the previous row to the current
v2 := v3 # current becomes previous
v1 += -1
if v1 != -1 then
again
v0 := 10
i := letter
clear
sprite v0 v0 8
again
This is pretty slow. Since our sprite is small and registers are not at a premium, we might try shuffling data around in larger chunks:
: letter 0x18 0x18 0x34 0x24 0x7C 0x62 0xC2 0xE7
: main
loop
i := letter
load v0
v7 := v0 # fetch the top row and move it to v7
load v6 # fetch the remainder of the sprite into v0-v6
i := letter
save v7 # write them all back
v0 := 10
i := letter
clear
sprite v0 v0 8
again
Nice! Unfortunately, this technique uses 8 registers for temporary storage, so you are likely to need to spill some data before employing it.
On the other hand, we might save ourselves quite a bit of grief by repeating our sprite data twice and indexing into it based on a rolling offset, essentially producing a “sliding window” into the underlying sprite data. This approach can be used for other kinds of animation, too:
: letter
0x18 0x18 0x34 0x24 0x7C 0x62 0xC2 0xE7
0x18 0x18 0x34 0x24 0x7C 0x62 0xC2 0xE7
: main
v1 := 0 # window offset
loop
v0 := 10
i := letter
i += v1
clear
sprite v0 v0 8
v1 += 1 # increment v1 modulo 8
v0 := 0b111
v1 &= v0
again
Scrolling horizontally requires bitshifts. Both shift instructions leave vf
with the bit that was shifted out. Rotating a byte left is easy, since we can simply or
vf
into the result of the shift:
v0 <<= v0 # shift most significant bit out left
v0 |= vF # OR it back in as the new least significant bit
Rotating right is slightly more complicated because we need to mask vf
’s 1 or 0 value into the most significant bit of the result.
v0 >>= v0 # shift the least significant bit out right
if vF == 1 then vF := 128
v0 |= vF # OR it back in as the new most significant bit
If we use an unrolled loop, we can employ both operations for an interesting effect:
: letter 0x18 0x18 0x34 0x24 0x7C 0x62 0xC2 0xE7
: main
loop
v2 := 0 # memory offset
loop
i := letter
i += v2
load v1 # read in two bytes
v0 <<= v0
v0 |= vF # rotate left
v1 >>= v1
if vF == 1 then vF := 128
v1 |= vF # rotate right
i := letter
i += v2
save v1 # write back two bytes
v2 += 2
if v2 != 8 then
again
clear
v0 := 10
i := letter
sprite v0 v0 8
again
As demonstrated here, if you have enough registers to spare you can very conveniently operate on chunks of memory at once. An entire sprite can often fit in the Chip8 register file, but you may need to spill and restore your working registers. While it may seem unintuitive coming from other architectures, consider copying sprite data from place to place for animation as an alternative to using frame offsets.
Taking full advantage of the limited set of arithmetic operations available in Chip8 is extremely important for writing efficient programs. Let’s look at some applications of operators which may not be immediately obvious.
If we xor
a register with 0xFF
it inverts all the bits in the original register- this is how you perform a not
:
vf := 0xFF
v0 ^= vf
Any number is 0 if you xor
it with itself, so xor
is often used as an equal-to operator in assembly language. Since the conditional branches in Chip8 can test if a register is equal to a constant or register this use of xor
is not often necessary.
Shifts leave the shifted out bit in vf
. Thus, we can use a left or right shift to obtain the most or least significant bit of a byte, respectively. We can apply this idea to count the number of 1 bits in a byte:
v0 := 0xF3 # number to examine
v1 := 0x00 # the count
loop
while v0 != 0
v0 >>= v0
v1 += vf
again
Of course, if speed was important this could be calculated using a 256-entry lookup table or an unrolled loop.
Sometimes it is useful to obtain the value (1 « N); that is, a particular single-bit vector for masking or setting bits in a register. There is no Chip8 instruction for doing multiple shifts at once, so like many operations the most efficient strategy ends up being to use a lookup table:
: bits 1 2 4 8 16 32 64 128
...
i := bits
i += v0 # index N
load v0 # result
Taking the bitwise or
of N with N+1 will have the effect of setting the least significant (or rightmost) zero bit in the byte:
v1 := v0 # use v1 as a temporary copy
v0 += 1
v0 |= v1
Similarly, the bitwise and
of N with N-1 will clear the least significant (or rightmost) one bit in the byte:
v1 := v0
v0 += -1
v0 &= v1
If a (nonzero) number becomes zero after performing this operation you know it had exactly one bit set and was thus a power of two.


"Iyengar's is serving the society from 30 years by providing high quality food products which are 100% Natural and Pure using the best quality ingredients gathered from the best sources at affordable prices by all classes."


Links on this page open their targets in a second window. If clicking on a link seems not to do anything, that's probably because that window is covered or minimized.
This sample processes a business order instance, as defined by UBL (Universal Business Language). It shows how JAXB helps when developing applications for industry-standard schema. The best thing is to start by running the sample, especially since many of the links in this document refer to the output.
$ JWSDP_HOME=<Your Java WSDP installation directory>
$ $JWSDP_HOME/apache-ant/bin/ant
> set JWSDP_HOME=<Your Java WSDP installation directory>
> %JWSDP_HOME%\apache-ant\bin\ant
This directory structure exists before running the project:
./cd-UBL-1.0 ) Subset of the bundle obtained from | | ) http://docs.oasis-open.org/ubl/cd-UBL-1.0.zip | | | ./xml/office ) Instance documents | | | ) Order instance | | ./UBL-Order-1.0-Office-Example.xml ) processed by | | ) this sample | | | ./xsd ) The UBL schema | | | ./codelist | | | | | ./UBL-CodeList-AcknowledgementResponseCode-1.0.xsd | | ./UBL-CodeList-AllowanceChargeReasonCode-1.0.xsd | | ./UBL-CodeList-ChannelCode-1.0.xsd | | ./UBL-CodeList-ChipCode-1.0.xsd | | ./UBL-CodeList-CountryIdentificationCode-1.0.xsd | | ./UBL-CodeList-CurrencyCode-1.0.xsd | | ./UBL-CodeList-DocumentStatusCode-1.0.xsd | | ./UBL-CodeList-LatitudeDirectionCode-1.0.xsd | | ./UBL-CodeList-LineStatusCode-1.0.xsd | | ./UBL-CodeList-LongitudeDirectionCode-1.0.xsd | | ./UBL-CodeList-OperatorCode-1.0.xsd | | ./UBL-CodeList-PaymentMeansCode-1.0.xsd | | ./UBL-CodeList-SubstitutionStatusCode-1.0.xsd | | | ./common | | | | | ./UBL-CommonAggregateComponents-1.0.xsd | | ./UBL-CommonBasicComponents-1.0.xsd | | ./UBL-CoreComponentParameters-1.0.xsd | | ./UBL-CoreComponentTypes-1.0.xsd | | ./UBL-SpecializedDatatypes-1.0.xsd | | ./UBL-UnspecializedDatatypes-1.0.xsd | | | ./maindoc | | | ./UBL-DespatchAdvice-1.0.xsd | ./UBL-Invoice-1.0.xsd | ./UBL-Order-1.0.xsd | ./UBL-OrderCancellation-1.0.xsd | ./UBL-OrderChange-1.0.xsd | ./UBL-OrderResponse-1.0.xsd | ./UBL-OrderResponseSimple-1.0.xsd | ./UBL-ReceiptAdvice-1.0.xsd | ./build.xml | ./docs | | | ./index.html ) | ./output.html ) Sample-specific documentation | ./xjb.html ) | ./src ) Application source code | | | ./samples/ubl/report ) Application package | | | ./PrintOrder.java ) Order printing | | ) application | | | ./facade ) Code implementing the | | ) facade design pattern | | | ./AddressFacade.java | ./OrderFacade.java | ./OrderLineTypeFacade.java | ./ubl.xjb ) Binding customizations
Running the project creates the directories gen-src
and classes
.
) Java bindings created by processing ./gen-src ) UBL schema with xjc using custom- | | ) izations in ubl.xjb. | | | ./org/oasis/ubl/codelist/acknowledgementresponse | ./org/oasis/ubl/codelist/allowancechargereason | ./org/oasis/ubl/codelist/channel | ./org/oasis/ubl/codelist/chip | ./org/oasis/ubl/codelist/countryidentification | ./org/oasis/ubl/codelist/currency | ./org/oasis/ubl/codelist/documentstatus | ./org/oasis/ubl/codelist/latitudedirection | ./org/oasis/ubl/codelist/linestatus | ./org/oasis/ubl/codelist/longitudedirection | ./org/oasis/ubl/codelist/operator | ./org/oasis/ubl/codelist/paymentmeans | ./org/oasis/ubl/codelist/substitutionstatus | ./org/oasis/ubl/commonaggregatecomponents | ./org/oasis/ubl/commonbasiccomponents | ./org/oasis/ubl/corecomponentparameters | ./org/oasis/ubl/corecomponenttypes | ./org/oasis/ubl/despatchadvice | ./org/oasis/ubl/invoice | ./org/oasis/ubl/order | ./org/oasis/ubl/ordercancellation | ./org/oasis/ubl/orderchange | ./org/oasis/ubl/orderresponse | ./org/oasis/ubl/orderresponsesimple | ./org/oasis/ubl/receiptadvice | ./org/oasis/ubl/specializeddatatypes | ./org/oasis/ubl/unspecializeddatatypes | ./classes ) Packages for the compiled bindings | ) and application code. | ./org/oasis/ubl/codelist/acknowledgementresponse ./org/oasis/ubl/codelist/allowancechargereason ./org/oasis/ubl/codelist/channel ./org/oasis/ubl/codelist/chip ./org/oasis/ubl/codelist/countryidentification ./org/oasis/ubl/codelist/currency ./org/oasis/ubl/codelist/documentstatus ./org/oasis/ubl/codelist/latitudedirection ./org/oasis/ubl/codelist/linestatus ./org/oasis/ubl/codelist/longitudedirection ./org/oasis/ubl/codelist/operator ./org/oasis/ubl/codelist/paymentmeans ./org/oasis/ubl/codelist/substitutionstatus ./org/oasis/ubl/commonaggregatecomponents ./org/oasis/ubl/commonbasiccomponents ./org/oasis/ubl/corecomponentparameters ./org/oasis/ubl/corecomponenttypes ./org/oasis/ubl/despatchadvice ./org/oasis/ubl/invoice ./org/oasis/ubl/order ./org/oasis/ubl/ordercancellation ./org/oasis/ubl/orderchange ./org/oasis/ubl/orderresponse ./org/oasis/ubl/orderresponsesimple ./org/oasis/ubl/receiptadvice ./org/oasis/ubl/specializeddatatypes ./org/oasis/ubl/unspecializeddatatypes ./samples/ubl/report ./samples/ubl/report/facade
If this is the first time you've run the sample, you'll see output similar to this. Here's what's happening in each step.
xjc
)
The schema are in the cd-UBL-1.0/xsd
directory. Ant places the
output in the gen-src
directory.
Binding customizations get applied as part of the schema compilation. Their main purpose is to package the code more logically than if package names were derived from the schema namespaces. These customizations are controlled by this external binding file.
compile
)
Ant places the output in the classes
directory.
run
)To create the Javadoc on, e.g., Unix:
$ $JWSDP_HOME/apache-ant/bin/ant
javadoc
Ant places the output in docs/api
.
PrintOrder
unmarshals a UBL order instance, does some
simple calculations, and prints a report to the screen.
PrintOrder
is in the samples.ubl.report
package. It imports classes having the following functions.
import samples.ubl.report.facade.OrderFacade; import samples.ubl.report.facade.OrderLineTypeFacade; import samples.ubl.report.facade.AddressFacade;
import java.io.FileInputStream; import java.io.IOException;
import java.text.NumberFormat;
import java.util.List;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller;
import org.oasis.ubl.order.Order;
PrintOrder
's main
method:
Unmarshaller
:
JAXBContext jc = JAXBContext.newInstance("org.oasis.ubl.order:" + "org.oasis.ubl.commonaggregatetypes"); Unmarshaller u = jc.createUnmarshaller();
Order order = (Order) u.unmarshal(new FileInputStream("cd-UBL-1.0/xml/office/" + "UBL-Order-1.0-Office-Example.xml"));
OrderFacade of = new OrderFacade(order); printLetterHead(of); printDate(of); printBuyer(of); printLineItems(of);
The private methods in PrintOrder
use the facade
objects to print the data as Strings
. For example:
private static void printLetterHead(OrderFacade order) { AddressFacade addr = order.getSellerAddress(); System.out.println(" " + order.getSellerName() + "\n " + addr.getStreet() + "\n " + addr.getCity() + ", " + addr.getState() + " " + addr.getZip()); }
The facade design pattern provides a simpler, higher-level interface. Typically, that's done to isolate an application from the complexity of the underlying subsystems. Here, our principle motivation is to isolate our application from changes to an evolving schema. Since we just wanted to print a simple report, our facades are read-only.
A look at printBuyer()
in PrintOrder
shows that getting the name of the buyer contact (a person,
usually) is just a matter of calling OrderFacade
's
getBuyerContact()
method:
private static void printBuyer(OrderFacade order) {
AddressFacade addr = order.getBuyerAddress();
System.out.println("\nSold To: "
+ order.getBuyerContact()
+ "\n c/o "
+ order.getBuyerName()
+ "\n "
+ addr.getStreet()
+ "\n "
+ addr.getCity()
+ ", "
+ addr.getState()
+ " "
+ addr.getZip());
}
getBuyerContact()
insulates our application from
potential changes in the schema.
In this snippet,public String getBuyerContact() { BuyerPartyType party = order.getBuyerParty(); return ((Name) party.getParty().getPartyName().getName().get(0)).getValue(); }
order
is a reference to org.oasis.ubl.order.Order
, which is
bound to
in<element name="Order" type="{urn:oasis:names:tc:ubl:Order:1:0}OrderType"/>
UBL-Order-1.0.xsd
. If that binding were to change,
for example, such that order.getBuyerParty()
returned,
let's say, PartyType
, we could make this one-line
change to getBuyerContact()
without affecting
PrintOrder
:
This pattern characterizes the other methods inPartyType party = order.getBuyerParty();
OrderFacade
and the methods in
OrderLineTypeFacade
and AddressFacade
.
For more information about using JAXB, refer to the Java Web Services Tutorial. For more information about UBL, visit OASIS' Universal Business Language Technical Committee site.


NEWS
LAMBORGHINI WORLD
Be sure to keep up with the latest news from Automobili Lamborghini.
HURACÁN EVO “AMPLIFIED SERIES”: THE ART OF ANTICIPATION
Lamborghini Integrated Vehicle Dynamics (LDVI) is the technological brain of the Huracán EVO. Based on the driver’s input, the external environment and the selected driving mode,...
Discover More


vignettes/wlp-git_workflow.Rmd
wlp-git_workflow.Rmd
This tutorial will show you how to use Git and Sourcetree to oversee your project’s workflow.
Using Git allows each member to work on their own part of the project in parallel with other members of your team, without worrying about conflicting versions.
The analogy goes like this:
master
branch is the “trunk” of the project - no changes are directly made herefeature
branch is an offshoot where individual members can work on some aspect in detail - once their purpose is fulfilled, they can be merged back into the master
branch (either directly, or via other feature
branches)This way, work can be compartmentalised while minimalising conflicts and localising each member’s changes, making the process easily accountable for each member.
From the Setup tutorial, you will have been able to clone
the repository into your own machine. We will now go through how you can go about making changes.
Refresh
and Pull
This will be what your interface will look like immediately after cloning.
Refresh
your repository status
by selecting it from this dropdown menu.
Now, you can pull
changes from the remote
repository into your local
repository. Pulling
a branch from the repository means that you are taking that branch and updating your own repository to match the contents of the branch you pulled. This is like synchronising your files between a cloud or online drive and your machine, except you can be quite specific about what you are pulling.
For the tutorial, you can just select the Pull
icon and confirm it on the pop-up window. If you have just cloned
the repository (from the setup tutorial), pulling
will not do anything, since both repositories will be exactly the same.
Checkout
and create branchesA branch
is an instantiation of the repository that allows you to make changes separate from other branches
.
This project already has remote
branches (they are not tracked by our Sourcetree yet), which we can pull to make them local
ly available. Moving from one branch
to another is known as a checkout
.
On the left side pane, select Remotes
, origin
, and then double-click development
. A window will pop up confirming that you would like to Checkout New Branch
. Selecting OK
with the box ticked, this will create a new local
branch called development
, which will have all the developments and changes from that branch on your computer.
Now, let’s create a new branch
from this development
branch. To create a new branch
, select the branch
icon: give it a useful name that tells us exactly what it is for (we will use fix-reversals
), and confirm. Your new branch will now appear on the left under your list of branches. You will now also see on the log
that a new branch has been created.
Keep in mind that you should still try to minimise conflicts with other members of the team by restricting the scope of your changes to a single issue (in our case: only dealing with gloss lines in a dictionary file). Though some conflicts will be inevitable, you can pre-empt them effectively by just sticking to your own parts of the project.
Now you can start to make changes to the file(s) in your repository. When you cloned
your repository, you should have put it somewhere in your directory. The branch
you are currently on is the version of the repository that you can access. If you checkout
other branches, then the files will change accordingly.
You can directly access the folder of your repository by clicking Explorer
.
For this tutorial, we’ll use the following issue as an example.
ISSUE:
We have `\gl` lines to indicate the gloss of a Warlpiri word, and `\rv` lines to indicate which English words should direct to this Warlpiri word in the 'reversed' dictionary. Historically, both functions were handled by the `gl` line, with `^` and `[]` used to indicate the `reversal` entry words, but this was deemed too clunky to validate. To address this, `\rv` lines were introduced: they are clones of `\gl` that have been reduced to limit the size of the reversed dictionary. The consequence is that `\gl` contains unnecessary reversal information and `\rv` is not always succinct. While this is not grammar-breaking, it is aesthetic clutter that can be fixed.
Of course, you can do this line-by-line, but you can also use script to help you out. How you can do this will be covered in another tutorial, but if you find yourself involved in reading or writing script, note the following:
#
).It is helpful to keep a track of your changes as you are making them. DiffMerge is a great desktop tool for this: simply supply the old file and the changed file, and it will show you what the differences are (this is called a diff
). There are also online tools for doing this on the fly (copying and pasting chunks of text).
Once you have completed your changes for the day (or for the entire issue), make sure you keep a note of where those files are saved. Script files belong inside the mini-wlp/scripts
folder, and lexicon files inside the mini-wlp/src
folder.
After you have finished making our changes, you can bring all our changes from the test file into the master file.
Commit
changesA commit
is a saved state of the branch
. By dividing your work up into stages that are summarised by single commits
, you can keep track of what your work progress.
Return to your Sourcetree window and you will see that the log records that there are Uncommitted changes
(i.e. the changes we made in Step 2). Head to File Status
.
Here you will see the changes that Sourcetree has detected: a new untracked
file called clean-reversals.R
(our script) and a modified wlp-lexicon_master.txt
(our lexicon file).
Notice that Sourcetree conveniently provides a diff
of all the changes; you can stage as many or as few changes as you want, but most of the time, you will want to select Stage All
.
You may now commit
the changes you have staged. Summarise those changes in your commit
label, make sure that Push changes immediately to -
is left unchecked, and select Commit
.
You will now see your commit on the log
!
When you are working on your own, you will be cycling through steps 2 and 3 until the aims set out by the feature
branch has been fulfilled. From there, you may proceed with the steps set out by the rest of the tutorial.
Checkout
development
branchOur fix-reversals
branch is now one commit ahead of development
(where we branched off from in Step 1). Once you have completed your work on this branch, it is time to merge back into the main branch
.
To merge, we first checkout the development
branch.
Pull
againRefresh your repository status. Sourcetree will let you know if there is anything new to pull (in our case, nothing - but if someone else has been working on the development
branch in the meantime, there may be new commits to pull
).
Merge
Now we will merge
our two branches: the changes in fix-reversals
will now appear in development
. If you did not need to pull anything in the last step, then this should run without any conflicts.
If someone did make their own changes to development
in the meantime, there may now be conflicts between their version and yours. Git will flag all the conflicts. Refer to the Git problem-solving tutorial on how to resolve merge conflicts.
Push
Now we are ready to push
our files back into the remote repository (where pull
ed in Step 0). Select Push
and a popup window will ask you which branches
you want to push
. If you would like your feature
branch to be available to your collaborators, you may select that to be pushed to a remote branch of the same name.
In this case, since all our work has already been merged into the development
branch, we can simply select development
.
branch
If you did not push
your feature
branch (fix-reversals
), and you have no use for it any more, you may delete
it.
NOTE: If you pushed
your feature
branch (as in Step 8), deleting
your branch will only delete
it locally (on your machine): it will make no difference to the branch on the remote repository. To delete
a remote branch requires a force delete
, which is very dangerous since this will affect how your collaborators use that branch - always discuss with them before deleting
remote branches.
You cannot delete
a branch that you are still on, so make sure you are on the development
branch (or any other branch) when you delete
the feature
branch.
You (and your team members) will cycle through steps 0 to 9 until the development
branch has reached a certain stage of completion. When that happens, your team may consider merging development
into the master
branch. This is basically the same process as set out in Steps 4 to 6: checkout
the master
branch, right-click development
and select Merge
. There should be no conflicts as no one should have been working directly on the master
branch.


The End of the Mobile Web Crisis
Typical Web Experience With a Smartphone
Headlines No Web Developer Likes to See
The Web is Dead. Long Live the Internet (2010)
The Mobile Web Is Dead (2014)
Native Apps Have Crushed Web Apps (2015)
The Problems with the Mobile Web (2016)
Special Sauce Ingridants (1990 - )
TCP/IP
HTTP 1.0
Basic static HTML tags (H1, H2, p, img)
Search Engines
Gave birth to the "Web"
Apps it replaced:
Newspapers, Magazines Delievered to Homes
Encyclopedias
244 years of Encyclopedia Comes to an end
Not everything is rosy
Web Fail: Someone is wrong on the Internet
New Apps it made possible
Pajama Pontificating
No Family recipe will be forgotten
Memes
Whistleblowing impervious to crackdowns
New Special Sauces:
HTTPS / SSL
Forms
Cookies
Server-side Web Application Containers (Perl CGI, ASP, JavaServlets)
Session State
"Shopping Carta"
Apps it replaced:
Sears Catalogs
Gargage Sales
Pick up joints
https://mic.com/articles/112062/the-way-most-people-meet-their-significant-others-is-not-what-you-think#.Ntpz8wSJf
New Apps it made possible
Day Trading in your pajamas
It was called eCommerce
HTML 5.0 -- Death to the Native Desktop Apps
Mobile Fail
Getting Started with Progressive Web Apps
Intalling web apps on a phone for realz.


I'll continue making the graphics library today.
The flow of events is...
Mouse click on canvas
Mouse click on graphical board
Selection on abstract board
Abstract board
Graphical board
Mouse clicks are passed in and board state is passed out.
Honestly, this feels like too much for a tic-tac-toe game. Let me stash some changes and see if I can push the project forward without these abstractions.
I made a winner checker. Then I merged in my previous graphics abstraction work, then I added a draw checker.
With such a small project, I can see the final product in my head from the start and I didn't really need any of the abstractions that I made. I'm not a big fan of my architecture, but I'm not sure if I want to mess with it at this point.
I added a game end notification.
I think a hobby should pick me up out of an emotional funk and get me in a better state of mind. This project is not necessarily doing that, but I need to remember why I'm doing this project.
I'm doing it because I want to learn Phaser. This first project helped me with that, so I was successful there. I also want to reshape my habits so that I start doing this stuff before any other hobbies, especially Reddit. On that front, I've cut into my Reddit time, so I'm successful there.
Now I feel better. Not in an ideal place, but better.


[PART VII.] AUTOMATED VICTIM INFORMATION AND
NOTIFICATION SYSTEM
[§353-131] Definitions. For purposes of this part:
"Offender" means a person in the custody of the department of public safety or the Hawaii paroling authority but does not include juveniles under the jurisdiction of the family court.
"System" means the statewide automated victim information and notification system.
"Victim" means a person against whom a crime has been committed by the offender and includes, in homicide cases, surviving immediate family members. [L 2012, c 190, pt of §1]


Regirock is weak against water-, grass-, ground-, steel- and fighting-type moves, so there are a whole lot of counters you can use against this thing. Check out some of the following below:
- Kyogre with Waterfall and Hydro Pump
- Machamp with Counter/Karate Chop and Dynamic Punch
- Venusaur with Vine Whip/Razor Leaf and Frenzy Plant
- Groudon with Mud Shot and Solar Beam
You can whip out any Community Day starter Pokémon, except fire-types, in this situation, too. Time to dust off that Hydro Cannon Swampert. Just don’t take fire-, ice-, flying-, or bug-type Pokémon.
Lucky players may encounter a Shiny Regiock. Do note that if you do see a Shiny, it will catch on the first ball you hit it with, so use a Pinap Berry to score some extra candy. Regirock’s Shiny is cool because he turns into a chunk of caramel chocolate.
Once you nab your Regirock, give it Rock Throw and Stone Edge for it make the most of its rock-typing, but do note that Regirock is not that great of an attacker.
Regirock will leave raids with its siblings on Nov. 4 at 4 p.m. ET.
For more information on raids, check out our guide here.


The properties of the LogImpl class are listed below. For a complete list of LogImpl class members, see the LogImpl Members topic.
| IsDebugEnabled | Checks if this logger is enabled for the DEBUG level. |
| IsErrorEnabled | Checks if this logger is enabled for the ERROR level. |
| IsFatalEnabled | Checks if this logger is enabled for the FATAL level. |
| IsInfoEnabled | Checks if this logger is enabled for the INFO level. |
| IsWarnEnabled | Checks if this logger is enabled for the WARN level. |
| Logger (inherited from LoggerWrapperImpl) | Gets the implementation behind this wrapper object. |
LogImpl Class | log4net.Core Namespace


Toggle navigation
LFE
Docs
Current
Dev
v1.2
v0.10
v0.9
v0.8
v0.7
Getting Started
Reference
Community
Blog
Documentation
Learning LFE
Quick Start
LFE Tutorial
Exercism.io
Language Comparison Chart
Casting SPELs with LFE
Subject Area Tutorials
Reference
User Guide
User Manual
Style Guide
LFE Programming Rules and Conventions
Building Applications
OTP
YAWS
Dragon
Tooling
Setting Up Text Editors
rebar3
lodox
Community
Discussion and Support
Mail list
IRC
Social Media
Blog
Twitter
Google
Other Resources
Presentations & Videos
History
Blank Page
Subheading
Content, etc.


| req_log/4 | Request logs provided as a cowboy hook. |
req_log(Status, Headers, IoData, Req) -> any()
Request logs provided as a cowboy hook.
Folsom metrics can be triggered by having the cowboy handler setting
a given metrics_source
in the meta
values of the cowboy_req
object. Counts for status codes returned will be accumulated.
If adding a meta
value named start_time
, whose value is obtained
by calling erlang:montonic_time(milli_seconds)
, time difference
calculation will be done between this time value and the end of the
response.
log_enabled
to true
in the cowboy_req
meta
object,
log lines for an HTTP status will be generated for each response.
Generated by EDoc


Feedback from Employer
I would like to say thank you to SFIT Placement Team on behalf of CloudFronts Technologies for your efforts to make your students extremely professional and at the same time friendly. The management and clients are very happy with Mr. Ashish Jagdale from MSBI Department and Mr. Mihir Kadam from MS Dynamics CRM Department. They are doing well at CloudFronts. Their enthusiasm and willingness to learn and grasp will reflect in the partnership for SFIT for years to come.
Warm Regards
Shikha Bhatnagar (Assoc CIPD)
HR Manager
CloudFronts Technologies, LLP
Feedback from Students
"I wish to convey my regards and extend my heartiest gratitude to the Training and Placement Cell of St. Francis Insititute of Teachnology (SFIT). The T&P department of SFIT helped me in being industry aware by holding regular training sessions, conducted both by internal and external faculties, and also by providing various opportunities to explore the corporate world. From being a member of the cell to being a participant in the process itself, the T&P cell has helped me develop an all round expertise in the technical domain as well as in improving my managerial skills. It was indeed an amazing experience to be guided by experienced professionals who had a constant goal of seeking the best possibilities for their students.
Currently, I am happily placed at Tata Consultancy Services and I owe this to the Training and Placement Department of SFIT for providing me with this opportunity and helping me with a direction to shape my knowledge and talents as per industry requirements. Lastly, I would like to thank Mr. Mrinmoy Choudhury, Head of T&P dept., SFIT and Bro. Tom Melchoir, Director, SFIT for being a constant support throughout the placement process, and instilling in us the code of ethics and discipline as expected by the corporate industry.
Thank you."
Regards,
Linus Castelino
<EMAIL_ADDRESS>I would like to express my appreciation towards the Training and Placement department of SFIT for giving students the opportunity to begin their career in some of the leading IT companies such as TCS,Capgemini and L&T. The various training programs organised by the placement department has helped students improve their aptitude and soft skills, which have made them industry ready.
I would like to specially commend Mr. Mrinmoy Chaudhury and Ms. Vidya Redij for their persistent efforts in getting a high placement record for the Academic year 2015-16. I would also like to express my gratitude to the other members of the T&P committee who have worked tirelessly to achieve the same.
In addition, I would also like to thank the Placement Committee for getting me placed in TCS through the Campus drives organised by our college and look forward to apply the skills and experience learnt at SFIT when I commence my career in TCS.
Sean Miranda
<EMAIL_ADDRESS>The training and placement department at SFIT have tried their level best at ensuring students like me are deemed industry worthy by conducting various academic technical and soft skill programs. Through their dedicated and sustained efforts and help, I secured a job at Capgemini India Pvt. Ltd.
I express my gratitude to Prof. Mrinmoy Chaudhury and his team for training and grooming us to be competent and successful engineers.
Nishant Kotian
BE Computers 2015
nktion@gmail.com


-
WE ARE LIU
RECOGNIZED FOR
EXCELLENCEAs the only university in Brooklyn offering a broad diversity of award-winning programs in the liberal and fine arts, health professions, business, pharmacy, education, and more— LIU Brooklyn offers opportunity for every student, all on the safest campus in New York City, as ranked by the Daily Beast.
-
WE ARE LIU
PASSPORT TO
GLOBAL LEADERSHIPDuring summer 2019 Study Abroad sessions, students earned credits while traveling and exploring world cultures in immersion-learning fieldwork in Nicaragua, Costa Rica, Tanzania, South Korea, Slovenia, China, and more.
STUDY ABROAD -
WE ARE LIU
INCREDIBLE ARTS AND
CULTUREKumble Theater for the Performing Arts is a dynamic, state-of-the art performance venue that serves one of the most diverse communities in the nation. Explore Brooklyn’s rich history, catch a Broadway show in Manhattan, or watch professional sports and amazing concerts just a few blocks away at the Barclays Center.
-
WE ARE LIU
A CENTER OF
INNOVATIONAt LIU Brooklyn, our students put their education into practice and bring their ideas to life. Innovative scientific and medical research, diverse experiential learning opportunities, and our new Entrepreneurship Lab are just a few of the ways we are fostering the entrepreneurial spirit.


Final_Space
Final Space is a serialized intergalactic space saga about an astronaut named Gary and his adorable, planet-destroying friend, Mooncake. The series will follow their adventures as they embark on a quest to unlock the mystery of "Final Space", the place where the entire universe ends.


Admin Settings
Site settings
Here you can select the cache mode.
SEO settings
Select whether or not the URLs are optimised for Search Engines.
Select to use a server's rewrite engine to catch URLs that meet specific conditions and rewrite them as directed.
Date & Time
This format is used to display dates on the website.
Languages
Mail Settings


Maxine Waters: Ben Carson Lacks the 'Intelligence' to Be HUD Secretary | Breitbart
by Pam KeyOn Sunday’s broadcast of MSNBC’s “AM Joy,” Rep. Maxine Waters (D-CA) said former neurosurgeon Ben Carson did not have the “intelligence” for his current position as Secretary of Housing and Urban Development.
Carson had said Waters lacks basic manners after she had written President Donald Trump a letter demanding answers on reports that the administration was considering moving homeless people off the streets in California.
Waters said, “I sent him a letter, and he sent me a letter claiming that I had no manner, etc. I basically said to my staff, I really don’t have time to be bonded by somebody who does not know the difference between REO and OEO. This guy just doesn’t have the background, the capability, the intelligence to do the job. He does not know what he’s doing. He doesn’t care about this issue.”
Follow Pam Key on Twitter @pamkeyNEN


About my awesome Landing-Page
This is a fantastic website presenting...
Feature:
One
This awesome feature will...
Best service
ever
Turn on that setting to unleash the full power of...
Last
but not least
The best customer support you can ever have.


|
| #define | MQTT_PORT LWIP_IANA_PORT_MQTT |
| |
| #define | MQTT_TLS_PORT LWIP_IANA_PORT_SECURE_MQTT |
| |
| #define | mqtt_subscribe(client, topic, qos, cb, arg) mqtt_sub_unsub(client, topic, qos, cb, arg, 1) |
| |
| #define | mqtt_unsubscribe(client, topic, cb, arg) mqtt_sub_unsub(client, topic, 0, cb, arg, 0) |
| |
|
| err_t | mqtt_publish (mqtt_client_t *client, const char *topic, const void *payload, u16_t payload_length, u8_t qos, u8_t retain, mqtt_request_cb_t cb, void *arg) |
| |
| err_t | mqtt_sub_unsub (mqtt_client_t *client, const char *topic, u8_t qos, mqtt_request_cb_t cb, void *arg, u8_t sub) |
| |
| void | mqtt_set_inpub_callback (mqtt_client_t *client, mqtt_incoming_publish_cb_t pub_cb, mqtt_incoming_data_cb_t data_cb, void *arg) |
| |
| mqtt_client_t * | mqtt_client_new (void) |
| |
| void | mqtt_client_free (mqtt_client_t *client) |
| |
| err_t | mqtt_client_connect (mqtt_client_t *client, const ip_addr_t *ip_addr, u16_t port, mqtt_connection_cb_t cb, void *arg, const struct mqtt_connect_client_info_t *client_info) |
| |
| void | mqtt_disconnect (mqtt_client_t *client) |
| |
| u8_t | mqtt_client_is_connected (mqtt_client_t *client) |
| |
MQTT client for lwIP
Author: Erik Andersson
Details of the MQTT protocol can be found at:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html
-----------------------------------------------------------------
1. Initial steps, reserve memory and make connection to server:
1.1: Provide storage
Static allocation:
mqtt_client_t static_client;
example_do_connect(&static_client);
Dynamic allocation:
mqtt_client_t *client = mqtt_client_new();
if(client != NULL) {
example_do_connect(&client);
}
1.2: Establish Connection with server
void example_do_connect(mqtt_client_t *client)
{
struct mqtt_connect_client_info_t ci;
err_t err;
/* Setup an empty client info structure */
memset(&ci, 0, sizeof(ci));
/* Minimal amount of information required is client identifier, so set it here */
ci.client_id = "lwip_test";
/* Initiate client and connect to server, if this fails immediately an error code is returned
otherwise mqtt_connection_cb will be called with connection result after attempting
to establish a connection with the server.
For now MQTT version 3.1.1 is always used */
err = mqtt_client_connect(client, ip_addr, MQTT_PORT, mqtt_connection_cb, 0, &ci);
/* For now just print the result code if something goes wrong */
if(err != ERR_OK) {
printf("mqtt_connect return %d\n", err);
}
}
Connection to server can also be probed by calling mqtt_client_is_connected(client)
-----------------------------------------------------------------
2. Implementing the connection status callback
static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status)
{
err_t err;
if(status == MQTT_CONNECT_ACCEPTED) {
printf("mqtt_connection_cb: Successfully connected\n");
/* Setup callback for incoming publish requests */
mqtt_set_inpub_callback(client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, arg);
/* Subscribe to a topic named "subtopic" with QoS level 1, call mqtt_sub_request_cb with result */
err = mqtt_subscribe(client, "subtopic", 1, mqtt_sub_request_cb, arg);
if(err != ERR_OK) {
printf("mqtt_subscribe return: %d\n", err);
}
} else {
printf("mqtt_connection_cb: Disconnected, reason: %d\n", status);
/* Its more nice to be connected, so try to reconnect */
example_do_connect(client);
}
}
static void mqtt_sub_request_cb(void *arg, err_t result)
{
/* Just print the result code here for simplicity,
normal behaviour would be to take some action if subscribe fails like
notifying user, retry subscribe or disconnect from server */
printf("Subscribe result: %d\n", result);
}
-----------------------------------------------------------------
3. Implementing callbacks for incoming publish and data
/* The idea is to demultiplex topic and create some reference to be used in data callbacks
Example here uses a global variable, better would be to use a member in arg
If RAM and CPU budget allows it, the easiest implementation might be to just take a copy of
the topic string and use it in mqtt_incoming_data_cb
*/
static int inpub_id;
static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len)
{
printf("Incoming publish at topic %s with total length %u\n", topic, (unsigned int)tot_len);
/* Decode topic string into a user defined reference */
if(strcmp(topic, "print_payload") == 0) {
inpub_id = 0;
} else if(topic[0] == 'A') {
/* All topics starting with 'A' might be handled at the same way */
inpub_id = 1;
} else {
/* For all other topics */
inpub_id = 2;
}
}
static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags)
{
printf("Incoming publish payload with length %d, flags %u\n", len, (unsigned int)flags);
if(flags & MQTT_DATA_FLAG_LAST) {
/* Last fragment of payload received (or whole part if payload fits receive buffer
See MQTT_VAR_HEADER_BUFFER_LEN) */
/* Call function or do action depending on reference, in this case inpub_id */
if(inpub_id == 0) {
/* Don't trust the publisher, check zero termination */
if(data[len-1] == 0) {
printf("mqtt_incoming_data_cb: %s\n", (const char *)data);
}
} else if(inpub_id == 1) {
/* Call an 'A' function... */
} else {
printf("mqtt_incoming_data_cb: Ignoring payload...\n");
}
} else {
/* Handle fragmented payload, store in buffer, write to file or whatever */
}
}
-----------------------------------------------------------------
4. Using outgoing publish
void example_publish(mqtt_client_t *client, void *arg)
{
const char *pub_payload= "PubSubHubLubJub";
err_t err;
u8_t qos = 2; /* 0 1 or 2, see MQTT specification */
u8_t retain = 0; /* No don't retain such crappy payload... */
err = mqtt_publish(client, "pub_topic", pub_payload, strlen(pub_payload), qos, retain, mqtt_pub_request_cb, arg);
if(err != ERR_OK) {
printf("Publish err: %d\n", err);
}
}
/* Called when publish is complete either with sucess or failure */
static void mqtt_pub_request_cb(void *arg, err_t result)
{
if(result != ERR_OK) {
printf("Publish result: %d\n", result);
}
}
-----------------------------------------------------------------
5. Disconnecting
Simply call mqtt_disconnect(client)
◆ MQTT_PORT
Default MQTT port (non-TLS)
◆ mqtt_subscribe
| #define mqtt_subscribe |
( |
|
client, |
|
|
|
topic, |
|
|
|
qos, |
|
|
|
cb, |
|
|
|
arg |
|
) |
| mqtt_sub_unsub(client, topic, qos, cb, arg, 1) |
◆ MQTT_TLS_PORT
◆ mqtt_unsubscribe
| #define mqtt_unsubscribe |
( |
|
client, |
|
|
|
topic, |
|
|
|
cb, |
|
|
|
arg |
|
) |
| mqtt_sub_unsub(client, topic, 0, cb, arg, 0) |
◆ mqtt_connection_cb_t
Function prototype for mqtt connection status callback. Called when client has connected to the server after initiating a mqtt connection attempt by calling mqtt_client_connect() or when connection is closed by server or an error
- Parameters
-
| client | MQTT client itself |
| arg | Additional argument to pass to the callback function |
| status | Connect result code or disconnection notification |
- See also
- mqtt_connection_status_t
◆ mqtt_incoming_data_cb_t
| typedef void(* mqtt_incoming_data_cb_t) (void *arg, const u8_t *data, u16_t len, u8_t flags) |
Function prototype for MQTT incoming publish data callback function. Called when data arrives to a subscribed topic
- See also
- mqtt_subscribe
- Parameters
-
| arg | Additional argument to pass to the callback function |
| data | User data, pointed object, data may not be referenced after callback return, NULL is passed when all publish data are delivered |
| len | Length of publish data fragment |
| flags | MQTT_DATA_FLAG_LAST set when this call contains the last part of data from publish message |
◆ mqtt_incoming_publish_cb_t
| typedef void(* mqtt_incoming_publish_cb_t) (void *arg, const char *topic, u32_t tot_len) |
Function prototype for MQTT incoming publish function. Called when an incoming publish arrives to a subscribed topic
- See also
- mqtt_subscribe
- Parameters
-
| arg | Additional argument to pass to the callback function |
| topic | Zero terminated Topic text string, topic may not be referenced after callback return |
| tot_len | Total length of publish data, if set to 0 (no publish payload) data callback will not be invoked |
◆ mqtt_request_cb_t
| typedef void(* mqtt_request_cb_t) (void *arg, err_t err) |
Function prototype for mqtt request callback. Called when a subscribe, unsubscribe or publish request has completed
- Parameters
-
| arg | Pointer to user data supplied when invoking request |
| err | ERR_OK on success ERR_TIMEOUT if no response was received within timeout, ERR_ABRT if (un)subscribe was denied |
◆ anonymous enum
Data callback flags
| Enumerator |
|---|
| MQTT_DATA_FLAG_LAST | Flag set when last fragment of data arrives in data callback
|
◆ mqtt_connection_status_t
Connection status codes
| Enumerator |
|---|
| MQTT_CONNECT_ACCEPTED | Accepted
|
| MQTT_CONNECT_REFUSED_PROTOCOL_VERSION | Refused protocol version
|
| MQTT_CONNECT_REFUSED_IDENTIFIER | Refused identifier
|
| MQTT_CONNECT_REFUSED_SERVER | Refused server
|
| MQTT_CONNECT_REFUSED_USERNAME_PASS | Refused user credentials
|
| MQTT_CONNECT_REFUSED_NOT_AUTHORIZED_ | Refused not authorized
|
| MQTT_CONNECT_DISCONNECTED | Disconnected
|
| MQTT_CONNECT_TIMEOUT | Timeout
|
◆ mqtt_client_connect()
Connect to MQTT server
- Parameters
-
| client | MQTT client |
| ip_addr | Server IP |
| port | Server port |
| cb | Connection state change callback |
| arg | User supplied argument to connection callback |
| client_info | Client identification and connection options |
- Returns
- ERR_OK if successful,
- See also
- err_t enum for other results
◆ mqtt_client_free()
Free MQTT client instance
- Parameters
-
| client | Pointer to instance to be freed |
◆ mqtt_client_is_connected()
Check connection with server
- Parameters
-
- Returns
- 1 if connected to server, 0 otherwise
◆ mqtt_client_new()
Create a new MQTT client instance
- Returns
- Pointer to instance on success, NULL otherwise
◆ mqtt_disconnect()
Disconnect from MQTT server
- Parameters
-
◆ mqtt_publish()
MQTT publish function.
- Parameters
-
| client | MQTT client |
| topic | Publish topic string |
| payload | Data to publish (NULL is allowed) |
| payload_length | Length of payload (0 is allowed) |
| qos | Quality of service, 0 1 or 2 |
| retain | MQTT retain flag |
| cb | Callback to call when publish is complete or has timed out |
| arg | User supplied argument to publish callback |
- Returns
- ERR_OK if successful ERR_CONN if client is disconnected ERR_MEM if short on memory
◆ mqtt_set_inpub_callback()
Set callback to handle incoming publish requests from server
- Parameters
-
| client | MQTT client |
| pub_cb | Callback invoked when publish starts, contain topic and total length of payload |
| data_cb | Callback for each fragment of payload that arrives |
| arg | User supplied argument to both callbacks |
◆ mqtt_sub_unsub()
MQTT subscribe/unsubscribe function.
- Parameters
-
| client | MQTT client |
| topic | topic to subscribe to |
| qos | Quality of service, 0 1 or 2 (only used for subscribe) |
| cb | Callback to call when subscribe/unsubscribe reponse is received |
| arg | User supplied argument to publish callback |
| sub | 1 for subscribe, 0 for unsubscribe |
- Returns
- ERR_OK if successful,
- See also
- err_t enum for other results


A jQuery plugin that overhauls the classic color pickers and provides users with a whole new way of selecting desired color codes. Softpedia.com
Do you know the difference between the usual HSL and the human perceived (CIE Lch) sliders?
Use the HSL hue slider, and the human perceived lightness will change a lot between the different hue angles (blue seems to be darker than yellow). Use the CIE hue slider, and the perceived lightness remains much more constant.
Update color from code: hsl(0,100%,50%) rgba(0,255,0,0.5) blue #ffff00 transparent
Hint: you can type in any CSS color (even named ones, like yellow).
The following demo uses the HSL sliders with preview.
 $(".hsl-demo").ColorPickerSliders({ flat: true, previewformat: 'hsl', order: { hsl: 1, preview: 2 } });
The following demo uses the CIE Lch sliders with human perceived lightness. It uses a different customswatches
name and different default swatches
, so the swatches are independent from the other color pickers on this page.
 $(".cielch-demo").ColorPickerSliders({ flat: true, customswatches: "different-swatches-groupname", swatches: ["rgb(174, 156, 227)","rgb(29, 179, 229)","rgb(54, 185, 163)","rgb(144, 176, 105)","rgb(224, 148, 110)","rgb(233, 137, 168)"], order: { cie: 1, preview: 2 } });
The following demo uses the RGB and opacity sliders. The swatches are disabled for this color picker.
 $(".rgb-demo").ColorPickerSliders({ flat: true, swatches: false, order: { rgb: 1, opacity: 2 }, labels: { rgbred: 'Red', rgbgreen: 'Green', rgbblue: 'Blue' } });
The following example is linked to different elements and rendered in popups. Only the cutom swatches are disabled for this demo, so you can use the predefined swatches.
<input id="color" type="text" class="demo-popup" value="#56B29A" data-color-format="hex"> <button type="button" class="demo-popup">button</button> span link $('.demo-popup').ColorPickerSliders({ previewontriggerelement: true, flat: false, color: '#cf966f', customswatches: false, swatches: ['red', 'green', 'blue'], order: { rgb: 1, preview: 2 } });
onchange()
settingthis span is updated on change
<input type="text" class="onchange-example" data-color-format="hex" value="GreenYellow"> this span is updated on change
The following demo uses all the sliders, and connects to a bunch of inputs to show the actual color values in different formats. The color format can be set on the inputs data-color-format
property.
The color can be updated via any of the connected inputs. The plugin uses the excellent Tiny Color plugin, so it handles all valid CSS color formats (CSS color names as well!).
<input type="text" class="full-demo-input" data-color-format="hsl"> <input type="text" class="full-demo-input" data-color-format="hex"> <input type="text" class="full-demo full-demo-input" data-color-format="rgb"> $(".full-demo").ColorPickerSliders({ flat: true, invalidcolorsopacity: 0, connectedinput: '.full-demo-input' });
This color picker can work internally in the CIE Lab color space, represented with the CIE Lch color model. The benefit is the consistent lightness and chroma values between the different colors, so it can represent yellow and blue with the same human perceived lightness. This is not the case with the more known RGB or HSL color models, where yellow is much brighter than blue. Altough, this color picker supports them as well, so you can decide which way to go.
In CIE Lch model, there are colors that can not be converted to RGB values (for example there is no dark yellow color with high chroma value). When there is an Lch variation that can not be represented in the RGB color space, then the color picker searches for the highest possible chroma value for that particular color (for example the only valid chroma value for black or white colors is 0), and uses the lowered chroma value for conversion. This way the color's hue and the lightness will not distorted.
The position markers on the sliders are always shows an exclamation mark when the actual Lch setting can not be converted to an RGB value, but there is more to it! You can make the invalid colors invisible or semi-transparent using the invalidcolorsopacity
setting. This way it is easier to find different hues or lightness with the same chroma.
You can notice that if the chroma is set to too high, then the preview shows the actual color with the highest possible chroma value. See it in action:
 $(".cielch-demo2").ColorPickerSliders({ flat: true, invalidcolorsopacity: 0.2, order: { cie: 1, preview: 2 } });
| Option | Description |
|---|---|
color |
This is the initial color if there is no valid (any CSS formatted) color value on the connected input element. Can be in any format that Tiny Color supports. |
previewformat |
This is the color format on the preview slider (if visible). Can be rgb , hsl or hex . Note that hex format can not represent the opacity value. |
preventtouchkeyboardonshow |
true : Makes the input readonly to prevent touch keyboard to show up on focus, needs a second click to become editable. |
swatches |
array : Array of CSS colors (can be CSS color names as well).false : The swatches are disabled. |
customswatches |
string : Name of the custom swatches group. Color pickers with the same customswatches name share the same swatch colors, so if you add a new color to one of the color pickers, then all the color pickers swatches will be updated on the page which has the same customswatches name.false : The custom swatches are disabled, so only the predefined swatches can be used. |
connectedinput |
selector or jQuery object : The connected input elements value will be automatically updated in sync with the color picker. The color format which the color is represented i the input can be set via the data-color-format property. It can be any of hex , hsl or rgb . If it is hex, then the opacity will be discarded. |
flat |
false : The color picker is rendered in a popup, which is shown on focus of the connected element.true : The color picker is rendered right after the connected element, and is always visible. |
disableautopopup |
false : The popup will be visible on blu or on click.true : No popup shown on blur or on click. Must trigger colorpickersliders.showPopup and colorpickersliders.hidePopup events to show/hide the popup. |
updateinterval |
Update interval of the sliders while dragging (ms). The default is 30. |
previewontriggerelement |
true : Preview of the color on the connected element's background.false : No preview on the connected element. |
previewcontrasttreshold |
30 : If previewontriggerelement is enabled, then if the lightness is below of this value, the element's text color will be white. Otherwise the text is black. |
erroneousciecolormarkers |
true : Unconvertable CIE colors are marked with an exclamation mark on the CIE sliders level marker.false : No exclamation mark on the markers. |
invalidcolorsopacity |
1 : Opacity of the invalid (unconvertable) area of the CIE sliders. |
finercierangeedges |
true : Sharper, more accurate edges of the valid CIE ranges on the sliders.false : Smoother edges of the valid CIE ranges on the sliders. |
order |
An object which defines which sliders appear and in which order. Possible properties: opacity , hsl , rgb , cie , preview . |
labels |
An object which defines the labels of the sliders. Possible properties: hslhue , hslsaturation , hsllightness , rgbred , rgbgreen , rgbblue , cielightness , ciechroma , ciehue , opacity , preview . |
onchange |
function(container, color) : This function is triggered when the color is changed with the sliders or via a connected input. The color parameter holds the actual color object in the following formats: rgb object, hsl object, cie lch object, Tiny Color object. |
titleswatchesadd |
string : Title of the add color to swatches button. |
titleswatchesreset |
string : Title of the reset swatches button. |
Example usage: $("#colorpicker").trigger("colorpickersliders.updateColor", "red");
The following events can be triggered on the element which the color picker is initialized on.
| Event | Description |
|---|---|
colorpickersliders.destroy |
function() : Destroys the color picker. |
colorpickersliders.reset |
function() : Reinitializes the color picker. |
colorpickersliders.updateColor |
function(newcolor) : Sets a new color for the color picker. |
colorpickersliders.showPopup |
function() : Shows the popup if the color picker uses it (it's not flat). |
colorpickersliders.hidePopup |
function() : Hides the popup if the color picker uses it (it's not flat). |


The email
and mobile
attribute/elements must be set on the additionalService
instance, in order for the recipient to receive electronic notification. These elements must the contain the recipient’s mobile phone number and/or e-mail address.
Basic input validation will be performed on both email and phone number provided.


Ezekiel 44:31
The priests shall not eat of any thing that is dead of itself, or torn, whether it be fowl or beast.


My Profile
{% include "boh/snippets/form/_general.html" with control=profile_form.username %}
{% include "boh/snippets/form/_general.html" with control=profile_form.first_name %}
{% include "boh/snippets/form/_general.html" with control=profile_form.last_name %}
{% include "boh/snippets/form/_general.html" with control=profile_form.email %}


--- title: "Using sparklyr with an Apache Spark cluster" output: html_document: toc: true toc_depth: 2 toc_float: collapsed: false params: width: 600 aliases: /articles/deployment-cdh.html ---
This document demonstrates how to use sparklyr
with an Cloudera Hadoop & Spark cluster. Data are downloaded from the web and stored in Hive tables on HDFS across multiple worker nodes. RStudio Server is installed on the master node and orchestrates the analysis in spark.
This demonstration is focused on adding RStudio integration to an existing Cloudera cluster. The assumption will be made that there no aid is needed to setup and administer the cluster.
##CDH 5
We will start with a Cloudera cluster CDH version 5.8.2 (free version) with an underlaying Ubuntu Linux distribution.
##Spark 1.6
The default Spark 1.6.0 parcel is in installed and running
For this demo, we have created and populated 3 tables in Hive. The table names are: flights, airlines and airports. Using Hue, we can see the loaded tables. For the links to the data files and their Hive import scripts please see Appendix A.
The latest version of R is needed. In Ubuntu, the default core R is not the latest so we have to update the source list. We will also install a few other dependencies.
sudo sh -c 'echo "deb http://cran.rstudio.com/bin/linux/ubuntu trusty/" >> /etc/apt/sources.list'
gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9
gpg -a --export E084DAB9 | sudo apt-key add -
sudo apt-get update
sudo apt-get install r-base
sudo apt-get install gdebi-core
sudo apt-get -y install libcurl4-gnutls-dev
sudo apt-get -y install libssl-dev
We will install the preview version of RStudio Server
wget https://s3.amazonaws.com/rstudio-dailybuilds/rstudio-server-1.0.40-amd64.deb
sudo gdebi rstudio-server-1.0.49-amd64.deb
Create a user called rstudio
that will perform the data analysis.
sudo adduser rstudio
To ease security restriction in this demo, we will add the new user to the default super group defined in the dfs.permissions.superusergroup setting in CDH
sudo groupadd supergroup
sudo usermod -a -G supergroup rstudio
Log in to RStudio Server by pointing a browser at your master node IP:8787.
Set the environment variable SPARK_HOME
and then run spark_connect
. After connecting you will be able to browse the Hive metadata in the RStudio Server Spark pane.
library(sparklyr)
library(dplyr)
library(ggplot2)
sc <- spark_connect(master = "yarn-client", version="1.6.0", spark_home = '/opt/cloudera/parcels/CDH/lib/spark/')
Once you are connected, you will see the Spark pane appear along with your hive tables.
You can inspect your tables by clicking on the data icon.
This is what the tables look like loaded in Spark via the History Server Web UI (port 18088)
Is there evidence to suggest that some airline carriers make up time in flight? This analysis predicts time gained in flight by airline carrier.
Use tbl_cache
to load the flights table into memory. Caching tables will make analysis much faster. Create a dplyr reference to the Spark DataFrame.
# Cache flights Hive table into Spark
tbl_cache(sc, 'flights')
flights_tbl <- tbl(sc, 'flights')
# Cache airlines Hive table into Spark
tbl_cache(sc, 'airlines')
airlines_tbl <- tbl(sc, 'airlines')
# Cache airports Hive table into Spark
tbl_cache(sc, 'airports')
airports_tbl <- tbl(sc, 'airports')
Filter the data to contain only the records to be used in the fitted model. Join carrier descriptions for reference. Create a new variable called gain
which represents the amount of time gained (or lost) in flight.
# Filter records and create target variable 'gain'
model_data <- flights_tbl %>%
filter(!is.na(arrdelay) & !is.na(depdelay) & !is.na(distance)) %>%
filter(depdelay > 15 & depdelay < 240) %>%
filter(arrdelay > -60 & arrdelay < 360) %>%
filter(year >= 2003 & year <= 2007) %>%
left_join(airlines_tbl, by = c("uniquecarrier" = "code")) %>%
mutate(gain = depdelay - arrdelay) %>%
select(year, month, arrdelay, depdelay, distance, uniquecarrier, description, gain)
# Summarize data by carrier
model_data %>%
group_by(uniquecarrier) %>%
summarize(description = min(description), gain=mean(gain),
distance=mean(distance), depdelay=mean(depdelay)) %>%
select(description, gain, distance, depdelay) %>%
arrange(gain)
Source: query [?? x 4]
Database: spark connection master=yarn-client app=sparklyr local=FALSE
description gain distance depdelay
<chr> <dbl> <dbl> <dbl>
1 ATA Airlines d/b/a ATA -5.5679651 1240.7219 61.84391
2 Northwest Airlines Inc. -3.1134556 779.1926 48.84979
3 Envoy Air -2.2056576 437.0883 54.54923
4 PSA Airlines Inc. -1.9267647 500.6955 55.60335
5 ExpressJet Airlines Inc. (1) -1.5886314 537.3077 61.58386
6 JetBlue Airways -1.3742524 1087.2337 59.80750
7 SkyWest Airlines Inc. -1.1265678 419.6489 54.04198
8 Delta Air Lines Inc. -0.9829374 956.9576 50.19338
9 American Airlines Inc. -0.9631200 1066.8396 56.78222
10 AirTran Airways Corporation -0.9411572 665.6574 53.38363
# ... with more rows
Predict time gained or lost in flight as a function of distance, departure delay, and airline carrier.

# Calculate average gains by predicted decile
model_deciles <- lapply(model_partition, function(x) {
sdf_predict(ml1, x) %>%
mutate(decile = ntile(desc(prediction), 10)) %>%
group_by(decile) %>%
summarize(gain = mean(gain)) %>%
select(decile, gain) %>%
collect()
})
# Create a summary dataset for plotting
deciles <- rbind(
data.frame(data = 'train', model_deciles$train),
data.frame(data = 'valid', model_deciles$valid),
make.row.names = FALSE
)
# Plot average gains by predicted decile
deciles %>%
ggplot(aes(factor(decile), gain, fill = data)) +
geom_bar(stat = 'identity', position = 'dodge') +
labs(title = 'Average gain by predicted decile', x = 'Decile', y = 'Minutes')
Compare actual gains to predicted gains for an out of time sample.
# Select data from an out of time sample
data_2008 <- flights_tbl %>%
filter(!is.na(arrdelay) & !is.na(depdelay) & !is.na(distance)) %>%
filter(depdelay > 15 & depdelay < 240) %>%
filter(arrdelay > -60 & arrdelay < 360) %>%
filter(year == 2008) %>%
left_join(airlines_tbl, by = c("uniquecarrier" = "code")) %>%
mutate(gain = depdelay - arrdelay) %>%
select(year, month, arrdelay, depdelay, distance, uniquecarrier, description, gain, origin,dest)
# Summarize data by carrier
carrier <- sdf_predict(ml1, data_2008) %>%
group_by(description) %>%
summarize(gain = mean(gain), prediction = mean(prediction), freq = n()) %>%
filter(freq > 10000) %>%
collect
# Plot actual gains and predicted gains by airline carrier
ggplot(carrier, aes(gain, prediction)) +
geom_point(alpha = 0.75, color = 'red', shape = 3) +
geom_abline(intercept = 0, slope = 1, alpha = 0.15, color = 'blue') +
geom_text(aes(label = substr(description, 1, 20)), size = 3, alpha = 0.75, vjust = -1) +
labs(title='Average Gains Forecast', x = 'Actual', y = 'Predicted')
Some carriers make up more time than others in flight, but the differences are relatively small. The average time gains between the best and worst airlines is only six minutes. The best predictor of time gained is not carrier but flight distance. The biggest gains were associated with the longest flights.


| env_bind {rlang} | R Documentation |
These functions create bindings in an environment. The bindings are
supplied through ...
as pairs of names and values or expressions.
env_bind()
is equivalent to evaluating a <-
expression within
the given environment. This function should take care of the
majority of use cases but the other variants can be useful for
specific problems.
env_bind()
takes named values which are bound in .env
.
env_bind()
is equivalent to base::assign()
.
env_bind_active()
takes named functions and creates active
bindings in .env
. This is equivalent to
base::makeActiveBinding()
. An active binding executes a
function each time it is evaluated. The arguments are passed to
as_function()
so you can supply formulas instead of functions.
Remember that functions are scoped in their own environment.
These functions can thus refer to symbols from this enclosure
that are not actually in scope in the dynamic environment where
the active bindings are invoked. This allows creative solutions
to difficult problems (see the implementations of dplyr::do()
methods for an example).
env_bind_lazy()
takes named expressions. This is equivalent
to base::delayedAssign()
. The arguments are captured with
exprs()
(and thus support call-splicing and unquoting) and
assigned to symbols in .env
. These expressions are not
evaluated immediately but lazily. Once a symbol is evaluated, the
corresponding expression is evaluated in turn and its value is
bound to the symbol (the expressions are thus evaluated only
once, if at all).
%<~%
is a shortcut for env_bind_lazy()
. It works like <-
but the RHS is evaluated lazily.
env_bind(.env, ...) env_bind_lazy(.env, ..., .eval_env = caller_env()) env_bind_active(.env, ...) lhs %<~% rhs
.env |
An environment. |
... |
<dynamic> Named objects ( |
.eval_env |
The environment where the expressions will be evaluated when the symbols are forced. |
lhs |
The variable name to which |
rhs |
An expression lazily evaluated and assigned to |
The input object .env
, with its associated environment
modified in place, invisibly.
Since environments have reference semantics (see relevant section
in env()
documentation), modifying the bindings of an environment
produces effects in all other references to that environment. In
other words, env_bind()
and its variants have side effects.
Like other side-effecty functions like par()
and options()
,
env_bind()
and variants return the old values invisibly.
Passing an environment wrapper like a formula or a function instead of an environment is soft-deprecated as of rlang 0.3.0. This internal genericity was causing confusion (see issue #427). You should now extract the environment separately before calling these functions.
env_poke()
for binding a single element.
# env_bind() is a programmatic way of assigning values to symbols # with `<-`. We can add bindings in the current environment: env_bind(current_env(), foo = "bar") foo # Or modify those bindings: bar <- "bar" env_bind(current_env(), bar = "BAR") bar # You can remove bindings by supplying zap sentinels: env_bind(current_env(), foo = zap()) try(foo) # Unquote-splice a named list of zaps zaps <- rep_named(c("foo", "bar"), list(zap())) env_bind(current_env(), !!!zaps) try(bar) # It is most useful to change other environments: my_env <- env() env_bind(my_env, foo = "foo") my_env$foo # A useful feature is to splice lists of named values: vals <- list(a = 10, b = 20) env_bind(my_env, !!!vals, c = 30) my_env$b my_env$c # You can also unquote a variable referring to a symbol or a string # as binding name: var <- "baz" env_bind(my_env, !!var := "BAZ") my_env$baz # The old values of the bindings are returned invisibly: old <- env_bind(my_env, a = 1, b = 2, baz = "baz") old # You can restore the original environment state by supplying the # old values back: env_bind(my_env, !!!old) # env_bind_lazy() assigns expressions lazily: env <- env() env_bind_lazy(env, name = { cat("forced!\n"); "value" }) # Referring to the binding will cause evaluation: env$name # But only once, subsequent references yield the final value: env$name # You can unquote expressions: expr <- quote(message("forced!")) env_bind_lazy(env, name = !!expr) env$name # By default the expressions are evaluated in the current # environment. For instance we can create a local binding and refer # to it, even though the variable is bound in a different # environment: who <- "mickey" env_bind_lazy(env, name = paste(who, "mouse")) env$name # You can specify another evaluation environment with `.eval_env`: eval_env <- env(who = "minnie") env_bind_lazy(env, name = paste(who, "mouse"), .eval_env = eval_env) env$name # Or by unquoting a quosure: quo <- local({ who <- "fievel" quo(paste(who, "mouse")) }) env_bind_lazy(env, name = !!quo) env$name # You can create active bindings with env_bind_active(). Active # bindings execute a function each time they are evaluated: fn <- function() { cat("I have been called\n") rnorm(1) } env <- env() env_bind_active(env, symbol = fn) # `fn` is executed each time `symbol` is evaluated or retrieved: env$symbol env$symbol eval_bare(quote(symbol), env) eval_bare(quote(symbol), env) # All arguments are passed to as_function() so you can use the # formula shortcut: env_bind_active(env, foo = ~ runif(1)) env$foo env$foo


This is an extension of the dynamic example, but this time the data is coming in from an hidden input field. The input field is updated in realtime, as we update the tags.


States are provided to simplify and accelerate the creation of dynamic user interfaces within your application.
You don’t need to know how to code to use states. Designers can create dynamic UI via options in the design tool:
For more advanced scenarios, developers can manipulate states via an API. You can use the States API to:
/** * Sets the current state of the application interface. * You can subscribe to changes in state using the following call: * davinci.states.subscribe("/davinci/states/state/changed", callback) * @return undefined */ davinci.states.setState(stateName); /** * Gets the current state of the application interface. * @return string */ davinci.states.getState();
In addition to the basic style changes set in the design tool, you may need to add more complex animations to your application, execute business logic, or trigger states changes via application events. The following examples demonstrate how to accomplish these types of goals.
You can add complex animations to your application by listening for the state changed event, and executing a callback which triggers the desired animation from your favorite toolkit. The following sample code illustrates how you might use the states API to implement your favorite slide effect for a login prompt.
<script src=”my/favorite/toolkit/effects.js”></script> <script> davinci.states.subscribe("/davinci/states/state/changed",function(event){ var loginPrompt = document.getElementById("loginPrompt"); var state = "Login Prompt"; if (event.newState == state) { my.favorite.toolkit.effects.slideIn(loginPrompt); } else if (event.oldState == state) { my.favorite.toolkit.effects.slideOut(loginPrompt); } }); </script>
You can execute business logic in your application when the user interface changes by listening for the state changed event, and executing a callback which triggers the desired logic. The following sample code illustrates how you might use the states API to implement a search results interface.
<script src=”my/business/logic.js”></script> <script src=”my/ui/logic.js”></script> <script> davinci.states.subscribe("/davinci/states/state/changed", function(event){ // If we’ve just changed to the Search Results state, then populate the results div if (event.newState == "Search Results") { var query = document.getElementById("searchField").value; var results = my.business.logic.getResults(query); my.ui.logic.populateSearchResultsDivWith(results); } }); </script>
You can trigger state changes via application events by simply calling the setState function within your code. The following sample code illustrates how you might use the states API to implement an inactivity based logout warning.
<script src=”my/ui/logic.js”></script> <script> setInterval(function(){ var state = davinci.states.getState(); // If we’ve already warned the user, then trigger the logout if (state == "Inactivity Warning") { davinci.states.setState("Logging Out"); my.ui.logic.logout(); // After 15 minutes, warn the user that they’ll soon be logged out } else if (my.ui.logic.timeSinceLastActivity() > 15*60*1000 ) { davinci.states.setState("Inactivity Warning"); } }, 60*1000); </script>


Caesar cipher its a simple shift cipher; which means all you need to know is how much to shift a character to get from clear text to cipher text.


My Account
Log Out
Home
|
Space
|
Checkout
Payment Completed!
You've booked
{{spacename}}
On {{datechoose}}
From {{time1}} to {{time2}}


SmartConnect Example
Step 1: Pair to a device
Pairing Code:
Pair to Device
Step 2: Send a Transaction
Amount in cents ($1.99 = 199):
Transaction Type:
Card.Purchase
Card.Refund
QR.Merchant.Purchase
QR.Refund
Send Transaction


Links
Interesting and/or useful things from the web.
--- title: Links ---
|
JSON Formatter helps to format and validate your JSON data. It also provides tree view and some other tools. |
|
|
Your go-to tool when needed to convert cURL syntax to any languague (Python, Node.js, R and many more) |
|
|
Encode or decode an URL to get it into a human-readable format. |
|
|
Tool to remove the background from a photo. It works automatically, in only 5 seconds and has a free version and an API. |
|
The easiest way to create GUIs in Python (acording to them). |
|
|
An excellent resource for programmers both beginner and experienced. Be sure to check out other related subreddits from their sidebar. |
|
Lots of open source fonts for your projects. |
|
|
Content that showcase Google’s design work. |
|
|
AI tools and resources by goolge. |
|
|
The best free stock photos & videos shared by talented creators. |
|
Some cool music for programming with a superb UI. |
|
|
Cool article by Dan Abramove, the creator of Redux, about the things he don't know. A must read to get some motivation. |


exercism solutions by Yanzhan
space age
all your base
grade school
atbash cipher
anagram
pangram
meetup
clock
hamming
linked list
scrabble score
acronym
luhn
grains
raindrops
hello world
robot name
etl
phone number
allergies
accumulate
bob
two fer
rna transcription
roman numerals
wordy
leap
word count
nucleotide count
flatten array


Overview
Package
Struct
Tree
Index
Struct ml_seq
any_struct
ml_seq
base type for exported sequences
Declared at line 23 in @seqr_tlm_interface
Fields Summary
%kind: string
Overview
Package
Struct
Tree
Index


Karibu!
Welcome to VJ NISO KALAKASEE.
A space where art meets passion leading to the creation of memorable products as well as services. Enjoy the content in this site and feel free to get in touch.
Welcome to VJ NISO KALAKASEE.
A space where art meets passion leading to the creation of memorable products as well as services. Enjoy the content in this site and feel free to get in touch.
Names:
Dennis Muindi Mumo
Date Of Birth:
29 | March | 1990
Address:
Mombasa, Kenya
Mobile Number:
+254 (0) 721 462 135
Email:
<EMAIL_ADDRESS>Seeking opportunities, collaborations and partnerships in areas such as
Photography, videograpy, graphic designs, music, dj, events etc. with like minded creatives.
Why you should seek my services!
Arts, fashion and entertainment are fields that i thrive in. This is due to the passion, commitment, creativity, connections and networks that I am able to bring together, so as to provide services that cuts across various demographics within the society albeit the main audience being the youth.
Music, photos, videos, fashion, events
To access the Entertainment Content kindly click or press the button below.
Bookings Info and Bookings form
To access the Bookings Content kindly click or press the button below.
Contact info and Contact form
To access the Contact Info kindly click or press the button below.
The is an Online Shop where you can purchase merchandise as a token of appreciation for the craftsmanship and growth of this community.
To access the Online Shop content kindly click or press the button below.


Node area is proportional to Pop. Closer Nodes have more respondents watching both.
Nodes only included if they have more than a 2% Pop.
Links have a 25% threshold. This is a relative average.
Ex. 16.1% of 3-gatsu no Lion watchers watched Ajin 2, while 49.4% of Ajin 2 watchers watch 3-gatsu no Lion. The average of that is over the threshold.
Using Pattern. Credit also to /u/sentenza99


NFL standings: Updated AFC, NFC playoff picture after Week 11
by Vinnie IyerWeek 11 in the NFL is done and with six weeks left in the 2019 regular season, the league-wide standings take on a lot more meaning in terms of which teams will end up making the playoffs in the AFC and NFC.
It's time again to check in on where every team stands to know where they all might finish later, from top playoff seeds to postseason also-rans who have top draft picks in mind.
Here's an updated look at what each conference field would look like if the playoffs started after Week 11.
NFL POWER RANKINGS:
Ravens, Packers, Vikings head north; Chiefs, Cowboys slip
NFL standings after Week 11
AFC playoff picture
Who would be in?
1. Patriots, first place, AFC East (9-1) — The Patriots returned to beat the Eagles coming off a bye and their first loss of the season to the Ravens and maintained their only one-game edge for home-field advantage, down a head-to-head tiebreaker. They have one more tough NFC gameagainst the Cowboysbefore two more critical AFC tests against the Texans and Chiefs.
2. Ravens, first place, AFC North (8-2) — The Ravens got their big win against the Patriots and backed that up by routing the Bengals and Texans. The Ravens have the key tiebreakers in place for the top seed, given the Chiefs, to whom they lost, are solidly behind them.
3. Chiefs, first place, AFC West (7-4) —The Chiefs get up here before their bye thanks to beating the Chargers, now holding ahalf-game lead over the Raiders for the division lead and a half-game lead over the Colts for the third seed.
4. Colts, first place, AFC South (6-4) — The Colts jumped back up here after beating the Jaguars. They hold the division lead over the Texans again because they beat them. They also beat the Chiefs, so they hold the tiebreaker there.
5. Bills, second place, AFC East (7-3) — The Bills are now returning closer to a tight wild-card hopeful pack, and that loss to the Browns can prove costly, even with a favorable schedule ahead. But taking care of the Dolphins as expected was helpful.
6. Texans, second place, AFC South (6-4) — The Texans fell here after falling hard to the Ravens on Sunday. They stay here coming out of Week 11 because they beat the Raiders.
Who can get there?
7. Raiders (6-4), 8. Steelers (5-5), 9. Titans (5-5), 10. Browns (4-6), 11. Jaguars (4-6), 12. Chargers (4-7)
The Raiders beat the Bengals to stay ahead of the Steelers and right behind the Texans, down only a tiebreaker. The Steelers fell hard to the Browns, who stayed alive after Thursday night. The Chargers are barely alive going into the bye after losing to the Chiefs on Monday night.
Who's likely out?
13. Broncos (3-7), 14. Jets (3-7), 15. Dolphins (2-8)
The Broncos suffered a tough loss at the Vikings, while the Jets got ahead of the Dolphins by beating the Redskins.
Who's out?
16. Bengals (0-10)
The Bengals are still headed to the top pick in the draft.
WEEK 11 NFL PICKS: Against the spread | Straight-up predictions
NFC playoff picture
Who would be in?
1. 49ers, first place, NFC West (9-1) — The 49ers now have at least one loss like everyone in the league but got out of Week 11 still a game ahead of the Seahawks, to whom they lost in overtime in Week 10. They survived the Cardinals, butfor playoff positioning purposes, critical games againstthe Packers and Saints are around the corner.
2. Packers, first place, NFC North (8-2) — The Packers were able to jump up here after beating the Panthers, while the Saints lost to the Buccaneers in Week 10. The Packers would end up No. 1 ahead of the Seahawks, should the 49ers get upset by the Cardinals.
3. Saints, first place, NFC South (8-2) — The Saints remain here after beating the Buccaneers; a win kept them behind the Packers because of a conference record tiebreaker and two full games ahead of the Cowboys, whom they beat.
4. Cowboys, first place, NFC East (6-4) — The Cowboys took advantage of the get-well game against the Lions to ensure they will stay at least a head-to-head tiebreaker over the Eagles. They probably can't rise higher than No. 4 given they lost to both the Packers and Saints.
5. Seahawks, second place, NFC West (8-2) — The Seahawks got their massive win against the 49ers and were rewarded with a well-deserved bye after going overtime on Monday night. They'll either stay here a little ahead of the Vikings or jump up to No. 2 behind the Packers should the 49ers lose.
6. Vikings, second place, NFC North (8-3) — The Vikings enjoyed a big Week 10 NFC win over the Cowboys that both fortified their wild-card position and put division heat on the first-place Packers, to whom they've lost. The Vikings cut the lead to a half-game with a win over the Broncos.
Who can get there?
7. Rams (6-4), 8. Eagles (5-5), 9. Panthers (5-5), 10. Bears (4-6), 11. Lions (3-6-1)
The Rams are seeing the division get away from them, but they got a much-needed win overthe Bears on Sunday night to set up a possible late wild-card surge, despite being two wins behind both the Seahawks and Vikings. The Eagles, after losing to the Patriots, are probably better off thinking more about how to finish ahead of the Cowboys in the East, now down a full game and a loss to them.
Who's likely out
12. Cardinals (3-7-1), 13. Falcons (3-7), 14. Buccaneers (2-7), 15. Giants (2-8), 16. Redskins (1-9)
Everyone here has a few positives of late — the Cardinals and Giants with their rookie quarterbacks, the Falcons with their defense. The Bucs and Redskins, however, saw more mistakes by their quarterbacks in their respective latest losses.


B-83 Bomb Deployment
Below is a sequence of images of a B-83 laydown deployment test drop from a B-1B Lancer.
Weapon Release
Canopy Deployment
Descent and Landing


New in the Java SE 7 release, the fork/join framework is an implementation of the
ExecutorService
interface
that helps you take advantage of multiple processors. It is designed for
work that can be broken into smaller pieces recursively. The
goal is to use all the available processing power to make your
application wicked fast.
As with any ExecutorService
, the fork/join framework distributes
tasks to worker threads in a thread pool. The fork/join
framework is distinct because it uses a work-stealing algorithm. Worker
threads that run out of things to do can steal tasks from other threads that are
still busy.
The center of the fork/join framework is the
ForkJoinPool
class, an extension of AbstractExecutorService
.
ForkJoinPool
implements the core work-stealing algorithm and can execute
ForkJoinTask
s.
Using the fork/join framework is simple. The first step is to write some code that performs a segment of the work. Your code should look similar to this:
if (my portion of the work is small enough) do the work directly else split my work into two pieces invoke the two pieces and wait for the results
Wrap this code as a ForkJoinTask
subclass, typically as one of its more
specialized types
RecursiveTask
(which can return a result) or
RecursiveAction
.
After your ForkJoinTask
is ready, create one that represents
all the work to be done and pass it to the invoke()
method
of a ForkJoinPool
instance.
To help you understand how the fork/join framework works, consider a simple example.  The original source image is represented by an array of integers, where each integer contains the color values for a single pixel. The blurred destination image is also represented by an integer array with the same size as the source.
Performing the blur is accomplished by working through the source array one pixel at a time. Each pixel is averaged with its surrounding pixels (the red, green, and blue components are averaged), and the result is placed in the destination array. Here is one possible implementation:
public class ForkBlur extends RecursiveAction { private int[] mSource; private int mStart; private int mLength; private int[] mDestination; private int mBlurWidth = 15; // Processing window size, should be odd. public ForkBlur(int[] src, int start, int length, int[] dst) { mSource = src; mStart = start; mLength = length; mDestination = dst; } protected void computeDirectly() { int sidePixels = (mBlurWidth - 1) / 2; for (int index = mStart; index < mStart + mLength; index++) { // Calculate average. float rt = 0, gt = 0, bt = 0; for (int mi = -sidePixels; mi <= sidePixels; mi++) { int mindex = Math.min(Math.max(mi + index, 0), mSource.length - 1); int pixel = mSource[mindex]; rt += (float)((pixel & 0x00ff0000) >> 16) / mBlurWidth; gt += (float)((pixel & 0x0000ff00) >> 8) / mBlurWidth; bt += (float)((pixel & 0x000000ff) >> 0) / mBlurWidth; } // Re-assemble destination pixel. int dpixel = (0xff000000 ) | (((int)rt) << 16) | (((int)gt) << 8) | (((int)bt) << 0); mDestination[index] = dpixel; } } . . .
Now you implement the abstract compute()
method, which either performs the blur directly or splits it into two smaller
tasks. A simple array length threshold helps determine whether the work is
performed or split.
protected static int sThreshold = 100000; protected void compute() { if (mLength < sThreshold) { computeDirectly(); return; } int split = mLength / 2; invokeAll(new ForkBlur(mSource, mStart, split, mDestination), new ForkBlur(mSource, mStart + split, mLength - split, mDestination)); }
If the previous methods are in a subclass of the RecursiveAction
class,
setting it up to run in a ForkJoinPool
is straightforward.
Create a task that represents all of the work to be done.
// source image pixels are in src // destination image pixels are in dst ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
Create the ForkJoinPool
that will run the task.
ForkJoinPool pool = new ForkJoinPool();
Run the task.
pool.invoke(fb);
For the full source code, including some extra code that shows the source
and destination images in windows, see the
class.
ForkBlur


java.sql.Connection.prepareStatement()
, java.sql.Connection.prepareCall()
, or any of their
variants which take a dynamically-constructed string as the statement to prepare.
Constructed SQL statements are a common source of security breaches. By default, this inspection ignores compile-time constants.
Example:
String bar() { return "bar"; }
Connection connection = DriverManager.getConnection("", "", "");
connection.("SELECT * FROM user WHERE name='" + bar() + "'");
Use the inspection settings to consider any static
final
fields as constants. Be careful, because strings like the
following will be ignored when the option is enabled:
static final String SQL = "SELECT * FROM user WHERE name='" + getUserInput() + "'";


These maps show how early spring is arriving in your state this year
Judicial originalism is a myth
Why "Made in China" could soon be a thing of the past