| < Day Day Up > |
4.5 Access ControlsI'll have a lot to say about access controls in Chapter 6. For now, I'll cover a few controls so that more enthusiastic readers can quickly start using Squid. Squid's default configuration file denies every client request. You must place additional access control rules in squid.conf before anyone can use the proxy. The simplest approach is to define an ACL that corresponds to your user's IP addresses and an access rule that tells Squid to allow HTTP requests from those addresses. Squid has many different ACL types. The src type matches client IP addresses, and the http_access rules are checked for client HTTP requests. Thus, you need to add only two lines: acl MyNetwork src <IP_ADDRESS>/16 http_access allow MyNetwork The tricky part is putting these lines in the right place. The order of http_access lines is very important, but the order of acl lines doesn't matter. You should also be aware that the default configuration file contains some important access controls. You shouldn't change or disrupt these until you fully comprehend their significance. When you edit squid.conf for the first time, look for this comment: # # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS # Insert your new rules below this comment, and before the http_access deny All line. For the sake of completeness, here is a suitable initial access control configuration, including the recommended default controls and the example earlier: acl All src 0/0 acl Manager proto cache_object acl Localhost src <IP_ADDRESS>/32 acl Safe_ports port 80 21 443 563 70 210 280 488<PHONE_NUMBER>-65535 acl SSL_ports 443 563 acl CONNECT method CONNECT acl MyNetwork src <IP_ADDRESS>/16 http_access allow Manager Localhost http_access deny Manager http_access deny !Safe_ports http_access deny CONNECT !SSL_ports http_access allow MyNetwork http_access deny All |
| < Day Day Up > |


The Internet of Cities Infrastructure is an interdisciplinary effort to create the scientific underpinnings that are needed for building and operating applications for future smart cities.
Currently, effective and efficient development and subsequent operation of smart city applications is not possible, due to the increasing number of involved stakeholders, conflicting requirements, fragmented available knowledge, and an abundance of sensory and environmental data.
In order to address the identified challenges, we provide a holistic approach to implement an ideal smart city loop by creating methodologies, frameworks, and approaches that will form the basis of an Internet of Cities.
Recently, IoT devices with embedded execution environments emerged that allow practitioners to deploy and execute custom application logic on the device. This approach fundamentally changes the overall process of designing, developing, deploying, and managing IoT systems. However, these devices exhibit significant differences in available execution environments, processing, and storage capabilities. To accommodate this diversity, a structured approach is needed to uniformly and transparently deploy application components onto a large number of heterogeneous devices. This is especially important in the context of current large-scale IoT systems, such as in the smart city domain. In this paper, we present LEONORE, a service oriented infrastructure that provides elastic provisioning of application components on resource-constrained and heterogeneous edge devices in large-scale IoT deployments.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
Copyright 2015 | Distributed Systems Group


You'll be finding awesome stuff on Etsy in a few days.
For questions or updates, check with @reid.
August 7, 2010


-
Default Tip.

-
Tip Above.

-
Tip Left.

-
Tip Right.
Bresaola salami short loin tongue t-bone venison turkey fatback pancetta frankfurter swine hamburger.
-
Tip Below.
Swine beef brisket t-bone, boudin rump hamburger.
-
Pastrami boudin pig, swine filet mignon venison flank chuck.


NinjaOx
News
-
Microgrids and Hybrid Power Generation
Microgrids are becoming increasingly popular because of the rapid rise in power demand due to population and industrial growth. In many locations, the current mains grid system is unable to cope with the increase in power demands. That´s why businesses, governments and even some individuals have begun to resort to generating their own power, to ensure reliability, but also to gain more control over rapidly rising electricity prices.
Islands are also becoming increasingly interesting in microgrids because of the above increasing demands, but also because the difficulty of obtaining electricity from the main island, (or mainland) electricity grid system.
The increase in the price of diesel, and the associated costs of diesel transportation to isolated island communities, has also let to the development of local microgrids into Hybrid PV/Diesel Microgrid Systems.
-
White Paper: Integration of Battery Energy Storage Systems into Hybrid Microgrids and Use of LiFePO4 Technology
The installation of a battery system is not critical for microgrids that are connected to the electricity network. The NinjaOx control system automatically starts and synchronizes backup motor generators, so in case of an impending mains failure and subsequent limited power supply, a backup power supply would be switched on as soon as possible, without the power outage. However, in parallel applications, backup batteries can also play a role of uninterruptable power supply (UPS), where they feed the load until the motor generator starts (can be used in critical applications, such as hospitals, data centers, etc.).
For island systems (so-called off-grid) with renewable resources, where diesel fuel consumption reduction is a priority, the usage of batteries is crucial. A high-capacity battery (not only in the role of UPS) is then available to cover power peaks and to eliminate the need for dynamic spinning reserve. Thanks to that, the load of the motor generator remains constant, thus extending its life and reducing fuel consumption.
The above mentioned can be applied only on condition that the battery is dimensioned correctly, and a suitable technology is chosen which can reduce diesel consumption by limiting the operation of diesel engine generators. During the project design an economic return on investment has to be taken into account though since the battery storage is still relatively expensive.
-
CEO´s COVID-19 Update
The COVID-19 situation is unfortunately becoming worse in Europe, and you might have noticed that in the Czech Republic, we are experiencing considerable increases in positive daily cases.
We would like to reassure you that NinjaOx maintain its business with no or very limited impact. We keep following the best-practice preventative measures to manage the highest safety level possible for our employees and partners.
From a stock point of view, we have good product availability, our supply chain is running smoothly, and our production continues as planned. We are closely working and planning with our production partners and are aligned on the required Health & Safety measures.
Featured products
-
InteliVision 12Touch
12,1" Colour Display Unit
-
InteliVision 12Touch OEM
Marine Approved 12,1" Colour Display Unit without name and company logo on its front face
-
InteliGen 500
Advanced paralleling gen-set controller with 5” colour display


So - before we talked about everything being in a box. Gridge-based design is when all those boxes are arranged in a way that makes sense to read. We start at the top, then track from left to right and down.
Responsive design means our web pages can adjust to best fit the size of the screen they're being displayed on - because sometimes, one size just doesn't fit all.
Semantics is about meaning. In html, semantic structure is used to give elements meaning that can be understood by both people, and the the browser. Neat, eh?


Author on Envato
Repository on GitHub
Welcome to documentation!
Component-based frameworks designed and built by the best Bootstrap creators in the world.
{{item.title}}
{{item.content}}
{{item.link.text}}
Mirele for clients
{{post.title}}
Mirele for developers
{{post.title}}
Mirele for you
{{item.content}}
Mirele Dev
{{item.content}}


There's a loving in your eyes all the way If I listen to your lies, would you say I'm a man (a man) without conviction I'm a man (a man) who doesn't know How to sell (to sell) a contradiction You come and go, you come and go
sers\ingenieria> set | findstr USER ALLUSERSPROFILE=C:\ProgramData FPS_BROWSER_USER_PROFILE_STRING=Default USERDOMAIN=DESKTOP-74NMUPM USERDOMAIN_ROAMINGPROFILE=DESKTOP-74NMUPM USERNAME=ingenieria USERPROFILE=C:\Users\ingenieria


ACTIVE INGREDIENTS (IN EACH CAPLET)
Ibuprofen, USP 200 mg (NSAID)*
Pseudoephedrine HCl, USP 30 mg
*nonsteroidal anti-inflammatory drug
PURPOSES
Pain reliever/Fever reducer
Nasal decongestant
USES
Temporarily relieves these symptoms associated with the common cold or flu:
- fever
- sinus pressure
- nasal congestion
- headache
- minor body aches and pains
WARNINGS
Allergy alert: Ibuprofen may cause a severe allergic reaction, especially in people allergic to aspirin. Symptoms may include:
- hives
- facial swelling
- asthma (wheezing)
- shock
- skin reddening
- rash
- blisters
If an allergic reaction occurs, stop use and seek medical help right away.
Stomach bleeding warning: This product contains an NSAID, which may cause severe stomach bleeding. The chance is higher if you:
- are age 60 or older
- have had stomach ulcers or bleeding problems
- take a blood thinning (anticoagulant) or steroid drug
- take other drugs containing prescription or nonprescription NSAIDs [aspirin, ibuprofen, naproxen, or others]
- have 3 or more alcoholic drinks every day while using this product
- take more or for a longer time than directed
Do not use
- if you have ever had an allergic reaction to any other pain reliever/fever reducer
- if you are now taking a prescription monoamine oxidase inhibitor (MAOI) (certain drugs for depression, psychiatric, or emotional conditions, or Parkinson’s disease), or for 2 weeks after stopping the MAOI drug. If you do not know if your prescription drug contains an MAOI, ask a doctor or pharmacist before taking this product.
- in children under 12 years of age
- right before or after heart surgery
Ask a doctor before use if
- stomach bleeding warning applies to you
- you have problems or serious side effects from taking pain relievers or fever reducers
- you have a history of stomach problems, such as heartburn
- you have high blood pressure, heart disease, liver cirrhosis, kidney disease, asthma, thyroid disease, diabetes or have trouble urinating due to an enlarged prostate gland
- you are taking a diuretic
Ask a doctor or pharmacist before use if you are
- under a doctor’s care for any serious condition
- taking any other drug
- taking any other product that contains pseudoephedrine or any other nasal decongestant
- taking aspirin for heart attack or stroke, because ibuprofen may decrease this benefit of aspirin
When using this product
- take with food or milk if stomach upset occurs
- the risk of heart attack or stroke may increase if you use more than directed or for longer than directed
Stop use and ask a doctor if
- you experience any of the following signs of stomach bleeding:
- feel faint
- have bloody or black stools
- vomit blood
- have stomach pain that does not get better
- symptoms continue or get worse
- any new symptoms appear
- you get nervous, dizzy, or sleepless
- fever gets worse or lasts more than 3 days
- nasal congestion lasts for more than 7 days
- redness or swelling is present in the painful area
If pregnant or breast-feeding
Ask a health professional before use. It is especially important not to use ibuprofen during the last 3 months of pregnancy unless definitely directed to do so by a doctor because it may cause problems in the unborn child or complications during delivery.
Keep out of reach of children.
In case of overdose, get medical help or contact a Poison Control Center right away (1-800-222-1222).
DIRECTIONS
- do not take more than directed
- the smallest effective dose should be used
- adults and children 12 years of age and over:
- take 1 caplet every 4 to 6 hours while symptoms persist. If symptoms do not respond to 1 caplet, 2 caplets may be used.
- do not use more than 6 caplets in any 24-hour period unless directed by a doctor
- children under 12 years of age: do not use
OTHER INFORMATION
- store at 20 - 25○ C (68 - 77○ F). Avoid excessive heat above 40○ C (104○ F).
- read all warnings and directions before use. Keep carton.
- TAMPER EVIDENT: DO NOT USE IF BLISTER UNITS ARE TORN, BROKEN OR SHOW ANY SIGNS OF TAMPERING.

Call 1-800-406-7984
PRINCIPAL DISPLAY PANEL
QC QUALITY CHOICE®
NDC 63868-453-20
*Compare to the active ingredients in Advil®Cold & Sinus
NON-DROWSY
IBUPROFEN AND PSEUDOEPHEDRINE HCl TABLETS, USP
Cold & Sinus Formula
Ibuprofen, USP 200 mg - Pain Reliever/Fever Reducer (NSAID)٭
Pseudoephedrine HCl, USP 30 mg - Nasal Decongestant
FOR RELIEF OF:
- Sinus Pressure
- Nasal Congestion
- Fever
20 COATED CAPLETS†(†Oval-Shaped Tablets)
٭nonsteroidal anti-inflammatory drug
©DISTRIBUTED BY QUALITY CHOICE
5089124/R0811
Chain Drug Marketing Association Inc.


Fans react in shock as Jose Mourinho is appointed new Tottenham boss
by Sarthak SharmaTottenham Hotspur shocked the world when they announced that they were parting ways with Mauricio Pochettino after what can only be called a successful five-year relationship, and his replacement has sent even more shock waves throughout the sporting world.
Jose Mourinho has been announced as the new Spurs head coach, and it is clear that fans around the globe are still trying to wrap their head around what just happened.
We wish you all the best Jose, you’re certainly going to need it!


[gecode-users] Gecode 4.1.0 released
Guido Tack
tack at gecode.org
Wed Jul 3 05:41:24 CEST 2013
Dear all,
we are releasing the next version of Gecode:
Gecode 4.1.0
http://www.gecode.org
This release adds a really useful feature and the required
infrastructure to Gist (it now can show information on the
alternatives in a search tree), has some new features, and fixes
quite a number of bugs (some of which are quite serious, in
particular for: LDSB, restart-based search, and FlatZinc).
On our web site, you find source packages, binary packages for Windows and Mac OS, and the full documentation.
Cheers,
Guido
More information about the users
mailing list


The purpose of this project was to analyze how weather changes as you get closer to the equator. To accomplish this, I first pulled data from the OpenWeatherMap API to assemble a dataset on over 500 cities.
After assembling the dataset, I used MatPlotLib to plot various aspects of the weather vs latitude. Factors I looked into included: temperature, cloudiness, wind speed, and humidity. This site provides the source data and visualizations created as part of the analysis, as well as explanations and descriptions of any trends and correlations.
This project can be found under my 'python-weather-api' repository.


Nobuu is a personal dashboard designed to eliminate distraction and provide inspiration, focus, and productivity. All while embodying minimalist styles and delivering them to your every day life. With Nobuu, less is more.
Leave The Clutter Behind
"Wow what a great service, I love it!"- Georgeanna R.
"You won't regret it. I use this every day!"
- Aigneis N.
"It's incredible. I am really satisfied with Nobuu. "
- Dareen O.


Pyanno: Python Annotations
|
|
This project came out of my work at Temboo,
a startup in the Tribeca neighborhood of New York City.
They're hiring software engineers who want to work in Python, Qt, Java.
Contact us for details.
|
from pyanno import raises, abstractMethod, returnType, parameterTypes, deprecatedMethod, \
privateMethod, protectedMethod, selfType, ignoreType
@abstractMethod
def func2():
pass
@returnType(int, int)
@parameterTypes(int, int)
def divisionAndModulus(numerator, denominator):
# return quotient and remainder of numerator and denominator
quotient, remainder = divmod(numerator, denominator)
return quotient, remainder
@raises(IOError, ValueError)
def func1(f, s):
f.write( int(s) )
@deprecatedMethod
def func2():
...
@privateMethod
def func3():
...
@protectedMethod
def func4():
...
Contents
Version 0.77 (August 28th, 2007)
Source distribution includes python source, license, and this document.
Pyanno is a Python module that provides annotations for
Python code.
The Pyanno annotations have two functions:
-
Provide a structured way to document Python code
-
Perform limited run-time checking
Conventional text comments
def getDistance(p1, p2):
"""
getDistance() expects to be given two Points;
it returns a floating point value representing the distance between those two points.
"""
...
Pyanno annotations
from geometry import Point
@returnType(float)
@parameterTypes(Point, Point)
def getDistance(p1, p2):
"""
getDistance() calculates the distance between two points.
"""
...
-
Type Checking
Python is a dynamically-typed language; it doesn't use explicit datatype declarations.
The @returnType and @parameterTypes annotations raise an Exception if a function or method is passed or returns
an invalid value.
You specify the types expected and returned by a function, using actual Python types.
-
Abstract Methods
Methods with the @abstractMethod annotations raise an Exception if called, with a meaningful message.
-
Deprecated Methods
Methods with the @deprecatedMethod annotations print a warning message if called.
-
Comparison With Text Comments
-
Pyanno annotations are able to perform limited run-time checking (though no compile-time checking).
-
Comments can be wrong.
They may have typos, or reflect a misunderstanding.
A function and its documentation easily fall out of sync as they are revised.
The annotations, by enforcing the documented behavior help catch programmer error and catch mistakes soon after they are made.
Also, some mistakes (such as typos) are caught at compile-time, since the annotations are code.
The following examples are all valid.
For brevity, I've skipped the actual function definition and show only the annotations.
from pyanno import raises, abstractMethod, returnType, parameterTypes, deprecatedMethod, \
privateMethod, protectedMethod, selfType, ignoreType, callableType
@returnType # returns nothing
@returnType ( ) # returns nothing
@returnType ( ' ' ) # returns nothing
@returnType ( str ) # returns a string (or None)
@returnType ( ' str ' ) # returns a string (example of string-escaping, equivalent to previous example)
@returnType ( str, int )
@returnType ( 'str', int )
@returnType ( ' str, int ' ) # string-escape multiple types in single string, equivalent to two previous examples
@returnType ( tuple ) # returns a tuple
@returnType ( () ) # equivalent to previous example
@returnType ( dict ) # returns a dict
@returnType ( {} ) # equivalent to previous example
@returnType ( list ) # returns a list
@returnType ( [] ) # equivalent to previous example
@returnType ( [int] ) # returns a list containing only ints
@returnType ( (int, ) ) # a tuple containing only ints (Note trailing comma)
@returnType ( {int:str} ) # a map with int keys and string values
@returnType ( {int: [ str ] } ) # a map with int keys and string-list values
@returnType ( QObject ) # class
@returnType ( 'QObject' ) # string-escaped, equivalent to previous example
@returnType ( ClassName('QObject') ) # class, reference valid even if QObject has not been imported.
@returnType ( ignoreType ) # One argument is required, but no type checking is done.
@returnType ( classType )
@returnType ( instanceType )
@returnType ( callableType ) # accepts any method, function, closure, lambda, class or callable instance.
@parameterTypes( selfType )
@parameterTypes( int ) # accepts an int argument
@parameterTypes( int, [str] ) # accepts an int and a list of strings
-
@abstractMethod raises an exception (AbstractMethodError) if the function is called.
Has no arguments.
-
@deprecatedMethod prints a warning if the function is called.
Has no arguments.
-
@privateMethod raises an exception (PrivateMethodError) if the function is called by another module.
Has no arguments.
-
@protectedMethod raises an exception (PrivateMethodError) if the function is called by a module in a different package.
Has no arguments.
-
@raises does no run-time checking; purely for documenting the exceptions that may be raised by this function.
Arguments: a list of Exceptions (each argument must be a subclass of BaseException).
Arguments to @raises may not be string-escaped or include ClassName.
-
@parameterTypes performs run-time checking on the arguments passed to the function.
Arguments: a list of types.
-
@returnType performs run-time checking on the arguments returned by the function.
Arguments: a list of types.
-
@parameterTypes, @returnType and @raises take a list of types. These are standard python types (ie. int, str, list, dict, etc. see the 'types' standard module) or classes (ie. QObject).
-
You can only refer to defined types and classes.
See below (String Escaping Types and Circular References) for workarounds.
-
Order of operations matters with python decorators. Python function decorators are applied in reverse order.
Pyanno annotations should be applied FIRST (before builtin annotations like @staticmethod), so they should appear LAST in the code.
For example,
@staticmethod
@returnType(bool)
def myMethod ():
return False
-
Runtime type checking is controlled by pyanno.DO_RUNTIME_VALIDATION.
Ultimately, this could be set by an environment variable.
-
Runtime type checking raise AbstractMethodError, ReturnTypeError, ParamTypeError, etc., all defined in
pyanno.py.
-
At this point, none of the annotations provide compile-time checking.
-
You can annotate constructors like any other method.
-
Python uses implicit tuples when returning multiple values. For example, 'return 1,2' is equivalent to 'return (1,2)'.
This doesn't effect our annotations.
-
Do not apply the same annotation more than once to the same function. The results are undefined.
-
None values are considered valid for all types.
-
Pyanno handles sip
(and hence pyqt) wrapper types seamlessly, though they aren't classes.
-
When annotating a method or function with keynamed/optional parameters, annotate all parameters as usual.
@parameterTypes( list, dict, str, int )
def function1( requiredParameter1, requiredParameter2, optionalParameter1='third', optionalParameter2=4 )
...
- Classes cannot refer to their own type within the class definition. 'self' references (and other references to the class being defined) should use string-escaped types or selfType. No type checking is done on selfType.
class A:
@parameterTypes( A ) # wrong. Definition of A cannot refer to A.
def method1(self):
...
@parameterTypes( selfType ) # valid. No type checking is done on selfType keyword.
def method2(self):
...
@parameterTypes( 'A' ) # valid. String-escaped type will be valid due to lazy evaluation.
def method3(self):
...
- class references should use classType.
-
callableType accepts any callable (ie. a method, function, closure, lambda, class or instance with a __call__() method).
- If you don't want to type check an argument, use ignoreType.
@parameterTypes( int, ignoreType, str ) # no type-checking performed on second argument.
def function1( arg1, arg2, arg3 ):
...
- If you don't want to check the class of an argument, use types.InstanceType.
You can check the types of tuple and list values, and dict key and value types.
@returnType ( (int, ) ) # a tuple containing only ints (Note trailing comma)
@returnType ( [int] ) # a list containing only ints
@returnType ( {int:str} ) # a map with int keys and string values
@returnType ( [QObject] ) # a list of QObjects.
# Collections can be arbitrarily nested:
@returnType ( {str:[{str:int}]} ) # a map whose keys are string and whose values are
# lists of dicts mapping strings to ints.
@returnType ( [ [int] ] ) # a list of lists which contain only ints
[int] means 'a list of ints', not 'a list containing one int.'
You cannot specify multiple valid types for collection contents, ie. '[int, str]' is not valid.
Warning: Make sure to use a trailing comma when parameterizing tuples with a single element.
(x,) is a tuple with a single element, (x) is just an element wrapped in parenthesis.
@returnType ( (int ) ) # wrong, missing trailing comma (means an int, not a tuple containing ints).
@returnType ( (int, ) ) # correct.
There are a number of situations where you cannot pass ordinary python types to annotations.
For example:
Class A:
@parameterTypes( selfType, A )
def compare(self, other):
return self.id == other.id
This is an ordinary comparison method.
Unfortunately, this annotation refers to class A within the definition of class A.
As such, it is undefined.
@parameterTypes( selfType, 'A' )
The solution is to quote the class in a string.
The annotations use lazy evaluation of their arguments.
You can string-escape multiple types in a single string. The following are equivalent:
@returnType ( str, int )
@returnType ( 'str', int )
@returnType ( ' str, int ' )
String-escaped and raw types can be mixed and matched arbitrarily:
@returnType ( 'str, Class1', str, 'int', str, 'Class2, Class1')
Python does not permit circular imports.
ie. if module A imports module B, B cannot also import A.
A class cannot be referenced in an annotation if it is not imported - even if string-escaped.
A solution is to use ClassName.
@parameterTypes( selfType, ClassName('TestClass1' ) )
def doSomething(self, other):
pass
- ClassName compares the designated class name (ie. 'TestClass1') with the name of the arguments class and superclasses.
- ClassName ignores module path (ie. 'utils.tests.Something.TestClass1').
- ClassName will not distinguish between classes with identical names.
- ClassName itself can be string-escaped (see above).
- Generally speaking, "String-Escaping" types is more convenient and concise than using ClassName.
Only use ClassName when you must (ie. when you cannot import the external class).
Other options are to use ignoreType, or not use an annotation in this case.
The arguments for @parameterTypes, @returnType, @privateMethod and @raises are optional.
The @abstractMethod and @deprecatedMethod annotations has no arguments.
These three forms:
@returnType
@returnType ( )
@returnType ( ' ' )
all mean the same thing: this method returns nothing (a value of type NoneType).
-
These annotations don't yet support "Positional Parameters" (ie. *args) or "Keyword Parameters" (ie. **argkw).
-
I'm not sure of the best way to annotate classes. One approach would be to annotate a stub new (class initialization) method.
-
No support yet for duck typing. This could easily be added by passing a validation function instead of a type or typename.
-
It would be nice to hide the annotations in stack traces.
-
It would also be nice to hide the implementation details of the annotations, so that all exceptions raised by the annotations appeared to have only a single reference in the stack to the annotations.
- We could easily modify the @privateMethod annotation to raise an exception on non-local access to a method. In fact, it could take a list of classes (friends?) that would be permitted access.
- @tbGetter and @tbSetter / @tbAccessor.
-
We could alter the type checking syntax to indicate that parameters cannot be 'None'. This would be more in the realm of assertions than type checking.
-
see Python Decorator Library at python.org.
These annotations have a common theme of bringing keywords and annotations
familiar to Java and C++ users into the Python world.
Given that these languages reflect a very different design philosophy from Python, this may seem questionable.
That is, are Pyanno annotations
"Pythonic"?
On the one hand, Pyanno annotations would have no value if Python was statically-typed, like Java or C++.
But Pyanno annotations do not make Python a statically-typed language,
(see
this).
After all, Pyanno type-checking occurs at run-time, not compile time.
It's not a question of statically-type or dynamic-typing, but of access to type-checking at our own discretion.
One can apply the annotations as narrowly as you like.
For example, you may only want to annotate the public interface for a library or module.
In this way, Pyanno annotations help offset a potential weakness of the language.
In many ways, their real value lies in providing more accurate documentation rather than helping to guarantee correctness.
-
Question: Why isn't Pyanno version 1.0?
Answer: Pyanno is a fairly new project.
Version 0.77 released August 28th, 2007.
Version 0.76 released August 11th, 2007.
-
Added the @deprecated, @privateMethod and @protectedMethod annotations.
-
Added type-checking of the arguments to the @raises annotation.
-
Improved the documentation.
-
Elaborated the unit test suite, which is still incomplete.
The unit tests are not part of the source distribution.
Version 0.75 released August 8th, 2007.
To do list & known bugs:
- Add a @deprecated annotation.
-
Pyanno requires Python 2.4 or higher.
-
Pyanno has no dependencies. It uses sip if available.
Pyanno annotations are implemented with Python's function decorators feature (new in Python 2.4):
In the interest of improving my goolge karma, allow me to mention:
python annotations,
annotating python,
python function decorators,
type safe python,
strongly typed python,
statically typed python,
python documentation,
python type safety,
python type checking,
python function decorators,
metaprogramming,
python introspection,


Resources Overview
This is an overview of the resources of your simulation. See the KPIs of the resources of the whole simulation scenario on the cards
below. Clicking on the Show details button will lead you to a detailed overview of the selected resource and its instances.
{{ resource.type }}
Show Details


Stewart-Haas to replace Suarez with Custer for 2020 NASCAR Cup
by Jim UtterStewart-Haas Racing will promote its Xfinity Series driver Cole Custer to replace Daniel Suarez in its NASCAR Cup Series line-up for 2020, Autosport has learned.
Sources have suggested the 21-year-old's deal will be officially announced within the coming week.
A request for comment from a SHR spokesperson was not immediately returned.
Custer is one of four drivers who will compete for the 2019 Xfinity title at Homestead this weekend.
Suarez, the 2016 Xfinity Series champion, joined SHR this season in a one-year deal after losing his Joe Gibbs Racing seat to Martin Truex Jr.
While he has shown flashes of competitiveness, Suarez failed to make the playoffs and so far this season has just four top-five finishes.
SHR is retaining Kevin Harvick, Kurt Busch and Clint Bowyer as the rest of its line-up.
It is also beginning a technical partnership with the small Go Fas team for next season, with no driver allocated to that entry yet.


| cli_text {cli} | R Documentation |
It is wrapped to the screen width automatically. It may contain inline markup. (See inline-markup.)
cli_text(..., .envir = parent.frame())
... |
The text to show, in character vectors. They will be concatenated into a single string. Newlines are not preserved. |
.envir |
Environment to evaluate the glue expressions in. |
cli_text("Hello world!") cli_text(packageDescription("cli")$Description) ## Arguments are concatenated cli_text("this", "that") ## Command substitution greeting <- "Hello" subject <- "world" cli_text("{greeting} {subject}!") ## Inline theming cli_text("The {.fn cli_text} function in the {.pkg cli} package") ## Use within container elements ul <- cli_ul() cli_li() cli_text("{.emph First} item") cli_li() cli_text("{.emph Second} item") cli_end(ul)


Special surprise for 7-year-old who asked Santa for food and a house
So many people have responded to the heartbreaking letter - and now Christmas is going to be a lot better for the family
by Liam ThorpA 7-year-old child who wrote a letter to Father Christmas asking for a house and some food for her family is set to get some amazing Christmas surprises after a staggering amount of money was raised.
This week the ECHO reported how Liverpool Councillor Gerard Woodhouse - who runs the L6 Community Centre in Everton - found the heartbreaking letter in the Santa Postbox in the centre.
It said: "Dear Father Christmas. Can you help? Can we have a home for Christmas?
"Mam wants us to be all together, can you give us some food and can I just have just nice doll for Christmas. Thank you."
Since the note was made public, a huge number of people have reached out to offer support to the family and to the L6 Centre that helps many struggling people in north Liverpool.
Cllr Woodhouse said that since the letter was featured in the ECHO and shared on social media, the centre has received close to £10,000 in donations.
He explained how this money will be used to help the child's family and others.
He said: "We cannot thank the public enough.
"All the money raised will be spend on supporting families who are referred to us to try and make there Christmas special.
"We are supporting the family of the child who wrote the letter with presents and a 3-day stay in a hotel over the Christmas period for the mum and kids, who do not usually live together."
The plight of the child and their family has touched hearts all across the country.
Amongst those offering support have been a local footballer and reality television star Gemma Collins.
If you want to contribute to the L6 fund, click here


# -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import grpc
from google import auth as google_auth
from google.auth import jwt as google_auth_jwt
from google.auth.transport import grpc as google_auth_transport_grpc
from google.auth.transport import requests as google_auth_transport_requests
from airflow.hooks.base_hook import BaseHook
from airflow.exceptions import AirflowConfigException
[docs]class GrpcHook(BaseHook):
"""
General interaction with gRPC servers.
"""
def __init__(self, grpc_conn_id, interceptors=None, custom_connection_func=None):
"""
:param grpc_conn_id: The connection ID to use when fetching connection info.
:type grpc_conn_id: str
:param interceptors: a list of gRPC interceptor objects which would be applied
to the connected gRPC channel. None by default.
:type interceptors: a list of gRPC interceptors based on or extends the four
official gRPC interceptors, eg, UnaryUnaryClientInterceptor,
UnaryStreamClientInterceptor, StreamUnaryClientInterceptor,
StreamStreamClientInterceptor.
::param custom_connection_func: The customized connection function to return gRPC channel.
:type custom_connection_func: python callable objects that accept the connection as
its only arg. Could be partial or lambda.
"""
self.grpc_conn_id = grpc_conn_id
self.conn = self.get_connection(self.grpc_conn_id)
self.extras = self.conn.extra_dejson
self.interceptors = interceptors if interceptors else []
self.custom_connection_func = custom_connection_func
[docs] def get_conn(self):
base_url = self.conn.host
if self.conn.port:
base_url = base_url + ":" + str(self.conn.port)
auth_type = self._get_field("auth_type")
if auth_type == "NO_AUTH":
channel = grpc.insecure_channel(base_url)
elif auth_type == "SSL" or auth_type == "TLS":
credential_file_name = self._get_field("credential_pem_file")
creds = grpc.ssl_channel_credentials(open(credential_file_name).read())
channel = grpc.secure_channel(base_url, creds)
elif auth_type == "JWT_GOOGLE":
credentials, _ = google_auth.default()
jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials(
credentials)
channel = google_auth_transport_grpc.secure_authorized_channel(
jwt_creds, None, base_url)
elif auth_type == "OATH_GOOGLE":
scopes = self._get_field("scopes").split(",")
credentials, _ = google_auth.default(scopes=scopes)
request = google_auth_transport_requests.Request()
channel = google_auth_transport_grpc.secure_authorized_channel(
credentials, request, base_url)
elif auth_type == "CUSTOM":
if not self.custom_connection_func:
raise AirflowConfigException(
"Customized connection function not set, not able to establish a channel")
channel = self.custom_connection_func(self.conn)
else:
raise AirflowConfigException(
"auth_type not supported or not provided, channel cannot be established,\
given value: %s" % str(auth_type))
if self.interceptors:
for interceptor in self.interceptors:
channel = grpc.intercept_channel(channel,
interceptor)
return channel
[docs] def run(self, stub_class, call_func, streaming=False, data={}):
with self.get_conn() as channel:
stub = stub_class(channel)
try:
rpc_func = getattr(stub, call_func)
response = rpc_func(**data)
if not streaming:
yield response
else:
for single_response in response:
yield single_response
except grpc.RpcError as ex:
self.log.exception(
"Error occurred when calling the grpc service: {0}, method: {1} \
status code: {2}, error details: {3}"
.format(stub.__class__.__name__, call_func, ex.code(), ex.details()))
raise ex
[docs] def _get_field(self, field_name, default=None):
"""
Fetches a field from extras, and returns it. This is some Airflow
magic. The grpc hook type adds custom UI elements
to the hook page, which allow admins to specify scopes, credential pem files, etc.
They get formatted as shown below.
"""
full_field_name = 'extra__grpc__{}'.format(field_name)
if full_field_name in self.extras:
return self.extras[full_field_name]
else:
return default


#include <PxConstraintDesc.h>
Public Member Functions | |
| virtual void | visualizeJointFrames (const PxTransform &parent, const PxTransform &child)=0 |
| virtual void | visualizeLinearLimit (const PxTransform &t0, const PxTransform &t1, PxReal value, bool active)=0 |
| virtual void | visualizeAngularLimit (const PxTransform &t0, PxReal lower, PxReal upper, bool active)=0 |
| virtual void | visualizeLimitCone (const PxTransform &t, PxReal tanQSwingY, PxReal tanQSwingZ, bool active)=0 |
| virtual void | visualizeDoubleCone (const PxTransform &t, PxReal angle, bool active)=0 |
| virtual void | visualizeLine (const PxVec3 &p0, const PxVec3 &p1, PxU32 color)=0 |
Protected Member Functions | |
| virtual | ~PxConstraintVisualizer () |
API used to visualize details about a constraint.
|
inlineprotectedvirtual |
|
pure virtual |
Visualize joint angular limit
| [in] | t0 | Transformation for the visualization |
| [in] | lower | Lower limit angle |
| [in] | upper | Upper limit angle |
| [in] | active | State of the joint - active/inactive |
|
pure virtual |
Visualize joint double cone
| [in] | t | Transformation for the visualization |
| [in] | angle | Limit angle |
| [in] | active | State of the joint - active/inactive |
|
pure virtual |
Visualize joint frames
| [in] | parent | Parent transformation |
| [in] | child | Child transformation |
|
pure virtual |
Visualize limit cone
| [in] | t | Transformation for the visualization |
| [in] | tanQSwingY | Tangent of the quarter Y angle |
| [in] | tanQSwingZ | Tangent of the quarter Z angle |
| [in] | active | State of the joint - active/inactive |
|
pure virtual |
Visualize line
| [in] | p0 | Start position |
| [in] | p1 | End postion |
| [in] | color | Color |
|
pure virtual |
Visualize joint linear limit
| [in] | t0 | Base transformation |
| [in] | t1 | End transformation |
| [in] | value | Distance |
| [in] | active | State of the joint - active/inactive |


2023-08-06
Starting tomorrow, I’ll attend a “half batch” of six weeks at the Recurse Center, a programming retreat. After lots of research and prep work, I booked some accommodation and flights, and arrived in Brooklyn yesterday. I’m very glad my combined Swiss–Toronto background has prepared me for high cost of living, but New York certainly puts all that into (expensive) perspective.
For the first two weeks, I’ll stay in Carroll Gardens, and then for three weeks in Prospect Heights. I still have to figure out something for the last week, but I hope that’ll be easier, being here and all.
The first two days, tomorrow and the day after tomorrow, have the hub not yet open for people starting their batch, to make sure everybody’s onboarding experience is the same, i.e., online. The hub was closed for over two years, and all batches took place online; it was reopened in June for a trial period of about three months—and recently, it was decided to keep it open until further notice!
Batches are now a mix of people attending virtually and in-person, and I wanted to wait until in-person was possible again. The trial also lined up well with my five-year anniversary at work, which gives me some extra time off in the form of a sabbatical. As far as I can tell, there is going to be a good number of in-person Recursers.
A big challenge was sifting through my long list of projects and selecting some that would be a good fit: challenging, but not so hard that I’d only get to “hello world” in six weeks, exciting, enabling me to learn new things…
To give you an idea of the unfiltered selection, here’s what the list initially looked like:
In the end, I settled on two projects: a main project, and a less challenging fallback project.
For the fallback project, I’m going to start reading the Pickaxe book to learn Ruby, and after a while start the Building Git project.
But for the main course, and notice how that wasn’t on the original list 😬 I want to work on a virtual “physical environment”. I’m envisioning a three-dimensional room with objects in it that behaves as if it were attached to the viewer, which could be a Google Cardboard, or a VR headset; imagine a ball in the room, which should roll towards the viewer when leaning back, to the right when tilting the viewer clockwise, and so on.
I think this could be web-based, using whatever magic there is when you can select “view in VR” on a website. This project would combine a lot of things for me:
Two of the three self-directives of Recurse Center are “build your volitional muscles”, and “learn generously”. (The third one is “work at the edge of your abilities”, which I think the previous section covers.)
I understand the “volitional muscle” as becoming good at realizing what excites me the most, and then acting on that realization. In other words (and as pretty much all alumni I’ve spoken with confirmed), the projects you planned working on might not be what you end up working on in reality. Especially for me, doing just half a batch, I think it is thus important to focus on my initial project to reach a “breaking point” sooner rather than later. The one scenario I want to avoid is realizing that I don’t want to work on a project a few days before my batch ends.
And learning generously is about sharing, pairing, demo-ing… one way I plan on doing that is by blogging regularly (hence this post!). Since this is still based on my own, very minimal static site generator, there’s no RSS feed to subscribe to—yet! I’ll try and add one during the first week or so.


public class StereoHttpRequestHandler
extends java.lang.Object
| Constructor and Description |
|---|
StereoHttpRequestHandler(org.apache.http.HttpRequest httpRequest)
Construct an NIO Request
|
| Modifier and Type | Method and Description |
|---|---|
StereoHttpRequestHandler |
andThen(java.lang.Runnable afterMapper)
After everything (error or not) do this.
|
StereoHttpRequestHandler |
cancelling(java.lang.Runnable cancellationMapper)
When the response is cancelled, if the cancellation mapper is set
it will be called.
|
StereoHttpRequestHandler |
exceptionally(java.util.function.Consumer<java.lang.Exception> exceptionMapper)
When the response fails, if the error mapper is set
it will be called with the exception.
|
org.apache.http.concurrent.FutureCallback<org.apache.http.HttpResponse> |
getApacheHttpCallback() |
org.apache.http.HttpRequest |
getRequest() |
StereoHttpRequestHandler |
map(java.util.function.Consumer<StereoResponse> mapper)
When the response is available, if the completion mapper is set
it will be called with the response.
|
public StereoHttpRequestHandler(org.apache.http.HttpRequest httpRequest)
httpRequest
- the HttpRequest
public org.apache.http.HttpRequest getRequest()
public org.apache.http.concurrent.FutureCallback<org.apache.http.HttpResponse> getApacheHttpCallback()
public StereoHttpRequestHandler map(java.util.function.Consumer<StereoResponse> mapper)
mapper
- a Consumer to accept the response.StereoHttpRequestHandler
public StereoHttpRequestHandler exceptionally(java.util.function.Consumer<java.lang.Exception> exceptionMapper)
exceptionMapper
- a Consumer to accept the error.StereoHttpRequestHandler
public StereoHttpRequestHandler cancelling(java.lang.Runnable cancellationMapper)
cancellationMapper
- a Consumer to accept the cancellation.StereoHttpRequestHandler
public StereoHttpRequestHandler andThen(java.lang.Runnable afterMapper)
afterMapper
- a Runnable to run after.StereoHttpRequestHandler


The industry's first standards-compliant AJAX based solution for rapidly creating all Java rich web applications that are easily maintained, extended, and scaled, at very low cost.


n_censored = total_count - n_events
// offset cumulative sum by one
total_count = numpy.concatenate(([0], total_count))
n_at_risk = n_samples - numpy.cumsum(total_count)
return times, n_events, n_at_risk[:-1], n_censored
n_censored = total_count - n_events
// offset cumulative sum by one
total_count = numpy.r_[0, total_count]
n_at_risk = n_samples - numpy.cumsum(total_count)
return times, n_events, n_at_risk[:-1], n_censored


Name of the podTemplate to inherit from.
A podTemplate may or may not inherit from an existing template.
This means that the podTemplate will inherit node selector, service account, image pull secrets, containerTemplates and volumes from the template it inherits from.
Service account and Node selector, when overridden, completely replace any value found on the “parent”.
Container templates that are added to the podTemplate, that has a matching containerTemplate (a containerTemplate with the same name) in the parent template, will inherit the configuration of the parent containerTemplate.
If no matching containerTemplate is found, the template is added as is.
Image Pull Secrets are combined (all secrets defined both on 'parent' and 'current' template are used).
By default, pod template inherits outer pod template definitions.
Inheritance can be stopped by using the empty string.


--- title: Code of Conduct ---
All attendees, speakers, sponsors and volunteers at our meetup are required to agree with the following code of conduct. Organizers will enforce this code throughout the event. We are expecting cooperation from all participants to help ensuring a safe environment for everybody.
TL;DR: Don’t be a Jerk
Our meetup is dedicated to providing a harassment-free meetup experience for everyone, regardless of gender, age, sexual orientation, disability, physical appearance, body size, race, or religion. We do not tolerate harassment of meetup participants in any form. Sexual language and imagery is not appropriate for any meetup venue, including talks, workshops, parties, Twitter and other online media. Conference participants violating these rules may be sanctioned or expelled from the meetup at the discretion of the meetup organizers.

Participants asked to stop any harassing behavior are expected to comply immediately.
Sponsors are also subject to the anti-harassment policy. In particular, sponsors should not use sexualised images, activities, or other material. Sponsors, volunteers, and speakers should not use sexualised clothing/uniforms/costumes, or otherwise create a sexualised environment.
If a participant engages in harassing behavior, the meetup organisers may take any action they deem appropriate, including warning the offender or expulsion from the meetup with no refund (if applicable).
If you are being harassed, notice that someone else is being harassed, or have any other concerns, please alert a meetup organizer immediately. Meetup organizers can be identified in person and can also be contacted via the meetup group page.
Meetup organizers will be happy to help participants contact venue security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the event and at future meetups. We value your attendance.
We expect participants to follow these rules at meetup venues, on the meetup page, and on meetup-related social media and websites.


MIxS Environmental Packages
Packages
The original MIGS/MIMS checklists included contextual data about the location from which a sample was isolated and how the sequence data were produced. However, standard descriptions for a more comprehensive range of environmental parameters, which would help to better contextualize a sample, were not included.
As of release 5.0, the following environmental packages are under the MIxS umbrella:
- Air
- Built-environment
- Host-associated
- Human-associated
- Human-gut
- Human-oral
- Human-skin
- Human-vaginal
- Hydrocarbon resources-cores
- Hydrocarbon resources-fluids/swabs
- Microbial mat/biofilm
- Miscellaneous natural or artificial environment
- Plant-associated
- Sediment
- Soil
- Wastewater/sludge
- Water
Seventeen environmental packages provide a wealth of environmental and epidemiological contextual data fields for a complete description of sampling environments. The environmental packages can be combined with any of the MIxS checklists. The package names describe high-level habitat terms in order to be exhaustive. The miscellaneous natural or artificial environment package contains a generic set of parameters, and is included for any other habitat that does not fall into the other categories. Whenever needed, multiple packages may be used for the description of the environment.
Legend (accessory elements)
As with the MIxS checklists, all descriptors in MIxS environmental packages are also complemented by accessory information that assists in correct usage and parsing of a descriptor.
- environmental package: name of the package descriptor belongs to; a descriptor may belong to multiple packages
- structured comment name: short name of a package descriptor. Consists of small case letters and underscores, and no spaces, desirable length no more than 30 characters
- item: full name of a package descriptor; should be short but also illustrative of the descriptor's purpose
- definition: an extended definition of the descriptor; including links to ontologies and other resources that can be used to fill in values for the descriptor
- package requirement: certain descriptors are mandatory for some packages, for example ‘depth’ is mandatory when using packages water, sediment or soil:
- mandatory (M): descriptor must be present for compliance with the package
- conditional mandatory (C): descriptor must be present for compliance with the package, but only when applicable to the study, i.e. if this item is not applicable for the study the metadata data will still be compliant even if it is left out
- optional (X): descriptor may or may not be present, not mandatory for compliance with checklist
- expected value: short definition and/or expected value of a descriptor; expressed in simple terms, such as boolean, date and time, measurement value, ontology name where applicable
- value syntax: a pseudo-code representation of the expected value of a given descriptor, for parsing purposes. if descriptor is of type enumeration, then the associated controlled vocabulary is also given here
- occurrence: indicates if a given descriptor may be used only once (1), multiple times (m), or none (0)
- position: position/pseudo-id of descriptor as it appears in ordered-lists of package descriptors
- preferred units: a unit suggestion if a descriptor is for a measurement value


Web container for Object Detection Project.
This simple project showcases end-2-end how to detect objects - birds
- in an outdoor environment using various external image detector APIs
The outdoor environement selected was the back garden!
of my house
The various cognitive API/libraries used were: Google, Azure, mobileNet, Yolo Detector.
Base filtering was undertaken with OpenCV 2.0
Scalability is achieved using Azure Event Hub feature at the messaging level and utilising docker images at the infrastructure level


Returns the index of the last occurrence of a character in a string, searching backward from a start index.
Syntax
|
LAST_INDEX_OF(expression) |
Terms
|
string |
The string to be searched. |
|
'character' |
The character being searched for, in quotes. |
|
startIndex |
The index from which to begin the backward search. The string index begins with zero (0). |
Usage
Use the LAST_INDEX_OF function to determine the index of the last occurrence of a character in a string. The backward search for the character begins at the designated start index.
LCFIRST
Converts the first character in a string to lower case.
Syntax
|
LCFIRST(expression) |
Terms
|
expression |
An expression whose result type is chararray. |
Usage
Use the LCFIRST function to convert only the first character in a string to lower case.
LOWER
Converts all characters in a string to lower case.
Syntax
|
LOWER(expression) |
Terms
|
expression |
An expression whose result type is chararray. |
Usage
Use the LOWER function to convert all characters in a string to lower case.
REGEX_EXTRACT
Performs regular expression matching and extracts the matched group defined by an index parameter.
Syntax
|
REGEX_EXTRACT (string, regex, index) |
Terms
|
string |
The string in which to perform the match. |
|
regex |
The regular expression. |
|
index |
The index of the matched group to return. |
Usage
Use the REGEX_EXTRACT function to perform regular expression matching and to extract the matched group defined by the index parameter (where the index is a 1-based parameter.) The function uses Java regular expression form.
The function returns a string that corresponds to the matched group in the position specified by the index. If there is no matched expression at that position, NULL is returned.
Example
This example will return the string '<IP_ADDRESS>'.
REGEX_EXTRACT('<IP_ADDRESS>:8020', '(.*)\:(.*)', 1);
REGEX_EXTRACT_ALL
Performs regular expression matching and extracts all matched groups.
Syntax
|
REGEX_EXTRACT (string, regex) |
Terms
|
string |
The string in which to perform the match. |
|
regex |
The regular expression. |
Usage
Use the REGEX_EXTRACT_ALL function to perform regular expression matching and to extract all matched groups. The function uses Java regular expression form.
The function returns a tuple where each field represents a matched expression. If there is no match, an empty tuple is returned.
Example
This example will return the tuple (<IP_ADDRESS>,8020).
REGEX_EXTRACT_ALL('<IP_ADDRESS>:8020', '(.*)\:(.*)');
REPLACE
Replaces existing characters in a string with new characters.
Syntax
|
REPLACE(string, 'oldChar', 'newChar'); |
Terms
|
string |
The string to be updated. |
|
'oldChar' |
The existing characters being replaced, in quotes. |
|
'newChar' |
The new characters replacing the existing characters, in quotes. |
Usage
Use the REPLACE function to replace existing characters in a string with new characters.
For example, to change "open source software" to "open source wiki" use this statement: REPLACE(string,'software','wiki');
STRSPLIT
Splits a string around matches of a given regular expression.
Syntax
|
STRSPLIT(string, regex, limit) |
Terms
|
string |
The string to be split. |
|
regex |
The regular expression. |
|
Limit |
The number of times the pattern (the compiled representation of the regular expression) is applied. |
Usage
Use the STRSPLIT function to split a string around matches of a given regular expression.
For example, given the string (open:source:software), STRSPLIT (string, ':',2) will return ((open,source:software)) and STRSPLIT (string, ':',3) will return ((open,source,software)).
SUBSTRING
Returns a substring from a given string.
Syntax
|
SUBSTRING(string, startIndex, stopIndex) |
Terms
|
string |
The string from which a substring will be extracted. |
|
startIndex |
The index (type integer) of the first character of the substring. The index of a string begins with zero (0). |
|
stopIndex |
The index (type integer) of the character following the last character of the substring. |
Usage
Use the SUBSTRING function to return a substring from a given string.
Given a field named alpha whose value is ABCDEF, to return substring BCD use this statement: SUBSTRING(alpha,1,4). Note that 1 is the index of B (the first character of the substring) and 4 is the index of E (the character following the last character of the substring).
TRIM
Returns a copy of a string with leading and trailing white space removed.
Syntax
|
TRIM(expression) |
Terms
|
expression |
An expression whose result is chararray. |
Usage
Use the TRIM function to remove leading and trailing white space from a string.
UCFIRST
Returns a string with the first character converted to upper case.
Syntax
|
UCFIRST(expression) |
Terms
|
expression |
An expression whose result type is chararray. |
Usage
Use the UCFIRST function to convert only the first character in a string to upper case.
UPPER
Returns a string converted to upper case.
Syntax
|
UPPER(expression) |
Terms
|
expression |
An expression whose result type is chararray. |
Usage
Use the UPPER function to convert all characters in a string to upper case.
Bag and Tuple Functions
TOBAG
Converts one or more expressions to type bag.
Syntax
|
TOBAG(expression [, expression ...]) |
Terms
|
expression |
An expression with any data type. |
Usage
Use the TOBAG function to convert one or more expressions to individual tuples which are then placed in a bag.
Example
In this example, fields f1 and f3 are converted to tuples that are then placed in a bag.
a = LOAD 'student' AS (f1:chararray, f2:int, f3:float); DUMP a; (John,18,4.0) (Mary,19,3.8) (Bill,20,3.9) (Joe,18,3.8) b = FOREACH a GENERATE TOBAG(f1,f3); DUMP b; ({(John),(4.0)}) ({(Mary),(3.8)}) ({(Bill),(3.9)}) ({(Joe),(3.8)})
TOP
Returns the top-n tuples from a bag of tuples.
Syntax
|
TOP(topN,column,relation) |
Terms
|
topN |
The number of top tuples to return (type integer). |
|
column |
The tuple column whose values are being compared. |
|
relation |
The relation (bag of tuples) containing the tuple column. |
Usage
TOP function returns a bag containing top N tuples from the input bag where N is controlled by the first parameter to the function. The tuple comparison is performed based on a single column from the tuple. The column position is determined by the second parameter to the function. The function assumes that all tuples in the bag contain an element of the same type in the compared column
Example
In this example the top 10 occurrences are returned.
A = LOAD 'data' as (first: chararray, second: chararray); B = GROUP A BY (first, second); C = FOREACH B generate FLATTEN(group), COUNT(*) as count; D = GROUP C BY first; // again group by first topResults = FOREACH D { result = TOP(10, 2, C); // and retain top 10 occurrences of 'second' in first GENERATE FLATTEN(result); }
TOTUPLE
Converts one or more expressions to type tuple.
Syntax
|
TOTUPLE(expression [, expression ...]) |
Terms
|
expression |
An expression of any datatype. |
Usage
Use the TOTUPLE function to convert one or more expressions to a tuple.
Example
In this example, fields f1, f2 and f3 are converted to a tuple.
a = LOAD 'student' AS (f1:chararray, f2:int, f3:float); DUMP a; (John,18,4.0) (Mary,19,3.8) (Bill,20,3.9) (Joe,18,3.8) b = FOREACH a GENERATE TOTUPLE(f1,f2,f3); DUMP b; ((John,18,4.0)) ((Mary,19,3.8)) ((Bill,20,3.9)) ((Joe,18,3.8))
File Commands
Note: Beginning with Pig 0.6.0, the file commands are now deprecated and will be removed in a future release. Start using Pig's -fs command to invoke the shell commands shell commands.
cat
Prints the content of one or more files to the screen.
Syntax
|
cat path [ path …] |
Terms
|
path |
The location of a file or directory. |
Usage
The cat command is similar to the Unix cat command. If multiple files are specified, content from all files is concatenated together. If multiple directories are specified, content from all files in all directories is concatenated together.
Example
In this example the students file in the data directory is printed.
grunt> cat data/students; joe smith john adams anne white
cd
Changes the current directory to another directory.
Syntax
|
cd [dir] |
Terms
|
dir |
The name of the directory you want to navigate to. |
Usage
The cd command is similar to the Unix cd command and can be used to navigate the file system. If a directory is specified, this directory is made your current working directory and all other operations happen relatively to this directory. If no directory is specified, your home directory (/user/NAME) becomes the current working directory.
Example
In this example we move to the /data directory.
grunt> cd /data
copyFromLocal
Copies a file or directory from the local file system to HDFS.
Syntax
|
copyFromLocal src_path dst_path |
Terms
|
src_path |
The path on the local file system for a file or directory |
|
dst_path |
The path on HDFS. |
Usage
The copyFromLocal command enables you to copy a file or a director from the local file system to the Hadoop Distributed File System (HDFS). If a directory is specified, it is recursively copied over. Dot "." can be used to specify that the new file/directory should be created in the current working directory and retain the name of the source file/directory.
Example
In this example a file (students) and a directory (/data/tests) are copied from the local file system to HDFS.
grunt> copyFromLocal /data/students students grunt> ls students /data/students <r 3> 8270 grunt> copyFromLocal /data/tests new_tests grunt> ls new_test /data/new_test/test1.data <r 3> 664 /data/new_test/test2.data <r 3> 344 /data/new_test/more_data
copyToLocal
Copies a file or directory from HDFS to a local file system.
Syntax
|
copyToLocal src_path dst_path |
Terms
|
src_path |
The path on HDFS. |
|
dst_path |
The path on the local file system for a file or directory. |
Usage
The copyToLocal command enables you to copy a file or a director from Hadoop Distributed File System (HDFS) to a local file system. If a directory is specified, it is recursively copied over. Dot "." can be used to specify that the new file/directory should be created in the current working directory (directory from which the script was executed or grunt shell started) and retain the name of the source file/directory.
Example
In this example two files are copied from HDFS to the local file system.
grunt> copyToLocal students /data grunt> copyToLocal data /data/mydata
cp
Copies a file or directory within HDFS.
Syntax
|
cp src_path dst_path |
Terms
|
src_path |
The path on HDFS. |
|
dst_path |
The path on HDFS. |
Usage
The cp command is similar to the Unix cp command and enables you to copy files or directories within DFS. If a directory is specified, it is recursively copied over. Dot "." can be used to specify that the new file/directory should be created in the current working directory and retain the name of the source file/directory.
Example
In this example a file (students) is copied to another file (students_save).
grunt> cp students students_save
ls
Lists the contents of a directory.
Syntax
|
ls [path] |
Terms
|
path |
The name of the path/directory. |
Usage
The ls command is similar to the Unix ls command and enables you to list the contents of a directory. If DIR is specified, the command lists the content of the specified directory. Otherwise, the content of the current working directory is listed.
Example
In this example the contents of the data directory are listed.
grunt> ls /data /data/DDLs <dir> /data/count <dir> /data/data <dir> /data/schema <dir>
mkdir
Creates a new directory.
Syntax
|
mkdir path |
Terms
|
path |
The name of the path/directory. |
Usage
The mkdir command is similar to the Unix mkdir command and enables you to create a new directory. If you specify a directory or path that does not exist, it will be created.
Example
In this example a directory and subdirectory are created.
grunt> mkdir data/20070905
mv
Moves a file or directory within the Hadoop Distributed File System (HDFS).
Syntax
|
mv src_path dst_path |
Terms
|
src_path |
The path on HDFS. |
|
dst_path |
The path on HDFS. |
Usage
The mv command is identical to the Unix mv command (which copies files or directories within DFS) except that it deletes the source file or directory as soon as it is copied.
If a directory is specified, it is recursively moved. Dot "." can be used to specify that the new file/directory should be created in the current working directory and retain the name of the source file/directory.
Example
In this example the output directory is copied to output2 and then deleted.
grunt> mv output output2 grunt> ls output File or directory output does not exist. grunt> ls output2 /data/output2/map-000000<r 3> 508844 /data/output2/output3 <dir> /data/output2/part-00000<r 3> 0
pwd
Prints the name of the current working directory.
Syntax
|
pwd |
Terms
|
none |
no parameters |
Usage
The pwd command is identical to Unix pwd command and it prints the name of the current working directory.
Example
In this example the name of the current working directory is /data.
grunt> pwd /data
rm
Removes one or more files or directories.
Syntax
|
rm path [path…] |
Terms
|
path |
The name of the path/directory/file. |
Usage
The rm command is similar to the Unix rm command and enables you to remove one or more files or directories.
Note: This command recursively removes a directory even if it is not empty and it does not confirm remove and the removed data is not recoverable.
Example
In this example files are removed.
grunt> rm /data/students grunt> rm students students_sav
rmf
Forcibly removes one or more files or directories.
Syntax
|
rmf path [path …] |
Terms
|
path |
The name of the path/directory/file. |
Usage
The rmf command is similar to the Unix rm -f command and enables you to forcibly remove one or more files or directories.
Note: This command recursively removes a directory even if it is not empty and it does not confirm remove and the removed data is not recoverable.
Example
In this example files are forcibly removed.
grunt> rmf /data/students grunt> rmf students students_sav
Shell Commands
fs
Invokes any FSShell command from within a Pig script or the Grunt shell.
Syntax
|
fs subcommand subcommand_parameters |
Terms
|
subcommand |
The FSShell command. |
|
subcommand_parameters |
The FSShell command parameters. |
Usage
Use the fs command to invoke any FSShell command from within a Pig script or Grunt shell. The fs command greatly extends the set of supported file system commands and the capabilities supported for existing commands such as ls that will now support globing. For a complete list of FSShell commands, see File System Shell Guide
Examples
In these examples a directory is created, a file is copied, a file is listed.
fs -mkdir /tmp fs -copyFromLocal file-x file-y fs -ls file-y
sh
Invokes any sh shell command from within a Pig script or the Grunt shell.
Syntax
|
sh subcommand subcommand_parameters |
Terms
|
subcommand |
The sh shell command. |
|
subcommand_parameters |
The sh shell command parameters. |
Usage
Use the sh command to invoke any sh shell command from within a Pig script or Grunt shell.
Note that only real programs can be run form the sh command. Commands such as cd are not programs but part of the shell environment and as such cannot be executed unless the user invokes the shell explicitly, like "bash cd".
Example
In this example the ls command is invoked.
grunt> sh ls bigdata.conf nightly.conf ..... grunt>
Utility Commands
exec
Run a Pig script.
Syntax
|
exec [–param param_name = param_value] [–param_file file_name] script |
Terms
|
–param param_name = param_value |
See Parameter Substitution. |
|
–param_file file_name |
See Parameter Substitution. |
|
script |
The name of a Pig script. |
Usage
Use the exec command to run a Pig script with no interaction between the script and the Grunt shell (batch mode). Aliases defined in the script are not available to the shell; however, the files produced as the output of the script and stored on the system are visible after the script is run. Aliases defined via the shell are not available to the script.
With the exec command, store statements will not trigger execution; rather, the entire script is parsed before execution starts. Unlike the run command, exec does not change the command history or remembers the handles used inside the script. Exec without any parameters can be used in scripts to force execution up to the point in the script where the exec occurs.
For comparison, see the run command. Both the exec and run commands are useful for debugging because you can modify a Pig script in an editor and then rerun the script in the Grunt shell without leaving the shell. Also, both commands promote Pig script modularity as they allow you to reuse existing components.
Examples
In this example the script is displayed and run.
grunt> cat myscript.pig a = LOAD 'student' AS (name, age, gpa); b = LIMIT a 3; DUMP b; grunt> exec myscript.pig (alice,20,2.47) (luke,18,4.00) (holly,24,3.27)
In this example parameter substitution is used with the exec command.
grunt> cat myscript.pig a = LOAD 'student' AS (name, age, gpa); b = ORDER a BY name; STORE b into '$out'; grunt> exec –param out=myoutput myscript.pig
In this example multiple parameters are specified.
grunt> exec –param p1=myparam1 –param p2=myparam2 myscript.pig
help
Prints a list of Pig commands or properties.
Syntax
|
-help [properties] |
Terms
|
properties |
List Pig properties. |
Usage
The help command prints a list of Pig commands or properties.
Example
Use "help" to get a list of commands.
$ pig -help Apache Pig version 0.8.0-dev (r987348) compiled Aug 19 2010, 16:38:44 USAGE: Pig [options] [-] : Run interactively in grunt shell. Pig [options] -e[xecute] cmd [cmd ...] : Run cmd(s). Pig [options] [-f[ile]] file : Run cmds found in file. options include: -4, -log4jconf - Log4j configuration file, overrides log conf -b, -brief - Brief logging (no timestamps) -c, -check - Syntax check etc …
Use "-help properties" to get a list of properties.
$ pig -help properties The following properties are supported: Logging: verbose=true|false; default is false. This property is the same as -v switch brief=true|false; default is false. This property is the same as -b switch debug=OFF|ERROR|WARN|INFO|DEBUG; default is INFO. This property is the same as -d switch aggregate.warning=true|false; default is true. If true, prints count of warnings of each type rather than logging each warning. etc …
kill
Kills a job.

Example
In this example the job with id job_0001 is killed.
grunt> kill job_0001
quit
Quits from the Pig grunt shell.
Syntax
|
exit |
Terms
|
none |
no parameters |
Usage
The quit command enables you to quit or exit the Pig grunt shell.
Example
In this example the quit command exits the Pig grunt shall.
grunt> quit
run
Run a Pig script.
Syntax
|
run [–param param_name = param_value] [–param_file file_name] script |
Terms
|
–param param_name = param_value |
See Parameter Substitution. |
|
–param_file file_name |
See Parameter Substitution. |
|
script |
The name of a Pig script. |
Usage
Use the run command to run a Pig script that can interact with the Grunt shell (interactive mode). The script has access to aliases defined externally via the Grunt shell. The Grunt shell has access to aliases defined within the script. All commands from the script are visible in the command history.
With the run command, every store triggers execution. The statements from the script are put into the command history and all the aliases defined in the script can be referenced in subsequent statements after the run command has completed. Issuing a run command on the grunt command line has basically the same effect as typing the statements manually.
For comparison, see the exec command. Both the run and exec commands are useful for debugging because you can modify a Pig script in an editor and then rerun the script in the Grunt shell without leaving the shell. Also, both commands promote Pig script modularity as they allow you to reuse existing components.
Example
In this example the script interacts with the results of commands issued via the Grunt shell.
grunt> cat myscript.pig b = ORDER a BY name; c = LIMIT b 10; grunt> a = LOAD 'student' AS (name, age, gpa); grunt> run myscript.pig grunt> d = LIMIT c 3; grunt> DUMP d; (alice,20,2.47) (alice,27,1.95) (alice,36,2.27)
In this example parameter substitution is used with the run command.
grunt> a = LOAD 'student' AS (name, age, gpa); grunt> cat myscript.pig b = ORDER a BY name; STORE b into '$out'; grunt> run –param out=myoutput myscript.pig
set
Assigns values to keys used in Pig.
Syntax
|
set key 'value' |
Terms
|
key |
Key (see table). Case sensitive. |
|
value |
Value for key (see table). Case sensitive. |
Usage
Use the set command to assign values to keys, as shown in the table. All keys and their corresponding values (for Pig and Hadoop) are case sensitive.
|
Key |
Value |
Description |
|
default_parallel |
a whole number |
Sets the number of reducers for all MapReduce jobs generated by Pig (see Use the Parallel Features). |
|
debug |
on/off |
Turns debug-level logging on or off. |
|
job.name |
Single-quoted string that contains the job name. |
Sets user-specified name for the job |
|
job.priority |
Acceptable values (case insensitive): very_low, low, normal, high, very_high |
Sets the priority of a Pig job. |
|
stream.skippath |
String that contains the path. |
For streaming, sets the path from which not to ship data (see DEFINE and About Auto-Ship). |
All Pig and Hadoop properties can be set, either in the Pig script or via the Grunt command line.
Examples
In this example key value pairs are set at the command line.
grunt> SET debug 'on' grunt> SET job.name 'my job' grunt> SET default_parallel 100
In this example default_parallel is set in the Pig script; all MapReduce jobs that get launched will use 20 reducers.
SET default_parallel 20; A = LOAD 'myfile.txt' USING PigStorage() AS (t, u, v); B = GROUP A BY t; C = FOREACH B GENERATE group, COUNT(A.t) as mycount; D = ORDER C BY mycount; STORE D INTO 'mysortedcount' USING PigStorage();
In this example multiple key value pairs are set in the Pig script. These key value pairs are put in job-conf by Pig (making the pairs available to Pig and Hadoop). This is a script-wide setting; if a key value is defined multiple times in the script the last value will take effect and will be set for all jobs generated by the script.
... SET mapred.map.tasks.speculative.execution false; SET pig.logfile mylogfile.log; SET my.arbitrary.key my.arbitary.value; ...


frozen_string_literal: true
Methods
- C
-
- T
-
Instance Public methods
Source:
show
def current_theme
cookie_theme = cookies['app-theme']
themes.key?(cookie_theme) ? cookie_theme : themes.keys.first
end
Source:
show
def themes
{
'day' => t('themes.day'),
'night' => t('themes.night')
}
end


The Crimson Fairy Book
by Andrew Lang
“The Cottager and His Cat”
by Andrew Lang
Additional Information
- Year Published: 1903
- Language: English
- Country of Origin: Iceland
- Source: Lang, A. (Ed.). (1903). The Crimson Fairy Book. London: Dover Publications.
-
Readability:
- Flesch–Kincaid Level: 7.1
- Word Count: 1,359
- Genre: Fairy Tale/Folk Tale
- Keywords: companion animals, not being greedy
- ✎ Cite This
Downloads
Once upon a time there lived an old man and his wife in a dirty, tumble-down cottage, not very far from the splendid palace where the king and queen dwelt. In spite of the wretched state of the hut, which many people declared was too bad even for a pig to live in, the old man was very rich, for he was a great miser, and lucky besides, and would often go without food all day sooner than change one of his beloved gold pieces.
But after a while he found that he had starved himself once too often. He fell ill, and had no strength to get well again, and in a few days he died, leaving his wife and one son behind him.
 Half of his wealth is ill-gotten, and this you must give back to the poor from whom he squeezed it. The other half you must throw into the sea. Watch, however, as the money sinks into the water, and if anything should swim, catch it and keep it, even if it is nothing more than a bit of paper.’
Then the man vanished, and the youth awoke.
The remembrance of his dream troubled him greatly. He did not want to part with the riches that his father had left him, for he had known all his life what it was to be cold and hungry, and now he had hoped for a little comfort and pleasure. Still, he was honest and good-hearted, and if his father had come wrongfully by his wealth he felt he could never enjoy it, and at last he made up his mind to do as he had been bidden. He found out who were the people who were poorest in the village, and spent half of his money in helping them, and the other half he put in his pocket. From a rock that jutted right out into the sea he flung it in. In a moment it was out of sight, and no man could have told the spot where it had sunk, except for a tiny scrap of paper floating on the water. He stretched down carefully and managed to reach it, and on opening it found six shillings wrapped inside. This was now all the money he had in the world.
The young man stood and looked at it thoughtfully. ‘Well, I can’t do much with this,’ he said to himself; but, after all, six shillings were better than nothing, and he wrapped them up again and slipped them into his coat.
He worked in his garden for the next few weeks, and he and his mother contrived to live on the fruit and vegetables he got out of it, and then she too died suddenly. The poor fellow felt very sad when he had laid her in her grave, and with a heavy heart he wandered into the forest, not knowing where he was going. By-and-by he began to get hungry, and seeing a small hut in front of him, he knocked at the door and asked if they could give him some milk. The old woman who opened it begged him to come in, adding kindly, that if he wanted a night’s lodging he might have it without its costing him anything.
Two women and three men were at supper when he entered, and silently made room for him to sit down by them. When he had eaten he began to look about him, and was surprised to see an animal sitting by the fire different from anything he had ever noticed before. It was grey in colour, and not very big; but its eyes were large and very bright, and it seemed to be singing in an odd way, quite unlike any animal in the forest. ‘What is the name of that strange little creature?’ asked he. And they answered, ‘We call it a cat.’
‘I should like to buy it—if it is not too dear,’ said the young man; ‘it would be company for me.’ And they told him that he might have it for six shillings, if he cared to give so much. The young man took out his precious bit of paper, handed them the six shillings, and the next morning bade them farewell, with the cat lying snugly in his cloak.
For the whole day they wandered through meadows and forests, till in the evening they reached a house. The young fellow knocked at the door and asked the old man who opened it if he could rest there that night, adding that he had no money to pay for it. ‘Then I must give it to you,’ answered the man, and led him into a room where two women and two men were sitting at supper. One of the women was the old man’s wife, the other his daughter. He placed the cat on the mantel shelf, and they all crowded round to examine this strange beast, and the cat rubbed itself against them, and held out its paw, and sang to them; and the women were delighted, and gave it everything that a cat could eat, and a great deal more besides.
After hearing the youth’s story, and how he had nothing in the world left him except his cat, the old man advised him to go to the palace, which was only a few miles distant, and take counsel of the king, who was kind to everyone, and would certainly be his friend. The young man thanked him, and said he would gladly take his advice; and early next morning he set out for the royal palace.
He sent a message to the king to beg for an audience, and received a reply that he was to go into the great hall, where he would find his Majesty.
The king was at dinner with his court when the young man entered, and he signed to him to come near. The youth bowed low, and then gazed in surprise at the crowd of little black creatures who were running about the floor, and even on the table itself. Indeed, they were so bold that they snatched pieces of food from the King’s own plate, and if he drove them away, tried to bite his hands, so that he could not eat his food, and his courtiers fared no better.
‘What sort of animals are these?’ asked the youth of one of the ladies sitting near him.
‘They are called rats,’ answered the king, who had overheard the question, ‘and for years we have tried some way of putting an end to them, but it is impossible. They come into our very beds.’
At this moment something was seen flying through the air. The cat was on the table, and with two or three shakes a number of rats were lying dead round him. Then a great scuffling of feet was heard, and in a few minutes the hall was clear.
For some minutes the King and his courtiers only looked at each other in astonishment. ‘What kind of animal is that which can work magic of this sort?’ asked he. And the young man told him that it was called a cat, and that he had bought it for six shillings.
And the King answered: ‘Because of the luck you have brought me, in freeing my palace from the plague which has tormented me for many years, I will give you the choice of two things. Either you shall be my Prime Minister, or else you shall marry my daughter and reign after me. Say, which shall it be?’
‘The princess and the kingdom,’ said the young man.
And so it was.


Traits are single-parameter predicates used by the standard library to categorize objects. For instance, the trait (supporter $) succeeds for an object that the player is allowed to put things on top of. The rule bodies of traits never contain any side effects (such as printing text).
As far as the Dialog compiler is concerned, traits are just ordinary predicates.
We declare that the table is a supporter by ensuring that the query (supporter #table) succeeds. The easiest way to achieve this is with the rule definition:
| (supporter #table) |
Trait predicates are supposed to fail for objects that aren't part of the category. For instance, if the player ever tries to put an object on top of themselves, the library will at some point make a query to (supporter #player) to check whether this is allowed. That query will fail (unless, of course, we also add (supporter #player) to our program).
In the standard library, as a convention, traits are named with a category noun or adjective preceding the object, e.g. (openable $), whereas dynamic per-object flags have the object first, followed by “is” and an adjective, e.g. ($ is open). Most per-object flags also have a negated form, whereas traits do not. You may of course ignore these conventions in your own code, if you wish. The Dialog programming language makes no syntactical difference between traits and dynamic flags, and (now) (openable #door) is under most circumstances a perfectly legal statement, transforming the trait into a dynamic predicate. The purpose of the naming convention is to make it easier to understand library code at a glance.
We can easily define our own traits. For instance, we can invent a trait called (fruit $), to determine whether an object is a fruit. Let's define:
| (fruit #apple) | |
| (fruit #orange) |
Now, querying (fruit $) for some object will succeed if that object is the apple or the orange, but fail otherwise. Then we could have a generic object description for fruit:
| (descr $Obj) | (fruit $Obj) It looks yummy! |
When the standard library wants to print the description of an object, it queries (descr $) with the desired object as parameter. Dialog tries each (descr $) rule definition in turn, in program order. When it gets to the fruit-rule above, the rule head matches, binding $Obj to the object in question. Dialog starts to execute the rule body, which immediately makes a query to (fruit $) for the given object. If that query succeeds, execution proceeds with the rest of the rule body, and “It looks yummy!” is printed. If it fails, the rule fails, and Dialog resumes to search through the remaining (descr $) rules in the program.
When a rule body begins with a query, Dialog provides syntactic sugar that allows us to move the query into the rule head. The following line of code is equivalent to the one in the previous example:
| (descr (fruit $)) | It looks yummy! |
It is possible to define inheritance relations between traits:
| (berry #blueberry) | |
| (berry #cherry) | |
| (fruit #apple) | |
| (fruit *(berry $)) |
That last rule is equivalent to:
| (fruit $Obj) | *(berry $Obj) |
What it means is: $Obj is a fruit given that $Obj is a berry. The asterisk (*) indicates a multi-query.  The asterisk makes it possible to loop over every fruit in the game, for instance like this:
| (intro) | |
| Welcome to the fruit game! Here you will meet \(and possibly eat\): | |
| (line) | |
| (exhaust) { | |
| *(fruit $Obj) | |
| (The $Obj). | |
| (line) | |
| } |
We can easily add inheritance relations between our own traits and those of the standard library, in either direction. The following line of code adds a rule to the edibility-trait of the standard library, saying that all fruit are edible. This allows the player to EAT THE BLUEBERRY:
| (edible *(fruit $)) |
Here is a complete example with edible fruit and berries:
| #player | |
| (current player *) | |
| (* is #in #room) | |
| #room | |
| (name *) | tutorial room |
| (room *) | |
| (look *) | This is a very nondescript room, dominated by a |
| wooden table. (notice #table) | |
| #table | |
| (name *) | wooden table |
| (descr *) | It's a sturdy wooden table. |
| (if) ($ is #on *) (then) | |
| There seems to be something on it. | |
| (endif) | |
| (supporter *) | |
| (* is #in #room) | |
| #blueberry | |
| (name *) | blueberry |
| (berry *) | |
| #cherry | |
| (name *) | dark red cherry |
| (berry *) | |
| #apple | |
| (name *) | green apple |
| (fruit *) | |
| %% All berries are fruit, and all fruit are edible. | |
| (fruit *(berry $)) | |
| (edible *(fruit $)) | |
| %% The following are not trait inheritance definitions (descr, dict, and the | |
| %% initial location are not traits), so no asterisk is required. | |
| (descr (fruit $)) | Yummy! |
| (dict (fruit $)) | fruit |
| (dict (berry $)) | berry |
| ((fruit $) is #on #table) | |
| (intro) | |
| Welcome to the fruit game! Here you will meet \(and possibly eat\): | |
| (line) | |
| (exhaust) { | |
| *(fruit $Obj) | |
| (The $Obj). | |
| (line) | |
| } |
Try this game! Try to examine the table, then SEARCH or LOOK ON it, then perhaps EAT BERRY or EAT CHERRY, and see if the description of the table really changes when it's empty.
Did you notice that it wasn't possible to pick up the fruit in this game? They were presumably eaten directly off the table. Objects that can be picked up are called items, and we will discuss this trait at length in Chapter 4. But first, we will take a step back and see how the various traits provided by the standard library fit together.
To print the name of an object, most of the time you'll want to use a predicate called (the $). This prints the correct determinate article for the given object, followed by its name. So, given the following object definition:
| #apple | |
| (name *) | green apple |
querying (the #apple) would result in the following text being printed:
To print the name of an object together with an indeterminate article, use (a $) instead. Querying (a #apple) results in:
If you want the article to start with an uppercase letter, use (The $) or (A $), respectively.
The standard library offers a lot of flexibility when it comes to declaring object names. We have seen the (name $) predicate, which provides the actual noun expression. But a number of linguistic traits affect how that name gets printed:
(an $)
Specifies that “an” is the correct indeterminate article for this object name.
(proper $)
Specifies that this is a proper noun, so that neither “a” nor “the” should appear before it.
(plural $)
Specifies that this is a plural noun, so that “some” should be used instead of “a” or “an”. This also changes the verb forms printed by certain predicates (see below).
(pair $)
Inherits all the properties of a plural noun, but also changes the indeterminate article “a” into “a pair of”.
(uncountable $)
Specifies that the indeterminate article “some” should be used, but that the noun behaves like a singular in every other respect.
(singleton $)
Specifies that “the” should be used, even in situations where “a” or “an” are usually called for.
(your $)
Specifies that “your” should be used instead of “a” or “the”.
Some examples:
| #orange | |
| (an *) | |
| (name *) | orange |
| #book | |
| (proper *) | |
| (name *) | A Clockwork Orange |
| #bookshelves | |
| (your *) | |
| (plural *) | |
| (name *) | bookshelves |
| #boots | |
| (pair *) | |
| (name *) | boots |
| #water | |
| (uncountable *) | |
| (name *) | water |
| #sun | |
| (singleton *) | |
| (name *) | sun |
To use an object name in a sentence, it is often necessary to select a matching verb form. Predicates are available for this, as well as for printing pronouns. To print the correct personal pronoun, for instance, use (it $). This will print the word “it” by default, but if the object has the plural trait, it will print the word “they” instead. And if the object happens to be the current player character, the word “you” is printed. There are several such predicates, corresponding to the rows of the following table. The columns displayed here, corresponding to how the linguistic traits have been set up, are not exhaustive.
| Predicate | Singular | Plural | Current player |
|---|---|---|---|
| (a $) | a/an | some | yourself |
| (A $) | A/An | Some | You |
| (the $) | the | the | yourself |
| (The $) | The | The | You |
| (it $) | it | they | you |
| (It $) | It | They | You |
| (its $) | its | their | your |
| (itself $) | itself | themselves | yourself |
| (that $) | that | those | yourself |
| (is $) | is | are | are |
| (isn't $) | isn't | aren't | aren't |
| (has $) | has | have | have |
| (does $) | does | do | do |
| (doesn't $) | doesn't | don't | don't |
| (s $) | (no space) s | ||
| (es $) | (no space) es | ||
| (it $ is) | it is | they're | you're |
| (the $ is) | (the $) is | (the $) are | you're |
| (The $ is) | (The $) is | (The $) are | You're |
| (That's $) | That's | Those are | You're |
The predicates (s $) and (es $) are used for attaching verb endings, e.g. (The $Obj) ponder(s $Obj) (its $Obj) existance.
For each of the objects in the previous example, the expression:
| You see (a $Obj). (The $Obj is) drawing attention to (itself $Obj). |
would produce:
And if $Obj is the current player character, the output is:
When the parameter is a list of several objects, such as [#orange #boots #book], that's handled too:
There are two additional traits, (male $) and (female $), that modify the pronouns accordingly.
Note: Don't confuse (a $) with (an $)! The former is a predicate for printing the indeterminate article (usually “a”) followed by the name of the object. The latter is a trait, specifying that “an” should be used instead. Thus, somewhere in the standard library, a rule definition for (a $) contains a query to the predicate (an $) in order to determine what article it needs to print.
Two additional predicates deserve to be mentioned here: Whenever the standard library describes an action (e.g. to narrate an automatic action such as opening a door before walking through it, or as part of a disambiguating question), it prints the names of the involved objects using (the full $) or (a full $). These predicates print the object name using (the $) or (a $), and then, if the query (clarify location of $) succeeds for the object, some additional information pertaining to its location is printed. By default, this flag is enabled for all non-singleton doors, so that the game might ask the player: Did you want to open the door to the north or the door to the east?
The standard library categorizes objects using a system of traits. Most of these traits model one of the following three different aspects of an object:
Arrows indicate inheritance.
Container objects allow the player to put other objects #in them. Supporter objects allow the player to put other objects #on them.
Actor containers are containers that the player is allowed to enter. Actor supporters are supporters that the player is allowed to climb on top of.
Rooms are actor containers with no parents in the object tree. They are organized into a map using connections; this will be explained in the chapter on moving around. Some of those connections involve doors (physical doors or other kinds of gatekeepers). Doors are conceptually located in the liminal space between rooms, but for practical reasons they appear as children of rooms in the object tree: When the player enters a room, the library automatically moves adjacent door objects inside the room object.
A less commonly used trait is (seat $), the category of objects that give the player a place to sit down. These can be divided into on-seats (that the player may sit on) and in-seats (that the player may sit in, such as armchairs). Some behaviour is common to all seats, for instance that when the player tries to go up, this is interpreted as a desire to leave the seat.
Note that e.g. an on-seat is a kind of seat, but an on-seat is also a kind of actor supporter. If you are familiar with object-oriented programming, you may recognize this as a case of multiple inheritance. In class-based programming languages, where objects have inherent types that determine what code to execute, multiple inheritance can be problematic. But in languages such as Dialog, where rules are always applied in source code order, this is not the case.
A vehicle is an object that moves with the player if the player attempts to go somewhere while the vehicle object is their parent. Usually, vehicles are either actor supporters or actor containers, but this is not enforced. For an example of a situation where a vehicle is neither a container or a supporter, the player might be #heldby some giant non-player character, and directing that character to move around.
The standard library defines twelve directions and seven relations. The directions are #north, #northwest, #west, #southwest, #south, #southeast, #east, #northeast, #up, #down, #in, and #out. The relations are #in, #on, #wornby, #under, #behind, #heldby, and #partof. Note that #in is both a relation and a direction.
Directions and relations are never part of the object tree. They only appear as predicate parameters, and inside action expressions. Both directions and relations have printed names, (name $), but the relations also have several name variants:
| Relation | (name $) | (present-name $) | (towards-name $) | (reverse-name $) |
|---|---|---|---|---|
| #in | in | inside of | into | out of |
| #on | on | on top of | onto | off |
| #wornby | worn by | worn by | worn by | off |
| #under | under | under | under | out from under |
| #behind | behind | behind | behind | out from behind |
| #heldby | held by | held by | held by | away from |
| #partof | part of | part of | part of | away from |
Dialog allows you to model objects that are understood by the parser, but do not really exist in the game world. For instance, a room description might call attention to a cockroach scuttling over the floor and disappearing into a hole in the wall. If the player then tries to do anything to the cockroach (such as EXAMINE it), a response message about the cockroach not being here is preferable to a generic parser error.
Actions involving (not here $) objects generally fail with the message: “(The $Obj) is not here.” Actions that involve the manipulation of (not reachable $) objects fail with the message: “You can't reach (The $Obj).” For (intangible $) objects, the message is: “(The $Obj) is intangible.”
For many actions, the player is allowed to refer to a collection of objects using the word ALL. Objects that are (excluded from all $) are silently omitted from such collections. This also applies to objects marked as (not here $) or (not reachable $), via trait inheritance.
Most objects in the game world cannot be picked up—by default, only items can. The standard response when the player tries to pick up a non-item is: “You can't take (the $Obj).” But if the object is (fine where it is $), that error message is replaced by: “That's fine where it is.”
Openable objects can be opened (unless they are locked) and closed. Lockable objects can be locked and unlocked. Lockable objects are openable by inheritance.
Items can be picked up by the player. Anything that is carried by the player (usually items) can be dropped, or put inside containers or on top of supporters. Wearable objects can be worn or removed. Wearable objects are items by inheritance.
Pushable objects can be pushed from room to room. Switchable objects can be turned on or off. Sharp objects can be used to cut other objects.
Edible objects can be eaten, which causes them to be removed from the object tree. The player may drink potable objects, but those are not removed (the player only takes a sip).
Consultable objects can be consulted about various subject matters. That is, objects and other topics can be looked up in them.
Animate objects can be instructed to do things, although they will refuse by default. They can also be talked to, given things, or shown things. Again, the default implementations of those actions merely print a stock response.
Male and female are better described as linguistic traits, as their main function is to replace the default pronouns. They are included in the diagram because of their inheritance relation to the animate trait.