--- layout: page title: "jQuery: Novice to Ninja" prev: OEBPS/ch02.html next: OEBPS/ch04.html book_path: books/earle-castledine-craig-sharkie-jquery-novice-to-ninja-_oeb/ --- {% include JB/setup %} {% raw %}
animate
,
which lets you animate a whole host of CSS properties to fashion some
striking effects of your own. Let’s have a look at an example of
animate
in action:
$('p').animate({ padding: '20px', fontSize: '30px' }, 2000);
animate
, we pass an object literal
containing the properties we would like to animate specified as
key/value pairs, much the same as when you assign multiple
properties with the css
function. There’s one
caveat that you’ll need to remember, though:
property names must be camel-cased in order to be used by the animate function;
that is to say, you’ll need to write backgroundColor
instead of
background-color
, and
marginLeft
instead of margin-left
.
That is unless of course you opt for
"background-color"
, and
"margin-left"
. Any property name made up of multiple
words needs to be modified with quotes in this way.
The time frame parameter works exactly the same way as the
simple animations we saw in Chapter 2: you
can pass a number of milliseconds, or one of the strings
slow
, fast
, or
normal
. Values for CSS properties can be set in
pixels, ems, percentages, or points. For example, you could write
100px
, 10em
,
50%
, or 16pt
.
Even more excitingly, the values you define can be
relative to the element’s current values: all you
need to do is specify
+=
or
-=
in front of the value, and that
value will be added to or subtracted from the element’s current
property. Let’s use this ability to make our navigation menu swing as we
pass our mouse over the menu items using the
hover
function:
$('#navigation li').hover(function() { $(this).animate({paddingLeft: '+=15px'}, 200); }, function() { $(this).animate({paddingLeft: '-=15px'}, 200); });
animate
to achieve
fine-grained control over the showing, hiding, and
toggling functions we saw in Chapter 2. We simply specify a property’s animation
value as show
, hide
, or
toggle
, rather than a numeric amount:
$('#disclaimer').animate({ opacity: 'hide', height: 'hide' }, 'slow');
animate
function also has some powerful
advanced options, which we’ll examine in detail over the course of this
chapter.
animate
function is, you’ll probably want to animate an element’s color.
However, animating color is a little bit tricky, because the color
values “in between” the start and end colors need to be calculated in a
special way. Unlike a height or width value that moves from one value to
another in a simple, linear manner, jQuery needs to do some extra math
to figure out what color is, say, three-quarters of the way between
light blue and orange.
This color-calculating functionality is omitted from the core
library. It makes sense when you think about it: most projects have no
need for this functionality, so jQuery can keep the size of the core
library to a minimum. If you want to animate color, you’re going to need
to download the
Color
Animations plugin.
$('#disclaimer').animate({'backgroundColor':'#ff9f5f'}, 2000);
linear
and
swing
. Any time you use an animation
function in jQuery, you can specify either of these parameters to
control the animation’s easing. The difference between them can be seen
in Figure 3.1, which shows how a property is
adjusted over the period of an animation depending on which easing
option you select.
swing
easing starts off slowly before gaining
speed, then towards the end of the animation it slows down again, nice
and gently. Visually, swing easing looks far more natural than linear
easing, and jQuery uses it by default if no easing parameter is
specified.
The linear
easing method has no acceleration or
deceleration: animations occur at a constant rate. It looks fairly
boring and a bit rigid in most circumstances, but it’s worth giving it a
try; it might just be appropriate for your purposes.
As an example, we’ll animate the first paragraph tag so that when
clicked, it grows and shrinks; we’ll use linear easing as it grows, and
swing easing as it shrinks. The difference is quite subtle, but if you
repeat the animations a few times you should be able to distinguish
between them; the shrinking animation feels more natural:
There’s quite a lot of jQuery in this statement, so now might be a
good time to pause and make sure you understand everything that’s going
on here:
animate
function. There are lots to choose
from, so we might as well jump straight into it and try a few:
$('p:first').animate({height: '+=300px'}, 2000, 'easeOutBounce'); $('p:first').animate({height: '-=300px'}, 2000, 'easeInOutExpo'); $('p:first').animate({height: 'hide'}, 2000, 'easeOutCirc'); $('p:first').animate({height: 'show'}, 2000, 'easeOutElastic');
animate
function will
cement your knowledge of it: it’s an important part of a jQuery
ninja’s arsenal!
animate
function works, let’s have a look at
our client’s latest round of requests. Today’s to-do list includes the
addition of a vitally important page component: the
StarTrackr! Daily “Who’s Hot Right Now?” List (or
the SDWHRNL for short). The list consists of the latest celebrities to
fall in or out of favor, along with an accompanying photo and brief bio.
We’ll apply some of the animation and easing techniques we’ve just
learned to implement the list as panes that can be opened and closed
independently.
The appearance of the widget in the page is shown in Figure 3.3.
In our HTML, we’ll implement the section as a div
element containing all our celebrities.
Each celebrity’s pane will be marked up as an h3
, followed by another div
containing an image and a short
paragraph:

Who’s Hot Right Now?

Beau Dandy

Content about Beau Dandy

Johnny Stardust

Content about Johnny Stardust

Glendatronix

Content about Glendatronix

:first
filter and call
the show
action to reveal only the first
pane:
$('#bio > div:first').show();
>
). A child selector selects all
the immediate children that match the selector. If we’d omitted the
child selector, our code would select all div
elements underneath the bio div
element, even if they were nested inside
other elements. For more details and code examples using this
selector, check out the jQuery API
documentation.
click
event, finding the next element (which
contains our content), and showing it, as we did in Chapter 2. But this time, we’ll employ a touch of
“bounce” easing to the content’s height, so that the panes bounce in and
out of view:
$('#bio h3').click(function() { $(this).next().animate( {'height':'toggle'}, 'slow', 'easeOutBounce' ); });
easeOutBounce
produces a great
bouncing-ball effect, which works wonderfully for content panes like
this. Give it a spin in your browser and see for yourself!
animate
function.
It turns out animate
can be called with a set
of extra options, like this:
animate(parameters, options);
The options
parameter is a bundle of
options packaged together as an object literal made up of key/value
pairs. We’re already familiar with several of the available options:
duration
,
easing
, and
complete
(the callback method).
There are, however, a couple of new ones:
step
and
queue
. Before we explain them,
let’s take a look at the syntax for calling the
animate
function with an
options
parameter:
$('p:first').animate(
{
height: '+=100px',
color: 'green'
},
{
duration: 'slow',
easing: 'swing',
complete: function() {alert('done!');},
queue: false
}
);
queue
parameter.
The queue is the list of animations waiting to occur on a
particular element. Every time we ask jQuery to perform an animation on
an element, that animation is added to the queue. The element executes
the queue one at a time until everything is complete. You’ve probably
already seen this if you’ve gone click-happy on one of our demos.
There are many situations where this will be undesirable, though.
Sometimes you’ll want multiple animations to occur at the same time. If
you disable the queue when you specify an animation, further animations
can run in parallel.
The animation queue can be controlled by using the
queue
option, as well as with the jQuery actions
stop
,
queue
, and
dequeue
. This combination of
actions and options gives us super-fine control over how our animations
run. But before we can really sink our teeth into these juicy options,
it’s time to unveil one of the most important jQuery techniques
around.
this
keyword to find our targets again. However, there’s a technique that
allows us to run multiple jQuery commands, one after the other, on the
same element(s). We call this chaining, so to release the ninja inside
of you, you’d better pay attention to this bit.
Chaining links two or more jQuery actions,
or methods, into a single statement. To chain an action, you simply
append it to the previous action. For example, let’s chain together the
hide
, slideDown
, and
fadeOut
actions. Our element quickly hides and
then slides into view, before fading away:
$('p:first').hide().slideDown('slow').fadeOut();You can chain together as many actions as you like. Be careful, though: chaining can quickly become addictive. As well as being able to chain actions based on your initial selector, you can also move around the DOM, adding and removing elements as you go, which can lead to some quite hairy statements. It’s often good to lay out your actions on separate lines for clarity. This takes up a lot more space, but is much easier to read and maintain. Our previous example could be rewritten like this:
$('p:first') .hide() .slideDown('slow') .fadeOut();It’s important to realize that the jQuery selector contains the modified results of each action that runs before launching the next action. This means that we can add and remove elements as we go along, only applying actions to the current selection. If you revisit some of our earlier examples, you might spot a few chained actions hidden in the code; for example, when we wrote:
$(this).next().animate()
. The
next
action moved our selection to the next DOM
element, and then the animate
action animated
it without affecting the original element.
You’ll have plenty of chances from now on to play with chaining;
the rest of this book is going to be filled with it. It’s the most fun
part of jQuery!
delay
action. Simply give it a
number, and it will delay the queue for that many milliseconds before
continuing. So, referring to the same example, we could write:
$('p:first') .hide() .slideDown('slow') .delay(2000) .fadeOut();This code will slide down the paragraph, and then wait two seconds before fading it out. It can be a great way to control your animations more precisely.

Home

About Us

Buy!

Gift Ideas

div
element, positioned behind whichever
navigation link the user is mousing over. Our first task, therefore,
will be to create the element and append it to the document:
$('

').css({ width: 0, height: $('#navigation li:first a').height() + 10 }).appendTo('#navigation');
css()
or
width()
in your code, jQuery
converts all the properties with units (em, in, pt, and so on) to
pixels. That’s what is happening when you set a width to, say, 30em
and jQuery returns 480 and omits the unit.
It certainly makes it a lot easier to manipulate dimensions,
and it’s why we were able to simply add 10 in our code. If you omit
the unit type yourself, jQuery goes right ahead and assumes you
meant pixels.
hover
function. Remember that hover
accepts two
parameters: the function that runs when the mouse moves
over the element, and the one that runs when the
mouse moves off the element. This is the general
outline of our event handler:
$('#navigation a').hover(function() { // Mouseover function … }, function() { // Mouseout function … });
// Mouseover function $('#navigation_blob').animate( { width: $(this).width() + 10, left: $(this).position().left }, { duration:'slow', easing: 'easeOutCirc', queue: false })
position
. This is an action that
does nothing on its own, but when called exposes two properties:
left
and
top
; these are the left and top
offsets of the selected element relative to its parent. In this case we
want the left
property, so we know where to move
the blob to in our navigation menu.
We set the queue
option to
false
, ensuring that our animations won’t pile up in
a line waiting to execute if our user is hover-happy. When you move to a
different link, a new animation will start regardless of whether the
current one is finished or not.
We still need to tell jQuery what to do when our user moves the
mouse off the link. This block of code is similar
to the one we just saw, although it includes more chained
actions:
// Mouseout function $('#navigation_blob').animate( { width: $(this).width() + 10, left: $(this).position().left }, { duration:'slow', easing: 'easeOutCirc', queue: false }) .animate( { left: $('#navigation li:first a').position().left }, 'fast' );
animate
actions together: the first one hides the blob with a bit of nice easing
applied, and the second whisks it off to the side (to the position of
the first link in the navigation).
width:
hide
in the mouseout’s first animation. So what’s happened?
jQuery is evolving and maturing, that’s what’s happened. It means that
we need to watch changelogs (records of alterations made to any
project) and have our code mature correspondingly.
div
, where there’s space for the icons to
expand. We’ve set a background color for the icons to be set against,
and employed a clever trick to keep the background images out of view;
notice that the list items are 20 pixels in height, but that the
background is offset 30 pixels from the top. As a result, they’ll be
invisible until we expand the height of the list items.
We’ll also set the background image of each link to a different icon:
#container { position: relative; } #navigation { position:absolute; width: inherit; top: 0; right: 0; margin: 0; } #navigation li { height:20px; float:left; list-style-type: none; width:70px; padding:3px; border-right:1px solid #3687AF; background-color: #015287; background-repeat: no-repeat; background-position: center 30px; } #navigation li a { color: #FFFFFF; } #navigation #home { background-image:url('home_icon.png'); } …
stop
action to clear the queue
for both the mouseover
event and the
mouseout
event. Then we just animate the height to
display the hidden icons, and shrink it back to normal when the hover
finishes. Some carefully chosen duration and easing settings give us the
groovy bouncing effect that we’re after. Make sure you experiment with
the settings in order to match the feel of your site:
$('#navigation li').hover(function() { $(this) .stop(true) .animate( {height: '60px'}, {duration: 500, easing: 'easeOutBounce'} ) }, function() { $(this) .stop(true) .animate( {height:'20px'}, {duration: 500, easing: 'easeOutCirc'} ) } );
$('p:first') .effect('shake', {times:3}, 300) .effect('highlight', {}, 3000) .hide('explode', {}, 1000);
effect
action, while others can be used this
way or in place of hide
,
show
, or toggle
parameters. Some examples of the latter are blind
,
clip
, puff
,
fold
, and slide
.
We’ll refrain from going through all of them in detail here;
you’re best off spending your Sunday afternoon exploring them. Not all
the effects are pure flair, but many are useful in common user
interaction scenarios, such as highlight
, which is a
standard way to indicate a new message to the user.
It’s a good idea to test out each function, so you’ll remember
them when appropriate. And if the jQuery UI assortment of effects just
isn’t enough for you, never mind: there are hundreds more available from
the plugin repository!
animate
function. You’ve also become briefly
acquainted with the extensive jQuery UI library. The best way to really
master these skills, however, is to put them into practice.  Try playing with every
property of every element on every page, until you feel like you can
really manipulate them.
Before we move on from animation to the next jQuery skill set for
you to master, we’ll turn our attention to scrolling and resizing: these
topics might be less flashy than animation, but they’re essential to a
good many user interface components. They’ll also help cement your
understanding of jQuery selectors, actions, and chaining. So what are we
waiting for?
scroll
, which fires when the user updates the
scroll position of an element, such as the window or a scrollable
div
. So, every time one of your users
interacts with a scrollbar on your site, an event will be fired that you
can catch and respond to.
To capture the scroll
event, we attach an event
handler to an element that has scrollbars, most often the window
element. The window itself is a JavaScript object, so all we need to do
is wrap it in our jQuery function to select it.
Of course, to see the scroll
event in action,
we have to set up an area with scrollbars! We have a few ideas for
scrolling effects that we’d like to pitch to the client, but in the
interests of learning how the scroll
event works,
let’s just fake a scrolling environment by setting overflow:
scroll;
on one of the div
s
in our page:
#news { height: 100px; width: 300px; overflow: scroll; }
scroll
event,
and add some arbitrary text to the page every time the
scroll
event fires:
$('#news').scroll(function() { $('#header') .append('You scrolled!'); });
scroll
event
will fire.
scroll
event.
Our first task is to set up our CSS to prepare for the animated
navigation. For the purpose of this exercise, we’ve applied a very large
height
property to the content in order to force it
to have a scrollbar (unless, of course, you have a huge
monitor!):
#navigation { position: relative; } #content { height: 2000px; }
scroll
event of the main window by updating the
top
position of the navigation block if the block
would normally be out of the viewport:
$(window).scroll(function () { $('#navigation').css('top', $(document).scrollTop()); });
scrollTop
action.
scrollTop
returns the top offset of the matched
element; in our example, we asked for the entire document’s top
position: $(document).scrollTop()
. This will always
be at the very top of the screen.
It works, sure, but why, you might ask.
Were you paying attention earlier when we first introduced
the scroll
event? Every time the user moves the
scrollbar, it fires many
scroll
events. Each one of those events
triggers our code to update the navigation position, so we expect the
navigation to be jittery and jump around.
It’s not jumpy because we’re embracing our ninja-nature. Ninjas
know that browsers should only do as much as they need to nail a goal.
Sure, we could have opted for position: relative
and
then set the element’s top
every time a scroll
event fired, but that would have been jittery. Our
solution works, nailing the task at hand. Despite that, how about we
smarten it up with some logic? Here’s how we do that:
var $window = $(window), $navigation = $(“#navigation”); $window.scroll(function() { if (!$navigation.hasClass("fixed") && ($window.scrollTop > ↵$navigation.offset().top)) { $navigation.addClass("fixed").data("top", ↵$navigation.offset().top); }
data
method to record what our
element’s initial top
property is. We don’t actually need that while we’re
scrolling down the page, but we sure do when we scroll back up. In our
code example in 13_floating_nav_1/script.js, when
we scrolled back to the top of the page, the navigation kept going past
its initial position. We’re now going to fix that:$window.scroll(function() { if (!$navigation.hasClass("fixed") && ($window.scrollTop() > ↵$navigation.offset().top)) { $navigation.addClass("fixed").data("top", ↵$navigation.offset().top); } else if ($navigation.hasClass("fixed") && ($window.scrollTop() ↵< $navigation.data("top"))) { $navigation.removeClass("fixed"); } });
fixed
class has
been set, and if the window has scrolled up past where the navigation
should be sitting. We do that by referring to the
data
attribute we set. When this condition is met, we
simply remove the fixed
class, and the element
drops back into the document flow.
href
attribute to
#
.
If we think about it, all we want to do is animate the page’s
scrolling position, which is represented by
scrollTop
in jQuery. We’ll also need to cancel the
default link action, otherwise the page will jump before
our animation has time to occur. If you’re new to JavaScript, there’s an
easy way to accomplish this: any function handling a link’s
click
event receives the event as a parameter—we’re
calling it e
—and then we use the event object’s
preventDefault
method:
$('a[href=#]').click(function() { $('html').animate({scrollTop: 0},'slow'); return false; // Return false to cancel the default link action }This code introduces a new kind of selector: the attribute selector. By enclosing an attribute and the value we want to look for in square brackets (
[]
), we can narrow a
selection to include only elements with a specific attribute value. In
this case, we’re looking for only those links with an href
value of #
.
This code works, and is certainly clear and simple, but it
does encounter a slight issue. If the user’s browser is operating in
quirks mode, the $('html')
selector
will fail. (Unsure what quirks mode means? Take the time to read the
SitePoint CSS reference page on the topic for a detailed
explanation.) While you should be marking up your
pages in a way that triggers standards mode, sometimes you’ll be working
with legacy code, and thus be without that luxury. To make the above
code work in quirks mode, you need to use the selector
$('body')
. We could also target both, just to be
sure: $('html, body')
. This in turn causes issues in
certain versions of the Opera browser, which (probably correctly) tries
to scroll both elements at the same time.
“But you said jQuery sorts out all our cross-browser issues!” you
might exclaim. To be fair, it sorts out most
cross-browser issues. This is a slightly trickier one, and is not
addressed in the core jQuery library. Fortunately for us, it’s fairly
simple to work around. Even more fortunately for us, someone has taken
the time to package that workaround (as well as a plethora of other
scrolling functionality) into a plugin called ScrollTo.
The
ScrollTo plugin, available from the plugin
repository, is a stable plugin for scrolling the screen and
overflowed elements. It’s more than capable of handling any of the
scrolling tasks we’ve seen so far.
After you’ve downloaded and included the plugin, you can rewrite
the top link functionality, and forget all your worries about obscure
browser bugs:
$('a[href=#]').click(function(e) { $.scrollTo(0,'slow'); e.preventDefault(); });
scrollTo
directly from the jQuery
alias. The plugin is clever, and knows that if we call it directly in
this way, we want to scroll the entire window. If we wanted to scroll a
specific overflowed element, we’d use the traditional selector syntax;
for example, $('div#scrolly').scrollTo(0,
'slow')
.
The ScrollTo plugin is feature-packed and not limited to scrolling
by an integer value. You can pass in a relative value (like
+=50px
), a DOM element (it will scroll the page to
find that element), a selector string, a hash value containing
x
and y
co-ordinates, or the
keyword
max
, which will scroll to the end of
the document. You can scroll horizontally as well as vertically, and it
also has some great options for fine-tuning your destination. You can
learn about all these options on the plugin’s
home page.
$('#fine_print').jScrollPane({ verticalGutter: 20 });
resize
event is a core jQuery event that
fires when a document view is resized. There are a number of reasons why
you’d want to react to this event, but before we examine a practical
example, let’s make sure we understand how the event works:
$(window).resize(function() { alert("You resized the window!"); });
resize
event.
Let’s get started. The default StarTrackr! website we’ve been
working with so far is a modest 650 pixels wide. Our first task is to
write some styles to make it wider. We’ll go for 850 pixels for the
wider version:
body #container { width: 850px; } body #container p { width: 650px; } body #header { background-image: url('../../css/images/header-corners-wide.png'); } body #celebs table { width: 650px; margin-left: 5px; }
body
to the beginning of each rule. This is so
they’ll take precedence over any rules in our base stylesheet
targeting the same elements, because they’re more specific, or have
more
specificity.
The next step is to write the jQuery code to add or remove our
new stylesheet. All we need to do is test to see if the
body
element’s width is greater
than 900 pixels, append the stylesheet to our head
element if it is, or remove it if it’s
not:
if ($('body').width() > 900) { $('<link rel="stylesheet" href="wide.css" type="text/css" />') .appendTo('head'); } else { $('link[href=wide.css]').remove(); }
$(document).ready(function() { stylesheetToggle(); $(window).resize(stylesheetToggle); }); function stylesheetToggle() { if ($('body').width() > 900) { $('<link rel="stylesheet" href="wide.css" type="text/css" />') .appendTo('head'); } else { $('link[href="wide.css"]').remove(); } }
stylesheetToggle
and used it
twice: once when the document first loads, and again whenever we
resize. You’ll notice that we only need to pass the function
name to the resize
event
handler, and we’ll let the event call the function. When we pass the
function and aren’t declaring a function, we have no need for the
function
keyword, any parentheses, or any curly
braces.
Once you get this passing-versus-invoking distinction
under your belt, it can come in really handy in shortening how you
write setTimeout()
s, so let’s look again.
When a function name is used in our code and is followed by
parentheses, we invoke the function and it executes. When we use the
function name in our code without those parentheses, we pass a
reference to the function, and another piece of script is needed to
invoke it.
resizable
function:
If we run this on our StarTrackr! site, we’re in for some unusual
results: every paragraph element instantly becomes resizable!
It’s a lot of fun to see this in action; suddenly our whole web
page becomes malleable. By default, the Resizable interaction adds small
handles in the bottom-right corners of the elements. These are styled in
the jQuery UI stylesheet, so have a look in there if you’re interested
in changing the way they look. The default handles are illustrated in
Figure 3.6.
Now let’s look at a simple situation where this functionality is
very handy: resizing textarea
elements.
textarea
, but make it resizable. Therefore,
the users with a lot to say will feel as if you’re letting them say
it. Here’s how we can go about doing this using jQuery UI’s Resizable
functionality:
$('textarea').resizable({ grid : [20, 20], minWidth : 153, minHeight : 30, maxHeight : 220, containment: 'parent' });
textarea
elements resizable, just like we did with the paragraph elements. The
effect is shown in Figure 3.7. However,
we’ve specified a few new parameters to improve the feel, and to show
the Resizable component’s flexibility. It has a plethora of
configuration options, which you can explore in more detail on the
jQuery UI
documentation site.
We’ve also constrained how far the element can be stretched by
specifying the
minHeight
,
minWidth
, and
maxHeight
properties. You’ll notice
that we’ve omitted the
maxWidth
property in favor of the
containment
parameter: this lets you
specify a container restricting the resizable element. You can use
either a jQuery selector as the parameter, or the special keyword
parent
to refer to the resizable
element’s parent element.
We’ve also used the
grid
option to confine the resizable
object to steps of a certain size. For some reason, this seems to add
a nice feel to the resizing interaction. The grid is specified as an
array containing two elements: the horizontal grid size and the
vertical grid size.
One other parameter you’ll want to look into is the
handles
parameter. This specifies
which sides of the element the handles will be attached to and,
consequently, in which directions the element can be stretched. The
parameter accepts the following options: n
,
e
, s
, w
,
ne
, se
, sw
,
nw
, and all
. You can specify any
number of these by separating them with a comma. For example,
{ handles : 'n, se'}
adds handles to the top- and
bottom-right of the element.
It’s common to see this kind of functionality built into input
pages where content length will vary significantly.
div
elements representing each pane, nested
inside a containing element that has fixed dimensions. We’ll encase
the table of contents in a block-level element, so that when the user
resizes the panes, the text won’t wrap and mess up our nested
list:

 …

 …

div
, and made the child elements each
consume 50% of the width by default. You could change this to specify
different values if it was necessary to start with an alternative to a
50:50 split. If you need to use a CSS border, you’ll have to specify
your widths in pixels and make sure they all add up:
#splitter { height: 150px; margin-top: 30px; margin-bottom: 50px; } #splitter .pane { width: 50%; height: 100%; float: left; } #splitter h2 { margin-bottom: 0; padding-bottom: 0; } #tocPane { overflow: hidden; background: #d6dde5 url(../images/handle.png) no-repeat ↵right center; } #tocPane .inner { width: 300px; } #contentPane { overflow: auto; } #contentPane .inner { padding: 0 5px; }
div
will
be resizable.
If you were to run the example with only a simple
resizable
statement, you’d notice that we’re
almost there: the two elements act somewhat like a split pane, except
that the right element’s width remains constant rather than expanding
to fill the remaining space when you drag the handle. To take care of
that, we’re going to have to do some calculations inside the resizable
widget’s
resize
function. This is an
event handler that fires as the component is being resized:
$('#splitter > div:first').resizable({ handles: 'e', minWidth: '100', maxWidth: '400', resize: function() { var remainingSpace = $(this).parent().width() - ↵$(this).outerWidth(); var divTwo = $(this).next(); var divTwoWidth = remainingSpace - (divTwo.outerWidth() - ↵divTwo.width()); divTwo.css('width', divTwoWidth + 'px'); } });
div
’s
outerWidth
. The
outerWidth
function is a useful
way to grab the total width of an element, including any padding and
borders (additionally, it can include margins if you pass it the
optional parameter true
). Perhaps unsurprisingly,
there’s a corresponding
outerHeight
function as
well.
Having calculated how much space is left to use up, we’re almost
ready to set the first element’s width. There’s just one remaining
catch: if the second div
has
borders or padding, we need to take these into consideration.
Unfortunately, the outerWidth
function is
read-only, so we can’t use it to set the total width.
To calculate how much of the element’s width consists of borders
and padding, we need to subtract the element’s
outerWidth
from its
width
. Subtracting that from the
remainingSpace
variable gives us exactly how many
pixels wide the second div
needs to
be, and we can complete our horizontal splitter.
var remainingSpace =
$(this).parent().width() - $(this).outerWidth();
assigns
the result of the calculation to a variable called
remainingSpace
. From now on, we can simply write
remainingSpace
in our code whenever we need to
access this value.
The following line (var divTwo =
$(this).next();
) is performing a very similar function,
except that this time we’re assigning a jQuery
selection to a variable (divTwo
). This
can subsequently be used like any other jQuery selection.
Using variables like this helps to make your code more
readable, as you can keep each line as concise as possible. It also
makes your code more efficient; retrieving a value from a variable
is much quicker for JavaScript than figuring out the value in the
first place.
$('#splitter > div:first').resizable({ handles: 's', minHeight: '50', maxHeight: '200', resize: function() { var remainingSpace = $(this).parent().height() - ↵$(this).outerHeight(); var divTwo = $(this).next(); var divTwoHeight = remainingSpace - ↵(divTwo.outerHeight() - divTwo.height()); divTwo.css('height', divTwoHeight + 'px'); } });


Guardiola provides Ederson, Laporte & Sane injury update ahead of Chelsea clash
Manchester City goalkeeper Ederson is set to be fit for his side’s Premier League clash against Chelsea at the Etihad on Saturday.
The Brazilian missed City’s 3-1 defeat to Liverpool a fortnight ago after his removal in the draw against Atalanta with a hamstring strain.
Claudio Bravo deputised for Ederson at Anfield and was arguably culpable for Sadio Mane’s crucial third goal when he stayed rooted to his line for Jordan Henderson’s cross.
However, Guardiola confirmed today that his number one is now fit again and is set to return against Chelsea.
‘Ederson is back,’ said Guardiola.
‘He trained in the last few days without pain.’
Advertisement Advertisement
However, the news on Aymeric Laporte and Leroy Sane was less positive.
The pair are both out with long-term knee injuries and recent reports had suggested the Frenchman in particular was ahead of schedule in his return.
But Guardiola says both players could still be out for another three months.
‘Laporte and Sane are still injured for two or three months.’


{% load static %} {% load cache %} {% cache 3600 call_action %}
Provide free home delivery for all product over $100
We ensure our product quality all times
Our product return policy is very easy & simple


Generic Sensor API
-
a set of interfaces which expose sensor devices to the web platform
-
easily extended with new sensor classes
-
modify/set the sampling frequency
-
detect sensor availability
-
high precision timestamps and clearly defined coordinate systems
-
interfaces are not bound to the DOM
-
and more!


Dotnet version: loading
Loading templates, please wait
Click an item to see more information
Loading template


meginmál
there's no heaven It's easy if you try No hell below us Above us only sky Imagine all the people Living for today...


--- layout: post title: Goodbye 2010 published: true permalink: /dear-2010 ---
Dear 2010,
You almost got me down with these health problems, but even so
1) Developers for Good has directly connected dozens of programmers with awesome volunteer opportunities in NYC,
2) Hirelite has placed dozens of software engineers with great jobs in NYC through efficient video interviews,
3) Girl Develop It has created a community of over 600 women, including 200+ students, who are psyched about software development,
4) xkcd helped me stay geeky and stay positive,
and
5) I am going to change the world anyway.
Bring it on, 2011!


pamcut(1) pamcut(1) NAME pamcut - cut a rectangle out of a PAM, PBM, PGM, or PPM image SYNOPSIS pamcut [-left leftcol] [-right rightcol] [-top toprow] [-bottom bottom‐ row] [-width width] [-height height] [-pad] [-verbose] [ left right width height ] [pnmfile] All options may be abbreviated to the shortest unique prefix. DESCRIPTION Reads a PAM, PBM, PGM, or PPM image as input. Extracts the specified rectangle, and produces the same kind of image as output. There are two ways to specify the rectangle to cut: arguments and options. Options are easier to remember and read, more expressive, and allow you to use defaults. Arguments were the only way available before July 2000. If you use both options and arguments, the two specifications get mixed in an unspecified way. To use options, just code any mixture of the -left, -right, -top, -bot‐ tom, -width, and -height options. What you don't specify defaults. It is an error to overspecify, i.e. to specify all three of -left, -right, and -width or -top, -bottom, and -height. To use arguments, specify all four of the left, right, width, and height arguments. left and top have the same effect as specifying them as the argument of a -left or -top option, respectively. width and height have the same effect as specifying them as the argument of a -width or -height option, respectively, where they are positive. Where they are not posi‐ tive, they have the same effect as specifying one less than the value as the argument to a -right or -bottom option, respectively. (E.g. width = 0 makes the cut go all the way to the right edge). Before July 2000, negative numbers were not allowed for width and height. Input is from Standard Input if you don't specify the input file pnmfile. Output is to Standard Output. If you are splitting a single image into multiple same-size images, pamdice is faster than running pamcut multiple times. OPTIONS -left The column number of the leftmost column to be in the output. If a nonnegative number, it refers to columns numbered from 0 at the left, increasing to the right. If negative, it refers to columns numbered -1 at the right, decreasing to the left. -right The column number of the rightmost column to be in the output, numbered the same as for -left. -top The row number of the topmost row to be in the output. If a non‐ negative number it refers to rows numbered from 0 at the top, increasing downward. If negative, it refers to columns numbered -1 at the bottom, decreasing upward. -bottom The row number of the bottom-most row to be in the output, num‐ bered the same as for -top. -width The number of columns to be in the output. Must be positive. -height The number of rows to be in the output. Must be positive. -pad If the rectangle you specify is not entirely within the input image, pamcut fails unless you also specify -pad. In that case, it pads the output with black up to the edges you specify. You can use this option if you need to have an image of certain dimen‐ sions and have an image of arbitrary dimensions. pnmpad also adds borders to an image, but you specify their width directly. -verbose Print information about the processing to Standard Error. SEE ALSO pnmcrop(1), pnmpad(1), pnmcat(1), pgmslice(1), pnm(5) AUTHOR Copyright (C) 1989 by Jef Poskanzer. 03 August 2000 pamcut(1)


With a culinary history that stretches back centuries, Italian cuisine is one of the world’s favorites. Spumoni ice cream, spaghetti, lasagna and pizza are traditional dishes that are widely available in the United States. Beyond these basic dishes, there are a number of regional favorites like Parmesan cheese and Parma ham. One part of Italy is even known for making a kind of maggot cheese. The cheese is fermented and allowed to sit out so that flies lay eggs. Afterward, it is packed at the perfect time for maggots to develop
China has one of the most diverse mixes of cultures and cuisines in the world. The main eight styles of cooking are: Fujian, Cantonese, Anhui, Zhejiang, Szechuan, Shandong and Hunan. In Chinese traditional medicine and culture, the opposites of yin and yang must always be kept in balance. This same balance extends to food. When cooking, the Chinese try to balance different colors, tastes, textures and smells. This focus has paid off and made Chinese cuisine one of the world’s finest.In a traditional Chinese meal, you can expect to have noodles or rice. Although many American-based Chinese restaurants use fried rice, most China-based Chinese restaurants serve basic steamed rice.
Over the last decade, Thai food has grown in popularity. Hands down, the most popular dish is pad thai. To truly experience Thai cuisine, you should step away from the basic pad thai and try some of the broths and noodle dishes that make this cuisine so delectable. This cuisine focuses on a lot of herbs and offers a range of sweet, sour, spicy and bitter tastes. It focuses on fresh herbs, so this cuisine always has a vivid flavor
India is one of the most densely populated countries on the planet. With so many people within the nation, Indian cuisine is highly varied. Curries are the traditional fare, but Indian food is not confined for just curry. There are a number of regions that make vegetarian dishes, and ayurvedic medicinal traditions are often used in creating food. Within India, visitors will find a range of sweet, hot and spicy dishes. Even better, the nation is home to millions of street food stands. At these stands, visitors can try out unique treats for a very cheap price.
Like Italian cuisine, Greek food dates back thousands of years. Many common Greek dishes have unknown origins because they have been around so long. This cuisine has a unique mix of different Mediterranean styles. Back in the day, the Greeks were well-positioned to become a major port for sea trading. Every time sailors returned from traveling, they brought back different dishes and dining styles. In Greece, visitors can expect fresh herbs, olive oil and feta.
Due to its location, Lebanon has adopted Arabic and Mediterranean influences. Lebanese food uses a lot of fresh fruit, vegetables and seafood. Other than fish, it does not contain a big focus on meat. When dining at a Lebanese restaurant, you can expect delicious pickles, unique salads, Arabic bread, vegetable dishes and vegetable dips.
The Hibachi or Teppanyaki grill are some of the most delectable of Japanese dining options.  This cuisine focuses on noodles, tofu, sushi and vegetables. Each meal is meticulously prepared and exceptionally delicious. Even better, Japanese restaurants often serve oolong or green tea.
American food is an extremely popular dining option. With so many cultures moving in and out of the country, American food encompasses a range of different dining styles. In Chicago, the deep dish pizza has become famous. Texas has five-alarm chili while the Pacific Northwest is home to microbreweries and coffee. At most traditional American diners, you can expect hot dogs, hamburgers, buffalo wings, biscuits & gravy and omelets.


The main table
The follow keys are "live";
- u Move selected element up
- d Move selected element down
- up arrow Move the selection up
- down arrow Move the selection down
- enter Toggle the fold on the selection
To do
bug when u and d typed when opened
Dynamic table manipulation and styling
This page tests the techniques used for dynamic manipultaion of tables.
add normal row
add expanded
delete a row
set text in a row
style a row
set a color
An empty table
Is here
add normal row
References
Most of the code is modified from the examples at
W3schools - dom manipulation
The trick I used to get nice border stylings I found at
CSS border styling


The Madagold company was created in March 2018 by a group of friends who have the same vision for the development of the country. Fight poverty by developing structures that will create many jobs. Madagold is a company which aims at the exploitation of mineral resources. Madagold will reinject a large part of its profiles in several major projects for the development of the country
In a geostrategic position, as a crossroads of the Indian Ocean between Asia and Africa (400 km east of Africa.)
Located 390 km from the capital, in the region of Vakinakaratra, district Miandrivazo (Tananarive–Antsirabe : 170km. Antsirabe-Miandrivazo : 220km)
The DABOLAVA project is an industrial gold mine project, located in the region of Vakinakaratra, 220 km from Antsirabe
in the district of Miandrivazo.
Several primary and artisanal gold deposit sites are located in:


The static method in row-level security (RLS) uses a fixed value in the DAX filter, while the dynamic method uses a DAX function.
RLS involves several configuration steps, which should be completed in the following order:
Create a report in Microsoft Power BI Desktop.
Import the data.
Confirm the data model between both tables.
Create the report visuals.
Create RLS roles in Power BI Desktop by using DAX.
Test the roles in Power BI Desktop.
Deploy the report to Microsoft Power BI service.
Add members to the role in Power BI service.
Test the roles in Power BI service.
Follow the typical steps to create a report in Power BI Desktop. Use Microsoft Power Query to retrieve and clean the data. Then, confirm that the relationship exists between the two tables by using the Modeling tab; it should be a one-to-many relationship on the empID column.
Your next step is to create a Power BI report.
Notice how the preceding table has rows for all sales, including all departments. You will be limiting visibility so that only employees of a specific department can see their own sales.
To create RLS roles in Power BI Desktop, select the Modeling tab, and then select Manage Roles.
On the Manage roles page, select Create.
Power BI row-level security (RLS) uses DAX to control who can see which data. Consider it as always adding another filter to the appropriate users, regardless of the filters, slicers, or interactions that the users choose on a Power BI report.
On the Manage roles page, create a role for each department and then add a DAX expression to it. For instance, you can create a role called Game and then add the DAX expression [department] = "Game". Then, whenever a member of that role interacts with the report, Power BI will add that filter to their interactions, thus limiting what they see.
A fixed value is used in the filter on the right side of the equal sign (in this case, "Game"). The intention is that, if you ever need to add a category, you will need to create a new role with a new value in the DAX expression.
Notice how the DAX filter is applied on the dimension table. Row-level security performs better when the data is organized in a star schema. Apply the DAX filter to a dimension table, as was done with the Products table.
The DAX filter is applied to every interaction, slicer, and filter that the user applies. If you have a DAX filter that performs poorly, the user experience will be negatively impacted. Therefore, keep the DAX filter as simple as possible.
You can validate that the filter is working by selecting the Modeling tab and then selecting View as Roles.
In the View as roles window, select the Game role. The report now renders as if you were in that role, and you will only see the records that are included in the Game department.
You can undo this filter by selecting View as roles again and then selecting None.
You can deploy the report to Power BI service by selecting the Publish button on the Home tab and then selecting a workspace.
To add members to the role in Power BI service, go to your workspace in Power BI service. Find the dataset that you created with the same name as your report. Select the ellipsis (...) button and then select Security.
In the Row-Level Security screen, you can add Microsoft Azure Active Directory (Azure AD) users and security groups to the security role. When members are added to this role, the DAX filter that you previously defined will be applied to them. If members are not added to the role, but they have access to the report, RLS will not apply to them. You can add the three people in the Game department to the Game role. Now, when those members sign in, they will only see the report with data that applies to them.
You can test the roles inside Power BI service by selecting the ellipsis (...) next to the Game role on the Row-Level Security screen and then selecting Test as role.
This selection will display the report as if you were a member of the role in Power BI service.
And there you have it! We've successfully implemented row-level security in Power BI.


It is very common that we need to manipulate array, collection and object in order to retrieve the data we want.
Lodash-es is a ES module of Lodash package which provides some great modular functions for us to manipulate arrays, objects, numbers, strings, etc.
Lodash is exported CommonJS module but lodash-es is exported as ES module. Since Angular is supporting ES6 Modules, we should use lodash-es so that we can do Named Import.
Refer to this link for Lodash Documentation, it can be used for both lodash and lodash-es.
npm i lodash-es
// IN item-list.component.ts
import sortBy from 'lodash-es/sortBy';
const itemCollection = [
{
item_id: 'abc001',
item_category: 'pen',
item_name: 'Brand A',
item_price: 2
},
{
item_id: 'abc002',
item_category: 'pen',
item_name: 'Brand B',
item_price: 3
},
{
item_id: 'abc003',
item_category: 'ruler',
item_name: 'Brand X',
item_price: 2
}
];
const sortedItemCollection = sortBy(itemCollection, 'item_id')


Thank You for completing the test, Here are Your results
Your Personality type is ESFJ
The personality test is based on Myers-Briggs Type Indicator (MBTI)
ESFJs are conscientious helpers, sensitive to the needs of others and energetically dedicated to their responsibilities. They are highly attuned to their emotional environment and attentive to both the feelings of others and the perception others have of them. ESFJs like a sense of harmony and cooperation around them, and are eager to please and provide.
ESFJs value loyalty and tradition, and usually make their family and friends their top priority. They are generous with their time, effort, and emotions. They often take on the concerns of others as if they were their own, and will attempt to put their significant organizational talents to use to bring order to other people's lives.


There were a ton of cheesehead Packer fans around downtown Seattle today. It was especially appropriate when I saw a few come out of Beecher’s at the market. Go Hawks!
There were a ton of cheesehead Packer fans around downtown Seattle today. It was especially appropriate when I saw a few come out of Beecher’s at the market. Go Hawks!
A new Mac mini would come in so handy in encoding this beastly box set. It’s okay though, I’m patient 😊
The new Mac mini looks fantastic! It would be great someday to replace my 2012 version with one of these.
By a stroke of what I can only call the Lord’s providence, we found a TV exactly the same as the one that was broken. $275 later and it’s up on the wall.
I’m so glad I don’t have to jump into the “Smart” TV era just yet.
Is there any decent non-smart TV out there anymore? I’m suddenly in the market for something to replace my Samsung plasma screen.
I heard about Alton Brown’s egg nog recipe the other day and had to give it a go. Now I’ve got a huge bowl of it chilling in my fridge for the next couple of months. Can’t wait to try it!
If you or someone you know has an app that needs updating, get in touch! I’m on the hunt for a fun side hustle.
Working on an updated version of Scorebook (which was written entirely in Objective-C). I’m making new stuff in Swift, and having to update a bunch of the old code to work with the new.
And our internet is back! 🎉
We are having a FIOS internet outage at home, and I’m realizing how impactful it is for my small kiddos.
The Mariners made a fake script for the 1994 World Series and had Dave Niehaus call it. This story is unbelievable and you have to hear the sound.
I really miss Dave. And Mariner playoff baseball.
The lack of intrinsicContentSize
on UIStackView
(and all arranged subviews having a 0,0 origin) is causing me a decent amount of grief this morning.
Getting back into a project I wrote a few years ago exclusively in Objective-C and adding new stuff in Swift. I constantly forget to remember @objc
declarations and have had to make a couple of wrappers so my Swift stuff will bridge correctly. But it’s good to be back in this app
It’s kind of surprising to me that a new line of iPhones were introduced today and I’m not really interested in upgrading to any of them (the XS being the only realistic option for me). I think that’s a credit to just how good the iPhone X is.
The bootleg from Pearl Jam’s 8/8 show at Safeco Field went on sale yesterday. Both home shows were really good, and I love going back and listening to their shows I went to.
I signed up for Feedbin as soon as Google Reader shutdown, and it’s truly a great service. They’re private by default and it’s one of the reasons I’ll continue my subscription as long as I can see.
Finnian keeps asking for “boing” — the kid cant get enough of bowling!
Atticus woke up and was babbling/playing at 3:15 in his room, then our fire alarm went off at 3:45. There was no fire and now I’m wide awake and how is yoir morning going?
I made a couple of PRs to an open source library that hasn’t been updated in a while, and they haven’t been responded to in about a week. It’s totally cool for me to just merge the branches in my fork and just use my fork, right? I want to do right by the original author.
You know that feeling of coming back to the world after several amazing days in a row? I’ve got a massive case of that right now. Pearl Jam twice last week, Xcoders, and the last 3 days have been great times with family. I’m so thankful for all the memories we made.
What a great Pearl Jam show last night. Both Wednesday and and last night were great sets that were way different from each other. Eddie broke out the harmonica for Footsteps on the second song and I knew we were in for a treat!
Pearl Jam show 1 of 2 last night was amazing! 3 hours and 2 encores. They brought all they had and are going to do it again tomorrow night. We were up in section 220 last night and will be in GA tomorrow.
Today is the day! Pearl Jam part 1!
If a bus comes 20 minutes after its posted time but 8 minutes before the next one, is it really late or really early?
Every time I manually edit a plist dictionary I forget to put the value before the key. Every. Time.


These instructions detail how to obtain the benchmarks used to evaluate Symbooglix and the tools used in evaluation. Symbooglix is open source an is available on GitHub.
WARNING: The sbb repo is very large. It takes roughly 13 GiB of space.
The gpu
and sbb
repository corresponds to the GPU benchmarks
and SV-COMP benchmarks discussed in the paper respectively.
git clone https://github.com/symbooglix/gpu.git
git clone --branch icst16 https://github.com/symbooglix/sbb.git
Each repo contains a program_list.txt
which can be given to
boogie-batch-runner.py
which will be used later.
We provide Docker images for each tool including Symbooglix which can be pulled from the DockerHub. Note that Duality is built on top of Corral, hence there is only a Corral image.
In order to run the tools via Docker you will need to install it if you haven't already. We used Docker 1.6.2, you can try older versions but things may not work correctly. Docker runs natively on Linux and can be indirectly run on Windows or OSX via the Boot2Docker project.
If you prefer to build the images from scratch run make
in
https://github.com/symbooglix/icst16-tools-docker-files.
The images can be found on our Docker organisation page. Run the following commands to pull down the Docker images
docker pull symbooglix/boogaloo:icst16
docker pull symbooglix/boogie:icst16
docker pull symbooglix/corral:icst16
docker pull symbooglix/gpuverify:icst16
docker pull symbooglix/symbooglix:icst16
Each image runs as the icst
user by default. This user has sudo access
so you can install additional packages. The password is icst
Each docker image has the boogie-runner framework installed which can
be invoked via the boogie-runner.py
or boogie-batch-runner.py
commands. Each docker image also has the boogie-runner config files (.yml
)
in the home directory. These instruct the boogie-runner framework how to run a tool. There
may be multiple configuration files. For example the corral image has
corral-64-gpu.yml
- Corral with a bound of 64 to run on the GPU benchmarkscorral-nb-gpu.yml
- Corral with a large bound to run on the GPU benchmarkscorral-8-svcomp.yml
- Corral with a bound 8 to run the SV-COMP benchmarkscorral-nb-svcomp.yml
- Corral with a large bound to run on the SV-COMP benchmarksduality-svcomp.yml
- Duality to run on the SV-COMP benchmarksTo run a tool you need to create a docker container and mount the benchmarks inside it as a volume. For example to create a Docker container for Corral/Duality and get shell access run:
docker run --rm -ti -v /path/to/benchmark/directory:/mnt symbooglix/corral:icst16
Note
/path/to/benchmark/directory
should be the path to the directory containing
one of the benchmark suites you downloaded earlier.
-v
flag is creating a volume inside the container. In the above example
the benchmark directory is mounted inside the container at /mnt
--rm
flag means that the container and any changes you
make in the container will be deleted when you leave the container.
Remove this flag if you want to keep the container.
symbooglix/corral:icst16
is the name of the image replace this with the image
you wish to useOnce you have shell access inside the container you can then run the tool inside container.
The tools are on the ase
user's PATH
inside the container so you
can invoke them directly if you wish. The tool executables are:
Boogie.exe
(in the symbooglix/boogie:icst16
image)boogaloo
(in the symbooglix/boogaloo:icst16
image)Corral.exe
(in the symbooglix/corral:icst16
image)gpuverify
(in the symbooglix/gpuverify:icst16
image)sbx.exe
(in the symbooglix/symbooglix:icst16
image)
The boogie-runner.py
tool allows a single benchmark to be run conveniently. To try it
run:
boogie-runner.py config.yml /path/to/boogie/program.bpl work_dir result.yml
config.yml
is one of the YAML configuration files in the home directory./path/to/boogie/program.bpl
is the path inside the container to the Boogie program you wish the tool to usework_dir
is a working directory for the run. It should not already eixst.result.yml
is the path to write the results to.
The boogie-batch-runner.py
tool allows multiple benchmarks to be run conveniently.
An example invocation if the Symbooglix image was being used with the GPU benchmarks mounted in
/mnt/
would be:
boogie-batch-runner.py --rprefix /mnt/other/ ~/symbooglix-gpu.yml /mnt/program_list.txt work_dir result.yml
The process is nearly identical to how Symbooglix is run when comparing it against other Boogie tools
(See Boogie tool comparison)
The only difference is that Symbooglix is run on a smaller subset (361 programs) of the SV-COMP benchmarks.
The program list to be be passed to boogie-batch-runner.py
is klee_comparision_program_list.txt
in the root of the sbb
repository.
The first stage is to obtain Docker images for the modified versions of KLEE. There are two versions, one is a 32-bit build of KLEE and one is a 64-bit build of KLEE. The reason for requiring two different versions is that the benchmarks are a mix of 32-bit and 64-bit x86 programs and KLEE does not work correctly when executing programs designed far a different architecture than the host machine.
First pull the images (alternatively you can build the 32-bit and 64-bit Docker images from source).
$ docker pull symbooglix/klee_svcomp32:latest
$ docker pull symbooglix/klee_svcomp64:latest
Now we need to get the SV-COMP 2015 benchmarks. These have been modified in several ways:
All these changes are visible as commits on top of the official SVCOMP 2015 tag. To obtain the benchmarks run:
$ git clone --branch klee_svcomp15_smack https://github.com/symbooglix/sv-benchmarks.git
Now we can build the benchmarks by using 64-bit Docker image (note the SV-COMP build system will take care of setting the architecture). Run the following:
$ cd sv-benchmarks/c
# Start a container, mounting the benchmarks inside the container at /mnt.
# Note that the --user= stuff is so that inside the container the same uid/gid is used so
# the volume mounted inside the container can be written to. Don't worry about the messages
# about not finding the group name or not having a username
$ docker run --rm -ti -v $(pwd):/mnt --user=$(id -u):$(id -g) symbooglix/klee_svcomp64
# Now go into the benchmark directory
I have no name!@bd3e8672a05b:/home/klee$ cd /mnt
# Now we will compile the benchmarks. Note you can use the -jN flag to build N benchmarks concurrently to speed things up
I have no name!@bd3e8672a05b:/home/klee$ make CC=clang-3.4 SUPPRESS_WARNINGS=1
# If everything compiled without errors then leave the container
I have no name!@bd3e8672a05b:/home/klee$ exit
Now check that inside sv-benchmarks/c
there is a directory called bin
. This contains all the compiled benchmarks (*.oi
and *.oc
files).
Now we need to obtain a version of the Boogie-Runner framework that has been modified to run KLEE benchmarks and install its
dependencies. Note the Boogie-Runner framework requires Python3. Note you need root access to run pip3
like this. If
you don't have root access use Virtualenv to create a virtual Python
enviroment and install the dependencies in it.
$ git clone https://github.com/symbooglix/boogie-runner.git
$ cd boogie-runner
$ git checkout 8e9c6b630a456696d68ca0a3b171f069d8e651d7
$ pip3 install --requirement requirements.txt
We now have everything needed to run KLEE on the benchmarks.
To run KLEE on the 32-bit benchmarks run the following where <BENCH_DIR>
is the path to the c
directory
in the location where you cloned the https://github.com/symbooglix/sv-benchmarks.git
repository and <WORK_DIR_32>
is a non-existant directory to be created and used as the working directory. The results will be written to results_32.yml
.
$ ./boogie-batch-runner.py --rprefix <BENCH_DIR>/bin/ <BENCH_DIR>/klee32_config.yml <BENCH_DIR>/program_list.filtered_sbb.32.txt <WORK_DIR_32> results_32.yml
The code for running on the 64-bit benchmarks is similiar. Note KLEE will fail to execute most of these.
$ ./boogie-batch-runner.py --rprefix <BENCH_DIR>/bin/ <BENCH_DIR>/klee64_config.yml <BENCH_DIR>/program_list.filtered_sbb.64.txt <WORK_DIR_64> results_64.yml


Welcome
Hello there, awesome person!
This is the link to Wikipedia
Click here for Youtube
Freecodecamp


Myself
Renuka Prasad A,I'm an aspiring full stack javascript developer, with interest in web design
and mobile app development.Currently iam trying to better my programming skills through FreeCodeCamp.My
hobbies are video games,movies(big fan of star wars and Dr.Who franchise).In my spare time i
like to blog about way the world works and ponder over the nature of life.


wf3cte¶
The charge transfer efficiency (CTE) of the UVIS detector has inevitably been declining over time as on-orbit radiation damage creates charge traps in the CCDs. Faint sources in particular can suffer large flux losses or even be lost entirely if observations are not planned and analyzed carefully. The CTE loss will depend on the morphology of the source, the distribution of electrons in the field of view (from sources, background, cosmic rays, and hot pixels) and the population of charge traps in the detector column between the source and the transfer register. And the magnitude of the CTE loss increases continuously with time as new charge traps form.
CTE is typically measured as a pixel-transfer efficiency, and would be unity for a perfect CCD. One indicator of CTE is the Extended Pixel Edge Response (EPER). Inefficient transfer of electrons in a flat-field exposure produces an exponential tail of charge in the overscan region. Analysis of monitoring observations through January 2013 shows that CTE continues to decline linearly over time (WFC3 ISR 2013-03).
The CTE correction step uses it’s own dark reference files which have themselves been corrected for CTE. The specific reference file used for any dataset may be found in the image header keyword DRKCFILE. This step also uses a special bias reference file as part of the CTE correction itself, referred to in the header by the BIACFILE keyword. This BIACFILE is only used to facilitate the CTE correction, the resulting corrected image then uses the normal BIASFILE to correct the science frame after the CTE correction has been performed. After the CTE correction has been performed and the data progresses through the rest of the pipeline, the special CTE corrected dark, DRKCFILE in the header, will be used for the dark current correction instead of the DARKFILE.
There is a PCTETAB refrence file which contains extensions of calibration images and tables of parameters used during the CTE correction stage. The header of this file also contains parameters for the CTE correction algorithm. These parameters, and important scalars which are used to correct the data are stored in the output image headers. See the UVIS2.0 reference ISR for more information.
This routine performs the CTE correction on raw data files. The calibration step keyword is PCTECORR, if this is set to PERFORM then the CTE correction will be applied to the dataset. Some caveats for its use:
- CTE corrections can ONLY be performed on RAW data which has not been calibrated in any way.
- Data which have already been through BLEVCORR, BIASCORR or DARKCORR will be rejected.
- The CTE correction step in the pipeline is currently only implemented for FULL FRAME images
The standalone call will produce a RAC fits file by default. This contains only the CTE corrected data, no other calibrations have been performed.
For more information the the WFC3 CTE please see the WFC3 CTE webpage .
Example¶
In Python without TEAL:
>>> from wfc3tools import wf3cte >>> wf3cte(filename)In Python with TEAL:
>>> from stsci.tools import teal >>> from wfc3tools import wf3cte >>> teal.teal('wf3cte')In Pyraf:
>>> import wfc3tools >>> epar wf3cte
Parameters¶
- input : str
Name of input files
- a single filename (
iaa012wdq_raw.fits
)- a Python list of filenames
- a partial filename with wildcards (
\*raw.fits
)- filename of an ASN table (
\*asn.fits
)- an at-file (
@input
)-1 : value, as in minus one, this will make sure only 1 processor/thread is used during processing, otherwise all available are used.
- verbose: bool, optional
- Print verbose time stamps?
The wf3cte function can also be called directly from the OS command line:
>>> wf3cte.e input [-options]
Where the OS options include:
- -v: verbose
- -1: turn off multiprocessing
Basic Steps In The CTE Correction¶
- The reference bias image named in the BIACFILE header keyword is subtracted from the data
- Parameters from the CTE parameter table, referenced in the PCTETAB header keyword, are read and stored
- The date is reformated so that each quadrant has been rotated such that the readout amp is located at the lower left of the array. The reoriented four quadrants are then arranged into a single 8412x2070 image (including the overscan) with amps CDAB in that order. In this format, the pixels are all parallel-shifted down, then serial-shifted to the left
- An additional bias correction is performed using the residual bias level measured for each amplifier from the steadiest pixels in the horizontal overscan, this value is then subtracted from all the pixels in each respective amp
- The image is corrected for gain
- The smoothest image that is consistent with being the observed image plus readnoise is found and subtracted. This is necessary becasue we want the CTE correction algorithm to produce the smoothest possible reconstruction, consistent with the original image and the known readnoise. The algorithm then constructs a model that is smoother where there pixel-to-pixel variations aren’t too large, then it respects the pixel values, using a 2sigma threshold to mitigate readnoise amplification, iteration is not done when the deblurring is less than the readnoise.
- The CTE correction itself is calculated and then subtracted from the original, raw, uncorrected and uncalibrated image.
- The corrected image is now ready to contiue through the rest of the pipeline. When the DARKCORR header keyword is set to perform, the CTE corrected image will use the dark reference file referred to in the DRKCFILE header keyword.
The PCTETAB and Algorithm Parameters¶
The following are new primary header keyords which will be updated in the data headers during the wf3cte step. They are also specified in the PCTETAB reference file.
| KEYWORD | DESCRIPTION |
|---|---|
| CTE_NAME | name of cte algorithm [string] |
| CTE_VER | version number of cte algorithm [string] |
| CTEDATE0 | date of wfc3/uvis installation in HST, in modified Julian days (MJD) |
| CTEDATE1 | reference date of CTE model pinning, in modified Julian days (MJD) |
| PCTETLEN | max length of CTE trail |
| PCTERNOI | readnoise amplitude for clipping |
| PCTENFOR | number of iterations used in CTE forward modeling |
| PCTENPAR | number of iterations used in the parallel transfer |
| PCTENSMD | readnoise mitigation algorithm |
| PCTETRSH | over-subtraction threshold |
| PCTEFRAC | cte scaling frac calculated from expstart and used in the algorithm |
| PCTERNOI | the readnoise clipping level to use |
| FIXROCR | make allowance for readout cosmic rays |
The PCTETAB reference file has 4 extensions, two tables and two images:
Filename: wfc3_cte.fits
No. Name Type Cards Dimensions Format
0 PRIMARY PrimaryHDU 21 ()
1 QPROF BinTableHDU 16 999R x 3C ['i', 'i', 'i']
2 SCLBYCOL BinTableHDU 20 8412R x 5C ['i', 'e', 'e', 'e', 'e']
3 RPROF ImageHDU 12 (999, 100) float32
4 CPROF ImageHDU 12 (999, 100) float32
The first extension lists the charge-trap levels, the columns are respectively the trap number, the charge-packet size it applies to (in electrons), and the size of the trap (also in electrons).
The second extension contains the CTE scalings as a function of column number. There are 5 columns, each with 8412 elements. The first column contains the integer column number in the amp readout-aligned large array. The other columns contain the CTE scaling appropriate for that column at the 512th, 1024th, 1536th and 2048th rows respectively.
The third extension contains the differential CTE trail profile as a function of charge level in the form of an image
The fourth extension contains the cumulative CTE trail profile as a function of charge level, also in the form of an image.
Output Files¶
If you are running the separate wf3cte.e step a _rac.fits file will be output. This the same as a _raw.fits file except the CTE correction has been applied to the data.
If the PCTECORR step is set to PEFORM:
- when the _raw.fits file enters calwf3, then no intermediate _rac.fits file will be saved, unless you specify the -s flag, which instructs calwf3.e to save all intermediate files.
- the calwf3 pipeline will produce both CTE calibrated product and non-CTE calibrated products. The CTE products have a ‘c’ at the end of their extension name, such as _blc, _rac, _crc, _flc, and the non-CTE calibrated products contain the familiar : _blv, _crj, _flt.


GitHub is a code hosting platform for collaboration and version control.
GitHub lets you (and others) work together on projects.
Repository:
A GitHub repository can be used to store a development project.
It can contain folders and any type of files (HTML, CSS, JavaScript, Documents, Data, Images).
A GitHub repository should also include a licence file and a README file about the project.
A GitHub repository can also be used to store ideas, or any resources that you want to share.
Branch:
A GitHub branch is used to work with different versions of a repository at the same time.
By default a repository has a master branch (a production branch).
Any other branch is a copy of the master branch (as it was at a point in time).
New Branches are for bug fixes and feature work separate from the master branch. When changes are ready, they can be merged into the master branch. If you make changes to the master branch while working on a new branch, these updates can be pulled in.
Commits:
At GitHub, changes are called commits.
Each commit (change) has a description explaining why a change was made.
Pull request:
Pull Requests are the heart of GitHub collaboration.
With a pull request you are proposing that your changes should be merged (pulled in) with the master.
Pull requests show content differences, changes, additions, and subtractions in colors (green and red).
As soon as you have a commit, you can open a pull request and start a discussion, even before the code is finished.


This is a standalone TensorFlow's graph visualizer frontend for directed graphs. The goal of this repository to provide a general purpose interactive graph visualizer (which TensorBoard already pretty much provided), as well as providing necessary documentations.
####TensorBoard graph visualization features:
I was too lazy to inlcude an actual screenshot for this striped-down version it is basically the same except for that the header panel is remvoed. The example is a tensorflow computational graph but the implement is actually quite domain-agnostic so should be easy to adapt.
####How to use:
To use gulp and plugins as webserver and livereload during development, run
git clone git://github.com/jzthree/GraphBoard.git; cd GraphBoard;npm run prepare;npm install gulp -g; gulp
(you may use nvm to install npm without root; expect some time to install all the dependencies). It will be served in localhost:8001 (if the port is also used it may throw an error).
If you are using Mac OS X, unfortunately currently there is an issue with gulp livereload. You can temporarily disable it by setting
livereload: { enable: false, ...}
in gulpfile.js.
I am running a gulp server on accio:8000 if you are in @functionlab.
After you started the gulp webserver, an example is in demo/index.html
. The example graph is in demo/data/graph_run_agraph.pbtxt
####Development:
(Work in progress and help welcomed) I have removed as much unnecessary parts as I can safely identify in the first look. There are still a lot of clean up that can be done (I didn't remove any node.js dependencies for example). The code is working standalone now. A documentation site generated by typedoc for the core typescript library tf-graph-common can be viewed at https://jzthree.github.io/GraphBoard/.
Tensorboard uses Google's Polymer 1.7 as the frontend framework https://www.polymer-project.org/1.0/docs/devguide/feature-overview. The component reuse is provided by html import. It is my first time to see it but it seems reasonably simple to use. The components hierarchy is shown below:
tf-tensorboard
tf-graph-dashboard
:Graph and control components.
*tf-graph-loader
:Load graph. This include example of calling tf-graph-common for building graph in its _parseAndConstructHierarchicalGraph function.
tf-graph-board
tf-graph
tf-graph-scene
:Display the main graph
tf-graph-minimap
:Display the minimap when graph is zoomed in
tf-graph-info
:Displays node info in the floating side window
tf-node-info
tf-node-list-item
tf-graph-control
:Display the left panel that provide some control utilities like choosing graph
*tf-dashboard
*tf-backend
*tf-backend
tf-graph-common is the major library for graph drawing. A documentation site generated by typedoc can be viewed at https://jzthree.github.io/GraphBoard/.
tg-graph-common
scene
annotation
contextmenu
edge
minimap
node
scene
colors
:Map op category to color. (This should be exposed as API)
common
externs
graph
hierarchy
layout
parser
proto
render
template
util
Polymer components
tfgraph
RenderHierarchy -> LayoutScene
Generated using TypeDoc


Back to templates
Plus Button
The plus button is for doing a lot of stuff from one core button.
So click it.
Close
Some sort of modal
Calls
Chats
Events
Files
Photos


TsaaP Notes Terms
These Terms of Service ("Terms") govern your access to and use of the services, including our various websites, SMS, APIs, email notifications, applications, buttons, and widgets, (the "Services" or “TsaaP Notes”), and any information, text, graphics, photos or other materials uploaded, downloaded or appearing on the Services (collectively referred to as "Content"). Your access to and use of the Services are conditioned on your acceptance of and compliance with these Terms. By accessing or using the Services you agree to be bound by these Terms.


1. Pick a date range to propose, the calander widgit will help set ranges.
{% endif %} {% if session.calendars is defined and session.email == False %}After the emails have been sent, you can go back to the home page and view the proposal
You may now exit the application or go to the home page and create a meeting for yourself
{% endif %}


John & Emily Get Married!
Registry
We understand that it's important to you to express your well wishes, and we welcome them! Some of you may want to give us gifts. The sentiment is appreciated; however, we have more than enough for our own lives, and it would give us great joy if you donated to one of the following organizations instead:
East Harlem Health Outreach Partnership (Donate)
Emily has spent a ton of time volunteering here and helping provide healthcare to uninsured patients in East Harlem. Let us know about your donation so we can properly thank you!
East Harlem Tutorial Program (Donate)
EHTP provides several educational programs for youth in East Harlem with an eye towards preparing them for college. John has spent some time volunteering with their high school robotics team. Let us know about your donation so we can properly thank you!
The Bronx Freedom Fund (Donate)
These folks do great work helping people pay bail so they can get back to their jobs and families while awaiting trial. Let us know about your donation so we can properly thank you!


To win this game.
Collect all the red apples but do not touch any green bar on in the area.
You have two displayed data on the top: your score and your chance.
After you collect all the apples, you are very welcome to play this game again if you like.


WITNESS LIST Constitutional Revision, Select Committee April 7, 1999-12:00A Board of Pardons & Paroles On: McElroy, Laura (Chairman Victor Rodriguez) Governor appointed state agencies On: Geiger, Richard (Self) Juries informed of good behavior. On: Place, Allen (Self)


NZ home ownership crashes to 70-year low
by Unconventional EconomistNew Zealand’s home ownership rate has plunged to 70-year lows, according to the latest Census:
According to the 2018 census, only 64.5 per cent of New Zealanders own their own home, compared to nearly 74 per cent in the early 1990s.
Shamubeel Eaqub said it was driven by a lack of affordability in New Zealand.
There are 1137 words left in this subscriber-only article.


EasyBook
Homepage
Exchange
Inherit
Explozre
signin
How to get points
Register to be a member of Easybook
Donate your used books and get points based on the value
Exchange books successfully
Still not enough points?
pay
here


Vectors
Learning objectives
In this section you will learn about vectors, how to create different types of vector, and how to manipulate them.
- Numeric Vectors: Definition and Creation
- Generating regular sequences
- Vector Arithmetic
- Useful functions applied to a vector
- Vectors with other types of data
- Automatic coercing within vectors
Numeric vectors
R operates on named data structures. The simplest data structure is the numeric vector: a single entity consisting of an ordered collection of numbers.
To set up a vector, we use the R function c()
which, in this context, can take an arbitrary number of arguments:
x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
x
## [1] 10.4 5.6 3.1 6.4 21.7
class(x)
## [1] "numeric"
You can also use the function c()
to concatenate several existing vectors
x <- c(10.4, 5.6, 3.1 )
y <- c(2,3,4)
z <- c(x,y)
z
## [1] 10.4 5.6 3.1 2.0 3.0 4.0
class(z)
## [1] "numeric"
Generating regular sequences
R has also a number of built-in functions for generating commonly used sequences of numbers.
The colon operator :
The :
creates regular sequence of integers. Its syntax is quite intuite: to create a regular sequence of integers from 1 to 10, just type:
1:10
## [1] 1 2 3 4 5 6 7 8 9 10
15:5
## [1] 15 14 13 12 11 10 9 8 7 6 5
The colon operator has high priority within an expression. Check the results of the following expressions to understand the order in which the operators are working:
2*1:15
## [1] 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
n <- 10
1:n-1
## [1] 0 1 2 3 4 5 6 7 8 9
1:(n-1)
## [1] 1 2 3 4 5 6 7 8 9
The seq()
function
The function seq() is more general. It has five arguments, only some of which may be specified in any one call. Consult the help file for more details. Look at the few examples to understand the function seq()
seq(1, 2, by=.2)
## [1] 1.0 1.2 1.4 1.6 1.8 2.0
seq(length=10, from =-1, by=2)
## [1] -1 1 3 5 7 9 11 13 15 17
The rep()
function
The function rep() can be used for replicating an object in several ways and creating vectors.
To put, several copies end-to-end, use the argument times
:
x <- c(1.34, 2.56)
(s5 <- rep(x, times=5))
## [1] 1.34 2.56 1.34 2.56 1.34 2.56 1.34 2.56 1.34 2.56
To repeat each element of x five times before moving on to the next, use the argument each
:
(s6 <- rep(x, each=3))
## [1] 1.34 1.34 1.34 2.56 2.56 2.56
Vector arithmetic
Vectors can be used in arithmetic expressions, in which case the operations are performed element by element.
For example, if you add two vectors:
\begin{equation} \left(\begin{matrix}a\\b\\c\\d \end{matrix} \right) + \left(\begin{matrix}e\\f\\g\\h \end{matrix} \right) = \left(\begin{matrix}a+e\\b+f\\c+g\\d+h \end{matrix} \right) \end{equation}
In R:
x <- c(10.4, 5.6, 3.4)
y <- c(3.1, 6.4, -2.1)
(z <- x + y)
## [1] 13.5 12.0 1.3
However, vectors occurring in the same expression do not need to be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated.
For example: \begin{equation} \left(\begin{matrix}a\\b\\c \end{matrix} \right) + e = \left(\begin{matrix}a+e\\b+e\\c+e \end{matrix} \right) \end{equation}
x <- c(10.4, 5.6)
y <- 3.1
(z <- x + y)
## [1] 13.5 8.7
While this is a very convenient R feature, it can be potentially misleading as it brings unruly results when the vectors are of different length, as in the following case:
\begin{equation}
\left(\begin{matrix}a\\b\\c\\d \end{matrix} \right) +
\left(\begin{matrix}e\\f\\g \end{matrix} \right) =
\left(\begin{matrix}a+e\\b+f\\c+g\\d+e \end{matrix} \right)
\end{equation}
x <- c(10.4, 5.6, 3.5)
y <- c(1,2)
z <- x + y
## Warning in x + y: longer object length is not a multiple of shorter object
## length
z
## [1] 11.4 7.6 4.5
Just to remind you of the potential danger, R will throw a warning message
The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a power. In addition all of the common arithmetic functions are available. log
, exp
, sin
, cos
, tan
, sqrt
and so on, all have their usual meaning.
x <- c(10.4, 5.6, 3.5)
log(x)
## [1] 2.341806 1.722767 1.252763
max
and min
select the largest and smallest elements of a vector respectively.
min(x)
## [1] 3.5
Useful functions applied to a vector
Several functions are very useful for basic statistics.
The sum()
function, sums up all the elements of the vector. The mean()
function calculates the mean value of all the elements of the vector. We can combine vector arithmetics with these functions to calculate very quickly some interesting statistics of the vector.
x <- c(10.4, 5.6, 3.5, 3.1, 7.2, 3.8, 10.2, 7.8)
mean(x)
## [1] 6.45
x - mean(x) #calculate the deviation from the mean
## [1] 3.95 -0.85 -2.95 -3.35 0.75 -2.65 3.75 1.35
We can calculate easily the sample variance $$ var(x) = \frac{1}{n-1} \sum_{i=1}^n (x_i - \bar{x})^2 $$
x <- c(10.4, 5.6, 3.5, 3.1, 7.2, 3.8, 10.2, 7.8)
mean(x)
## [1] 6.45
v<- sum((x - mean(x))^2) / (length(x)-1) #calculate the variance
v
## [1] 8.531429
var(x)
## [1] 8.531429
Note that base R already has a built-in function for calculating the sample variance var()
.
Vectors with other types of data
Vectors can contain other types of data, in particular characters and logicals.
The elements of a logical vector can have the values TRUE
, FALSE
, and NA
(for “not available”). The first two are often abbreviated as T and F, respectively. Note however that T and F are just variables which are set to TRUE and FALSE by default, but are not reserved words and hence can be overwritten by the user. Hence, it is better to always use TRUE and FALSE.
Automatic coercing within vectors
In general, coercion is an attempt by R to be flexible with data types. When an entry does not match the expected type, R tries to guess what we meant. But this can also lead to confusion.
We earlier said that vectors must be all of the same type. So if we try to combine say numbers and characters, you might expect an error. But let’s try to combine numeric and characters in the same vector:
c(1, "South Africa", 3, "England")
## [1] "1" "South Africa" "3" "England"
We do not even get a warning !! So what has happened?
R has converted the 1 and the 3 to character strings. And the class of the vector is character. Even though 1 and 3 were originally numbers when we wrote it out, R has converted them to character.
R coerced the data into a character string. It guessed that because we put a character string there in the middle, we meant the 1 and the 3 to actually also be character strings.
Again, be aware that R will coerce variables without any warning ! It will only throw an error, when it attemps to coerce a variable into a new type, but cannot do it.
Index vectors to obtain subsets of a vector
Subsets of the elements of a vector may be selected by appending to the name of the vector an index vector in square brackets. More generally any expression that evaluates to a vector may have subsets of its elements similarly selected by appending an index vector in square brackets immediately after the expression.
Such index vectors can be any of four distinct types.
Index = A logical vector.
In this case the index vector is recycled to the same length as the vector from which elements are to be selected. Values corresponding to TRUE in the index vector are selected and those corresponding to FALSE are omitted. For example, the following lines reates (or re-creates) an object `yv which will contain the values of x greater than 4, in the same order.
y <- x[x > 4]
y
## [1] 10.4 5.6 7.2 10.2 7.8
Index = A vector of integers.
In this case the values in the index vector must lie in the set {1, 2, …, length(x)}. The corresponding elements of the vector are selected and concatenated, in that order, in the result. The index vector can be of any length and the result is of the same length as the index vector.
x <- rnorm(20)
(y <- x[1:10])
## [1] 0.09220648 1.12491187 0.53665207 1.81840151 -0.38831663 0.06935517
## [7] -2.59814157 -0.20936368 0.94048022 -0.27008015
(z <- x[c(1,3,2,7)])
## [1] 0.09220648 0.53665207 1.12491187 -2.59814157
The use of index vectors can be very powerful to create complex sequences:
c("x","y")[rep(c(1,2,2,1), times=2)]
## [1] "x" "y" "y" "x" "x" "y" "y" "x"
Index = A vector of negative Integers
Such an index vector specifies the values to be excluded rather than included. Thus:
x[-(1:5)] # gives y all but the first five elements of x.
## [1] 0.06935517 -2.59814157 -0.20936368 0.94048022 -0.27008015 1.94953530
## [7] -1.46875658 1.35834277 -1.23067250 -0.54102607 -0.55928871 0.62858631
## [13] -0.97861047 0.98952395 -1.33371635
Index = A vector of character strings.
This possibility only applies where an object has a names attribute to identify its components. In this case a sub-vector of the names vector may be used in the same way as the positive integral labels in item 2 further above.
fruit <- c(5, 10, 1, 20)
names(fruit) <- c("orange", "banana", "apple", "peach")
lunch <- fruit[c("apple","orange")]
lunch
## apple orange
## 1 5
Note in this case, that we added a feature to the vector, because each element of the vector is associated with a name. This is obtained by using the function names()
.
The advantage is that alphanumeric names are often easier to remember than numeric indices.