import re
from dataclasses import dataclass
from typing import Optional, Union, Dict, Tuple, overload, Any, cast
from typing_extensions import Protocol
from pathlib import PurePath
from ._helpers_private import _init_pure_path
[docs]class Braces:
[docs] def __init__(self, open_char: str, close_char: str):
self._open: str = open_char
self._close: str = close_char
def __repr__(self) -> str:
return f"{self.open}{self.close}"
@property
def open(self) -> str:
"""opening character passed to :func:`Braces.__init__`"""
return self._open
@property
def close(self) -> str:
"""closing character passed to :func:`Braces.__init__`"""
return self._close
[docs] def enclose(self, text: str) -> str:
"""wrap text in open and close char"""
return f"{self.open}{text}{self.close}"
ARROW = Braces("<", ">")
BRACKET = Braces("[", "]")
CURLY = Braces("{", "}")
PAREN = Braces("(", ")")
BRACES_KINDS = [ARROW, BRACKET, CURLY, PAREN]
class Flag:
pass
KEEP = Flag()
PATTERN = re.compile(
r"^"
r"(?P<base>.+)"
r"(?P<sep>[._])"
r"(?P<open>[\[{<(])?"
r"(?P<start>\d+|#+)"
r"(-(?P<end>\d*|#*))?"
r"(?P<close>[\]}>)])?"
r"(?P<extension>\..+)?"
r"$"
)
[docs]class NameABC(Protocol):
base: str
extension: Optional[str]
def __str__(self) -> str:
return self.formatted()
[docs] @classmethod
def from_path(cls, path: Union[str, PurePath]) -> "NameABC":
"""New :class:`NameABC` instance from ``pathlib.Path`` or ``str``"""
raise NotImplementedError
[docs] def alter(
self,
base: Union[str, Flag] = KEEP,
extension: Optional[Union[str, Flag]] = KEEP,
**kwargs: Union[Any, Flag],
) -> "NameABC":
"""
Returns new `NameABC` with changes to fields. Each argument should accept the
``perfsprocket.KEEP`` flag as the default, which signals that a value should not
change. ``None`` values should be signals to change a field to ``None``. Methods
should also include **kwargs so other Name conventions arguments can be passed
without effect.
"""
raise NotImplementedError
[docs]@dataclass(frozen=True)
class FileName(NameABC):
base: str
extension: Optional[str]
def __post_init__(self) -> None:
if self.extension is not None and not self.extension.startswith("."):
object.__setattr__(self, "extension", f".{self.extension}")
[docs] @classmethod
def from_path(cls, path: Union[str, PurePath]) -> "FileName":
"""New :class:`FileName` instance from ``pathlib.Path`` or ``str``"""
path = _init_pure_path(path)
return FileName(base=path.stem, extension=path.suffix)
[docs] def alter(
self,
base: Union[str, Flag] = KEEP,
extension: Optional[Union[str, Flag]] = KEEP,
**kwargs: Union[Any, Flag],
) -> "FileName":
"""
Make changes to name.
``KEEP``: keep current value
``None``: Change value to ``None``
:return: new object
"""
# We can cast this since KEEP is the only Flag type defined.
base_arg = self.base if base is KEEP else base
base_arg = cast(str, base_arg)
extension_arg = self.extension if extension is KEEP else extension
extension_arg = cast(Optional[str], extension_arg)
return FileName(base=base_arg, extension=extension_arg)
[docs]@dataclass(frozen=True)
class SeqName(FileName):
delim: Optional[str] = "."
start: Union[int, str] = "#"
end: Optional[Union[int, str]] = None
pad: int = 0
brackets: Optional[Braces] = None
def __post_init__(self) -> None:
super().__post_init__()
object.__setattr__(self, "start", _post_init_start_end(self.start))
object.__setattr__(self, "end", _post_init_start_end(self.end))
[docs] @classmethod
def from_path(cls, path: Union[str, PurePath]) -> "SeqName":
"""Parse file sequence filename from path"""
path = _init_pure_path(path)
pieces = _extract_pieces_from_str(path)
base, delim, start, num_end, pad, brackets, extension = pieces
new = cls(
base=base,
extension=extension,
delim=delim,
start=start,
end=num_end,
pad=pad,
brackets=brackets,
)
return new
[docs] def alter(
self,
base: Union[str, Flag] = KEEP,
extension: Optional[Union[str, Flag]] = KEEP,
delim: Union[str, Flag] = KEEP,
start: Union[int, str, Flag] = KEEP,
end: Optional[Union[int, str, Flag]] = KEEP,
pad: Union[int, Flag] = KEEP,
brackets: Optional[Union[Braces, Flag]] = KEEP,
**kwargs: Union[Any, Flag],
) -> "SeqName":
"""
Make changes to name.
``KEEP``: keep current value
``None``: Change value to ``None``
:return: new object
"""
new = base, extension, delim, start, end, pad, brackets
names = ["base", "extension", "delim", "start", "end", "pad", "brackets"]
kwargs = dict()
for new_value, base in zip(new, names):
if new_value is KEEP:
new_value = getattr(self, base)
kwargs[base] = new_value # type: ignore
# As long as params are typed correctly, we don't need to worry about type
# checks here.
return SeqName(**kwargs) # type: ignore
def _num_end_from_match(groups: Dict[str, Optional[str]]) -> Optional[Union[int, str]]:
"""extract end frame from REGEX match."""
num_end: Optional[str] = groups["end"]
if num_end:
if "#" in num_end:
result: Optional[Union[int, str]] = "#"
else:
result = int(num_end)
else:
result = None
return result
def _padding_from_match(groups: Dict[str, Optional[str]]) -> int:
"""deduces padding from REGEX match"""
start = groups["start"]
start = cast(str, start)
padding = len(start)
return padding
def _brackets_from_match(groups: Dict[str, Optional[str]]) -> Optional[Braces]:
"""converts regex match to Brackets object"""
open_char = groups["open"]
close_char = groups["close"]
if open_char is None and close_char is None:
return None
for this_bracket in BRACES_KINDS:
if open_char != this_bracket.open:
continue
elif close_char != this_bracket.close:
continue
return this_bracket
raise ValueError(f"Bracket Type: {open_char}{close_char} Not Recognized")
def _format_range_pieces(seq_name: "SeqName") -> Tuple[str, str, str]:
"""
Returns open_bracket, close_bracket, range_separator. Non-relevant pieces are
returned as empty string so concatenation does not need to run checks.
"""
open_bracket = ""
close_bracket = ""
range_sep = ""
if seq_name.end is not None:
range_sep = "-"
if seq_name.brackets is not None:
open_bracket = seq_name.brackets.open
close_bracket = seq_name.brackets.close
return open_bracket, close_bracket, range_sep
def _format_file_nums(seq_name: "SeqName") -> Tuple[str, str]:
fill_start = "#" if seq_name.start == "#" else "0"
fill_end = "#" if seq_name.end == "#" else "0"
start_str = str(seq_name.start).rjust(seq_name.pad, fill_start)
if seq_name.end is not None:
end_str = str(seq_name.end).rjust(seq_name.pad, fill_end)
else:
end_str = ""
return start_str, end_str
def _run_filename_regex(path: PurePath) -> Dict[str, Optional[str]]:
"""extracts sequence name parts from regex"""
file_name = path.name
result = re.match(PATTERN, file_name)
if result is None:
raise ValueError
# Stub file for re is wrong here. None can be a value if group is optional.
# We need to ignore MyPy complaining that Optional[str] is incorrect
groups: Dict[str, Optional[str]] = result.groupdict() # type: ignore
return groups
PiecesType = Tuple[
str,
str,
Union[int, str],
Optional[Union[int, str]],
int,
Optional[Braces],
Optional[str],
]
def _extract_pieces_from_str(path: PurePath) -> PiecesType:
"""extracts filename pieces from regex"""
groups = _run_filename_regex(path)
num_end = _num_end_from_match(groups)
padding = _padding_from_match(groups)
brackets = _brackets_from_match(groups)
# need to do some casting shenanigans since our regex guarantees some returns
base = groups["base"]
base = cast(str, base)
extension = groups["extension"]
sep = groups["sep"]
start = groups["start"]
start = cast(str, start)
if "#" in start:
start_arg: Union[int, str] = "#"
else:
start_arg = int(start)
sep = cast(str, sep)
return base, sep, start_arg, num_end, padding, brackets, extension
@overload
def _post_init_start_end(value: None) -> None:
...
@overload # noqa: F811
def _post_init_start_end(value: Union[int, str]) -> Union[int, str]:
...
def _post_init_start_end( # noqa: F811
value: Optional[Union[int, str]]
) -> Optional[Union[int, str]]:
"""
parses start and end values, returns int when castable, raises value error if
not and string is not "#"
"""
if value is None:
return None
if isinstance(value, str):
if "#" in value:
return "#"
else:
raise ValueError("start/end must be int or '#'")
else:
return value


Password Generatormore_vert
Password Generatorclose
This is a password generator that I built for an assignment. GitHub
Apartment Listmore_vert
Apartment Listclose
This was a group project that I designed, project managed, and helped build. GitHub


This application was created by Alicia Peaker, Director of Digital Scholarship, Critical Making, and Digital Collections Management at Bryn Mawr College in collaboration with Jie Shi, Assistant Professor of History of Art, and Project Director. The mirror and its components were designed and created by Jialu Guo ('19). Nisha Choudhary ('21) helped with converting the mirror components into usable file formats. Matt Jameson (Ph.D. Candidate, Classical and Near Eastern Archaeology) consulted on the design of the application and created several
3D photogrammetry models of TLV mirrors that inspired its production.


😱 Testophobia Viewer
<
>
?
Image Diff
Image Comparison
Side-By-Side
No golden image available (new test action?)


You are viewing an historical archive of past issues. Please report new issues to the appropriate project issue tracker on GitHub.
Comments
-
Greg Hurrell
Status changed:
- From: New
- To: Open
-
Greg Hurrell
The pop-up is not broken for all products. Some examples:
- wincent.com: this ticket, ticket #1288, works
- Synergy: eg. ticket #59, broken
- Synergy Advance: eg. ticket #61, broken
- WinSwitch: eg. ticket #85, broken
- WOCommon: eg. ticket #494, broken
- Wincent Strings Utility: eg. ticket #1104, broken
Basically looks like all are broken except for the wincent.com tickets.
-
Greg Hurrell
Broken
- Hextrapolate: eg. ticket #1275, broken
- Install: eg. ticket #235, broken
- WODebug: eg. ticket #448, broken
- REnamer: eg. ticket #1126, broken
Working
- atosym: eg. ticket #1273, works
- buildtools: (no example available), appears to work
- wikitext: eg. ticket #1251, works
Unknown
There are a few products for which there aren't any tickets, so I don't know if they work:
- WOHotKey
- Walrus
- etc...
-
Greg Hurrell
As a first guess I'd say we have a case-sensitivity issue here.
-
Greg Hurrell
Ok, as the fix was pretty minor (see below), I've just uploaded a new ajax.js file rather than doing a full deployment:
diff --git a/public/javascripts/ajax.js b/public/javascripts/ajax.js index e1dee88..3c98f23 100644 --- a/public/javascripts/ajax.js +++ b/public/javascripts/ajax.js @@ -133,14 +133,14 @@ function ajax_select(selector, class_name, attribute_name, options, include_blan var model_id = $(selector).attr('id'); // issue_22 var record_id = model_id.match(/_(\d+)$/)[1]; // 22 var field_id = $('#' + model_id + '_' + attribute_name); // issue_22_status - var field_text = field_id.text(); // eg. New, Open, Closed (first letter capitalized by humanize method) + var field_text = field_id.text(); // eg. New, Open, Closed var new_contents = '<select id="' + class_name + '_' + attribute_name + '" name="' + class_name + '[' + attribute_name + ']">'; if (include_blank) { new_contents = new_contents + '<option value=""></option>'; } var selection_found = false; for (var i = 0; i < options.length; i++) { - if (field_text.toLowerCase() == options[i][0]) { + if (field_text.toLowerCase() == options[i][0].toLowerCase()) { new_contents = new_contents + '<option value="' + options[i][1] + '" selected="selected">' + options[i][0] + '</option>'; selection_found = true; } else {
-
Greg Hurrell
Status changed:
- From: Open
- To: Closed
Add a comment
Comments are now closed for this issue.


Yesterday I started converting a small utility app from a jQuery+Node setup to an Ember Octane app—with TypeScript, of course!—which we could deploy statically via simple static hosting a la GitHub Pages or whatever… and it’s a really good experience.


Do I need to know anything about websites or programming?
No! Workshops are for beginners. You don’t need to know anything about it. However, if you have a little bit of technical knowledge (i.e. you know what HTML or CSS are) you still can apply!
I am not living in Germany, can I attend?
Of course! Workshops will be in English, so if you have no troubles with speaking and understanding English - you should apply. If you need financial aid to get to Berlin or you need assistance with booking flights or hotel in Berlin - let us know. We are willing to help you!

Yes. We have no hardware, so we expect you to bring your computer with you. It is also important for us that you will take home everything you’ll write and create during workshops.
Do I need to have something installed on my laptop?
It would be helpful to have Django installed before workshops, but wouldn't expect you to install anything on your own.We will make sure that one of our coaches will help you out with this task.
Is EuroPython conference good for a total beginner?
As a workshop attendee you will get a free ticket to EuroPython - conference for Python programmers. Even though you are new to programming,conference is a good place to meet many interesting people in the industry and find inspiration.
Is food provided?
Yes. Thanks to EuroPython, snacks and lunch will be served during workshops.


Lying about 80 miles south of Grenada, Chaguaramas is a sheltered bay. It lies on the extreme western end of Trinidad's northern coast, about 10nm from Port-of-Spain. The approach is via the narrow Boca (be aware of strong currents).
The majority of boat yards and marine services are located in Chaguaramas.
Position 10°40.5'W, 61°38.3'W.
Safety & Security
In the past much has been reported about crime and theft towards yachties in Chaguaramas. While unemployment has triggered an increase in theft from yachts in the Chaguaramas area over the past few years, one must note that Trinidad has the highest concentration of boats for hurricane season in the Caribbean. Co-operation between the local marine business community, the cruising community and the authorities has improved the situation considerably. Security patrols at night have helped to reduce the number of thefts from boats here, this is IN ADDITION to the security service that each and every yard and marina has, however thefts do still occur.
A good source of up-to-date security information by cruisers is the Yahoo Trinidad for Cruising Sailors Forum.
Entry formalities can be completed here as there is a permanent Customs office.
Be sure to fly the Q
flag.
Tie up to the Customs Dock, which is located next to Crew’s Inn Marina, at the eastern end of Chaguaramas Bay. It is at the base of the red-striped lighthouse. This must be done even if you have a reserved berth in the Crew's Inn marina.
Proceed with all the crew, passports and papers to the Customs Office (there are direction signs to it in the marina). The Immigration office is close to the Customs office. An overtime fee is payable to Customs if arriving outside normal working hours (which can also include lunch hours 12 - 1pm).
Conservative attire is the standard and is expected of visitors when clearing in/out.
A clearance-out certificate from the last port will be required. Additional forms are required if any crew are leaving Trinidad by air.
Immigration and Customs are both open 24 hours a day, seven days per week.
There is a US $100 charge if remaining at the Customs dock overnight.
Last updated September 2015.
Their are a number of marinas here, all with varying levels of security. Transient berths are is demand so booking in advance, if possible, may be advisable.
Moorings
There are about 25 cylindrical mooring buoys in the anchorage area controlled by YSATT. These are checked monthly for wear and tear. Moorings can not be reserved in advance of arrival; they are strictly accommodated on a first come first served basis. Upon arrival in Trinidad, contact the YSATT office or speak to the water taxi operator to advise of your need for a mooring. See YSATT moorings for more information.
There may also be other moorings for rent in the bay.
If using these moorings, be aware that while it can blow for days from the east with flat seas, when a W or NW wind blows the bay is wide open and provides no protection. The seas and surge make up quickly and one must be careful to secure the mooring lines to prevent chafe.
The Trinidad and Tobago Sailing Association in Harts Bay also have mooring buoys available, however this is not in Chaguarmas. Prices are cheap, however facilities are basic and there is no security.
Anchoring
The harbour is deep and the holding can be poor. Beware of a sunken barge at Latitude 10-40.465N, Longitude 61-38.319W. It is in 70ft of water but can snag anchors.
It is also possible to anchor off the town or close to Carenage Bay. The bay can be rolly in a southerly wind as well as uncomfortable due to the number of craft operating around the bay at high speed. Be sure to anchor in the designated anchorage area.
Another option is to anchor in Escondida Cove. It is exposed in westerly winds but otherwise, well sheltered.
The YSATT shuttle (water taxi) operates from 0730 to 2230 Monday to Saturday and can be called via VHF, call sign "YSATT Shuttle", on Channel 68. It is available for any journey within the bay. The shuttle became privately owned in October 2007, and now charges from TT$10/person to TT$30/person, depending on how far out into the bay you are going. Bookings can be made in advance for trips on Sundays and public holidays. Note: It has been reported (April 2015) that this water taxi is out of service, but there others available.
Note that Chaguaramas is a commercial harbour, and there are frequent oil and diesel spills here. Also there are party boats that play loud music until well into the night.
Last updated January 2016.


Automatic Reference Counting
Swift uses Automatic Reference Counting (ARC) to track and manage your app’s memory usage. In most cases, this means that memory management “just works” in Swift, and you do not need to think about memory management yourself. ARC automatically frees up the memory used by class instances when those instances are no longer needed.
However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you. This chapter describes those situations and shows how you enable ARC to manage all of your app’s memory. Using ARC in Swift is very similar to the approach described in Transitioning to ARC Release Notes for using ARC with Objective-C.
Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.
How ARC Works
Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.
Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.
However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.
To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.
To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes a strong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.
ARC in Action
Here’s an example of how Automatic Reference Counting works. This example starts with a simple class called Person
, which defines a stored constant property called name
:
class Person {
let name: String
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}
The Person
class has an initializer that sets the instance’s name
property and prints a message to indicate that initialization is underway. The Person
class also has a deinitializer that prints a message when an instance of the class is deallocated.
The next code snippet defines three variables of type Person?
, which are used to set up multiple references to a new Person
instance in subsequent code snippets. Because these variables are of an optional type (Person?
, not Person
), they are automatically initialized with a value of nil
, and do not currently reference a Person
instance.
var reference1: Person?
var reference2: Person?
var reference3: Person?
You can now create a new Person
instance and assign it to one of these three variables:
reference1 = Person(name: "John Appleseed")
// Prints "John Appleseed is being initialized"
Note that the message "John Appleseed is being initialized"
is printed at the point that you call the Person
class’s initializer. This confirms that initialization has taken place.
Because the new Person
instance has been assigned to the reference1
variable, there is now a strong reference from reference1
to the new Person
instance. Because there is at least one strong reference, ARC makes sure that this Person
is kept in memory and is not deallocated.
If you assign the same Person
instance to two more variables, two more strong references to that instance are established:
reference2 = reference1
reference3 = reference1
There are now three strong references to this single Person
instance.
If you break two of these strong references (including the original reference) by assigning nil
to two of the variables, a single strong reference remains, and the Person
instance is not deallocated:
reference1 = nil
reference2 = nil
ARC does not deallocate the Person
instance until the third and final strong reference is broken, at which point it’s clear that you are no longer using the Person
instance:
reference3 = nil
// Prints "John Appleseed is being deinitialized"
Strong Reference Cycles Between Class Instances
In the examples above, ARC is able to track the number of references to the new Person
instance you create and to deallocate that Person
instance when it’s no longer needed.
However, it’s possible to write code in which an instance of a class never gets to a point where it has zero strong references. This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as a strong reference cycle.
You resolve strong reference cycles by defining some of the relationships between classes as weak or unowned references instead of as strong references. This process is described in Resolving Strong Reference Cycles Between Class Instances. However, before you learn how to resolve a strong reference cycle, it’s useful to understand how such a cycle is caused.
Here’s an example of how a strong reference cycle can be created by accident. This example defines two classes called Person
and Apartment
, which model a block of apartments and its residents:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment \(unit) is being deinitialized") }
}
Every Person
instance has a name
property of type String
and an optional apartment
property that is initially nil
. The apartment
property is optional, because a person may not always have an apartment.
Similarly, every Apartment
instance has a unit
property of type String
and has an optional tenant
property that is initially nil
. The tenant property is optional because an apartment may not always have a tenant.
Both of these classes also define a deinitializer, which prints the fact that an instance of that class is being deinitialized. This enables you to see whether instances of Person
and Apartment
are being deallocated as expected.
This next code snippet defines two variables of optional type called john
and unit4A
, which will be set to a specific Apartment
and Person
instance below. Both of these variables have an initial value of nil
, by virtue of being optional:
var john: Person?
var unit4A: Apartment?
You can now create a specific Person
instance and Apartment
instance and assign these new instances to the john
and unit4A
variables:
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
Here’s how the strong references look after creating and assigning these two instances. The john
variable now has a strong reference to the new Person
instance, and the unit4A
variable has a strong reference to the new Apartment
instance:
You can now link the two instances together so that the person has an apartment, and the apartment has a tenant. Note that an exclamation mark (!
) is used to unwrap and access the instances stored inside the john
and unit4A
optional variables, so that the properties of those instances can be set:
john!.apartment = unit4A
unit4A!.tenant = john
Here’s how the strong references look after you link the two instances together:
Unfortunately, linking these two instances creates a strong reference cycle between them. The Person
instance now has a strong reference to the Apartment
instance, and the Apartment
instance has a strong reference to the Person
instance. Therefore, when you break the strong references held by the john
and unit4A
variables, the reference counts do not drop to zero, and the instances are not deallocated by ARC:
john = nil
unit4A = nil
Note that neither deinitializer was called when you set these two variables to nil
. The strong reference cycle prevents the Person
and Apartment
instances from ever being deallocated, causing a memory leak in your app.
Here’s how the strong references look after you set the john
and unit4A
variables to nil
:
The strong references between the Person
instance and the Apartment
instance remain and cannot be broken.
Resolving Strong Reference Cycles Between Class Instances
Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.
Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.
Use a weak reference when the other instance has a shorter lifetime—that is, when the other instance can be deallocated first. In the Apartment
example above, it’s appropriate for an apartment to be able to have no tenant at some point in its lifetime, and so a weak reference is an appropriate way to break the reference cycle in this case. In contrast, use an unowned reference when the other instance has the same lifetime or a longer lifetime.
Weak References
A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak
keyword before a property or variable declaration.
Because a weak reference does not keep a strong hold on the instance it refers to, it’s possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil
when the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed to nil
at runtime, they are always declared as variables, rather than constants, of an optional type.
You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.
The example below is identical to the Person
and Apartment
example from above, with one important difference. This time around, the Apartment
type’s tenant
property is declared as a weak reference:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment \(unit) is being deinitialized") }
}
The strong references from the two variables (john
and unit4A
) and the links between the two instances are created as before:
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john
Here’s how the references look now that you’ve linked the two instances together:
The Person
instance still has a strong reference to the Apartment
instance, but the Apartment
instance now has a weak reference to the Person
instance. This means that when you break the strong reference held by the john
variable by setting it to nil
, there are no more strong references to the Person
instance:
john = nil
// Prints "John Appleseed is being deinitialized"
Because there are no more strong references to the Person
instance, it’s deallocated and the tenant
property is set to nil
:
The only remaining strong reference to the Apartment
instance is from the unit4A
variable. If you break that strong reference, there are no more strong references to the Apartment
instance:
unit4A = nil
// Prints "Apartment 4A is being deinitialized"
Because there are no more strong references to the Apartment
instance, it too is deallocated:
Unowned References
Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned
keyword before a property or variable declaration.
An unowned reference is expected to always have a value. As a result, ARC never sets an unowned reference’s value to nil
, which means that unowned references are defined using nonoptional types.
The following example defines two classes, Customer
and CreditCard
, which model a bank customer and a possible credit card for that customer. These two classes each store an instance of the other class as a property. This relationship has the potential to create a strong reference cycle.
The relationship between Customer
and CreditCard
is slightly different from the relationship between Apartment
and Person
seen in the weak reference example above. In this data model, a customer may or may not have a credit card, but a credit card will always be associated with a customer. A CreditCard
instance never outlives the Customer
that it refers to. To represent this, the Customer
class has an optional card
property, but the CreditCard
class has an unowned (and nonoptional) customer
property.
Furthermore, a new CreditCard
instance can only be created by passing a number
value and a customer
instance to a custom CreditCard
initializer. This ensures that a CreditCard
instance always has a customer
instance associated with it when the CreditCard
instance is created.
Because a credit card will always have a customer, you define its customer
property as an unowned reference, to avoid a strong reference cycle:
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { print("\(name) is being deinitialized") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { print("Card #\(number) is being deinitialized") }
}
This next code snippet defines an optional Customer
variable called john
, which will be used to store a reference to a specific customer. This variable has an initial value of nil, by virtue of being optional:
var john: Customer?
You can now create a Customer
instance, and use it to initialize and assign a new CreditCard
instance as that customer’s card
property:
john = Customer(name: "John Appleseed")
john!.card = CreditCard(number: 1234_5678_9012_3456, customer: john!)
Here’s how the references look, now that you’ve linked the two instances:
The Customer
instance now has a strong reference to the CreditCard
instance, and the CreditCard
instance has an unowned reference to the Customer
instance.
Because of the unowned customer
reference, when you break the strong reference held by the john
variable, there are no more strong references to the Customer
instance:
Because there are no more strong references to the Customer
instance, it’s deallocated. After this happens, there are no more strong references to the CreditCard
instance, and it too is deallocated:
john = nil
// Prints "John Appleseed is being deinitialized"
// Prints "Card #1234567890123456 is being deinitialized"
The final code snippet above shows that the deinitializers for the Customer
instance and CreditCard
instance both print their “deinitialized” messages after the john
variable is set to nil
.
Unowned References and Implicitly Unwrapped Optional Properties
The examples for weak and unowned references above cover two of the more common scenarios in which it’s necessary to break a strong reference cycle.
The Person
and Apartment
example shows a situation where two properties, both of which are allowed to be nil
, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference.
The Customer
and CreditCard
example shows a situation where one property that is allowed to be nil
and another property that cannot be nil
have the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.
However, there is a third scenario, in which both properties should always have a value, and neither property should ever be nil
once initialization is complete. In this scenario, it’s useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.
This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete, while still avoiding a reference cycle. This section shows you how to set up such a relationship.
The example below defines two classes, Country
and City
, each of which stores an instance of the other class as a property. In this data model, every country must always have a capital city, and every city must always belong to a country. To represent this, the Country
class has a capitalCity
property, and the City
class has a country
property:
class Country {
let name: String
var capitalCity: City!
init(name: String, capitalName: String) {
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City {
let name: String
unowned let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}
To set up the interdependency between the two classes, the initializer for City
takes a Country
instance, and stores this instance in its country
property.
The initializer for City
is called from within the initializer for Country
. However, the initializer for Country
cannot pass self
to the City
initializer until a new Country
instance is fully initialized, as described in Two-Phase Initialization.
To cope with this requirement, you declare the capitalCity
property of Country
as an implicitly unwrapped optional property, indicated by the exclamation mark at the end of its type annotation (City!
). This means that the capitalCity
property has a default value of nil
, like any other optional, but can be accessed without the need to unwrap its value as described in Implicitly Unwrapped Optionals.
Because capitalCity
has a default nil
value, a new Country
instance is considered fully initialized as soon as the Country
instance sets its name
property within its initializer. This means that the Country
initializer can start to reference and pass around the implicit self
property as soon as the name
property is set. The Country
initializer can therefore pass self
as one of the parameters for the City
initializer when the Country
initializer is setting its own capitalCity
property.
All of this means that you can create the Country
and City
instances in a single statement, without creating a strong reference cycle, and the capitalCity
property can be accessed directly, without needing to use an exclamation mark to unwrap its optional value:
var country = Country(name: "Canada", capitalName: "Ottawa")
print("\(country.name)'s capital city is called \(country.capitalCity.name)")
// Prints "Canada's capital city is called Ottawa"
In the example above, the use of an implicitly unwrapped optional means that all of the two-phase class initializer requirements are satisfied. The capitalCity
property can be used and accessed like a nonoptional value once initialization is complete, while still avoiding a strong reference cycle.
Strong Reference Cycles for Closures
You saw above how a strong reference cycle can be created when two class instance properties hold a strong reference to each other. You also saw how to use weak and unowned references to break these strong reference cycles.
A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance. This capture might occur because the closure’s body accesses a property of the instance, such as self.someProperty
, or because the closure calls a method on the instance, such as self.someMethod()
. In either case, these accesses cause the closure to “capture” self
, creating a strong reference cycle.
This strong reference cycle occurs because closures, like classes, are reference types. When you assign a closure to a property, you are assigning a reference to that closure. In essence, it’s the same problem as above—two strong references are keeping each other alive. However, rather than two class instances, this time it’s a class instance and a closure that are keeping each other alive.
Swift provides an elegant solution to this problem, known as a closure capture list. However, before you learn how to break a strong reference cycle with a closure capture list, it’s useful to understand how such a cycle can be caused.
The example below shows how you can create a strong reference cycle when using a closure that references self
. This example defines a class called HTMLElement
, which provides a simple model for an individual element within an HTML document:
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
The HTMLElement
class defines a name
property, which indicates the name of the element, such as "h1"
for a heading element, "p"
for a paragraph element, or "br"
for a line break element. HTMLElement
also defines an optional text
property, which you can set to a string that represents the text to be rendered within that HTML element.
In addition to these two simple properties, the HTMLElement
class defines a lazy property called asHTML
. This property references a closure that combines name
and text
into an HTML string fragment. The asHTML
property is of type () -> String
, or “a function that takes no parameters, and returns a String
value”.
By default, the asHTML
property is assigned a closure that returns a string representation of an HTML tag. This tag contains the optional text
value if it exists, or no text content if text
does not exist. For a paragraph element, the closure would return "<p>some text</p>"
or "<p />"
, depending on whether the text
property equals "some text"
or nil
.
The asHTML
property is named and used somewhat like an instance method. However, because asHTML
is a closure property rather than an instance method, you can replace the default value of the asHTML
property with a custom closure, if you want to change the HTML rendering for a particular HTML element.
For example, the asHTML
property could be set to a closure that defaults to some text if the text
property is nil
, in order to prevent the representation from returning an empty HTML tag:
let heading = HTMLElement(name: "h1")
let defaultText = "some default text"
heading.asHTML = {
return "<\(heading.name)>\(heading.text ?? defaultText)</\(heading.name)>"
}
print(heading.asHTML())
// Prints "<h1>some default text</h1>"
The HTMLElement
class provides a single initializer, which takes a name
argument and (if desired) a text
argument to initialize a new element. The class also defines a deinitializer, which prints a message to show when an HTMLElement
instance is deallocated.
Here’s how you use the HTMLElement
class to create and print a new instance:
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
// Prints "<p>hello, world</p>"
Unfortunately, the HTMLElement
class, as written above, creates a strong reference cycle between an HTMLElement
instance and the closure used for its default asHTML
value. Here’s how the cycle looks:
The instance’s asHTML
property holds a strong reference to its closure. However, because the closure refers to self
within its body (as a way to reference self.name
and self.text
), the closure captures self, which means that it holds a strong reference back to the HTMLElement
instance. A strong reference cycle is created between the two. (For more information about capturing values in a closure, see Capturing Values.)
If you set the paragraph
variable to nil
and break its strong reference to the HTMLElement
instance, neither the HTMLElement
instance nor its closure are deallocated, because of the strong reference cycle:
paragraph = nil
Note that the message in the HTMLElement
deinitializer is not printed, which shows that the HTMLElement
instance is not deallocated.
Resolving Strong Reference Cycles for Closures
You resolve a strong reference cycle between a closure and a class instance by defining a capture list as part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference. The appropriate choice of weak or unowned depends on the relationships between the different parts of your code.
Defining a Capture List
Each item in a capture list is a pairing of the weak
or unowned
keyword with a reference to a class instance (such as self
) or a variable initialized with some value (such as delegate = self.delegate!
). These pairings are written within a pair of square braces, separated by commas.
Place the capture list before a closure’s parameter list and return type if they are provided:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in
keyword:
lazy var someClosure: () -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
Weak and Unowned References
Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.
Conversely, define a capture as a weak reference when the captured reference may become nil
at some point in the future. Weak references are always of an optional type, and automatically become nil
when the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.
An unowned reference is the appropriate capture method to use to resolve the strong reference cycle in the HTMLElement
example from earlier. Here’s how you write the HTMLElement
class to avoid the cycle:
class HTMLElement {
let name: String
let text: String?
lazy var asHTML: () -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
init(name: String, text: String? = nil) {
self.name = name
self.text = text
}
deinit {
print("\(name) is being deinitialized")
}
}
This implementation of HTMLElement
is identical to the previous implementation, apart from the addition of a capture list within the asHTML
closure. In this case, the capture list is [unowned self]
, which means “capture self as an unowned reference rather than a strong reference”.
You can create and print an HTMLElement
instance as before:
var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
// Prints "<p>hello, world</p>"
Here’s how the references look with the capture list in place:
This time, the capture of self
by the closure is an unowned reference, and does not keep a strong hold on the HTMLElement
instance it has captured. If you set the strong reference from the paragraph
variable to nil
, the HTMLElement
instance is deallocated, as can be seen from the printing of its deinitializer message in the example below:
paragraph = nil
// Prints "p is being deinitialized"
For more information about capture lists, see Capture Lists.
Copyright © 2017 Apple Inc. All rights reserved. Terms of Use | Privacy Policy | Updated: 2017-09-19


"use strict";
/**************************
* Import important stuff *
**************************/
// Nothing
/********************
* The Stream class *
********************/
/**
* A dead simple readable and writable object stream. Really a queue, but I don't bother renaming it
*/
class Stream {
/**
* Creates a new stream
*/
constructor() {
/**
* The internal buffer for the stream
*
* @type Object[]
*
* @private
*/
this._buffer = [];
}
/**
* Writes an object to the stream
*
* @param {Object} obj The object to write
*/
write(obj) {
this._buffer.push(obj);
}
/**
* Reads an object from the stream
*
* @returns {Object} The next object in the stream
*
* @throws {Error} If the stream is empty
*/
read() {
// Check if there is something to be read
if (this._buffer.length === 0) {
throw new Error("Stream is empty");
}
// Return the next object from the stream
return this._buffer.shift();
}
/**
* Number of objects waiting to be read from the stream
*
* @type Integer
*/
get length() {
return this._buffer.length;
}
/**
* A snapshot of the stream's internal buffer
*
* @type Object[]
*
* @readonly
*/
get snapshot() {
return [...this._buffer];
}
}
/*************
* Export it *
*************/
module.exports = Stream;


The 'add' button below is a bookmarklet.
* Adding some pages may take a while, please be patient - it's worth it!
Sorry, it looks like you haven't added any pages yet.
Use the bookmarklet in the welcome tab to add some.
This is an application I've wanted to write for a long time, but never could due to browser constraints.
The 10k apart contest seemed like the perfect excuse to finally sit down and actually do it.
All the source code for this project is available on github at jimbojw/10k.


A pain point for would-be readers with the way I’ve designed this site: there’s no easy way for people to subscribe to just one specific topic at present. I can generate per-topic feeds… but I’m already seeing painfully-rapid growth in build times.


Example (partial1) showMessage (Basic) for partialLite
This content will be overridden with content of ShowMessage.html
(please host examples on web server not file://)


@JvmStatic fun of(contents: ByteArray): Sha256Hash
Creates a new instance containing the calculated (one-time) hash of the given bytes.
contents
- the bytes on which the hash value is calculated
Return
a new instance containing the calculated (one-time) hash
@JvmStatic fun of(file: File): Sha256Hash
Creates a new instance containing the calculated (one-time) hash of the given file's contents.
The file contents are read fully into memory, so this method should only be used with small files.
file
- the file on which the hash value is calculated
IOException
- if an error occurs while reading the file
Return
a new instance containing the calculated (one-time) hash


And so, with the boy now gradually making headway through his own efforts, he began to both read and speak both languages, namely Greek and Latin. Vergil was delighted and marvelled at such a speed of talent in the boy and conceived a better hope about him, expended a greater care for him. Indeed the boy applied his mind to the words of his teacher, who was of a naturally discriminating character, and whatever he heard once, he immediately comprehended and committed every strict detail to memory, and there was no need for him to ask his teacher again. From which it happened that within the circuit of a single year he surpassed his companions, who were older than he, and preceded him by five, or even seven, years under the education of the teachers, and he asked Vergil to instruct him in deeper matters, as far as he deemed him worthy. Indeed Vergil, seeing a child's ignorance dispelled in him, and that he was already fit to be gaining sound instruction, willingly assented to the boy's desire.
Therefore, on account of his esteem, he condensed, with a certain wonderful and ineffable innate logic, an immense body of works of the liberal arts with such conciseness that they fit in a handbook, and that anyone could easily learn to perfection in three years the things that he himself had prevailed upon only with a great deal of sweat. But he was unwilling to relinquish this book to anyone for even an hour, not to a teacher, or a student, not even to the emperor of the world, Augustus himself, excepting only to Lucinius whose progress he was urging on. To him, whose advantage he had devoted himself to, he delivered the book, discussing the arts with him in a friendly manner, in his chamber and apart from the others.
And in fact, he first exposed him to grammar, which is first and the mother of the arts. And he comprehended it with such swiftness that even Vergil marvelled. After that he fell to logic, in which he was so sharp that he was said to be a marvel. For none, even among the experienced teachers, was cleverer in proposing questions, and none was readier at solving them. Then he crossed over to flowery fields of rhetoric, out of which he faultlessly prepared a grace of eloquence.
And so, having attained complete mastery of these three subjects, he moved to the remaining four, which we call the quadrivium, and grasped them without much effort, and pronounced the last of these, namely astronomy, to be more worthy than the others; to which he surrendered his intellect so thoroughly, that, through certain principles that Vergil had related to him, from the movement of the planets and the other stars, and from the appearance of the atmosphere, he could find out whatever might happen throughout the whole world. Which was very useful for him to learn, as will be shown further on.
And so, even after Lucinius had achieved mastery of the knowledge of all the arts, he still did not neglect attending to Vergil again about the books of poets and philosophers. And so, then and thereafter directing his mind's eye to the higher philosophy, he gained the name and honor of the great philosophers, but not without the envy of many. For those who begrudged him the most were those who had not succeeded in reaching to his height of understanding, and who were pained to see a mere boy be shown the respect that was denied them in their old age. From that point on, they thought to destroy him, by poison or by some other method, but their fear of Vergil and the authority of the royal family curbed their malice a little. However, since envy always masters and torments whoever has it and does not suffer him even a moment's rest, their hatred, which was germinated and incited by envy, could not be restrained for long, so that, after deceitfully inviting him to a banquet, they adulterated his wine with poison.
But this did not escape his notice, because, through the aforesaid principles, he had already learned of this very thing along with their ill-will towards him. But even so, cleverly pretending not to know these things, he said to those proffering the invitation that it would not to be seemly or to responsible for such a banquet of such men to be celebrated without Vergil and the nobility of Rome. He would indeed accept their munificence if Vergil came, and was even prepared, when it was suitable, to repay this bounty in his turn. But he yet affirmed that he neither dared nor was able to do anything, or much at all, without Vergil, since he had been entrusted with his good faith and he was terrified of his master's staff above all.
After hearing such words, they, blinded by their malice, invite Vergil, and they also summon some of the Roman citizens, little considering whether they might also die of that deadly drink, but only that Lucinius should not evade their poisonous hands. And so, with the banquet prepared, they sit down to eat, each according to his age or his distinctive rank, but, as is natural, with Vergil having the best seat at the banquet, as Caesar had commanded that he be honored by all. Indeed, the one who had made the invitation and who was the head of the ill-wishers was serving, along with certain others. Dishes, too many to count, are set near the banqueters, different sorts of spiced wine are drunk in toasts and the banquet is celebrated with great joy and abundance. But in the meantime Lucinius, turning his rules over in his mind, was waiting for when the draught that they had mixed for him was carried in.
Therefore, once the banquet was over and the guests had been refreshed with everything that could be contrived by art for refined consumption, lo, that vermin, that twisted serpent, whom we have called the head of the ill-wishers, brought a golden cup of great capacity, full of death, and put it before Vergil. And straight away the guests' nostrils are seized with a certain sweet scent, the desire of each one is inflamed by the drink. Now they all were demanding the deadly draught, and even now it was being extended to Vergil, when Lucinius, snatching the cup and motioning everyone to silence, said "I fear that this sweetness may contain something bitter, for a bee with honey bears a sting and a fisherman puts meat on his hook to catch fish." But at these words those men, confounded with their guilty conscience, blushed red enough that, according to the poet: "in expression and complexion they confessed their crime." Nevertheless, trying anything to dissemble and answer, they said that the king's son, who said such things, albeit in jest, in public, did not thank them fairly for the services that they had supplied.
But he said: "I didn't say this in jest, but in anger. But you can prove that you are innocent and have invited my companions and me with a good and simple heart if you drink the first draught. Otherwise, by the well-being of my father and of Caesar, you have plotted against our lives."
What could they do, where could they turn, what could they reply to the charges? All around them were difficulties, a catch in their throats, and despair for their safety. For they saw two choices for them, one of which they could not avoid, namely, to drink or to die. But they didn't know which one to choose; for they knew that drinking it would be the death of them, but that if they didn't, they'd be handed over as criminals to Caesar to be tortured in various ways. Still they deemed it better to die by their own hands than to expose themselves to the mockery of others: "In this," they said, "you will know, Lucinius, that we had plotted no evil for you or your dinnermates, if we survive for three days after consuming this wine."
And the one who had brought the cup picked it up and drank, and then handed it to his fellow evil-doers for them to drink. And they drank and, as the wise adage says, falling into the pit that they had dug for others, still at the feast, they at once breathed their last with their eyes bursting from their heads.
And so the illlustrious the boy, freeing himself and his friends from death through his diligence, cleverly punished his rivals and gained a renowned name for himself with both highborn and low, and after that no one dared try anything untoward against him, nor even to think of it, with everyone believing that he had the second sight, because of his foreknowledge of the future. But although he was so great and valued so much by men and Vergil declared him to be his equal in every skill, nevertheless he never desired to sit down in his presence or to be his equal, but always remained under his rod and instruction as in the time when he first learned the elements of his letters. From this especially was his humility proven, for although he was of tall stature, and Vergil was truly short, when walking or standing with his teacher, he held his body hunched over, so that he wouldn't appear to be taller or better than him.


|
e-puck
1.0
|
Accessing the accelerometer data. More...
Data Structures | |
| struct | TypeAccSpheric |
| struct to store the acceleration vector in spherical coord More... | |
| struct | TypeAccRaw |
| struct to store the acceleration raw data in carthesian coord More... | |
Macros | |
| #define | CST_RADIAN (180.0/3.1415) |
| #define | ANGLE_ERROR 666.0 |
| #define | FILTER_SIZE 5 |
| #define | ACCX_BUFFER 0 |
| #define | ACCY_BUFFER 1 |
| #define | ACCZ_BUFFER 2 |
| #define | GRAVITY 768 |
| #define | GRAVITY_LSM330 16384 |
Functions | |
| int | e_get_acc (unsigned int captor) |
| Read the last value of a given accelerator axes. More... | |
| int | e_get_acc_filtered (unsigned int captor, unsigned int filter_size) |
| Read the value of a channel, filtered by an averaging filter. More... | |
| TypeAccSpheric | e_read_acc_spheric (void) |
| calculate and return the accel. in spherical coord More... | |
| float | e_read_orientation (void) |
| calculate and return the orientation angle More... | |
| float | e_read_inclination (void) |
| calculate and return the inclination angle More... | |
| float | e_read_acc (void) |
| calculate and return the intensity of the acceleration More... | |
| TypeAccRaw | e_read_acc_xyz (void) |
| calculate and return acceleration on the x,y,z axis More... | |
| int | e_read_acc_x (void) |
| calculate and return acceleration on the x axis More... | |
| int | e_read_acc_y (void) |
| calculate and return acceleration on the y axis More... | |
| int | e_read_acc_z (void) |
| calculate and return acceleration on the z axis More... | |
| void | e_acc_calibr (void) |
| initialize de ad converter and calculate the zero values More... | |
| void | e_display_angle (void) |
| light the led according to the orientation angle More... | |
Accessing the accelerometer data.
The functions of this file are made to deal with the accelerometer data. You can know the magnitude, the orientation, the inclination, ... of the acceleration that the e-puck is enduring.
Two structures are used:
A little exemple to read the accelerator.
| #define ACCX_BUFFER 0 |
| #define ACCY_BUFFER 1 |
| #define ACCZ_BUFFER 2 |
| #define ANGLE_ERROR 666.0 |
| #define CST_RADIAN (180.0/3.1415) |
| #define FILTER_SIZE 5 |
| #define GRAVITY 768 |
| #define GRAVITY_LSM330 16384 |
| void e_acc_calibr | ( | void | ) |
initialize de ad converter and calculate the zero values
It reads two times the average_size to avoid edge effects then it reads 100 values and average them to initiate the "zero" value of the accelerometer
| void e_display_angle | ( | void | ) |
light the led according to the orientation angle
| int e_get_acc | ( | unsigned int | captor | ) |
Read the last value of a given accelerator axes.
| captor | ID of the AD channel to read (must be 0 = x, 1 = y or 2 = z) |
| int e_get_acc_filtered | ( | unsigned int | captor, |
| unsigned int | filter_size | ||
| ) |
Read the value of a channel, filtered by an averaging filter.
| captor | ID of the AD channel to read (must be 0 to 2) |
| filter_size | size of the filter (must be between 1 and SAMPLE_NUMBER) |
| float e_read_acc | ( | void | ) |
calculate and return the intensity of the acceleration
| TypeAccSpheric e_read_acc_spheric | ( | void | ) |
calculate and return the accel. in spherical coord
| int e_read_acc_x | ( | void | ) |
calculate and return acceleration on the x axis
| TypeAccRaw e_read_acc_xyz | ( | void | ) |
calculate and return acceleration on the x,y,z axis
| int e_read_acc_y | ( | void | ) |
calculate and return acceleration on the y axis
| int e_read_acc_z | ( | void | ) |
calculate and return acceleration on the z axis
| float e_read_inclination | ( | void | ) |
calculate and return the inclination angle
| float e_read_orientation | ( | void | ) |
calculate and return the orientation angle


Milestones of the space race era
Russia Launches Sputnik
On July 29, 1957, in recognition of the 1957-1958 International Geophysical Year, the White House announced that the U.S. intended to launch satellites by the spring of 1958. This became known as Project Vanguard. On July 31, the Soviets announced that they intended to launch a satellite by the fall of 1957.
Sputnik is regarded as the beginning of the Space Race.
The Explorer 1
Explorer 1 (international designation 1958 Alpha 1) was the first Earth satellite of the United States, launched on February 1, 1958 at 03:48 UTC from LC-26 at Cape Canaveral Air Force Station as part of the United States program for the International Geophysical Year and in response to the launch of the Soviet satellite Sputnik 1. It was the first spacecraft to recognize the Van Allen radiation belt, although Sputnik 2 detected it earlier.
Lunokhod 1
Lunokhod 1 (Луноход, moon walker in Russian) was the first of two unmanned lunar rovers landed on the Moon by the Soviet Union as part of its Lunokhod program. The spacecraft which carried Lunokhod 1 was named Luna 17. Lunokhod was the first roving remote-controlled robot to land on another celestial body.
Luna 17 was launched on November 10, 1970 at 14:44:01 UTC. After reaching earth parking orbit, the final stage of Luna 17's launching rocket fired to place it into a trajectory towards the Moon (1970-11-10 at 14:54 UTC). After two course correction maneuvers (on November 12 and 14), it entered lunar orbit on November 15, 1970 at 22:00 UTC.
End of the Space Race
The 17 July 1975 rendezvous of the Apollo and Soyuz spacecraft traditionally marks the end of the Space Race
While the Sputnik 1 launch can clearly be called the start of the Space Race, its end is more debatable. Most hotly contested during the 1960s, the Space Race continued apace through the U.S. Apollo moon landing of 1969. Although they followed Apollo 11 with five more manned lunar landings, American space scientists turned to new arenas. Skylab was to gather data, and the Space Shuttle was intended to return spaceships intact from space journeys.
Use only this div for one big section of content
Instead of using this template with fixed height + images as above, and would rather just have one big content area to do what you want in, then use this div instead (content_instance_big).


During the summers of 2016 and 2017, I had acquired practical experience in web penetration test through my internships at Cagetest Inc., a cybersecurity startup based in Shanghai, China, by conducting techniques including but not limited to SQLi, RCE, XSS and Java deserialization.
Having been studying at the University of Washington for four years, I did projects on Mobile Apps in Swift, database and data structure implementation in Java, machine learning algorithms in Python, RDBMS on MySQL/SQL Server, NoSQL and parallel data processing using Spark, and more to come!
I interned at Kaikai Kiki New York's Seattle office as a data and project management intern. I conducted an ethnographic research on the original file storage structure, re-organized the system and ultimately streamlined the workflow for retrieving documents as well as adding new ones into the archive.
The admission to UW marks the beginning of my journey at this beautiful campus in a beautiful city.
Upon receiving my first internship offer from Cagetest Inc., a cybersecurity startup based in Shanghai, China. I worked as a security analyst intern where I tested, penetrated and gained total control over clients' web applications and server.
After majoring in Japanese for a year, I was privileged to have the opportunity to study with the smart and innovative minds at the Information School.
While pursuing in the tech field, I have not halted my study in Japanese. Having studied Japanese including a honor program and received The Betty and Hiro Ogawa Scholarship, I interned at Kaikai Kiki, a Japanese fine art company as a project manager and data archivist.
Student at the University of Washington studying Informatics and Japanese


Featured
Projects
Aadat- Atif Aslam | Cover
Cover of the song: Aadat (Remix) By Atif Aslam, From KalyugSinger - Shaan Raina
Piano - Yash Gupta
Guitar - Pranav Kapur
Drums - Gurman Singh
Cover of the song: Dil Diyan Gallan By Atif Aslam
MaximusSinger - Shaan Raina
Keyboard - Yash Gupta
Guitar - Pranav Kapur
Cajon - Gurman Singh
Recent
Projects
This is
The ROCK Empire
Members
-
Pranav Kapur [Founder]
A Guitarist 🎸, Video/Audio Editor🎥, Music Producer 🎧, National Instrumental Battle winner, Zonal rap battle runner-up, Basically the brains behind The Rock Empire,
Pranav Kapur -
Gurman Singh [Founder]
A musician🎧, Dj, Producer, One who can play over 20 instruments! He has a graduation in Tabla and is also a national winner. He also performs with different Celeb singers like Honey Singh , Alfaaz , Guru Randhawa and many more,
Gurman Singh -
Shaan Raina
A Singer, with a Third year deg in classical music🎧, Photographer, Guitarist🎸, Pianinst, Cyclist. An overall achiever, with an awesome sense of humour and the voice of The Band,
Shaan Raina -
Yash Gupta
A Pianist | A Composer | A Producer | A Photographer and Much more... A thinker, with a passion to be the best in his field, always behind the piano, the sound of the Band,
Yash Gupta -
Gurumehar Sidha
An Aspiring young Rapper, A member of our band, an over achiever, and being an outstanding emcee, he tends to reach heights difficult for others to reach, with a talent that is unique in every kind,
Gurumehar Sidha


Android
Quickstart with a HelloWorld Example
HelloWorld is a simple image classification application that demonstrates how to use PyTorch Android API. This application runs TorchScript serialized TorchVision pretrained resnet18 model on static image which is packaged inside the app as android asset.
1. Model Preparation
Let’s start with model preparation. If you are familiar with PyTorch, you probably should already know how to train and save your model. In case you don’t, we are going to use a pre-trained image classification model (MobileNetV2). To install it, run the command below:
pip install torchvision
To serialize the model you can use python script in the root folder of HelloWorld app:
import torch
import torchvision
from torch.utils.mobile_optimizer import optimize_for_mobile
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()
example = torch.rand(1, 3, 224, 224)
traced_script_module = torch.jit.trace(model, example)
traced_script_module_optimized = optimize_for_mobile(traced_script_module)
traced_script_module_optimized._save_for_lite_interpreter("app/src/main/assets/model.ptl")
If everything works well, we should have our model - model.ptl
generated in the assets folder of android application.
That will be packaged inside android application as asset
and can be used on the device.
More details about TorchScript you can find in tutorials on pytorch.org
2. Cloning from github
git clone https://github.com/pytorch/android-demo-app.git
cd HelloWorldApp
If Android SDK and Android NDK are already installed you can install this application to the connected android device or emulator with:
./gradlew installDebug
We recommend you to open this project in Android Studio 3.5.1+. At the moment PyTorch Android and demo applications use android gradle plugin of version 3.5.0, which is supported only by Android Studio version 3.5.1 and higher. Using Android Studio you will be able to install Android NDK and Android SDK with Android Studio UI.
3. Gradle dependencies
Pytorch android is added to the HelloWorld as gradle dependencies in build.gradle:
repositories {
jcenter()
}
dependencies {
implementation 'org.pytorch:pytorch_android_lite:1.9.0'
implementation 'org.pytorch:pytorch_android_torchvision:1.9.0'
}
Where org.pytorch:pytorch_android
is the main dependency with PyTorch Android API, including libtorch native library for all 4 android abis (armeabi-v7a, arm64-v8a, x86, x86_64).
Further in this doc you can find how to rebuild it only for specific list of android abis.
org.pytorch:pytorch_android_torchvision
- additional library with utility functions for converting android.media.Image
and android.graphics.Bitmap
to tensors.
4. Reading image from Android Asset
All the logic happens in org.pytorch.helloworld.MainActivity
.
As a first step we read image.jpg
to android.graphics.Bitmap
using the standard Android API.
Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("image.jpg"));
5. Loading Mobile Module
Module module = Module.load(assetFilePath(this, "model.ptl"));
org.pytorch.Module
represents torch::jit::mobile::Module
that can be loaded with load
method specifying file path to the serialized to file model.
6. Preparing Input
Tensor inputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap,
TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB);
org.pytorch.torchvision.TensorImageUtils
is part of org.pytorch:pytorch_android_torchvision
library.
The TensorImageUtils#bitmapToFloat32Tensor
method creates tensors in the torchvision format using android.graphics.Bitmap
as a source.
All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of
[0, 1]
and then normalized usingmean = [0.485, 0.456, 0.406]
andstd = [0.229, 0.224, 0.225]
inputTensor
’s shape is 1x3xHxW
, where H
and W
are bitmap height and width appropriately.
7. Run Inference
Tensor outputTensor = module.forward(IValue.from(inputTensor)).toTensor();
float[] scores = outputTensor.getDataAsFloatArray();
org.pytorch.Module.forward
method runs loaded module’s forward
method and gets result as org.pytorch.Tensor
outputTensor with shape 1x1000
.
8. Processing results
Its content is retrieved using org.pytorch.Tensor.getDataAsFloatArray()
method that returns java array of floats with scores for every image net class.
After that we just find index with maximum score and retrieve predicted class name from ImageNetClasses.IMAGENET_CLASSES
array that contains all ImageNet classes.
float maxScore = -Float.MAX_VALUE;
int maxScoreIdx = -1;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > maxScore) {
maxScore = scores[i];
maxScoreIdx = i;
}
}
String className = ImageNetClasses.IMAGENET_CLASSES[maxScoreIdx];
In the following sections you can find detailed explanations of PyTorch Android API, code walk through for a bigger demo application, implementation details of the API, how to customize and build it from source.
PyTorch Demo Application
We have also created another more complex PyTorch Android demo application that does image classification from camera output and text classification in the same github repo.
To get device camera output it uses Android CameraX API.
All the logic that works with CameraX is separated to org.pytorch.demo.vision.AbstractCameraXActivity
class.
void setupCameraX() {
final PreviewConfig previewConfig = new PreviewConfig.Builder().build();
final Preview preview = new Preview(previewConfig);
preview.setOnPreviewOutputUpdateListener(output -> mTextureView.setSurfaceTexture(output.getSurfaceTexture()));
final ImageAnalysisConfig imageAnalysisConfig =
new ImageAnalysisConfig.Builder()
.setTargetResolution(new Size(224, 224))
.setCallbackHandler(mBackgroundHandler)
.setImageReaderMode(ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
.build();
final ImageAnalysis imageAnalysis = new ImageAnalysis(imageAnalysisConfig);
imageAnalysis.setAnalyzer(
(image, rotationDegrees) -> {
analyzeImage(image, rotationDegrees);
});
CameraX.bindToLifecycle(this, preview, imageAnalysis);
}
void analyzeImage(android.media.Image, int rotationDegrees)
Where the analyzeImage
method process the camera output, android.media.Image
.
It uses the aforementioned TensorImageUtils.imageYUV420CenterCropToFloat32Tensor
method to convert android.media.Image
in YUV420
format to input tensor.
After getting predicted scores from the model it finds top K classes with the highest scores and shows on the UI.
Language Processing Example
Another example is natural language processing, based on an LSTM model, trained on a reddit comments dataset.
The logic happens in TextClassificattionActivity
.
Result class names are packaged inside the TorchScript model and initialized just after initial module initialization.
The module has a get_classes
method that returns List[str]
, which can be called using method Module.runMethod(methodName)
:
mModule = Module.load(moduleFileAbsoluteFilePath);
IValue getClassesOutput = mModule.runMethod("get_classes");
The returned IValue
can be converted to java array of IValue
using IValue.toList()
and processed to an array of strings using IValue.toStr()
:
IValue[] classesListIValue = getClassesOutput.toList();
String[] moduleClasses = new String[classesListIValue.length];
int i = 0;
for (IValue iv : classesListIValue) {
moduleClasses[i++] = iv.toStr();
}
Entered text is converted to java array of bytes with UTF-8
encoding. Tensor.fromBlobUnsigned
creates tensor of dtype=uint8
from that array of bytes.
byte[] bytes = text.getBytes(Charset.forName("UTF-8"));
final long[] shape = new long[]{1, bytes.length};
final Tensor inputTensor = Tensor.fromBlobUnsigned(bytes, shape);
Running inference of the model is similar to previous examples:
Tensor outputTensor = mModule.forward(IValue.from(inputTensor)).toTensor()
After that, the code processes the output, finding classes with the highest scores.
More PyTorch Android Demo Apps
D2go
D2Go demonstrates a Python script that creates the much lighter and much faster Facebook D2Go model that is powered by PyTorch 1.8, torchvision 0.9, and Detectron2 with built-in SOTA networks for mobile, and an Android app that uses it to detect objects from pictures in your photos, taken with camera, or with live camera. This demo app also shows how to use the native pre-built torchvision-ops library.
Image Segmentation
Image Segmentation demonstrates a Python script that converts the PyTorch DeepLabV3 model and an Android app that uses the model to segment images.
Object Detection
Object Detection demonstrates how to convert the popular YOLOv5 model and use it in an Android app that detects objects from pictures in your photos, taken with camera, or with live camera.
Neural Machine Translation
Neural Machine Translation demonstrates how to convert a sequence-to-sequence neural machine translation model trained with the code in the PyTorch NMT tutorial and use the model in an Android app to do French-English translation.
Question Answering
Question Answering demonstrates how to convert a powerful transformer QA model and use the model in an Android app to answer questions about PyTorch Mobile and more.
Vision Transformer
Vision Transformer demonstrates how to use Facebook’s latest Vision Transformer DeiT model to do image classification, and how convert another Vision Transformer model and use it in an Android app to perform handwritten digit recognition.
Speech recognition
Speech Recognition demonstrates how to convert Facebook AI’s wav2vec 2.0, one of the leading models in speech recognition, to TorchScript and how to use the scripted model in an Android app to perform speech recognition.
Video Classification
TorchVideo demonstrates how to use a pre-trained video classification model, available at the newly released PyTorchVideo, on Android to see video classification results, updated per second while the video plays, on tested videos, videos from the Photos library, or even real-time videos.
PyTorch Android Tutorial and Recipes
Image Segmentation DeepLabV3 on Android
A comprehensive step-by-step tutorial on how to prepare and run the PyTorch DeepLabV3 image segmentation model on Android.
PyTorch Mobile Performance Recipes
List of recipes for performance optimizations for using PyTorch on Mobile.
Making Android Native Application That Uses PyTorch Android Prebuilt Libraries
Learn how to make Android application from the scratch that uses LibTorch C++ API and uses TorchScript model with custom C++ operator.
Fuse Modules recipe
Learn how to fuse a list of PyTorch modules into a single module to reduce the model size before quantization.
Quantization for Mobile Recipe
Learn how to reduce the model size and make it run faster without losing much on accuracy.
Script and Optimize for Mobile
Learn how to convert the model to TorchScipt and (optional) optimize it for mobile apps.
Model Preparation for Android Recipe
Learn how to add the model in an Android project and use the PyTorch library for Android.
Building PyTorch Android from Source
In some cases you might want to use a local build of PyTorch android, for example you may build custom LibTorch binary with another set of operators or to make local changes, or try out the latest PyTorch code.
For this you can use ./scripts/build_pytorch_android.sh
script.
git clone https://github.com/pytorch/pytorch.git
cd pytorch
sh ./scripts/build_pytorch_android.sh
The workflow contains several steps:
1. Build libtorch for android for all 4 android abis (armeabi-v7a, arm64-v8a, x86, x86_64)
2. Create symbolic links to the results of those builds:
android/pytorch_android/src/main/jniLibs/${abi}
to the directory with output libraries
android/pytorch_android/src/main/cpp/libtorch_include/${abi}
to the directory with headers. These directories are used to build libpytorch_jni.so
library, as part of the pytorch_android-release.aar
bundle, that will be loaded on android device.
3. And finally run gradle
in android/pytorch_android
directory with task assembleRelease
Script requires that Android SDK, Android NDK, Java SDK, and gradle are installed. They are specified as environment variables:
ANDROID_HOME
- path to Android SDK
ANDROID_NDK
- path to Android NDK
GRADLE_HOME
- path to gradle
JAVA_HOME
- path to JAVA JDK
After successful build, you should see the result as aar file:
$ find android -type f -name *aar
android/pytorch_android/build/outputs/aar/pytorch_android-release.aar
android/pytorch_android_torchvision/build/outputs/aar/pytorch_android_torchvision-release.aar
Using the PyTorch Android Libraries Built from Source or Nightly
First add the two aar files built above, or downloaded from the nightly built PyTorch Android repos at here and here, to the Android project’s lib
folder, then add in the project’s app build.gradle
file:
allprojects {
repositories {
flatDir {
dirs 'libs'
}
}
}
dependencies {
// if using the libraries built from source
implementation(name:'pytorch_android-release', ext:'aar')
implementation(name:'pytorch_android_torchvision-release', ext:'aar')
// if using the nightly built libraries downloaded above, for example the 1.8.0-snapshot on Jan. 21, 2021
// implementation(name:'pytorch_android-1.8.0-20210121.092759-172', ext:'aar')
// implementation(name:'pytorch_android_torchvision-1.8.0-20210121.092817-173', ext:'aar')
...
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.facebook.fbjni:fbjni-java-only:0.0.3'
}
Also we have to add all transitive dependencies of our aars. As pytorch_android
depends on com.android.support:appcompat-v7:28.0.0
or androidx.appcompat:appcompat:1.2.0
, we need to one of them. (In case of using maven dependencies they are added automatically from pom.xml
).
Using the Nightly PyTorch Android Libraries
Other than using the aar files built from source or downloaded from the links in the previous section, you can also use the nightly built Android PyTorch and TorchVision libraries by adding in your app build.gradle
file the maven url and the nightly libraries implementation as follows:
repositories {
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
dependencies {
...
implementation 'org.pytorch:pytorch_android:1.8.0-SNAPSHOT'
implementation 'org.pytorch:pytorch_android_torchvision:1.8.0-SNAPSHOT'
}
This is the easiest way to try out the latest PyTorch code and the Android libraries, if you do not need to make any local changes. But be aware you may need to build the model used on mobile in the latest PyTorch - using either the latest PyTorch code or a quick nightly install with commands like pip install --pre torch torchvision -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html
- to avoid possible model version mismatch errors when running the model on mobile.
Custom Build
To reduce the size of binaries you can do custom build of PyTorch Android with only set of operators required by your model. This includes two steps: preparing the list of operators from your model, rebuilding pytorch android with specified list.
1. Verify your PyTorch version is 1.4.0 or above. You can do that by checking the value of torch.__version__
.
2. Preparation of the list of operators
List of operators of your serialized torchscript model can be prepared in yaml format using python api function torch.jit.export_opnames()
.
To dump the operators in your model, say MobileNetV2
, run the following lines of Python code:
# Dump list of operators used by MobileNetV2:
import torch, yaml
model = torch.jit.load('MobileNetV2.pt')
ops = torch.jit.export_opnames(model)
with open('MobileNetV2.yaml', 'w') as output:
yaml.dump(ops, output)
3. Building PyTorch Android with prepared operators list.
To build PyTorch Android with the prepared yaml list of operators, specify it in the environment variable SELECTED_OP_LIST
. Also in the arguments, specify which Android ABIs it should build; by default it builds all 4 Android ABIs.
# Build PyTorch Android library customized for MobileNetV2:
SELECTED_OP_LIST=MobileNetV2.yaml scripts/build_pytorch_android.sh arm64-v8a
After successful build you can integrate the result aar files to your android gradle project, following the steps from previous section of this tutorial (Building PyTorch Android from Source).
Use PyTorch JIT interpreter
PyTorch JIT interpreter is the default interpreter before 1.9 (a version of our PyTorch interpreter that is not as size-efficient). It will still be supported in 1.9, and can be used via build.gradle
:
repositories {
jcenter()
}
dependencies {
implementation 'org.pytorch:pytorch_android:1.9.0'
implementation 'org.pytorch:pytorch_android_torchvision:1.9.0'
}
Android Tutorials
Watch the following video as PyTorch Partner Engineer Brad Heintz walks through steps for setting up the PyTorch Runtime for Android projects:
The corresponding code can be found here.
Checkout our Mobile Performance Recipes which cover how to optimize your model and check if optimizations helped via benchmarking.
In addition, follow this recipe to learn how to make Native Android Application that use PyTorch prebuilt libraries.
API Docs
You can find more details about the PyTorch Android API in the Javadoc.


Man who escaped sinking car in Arranmore pier tragedy tells victim's family of tragic last moments
The incident claimed the life of a young RNLI volunteer off Co Donegal
by Stephen MaguireThe man who escaped from the sinking wreckage of a car which claimed the life of another young man off Co Donegal has told the dead man's family of his last tragic moments.
Lee Early perished when his car slid off a pier on Arranmore Island into freezing waters just after 5am on Sunday morning.
The 26-year-old drowned but another man, in his 30s, managed to swim to safety from the stricken car off Poolawaddy Pier.
Now it has been revealed how the man was able to pinpoint the exact location of the car before it was swept out to sea.
Island spokesperson Jerry Early, a cousin of the dead man's father Jimmy, said it is a small but very comforting consolation for the bereaved family.
Mr Early said: "The man who survived has been able to speak to the family. He is devastated at what happened.
"He is full of sadness and has so many questions of his own he is trying to answer.
"We have lost one of our community and we could have lost two and we are thankful that it is not the case.
"It is a small comfort but at least he was able to tell Lee's family what happened and they will not be left wondering what exactly did happen in the years to come.
"He was also a great help to the lifeboat in locating the car and locating Lee as it could have been swept out to sea."
A full investigation into the circumstances surrounding the tragedy has been launched by Gardai.
Lee's remains were taken by the Arranmore Ferry back to the island at 5pm today after a post mortem was carried out at Letterkenny University Hospital.
Mr Early said the entire island is just "numb" with the loss of one of their own.
He said that Lee was a real islander who would be one of the people expected to remain living on the island despite the challenges which constantly face the population of around 450 inhabitants.
"He was a real islander. If he was in Letterkenny he'd be longing to get back to the island. He was one of the people you would look to who would be driving the island forward.
"He was a devil and an angel. He would always be in the background but you could always depend on him.
"The island is just numb and the people are numb. We will regroup as a community and we will come together in the coming days and help the Early family as best we can. That's what island communities are best at, looking after eachother," he said.
Lee was also a volunteer with the local RNLI and his father is the coxswain of the island's lifeboat.
It has also been revealed how the RNLI offered to stand down the lifeboat for the coming days in light of the tragedy but the offered was declined by the dedicated crew from the island.
A huge gathering is expected for Lee's funeral which takes place on Wednesday at noon at St Crone's Church with burial later in the adjoining cemetery.
The local Arranmore Hostel has offered free accommodation to anybody traveling to the island for the wake or the funeral.
Lee is survived by his father Jimmy, mother Noreen, brother Adam, sisters Rachel and Laura and a wide circle of family and friends.
How to follow the Irish Mirror on social media
You can like our main Facebook page here.
Our Irish Mirror Sports page - which brings you all your Irish and UK sports news - can be found here.
You can also check out our Irish Mirror GAA sports page.
The Irish Mirror Twitter account is @IrishMirror while our sports account is @MirrorSportIE.
Our Instagram account can be found here.


This event is organised by University of Bristol!
Cycling is widely regarded as a very effective and efficient mode of transportation optimal for short to moderate distances. Bicycles provide numerous benefits by comparison with motor vehicles, including the sustained physical exercise necessarily involved in cycling, that cycling involves a reduced consumption of fossil fuels, less air or noise pollution, much reduced traffic congestion, easier parking, greater maneuverability, and access to both roads and paths. The advantages also include reduced financial cost to the user as well as to society at large (negligible damage to roads, less road area required).(Source: wikipedia.org)


The recommended approaches to scrolling are using [page]
and [namedDest]
.
If you want to scroll within a page, there's a third option. NgxExtendedPdfViewerService
offers a programmatic API:
scrollPageIntoView(42)
is equivalent to [page]="42"
.scrollPageIntoView(42, {{ '{' }}top: '100%'})
scrolls to the bottom of page 42.scrollPageIntoView(42, {{ '{' }}top: '50%'})
scrolls to the middle of page 42.scrollPageIntoView(42, {{ '{' }}top: 500 })
scrolls to page 42, and then 500 pixels down.scrollPageIntoView(42, {{ '{' }}left: '100%' })
scrolls to the right hand side of the page.Note that numerical values refer to pixels, so which part of the page become visible depends on the zoom level. Better use percentages.
The left
parameter can be confusing, especially if your PDF document features bot
landscape and portrait pages. In theory, the left
parameters causes the page
to scroll to the left by a given percentage. However, that's not always possible because the
horizontal scrollbar doesn't allow for arbitrary scrolling. In particular, 100% would indicate
the page scrolls out of the visible area, but the scrollbar doesn't allow that. You can see this in the
demo by setting the zoom level to different settings and by clicking the left="90%"
buttons.


Profile
Edit Profile Picture
Name
Department
CS
Designation
HoD
Age
Password
Generate Password
Reset


Your web browser doesn’t support this experience. Please try again using Google Chrome and WebGL-compatible hardware.


- What is the install challenge
- How we started
- Current iteration
- How we are going to improve it later
- Close
Mesosphere’s Data Center Operating System (DCOS) is a distributed cluster manager and resource scheduler that enables companies to execute their application with high parallelization and availability. The DCOS ecosystem consists of many open source and proprietary tools to manage executing client applications in the cluster. The core utilities are Apache Mesos, Mesos DNS, Mesosphere’s Marathon, Nginx, Apache Zookeeper and Zookeeper Exhibitor (FOSS from Netflix). The production-read version of DCOS runs 3-5 Apache Mesos Masters with ‘n’ number of Apache Mesos Agents.
Properly configuring and installing this suite of tools to large on-premise deployments poses many challenges:
- Bootstrapping the cluster for high availability
- Bootstrapping the cluster from a single target “bootstrapping” host
- Scoping the configuration available to Mesosphere clients
- Master discovery configuration
- Exhibitor configuration
- Continuous integration tests on the actual software that manages DCOS installation
Because of the complexity with bootstrapping a highly available cluster from scratch we have to present the end-user with a lot of implementation details and configuration which is often times confusing and sets a barrier to entry to using DCOS.
Traditionally, you can ship software to a node using well-known package managers (Aptitude or Yum). However, DCOS is designed to run on any linux distribution, which means we’d have to support all the package management repos our potential customers require: Yum, Aptitude, Pacman, Zypper, etc. Furthermore, since this is a distributed cluster, we have to seed each deployment package with site-specific configuration for each part of the DCOS system. This means the package manager would have to include some way for us to configure cluster wide settings for things like Zookeepers' zoo.cfg file (managed by Exhibitor), Mesos DNS configuration, and other distributed utilities.
In the end, we would have to configure every node in the cluster with our package repo and this site-specific configuration before the DCOS package actually installs. We could use configuration management for this, but in that case we’d also have to write Puppet modules, Chef cookbooks, Ansible playbooks and Salt code to name a few, to ensure we cover all the possible customer requirements for installing DCOS at a given site.
This locks us in to managing a package repo per customer (not to mention tests on each built package system) and a given installation method using configuration management. Let’s not even begin to talk about the complexity of maintaining those configuration management codebases across multiple versions of the configuration management suite (in other words, customer A is running Puppet 3x, customer B is running Puppet 2x and customer C is running Puppet 4x - good luck keeping that complicated module cross functional across all versions previous and future - and that’s for just a single configuration management suite).
In the end, we opted to design an installer that any customer could run, regardless of configuration management implementation or underlying operating system package managers. This installer can easily integrate with existing configuration management systems or install the cluster via SSH to the distributed nodes. It can also walk customers through the often complicated process of configuring the underlying system before it installs with a user-friendly web UI.
How We Started
Our first try at the on-premise installer was a CLI tool that automated configuring and building a bootstrap tarball. It used a JSON configuration file that had some drawbacks. Primarily, we use only string-based variables in our configuration file templates, so we required anything other than strings (such as arrays) in the JSON config, had to be strings:
1
|
|
This was obviously less than ideal.
Secondly, the CLI utility required the end-user to have some way to distribute the tarball it created. This left a lot up to the end-user, and was a point of contention.
Lastly, the end user had a lot of configurated exposed to her that was often confusing. The biggest hurdle was sometimes explaining what Exhibitor was, how to configure it, and in some cases why it needed its own Zookeeper quorum to bootstrap the DCOS quorom.
All of these issues pointed towards a major overhaul of this installation process.
Our Current Iteration
User Interface
On the outset, we wanted to create an installer that had a user interface. This UI would allow us to walk the user through configuring the DCOS cluster. It would also allow us to quickly copy and paste configuration into the UI, and abstract all the complexity of this process to a clean interface.
Internally Bootstrap Exhibitor
We also wanted to remove the Exhibitor configuration from the end-user, getting rid of this confusing configuration piece would lower the barrier to entry and solve many of our support calls. Under the hood, we achieve this by writing our own static ensamble for bootstrapping exhibitor. This new backend to exhibitor allowed us to pass it our static master list to the backend, and it writes this, regardless of cluster state, to the zoo.cfg.
SSH Deploy
This new installer would also have a deploy option. The deploy option would leverage SSH on the backend to execute preflight checks on the target hosts in the cluster; install the DCOS tarball to the machines; and execute post-flight checks on the target hosts to enure the cluster was in a working state.
YAML Configuration File
This new installer levareages a YAML configuration file. The UI walks the user through building this YAML file but the beauty is that we can ship pre-built YAML files with in-line comments. JSON doesn’t allow us to put comments in the file, and with that option available we can make more clear what each configuration parameter does without having the end-user touch the UI.
Configuration Management Integration
Our previous installer shipped around the installer script, which would pull the tarball from the configuration machine. In this way, it was partially on its way to integrating with configuration management. However, the previous installer did not ship a server to serve that tarball. It was up to the end-user to configure an NGINX, Apache or other server that would allow the script to pull down the tarball from the host machine.
For many systems administrators this was fine, however, for many it was just another barrier to entry. To simplify this process we’re now shipping a built in server and an option to execute the CLI mode of the installer with --bootstrap_url
.
--bootstrap_url
exposes a URL on the installer host: http://$INSTALLER_IP:9000/bootstrap
With this feature, you can expose the bootstrap URL on the installer host and write a very simple Puppet module, Chef cookbook or Ansible playbook to pull the tarball, extract it to the filesystem and create the required symlinks. This is a far more simple option to management of your configuration management code than building all the current and possible future config files for DCOS. Now it’s just three unix-level operations.


ORDER NOW
HOME PAGE
OUR SHOP SALES DATA
Create Your Own Shop
Shop Name
Minimum Value
Maximum Value
Average Value Value


Global instance of a 2x2 identity matrix. Use as read-only.
Global instance of an identity transform. Use as read-only.
Global instance of a zero'ed vector. Use as read-only.
Creates an ABS number.
Number to ABS.
Absolute value of a.
Clamp a number to the range of low to high.
Number to clamp.
Low range.
High range.
Number a clamped to range of low to high.
Check if a number is a power of 2.
Number to check if it is a power of 2.
True if x is a power of 2, otherwise false.
Determines if a number is valid. A number is valid if it is finite.
Number to check for validity.
True if x is valid, otherwise false.
Determines the max number.
First number.
Second number.
a or b depending on which is the maximum.
Determines the minimum number.
First number.
Second number.
a or b depending on which is the minimum.
Calculates the next power of 2 after the given number.
Number to start search for the next power of 2.
The next number that is a power of 2.
Generates a random number.
Returns a random number between lo and hi.
Lowest random number.
Highest random number.
Number between lo and hi.
Swaps a and b objects.
a -> b.
b -> a.
Generated using TypeDoc
Math utility functions.