| Top |
Date and Time FunctionsDate and Time Functions — calendrical calculations and miscellaneous time stuff |
| #define | G_USEC_PER_SEC |
| struct | GTimeVal |
| struct | GDate |
| typedef | GTime |
| enum | GDateDMY |
| typedef | GDateDay |
| enum | GDateMonth |
| typedef | GDateYear |
| enum | GDateWeekday |
| #define | G_DATE_BAD_DAY |
| #define | G_DATE_BAD_JULIAN |
| #define | G_DATE_BAD_YEAR |
The GDate data structure represents a day between January 1, Year 1,
and sometime a few thousand years in the future (right now it will go
to the year 65535 or so, but g_date_set_parse()
only parses up to the
year 8000 or so - just count on "a few thousand"). GDate is meant to
represent everyday dates, not astronomical dates or historical dates
or ISO timestamps or the like. It extrapolates the current Gregorian
calendar forward and backward in time; there is no attempt to change
the calendar to match time periods or locations. GDate does not store
time information; it represents a day.
The GDate implementation has several nice features; it is only a 64-bit struct, so storing large numbers of dates is very efficient. It can keep both a Julian and day-month-year representation of the date, since some calculations are much easier with one representation or the other. A Julian representation is simply a count of days since some fixed day in the past; for GDate the fixed day is January 1, 1 AD. ("Julian" dates in the GDate API aren't really Julian dates in the technical sense; technically, Julian dates count from the start of the Julian period, Jan 1, 4713 BC).
GDate is simple to use. First you need a "blank" date; you can get a
dynamically allocated date from g_date_new()
, or you can declare an
automatic variable or array and initialize it to a sane state by
calling g_date_clear()
. A cleared date is sane; it's safe to call
g_date_set_dmy()
and the other mutator functions to initialize the
value of a cleared date. However, a cleared date is initially
invalid, meaning that it doesn't represent a day that exists.
It is undefined to call any of the date calculation routines on an
invalid date. If you obtain a date from a user or other
unpredictable source, you should check its validity with the
g_date_valid()
predicate. g_date_valid()
is also used to check for
errors with g_date_set_parse()
and other functions that can
fail. Dates can be invalidated by calling g_date_clear()
again.
It is very important to use the API to access the GDate struct. Often only the day-month-year or only the Julian representation is valid. Sometimes neither is valid. Use the API.
GLib also features GDateTime which represents a precise time.
void
g_get_current_time (GTimeVal *result
);
Equivalent to the UNIX gettimeofday()
function, but portable.
You may find g_get_real_time()
to be more convenient.
void
g_usleep (gulong microseconds
);
Pauses the current thread for the given number of microseconds.
There are 1 million microseconds per second (represented by the
G_USEC_PER_SEC macro). g_usleep()
may have limited precision,
depending on hardware and operating system; don't rely on the exact
length of the sleep.
void g_time_val_add (GTimeVal *time_
,glong microseconds
);
Adds the given number of microseconds to time_
. microseconds
can
also be negative to decrease the value of time_
.
gboolean g_time_val_from_iso8601 (const gchar *iso_date
,GTimeVal *time_
);
Converts a string containing an ISO 8601 encoded date and time
to a GTimeVal and puts it into time_
.
iso_date
must include year, month, day, hours, minutes, and
seconds. It can optionally include fractions of a second and a time
zone indicator. (In the absence of any time zone indication, the
timestamp is assumed to be in local time.)
Since 2.12
gchar *
g_time_val_to_iso8601 (GTimeVal *time_
);
Converts time_
into an RFC 3339 encoded string, relative to the
Coordinated Universal Time (UTC). This is one of the many formats
allowed by ISO 8601.
ISO 8601 allows a large number of date/time formats, with or without
punctuation and optional elements. The format returned by this function
is a complete date and time, with optional punctuation included, the
UTC time zone represented as "Z", and the tv_usec
part included if
and only if it is nonzero, i.e. either
"YYYY-MM-DDTHH:MM:SSZ" or "YYYY-MM-DDTHH:MM:SS.fffffZ".
This corresponds to the Internet date/time format defined by RFC 3339, and to either of the two most-precise formats defined by the W3C Note Date and Time Formats. Both of these documents are profiles of ISO 8601.
Use g_date_time_format()
or g_strdup_printf()
if a different
variation of ISO 8601 format is required.
Since 2.12
gint64
g_get_monotonic_time (void
);
Queries the system monotonic time.
The monotonic clock will always increase and doesn't suffer discontinuities when the user (or NTP) changes the system time. It may or may not continue to tick during times where the machine is suspended.
We try to use the clock that corresponds as closely as possible to
the passage of time as measured by system calls such as poll()
but it
may not always be possible to do this.
Since 2.28
gint64
g_get_real_time (void
);
Queries the system wall-clock time.
This call is functionally equivalent to g_get_current_time()
except
that the return value is often more convenient than dealing with a
GTimeVal.
You should only use this call if you are actually interested in the real
wall-clock time. g_get_monotonic_time()
is probably more useful for
measuring intervals.
Since 2.28
GDate *
g_date_new (void
);
Allocates a GDate and initializes
it to a sane state. The new date will
be cleared (as if you'd called g_date_clear()
) but invalid (it won't
represent an existing day). Free the return value with g_date_free()
.
GDate * g_date_new_dmy (GDateDay day
,GDateMonth month
,GDateYear year
);
Like g_date_new()
, but also sets the value of the date. Assuming the
day-month-year triplet you pass in represents an existing day, the
returned date will be valid.
GDate *
g_date_new_julian (guint32 julian_day
);
Like g_date_new()
, but also sets the value of the date. Assuming the
Julian day number you pass in is valid (greater than 0, less than an
unreasonably large number), the returned date will be valid.
void g_date_clear (GDate *date
,guint n_dates
);
Initializes one or more GDate structs to a sane but invalid
state. The cleared dates will not represent an existing date, but will
not contain garbage. Useful to init a date declared on the stack.
Validity can be tested with g_date_valid()
.
void g_date_set_day (GDate *date
,GDateDay day
);
Sets the day of the month for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
void g_date_set_month (GDate *date
,GDateMonth month
);
Sets the month of the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
void g_date_set_year (GDate *date
,GDateYear year
);
Sets the year for a GDate. If the resulting day-month-year triplet is invalid, the date will be invalid.
void g_date_set_dmy (GDate *date
,GDateDay day
,GDateMonth month
,GDateYear y
);
Sets the value of a GDate from a day, month, and year.
The day-month-year triplet must be valid; if you aren't
sure it is, call g_date_valid_dmy()
to check before you
set it.
void g_date_set_julian (GDate *date
,guint32 julian_date
);
Sets the value of a GDate from a Julian day number.
void g_date_set_time (GDate *date
,GTime time_
);
g_date_set_time
has been deprecated since version 2.10 and should not be used in newly-written code.
Use g_date_set_time_t()
instead.
Sets the value of a date from a GTime value. The time to date conversion is done using the user's current timezone.
void g_date_set_time_t (GDate *date
,time_t timet
);
Sets the value of a date to the date corresponding to a time specified as a time_t. The time to date conversion is done using the user's current timezone.
To set the value of a date to the current day, you could write:
1 |
g_date_set_time_t (date, time (NULL)); |
Since 2.10
void g_date_set_time_val (GDate *date
,GTimeVal *timeval
);
Sets the value of a date from a GTimeVal value. Note that the
tv_usec
member is ignored, because GDate can't make use of the
additional precision.
The time to date conversion is done using the user's current timezone.
Since 2.10
void g_date_set_parse (GDate *date
,const gchar *str
);
Parses a user-inputted string str
, and try to figure out what date it
represents, taking the current locale into account. If the
string is successfully parsed, the date will be valid after the call.
Otherwise, it will be invalid. You should check using g_date_valid()
to see whether the parsing succeeded.
This function is not appropriate for file formats and the like; it isn't very precise, and its exact behavior varies with the locale. It's intended to be a heuristic routine that guesses what the user means by a given string (and it does work pretty well in that capacity).
void g_date_add_days (GDate *date
,guint n_days
);
Increments a date some number of days. To move forward by weeks, add weeks*7 days. The date must be valid.
void g_date_subtract_days (GDate *date
,guint n_days
);
Moves a date some number of days into the past. To move by weeks, just move by weeks*7 days. The date must be valid.
void g_date_add_months (GDate *date
,guint n_months
);
Increments a date by some number of months. If the day of the month is greater than 28, this routine may change the day of the month (because the destination month may not have the current day in it). The date must be valid.
void g_date_subtract_months (GDate *date
,guint n_months
);
Moves a date some number of months into the past. If the current day of the month doesn't exist in the destination month, the day of the month may change. The date must be valid.
void g_date_add_years (GDate *date
,guint n_years
);
Increments a date by some number of years. If the date is February 29, and the destination year is not a leap year, the date will be changed to February 28. The date must be valid.
void g_date_subtract_years (GDate *date
,guint n_years
);
Moves a date some number of years into the past. If the current day doesn't exist in the destination year (i.e. it's February 29 and you move to a non-leap-year) then the day is changed to February 29. The date must be valid.
gint g_date_days_between (const GDate *date1
,const GDate *date2
);
Computes the number of days between two dates.
If date2
is prior to date1
, the returned value is negative.
Both dates must be valid.
gint g_date_compare (const GDate *lhs
,const GDate *rhs
);
qsort()-style comparison function for dates. Both dates must be valid.
void g_date_clamp (GDate *date
,const GDate *min_date
,const GDate *max_date
);
If date
is prior to min_date
, sets date
equal to min_date
.
If date
falls after max_date
, sets date
equal to max_date
.
Otherwise, date
is unchanged.
Either of min_date
and max_date
may be NULL
.
All non-NULL
dates must be valid.
date |
a GDate to clamp |
|
min_date |
minimum accepted value for |
|
max_date |
maximum accepted value for |
void g_date_order (GDate *date1
,GDate *date2
);
Checks if date1
is less than or equal to date2
,
and swap the values if this is not the case.
GDateDay
g_date_get_day (const GDate *date
);
Returns the day of the month. The date must be valid.
GDateMonth
g_date_get_month (const GDate *date
);
Returns the month of the year. The date must be valid.
GDateYear
g_date_get_year (const GDate *date
);
Returns the year of a GDate. The date must be valid.
guint32
g_date_get_julian (const GDate *date
);
Returns the Julian day or "serial number" of the GDate. The Julian day is simply the number of days since January 1, Year 1; i.e., January 1, Year 1 is Julian day 1; January 2, Year 1 is Julian day 2, etc. The date must be valid.
GDateWeekday
g_date_get_weekday (const GDate *date
);
Returns the day of the week for a GDate. The date must be valid.
guint
g_date_get_day_of_year (const GDate *date
);
Returns the day of the year, where Jan 1 is the first day of the year. The date must be valid.
guint8 g_date_get_days_in_month (GDateMonth month
,GDateYear year
);
Returns the number of days in a month, taking leap years into account.
gboolean
g_date_is_first_of_month (const GDate *date
);
Returns TRUE
if the date is on the first of a month.
The date must be valid.
gboolean
g_date_is_last_of_month (const GDate *date
);
Returns TRUE
if the date is the last day of the month.
The date must be valid.
gboolean
g_date_is_leap_year (GDateYear year
);
Returns TRUE
if the year is a leap year.
For the purposes of this function, leap year is every year divisible by 4 unless that year is divisible by 100. If it is divisible by 100 it would be a leap year only if that year is also divisible by 400.
guint
g_date_get_monday_week_of_year (const GDate *date
);
Returns the week of the year, where weeks are understood to start on Monday. If the date is before the first Monday of the year, return
The date must be valid.
guint8
g_date_get_monday_weeks_in_year (GDateYear year
);
Returns the number of weeks in the year, where weeks are taken to start on Monday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it's a leap year. This function is basically telling you how many Mondays are in the year, i.e. there are 53 Mondays if one of the extra days happens to be a Monday.)
guint
g_date_get_sunday_week_of_year (const GDate *date
);
Returns the week of the year during which this date falls, if weeks are understood to being on Sunday. The date must be valid. Can return 0 if the day is before the first Sunday of the year.
guint8
g_date_get_sunday_weeks_in_year (GDateYear year
);
Returns the number of weeks in the year, where weeks are taken to start on Sunday. Will be 52 or 53. The date must be valid. (Years always have 52 7-day periods, plus 1 or 2 extra days depending on whether it's a leap year. This function is basically telling you how many Sundays are in the year, i.e. there are 53 Sundays if one of the extra days happens to be a Sunday.)
guint
g_date_get_iso8601_week_of_year (const GDate *date
);
Returns the week of the year, where weeks are interpreted according to ISO 8601.
Since 2.6
gsize g_date_strftime (gchar *s
,gsize slen
,const gchar *format
,const GDate *date
);
Generates a printed representation of the date, in a
locale-specific way.
Works just like the platform's C library strftime()
function,
but only accepts date-related formats; time-related formats
give undefined results. Date must be valid. Unlike strftime()
(which uses the locale encoding), works on a UTF-8 format
string and stores a UTF-8 result.
This function does not provide any conversion specifiers in
addition to those implemented by the platform's C library.
For example, don't expect that using g_date_strftime()
would
make the %F provided by the C99 strftime()
work on Windows
where the C library only complies to C89.
void g_date_to_struct_tm (const GDate *date
,struct tm *tm
);
Fills in the date-related bits of a struct tm using the date
value.
Initializes the non-date parts with something sane but meaningless.
gboolean
g_date_valid (const GDate *date
);
Returns TRUE
if the GDate represents an existing day. The date must not
contain garbage; it should have been initialized with g_date_clear()
if it wasn't allocated by one of the g_date_new()
variants.
gboolean
g_date_valid_day (GDateDay day
);
Returns TRUE
if the day of the month is valid (a day is valid if it's
between 1 and 31 inclusive).
gboolean
g_date_valid_month (GDateMonth month
);
Returns TRUE
if the month value is valid. The 12 GDateMonth
enumeration values are the only valid months.
gboolean
g_date_valid_year (GDateYear year
);
Returns TRUE
if the year is valid. Any year greater than 0 is valid,
though there is a 16-bit limit to what GDate will understand.
gboolean g_date_valid_dmy (GDateDay day
,GDateMonth month
,GDateYear year
);
Returns TRUE
if the day-month-year triplet forms a valid, existing day
in the range of days GDate understands (Year 1 or later, no more than
a few thousand years in the future).
gboolean
g_date_valid_julian (guint32 julian_date
);
Returns TRUE
if the Julian day is valid. Anything greater than zero
is basically a valid Julian, though there is a 32-bit limit.
gboolean
g_date_valid_weekday (GDateWeekday weekday
);
Returns TRUE
if the weekday is valid. The seven GDateWeekday enumeration
values are the only valid weekdays.
#define G_USEC_PER_SEC 1000000
Number of microseconds in one second (1 million). This macro is provided for code readability.
struct GTimeVal { glong tv_sec; glong tv_usec; };
Represents a precise time, with seconds and microseconds.
Similar to the struct timeval returned by the gettimeofday()
UNIX system call.
GLib is attempting to unify around the use of 64bit integers to represent microsecond-precision time. As such, this type will be removed from a future version of GLib.
struct GDate { guint julian_days : 32; /* julian days representation - we use a * bitfield hoping that 64 bit platforms * will pack this whole struct in one big * int */ guint julian : 1; /* julian is valid */ guint dmy : 1; /* dmy is valid */ /* DMY representation */ guint day : 6; guint month : 4; guint year : 16; };
Represents a day between January 1, Year 1 and a few thousand years in the future. None of its members should be accessed directly.
If the GDate is obtained from g_date_new()
, it will be safe
to mutate but invalid and thus not safe for calendrical computations.
If it's declared on the stack, it will contain garbage so must be
initialized with g_date_clear()
. g_date_clear()
makes the date invalid
but sane. An invalid date doesn't represent a day, it's "empty." A date
becomes valid after you set it to a Julian day or you set a day, month,
and year.
guint |
the Julian representation of the date |
|
guint |
this bit is set if |
|
guint |
this is set if |
|
guint |
the day of the day-month-year representation of the date, as a number between 1 and 31 |
|
guint |
the day of the day-month-year representation of the date, as a number between 1 and 12 |
|
guint |
the day of the day-month-year representation of the date |
typedef gint32 GTime;
Simply a replacement for time_t. It has been deprecated since it is not equivalent to time_t on 64-bit platforms with a 64-bit time_t. Unrelated to GTimer.
Note that GTime is defined to always be a 32-bit integer,
unlike time_t which may be 64-bit on some systems. Therefore,
GTime will overflow in the year 2038, and you cannot use the
address of a GTime variable as argument to the UNIX time()
function.
Instead, do the following:
1 2 3 4 5 |
time_t ttime; GTime gtime; time (&ttime); gtime = (GTime)ttime; |
This enumeration isn't used in the API, but may be useful if you need to mark a number as a day, month, or year.
typedef guint8 GDateDay; /* day of the month */
Integer representing a day of the month; between 1 and 31. G_DATE_BAD_DAY represents an invalid day of the month.
Enumeration representing a month; values are G_DATE_JANUARY, G_DATE_FEBRUARY, etc. G_DATE_BAD_MONTH is the invalid value.
typedef guint16 GDateYear;
Integer representing a year; G_DATE_BAD_YEAR is the invalid value. The year must be 1 or higher; negative (BC) years are not allowed. The year is represented with four digits.
Enumeration representing a day of the week; G_DATE_MONDAY, G_DATE_TUESDAY, etc. G_DATE_BAD_WEEKDAY is an invalid weekday.


THE ELEMENTS
preparing for adventure
☰ Menu
Home
Preston
Soda Springs
Fish Haven
Storm Center
Gallery
Storm Center
Full Name
Email
Phone Number
Zip Code
Storm Date
Storm Type
Storm Severity
Rating 1 to 10
5
Select Region...
Preston
Soda Springs
Fish Haven
User In-Danger
Level
Yes
No
Maybe
Additional Information/Comments


Breaking Removed wrapping around rondell items. Selector now has to select the items parent. All children will become rondell items.
Breaking CSS classes can't be customized anymore to reduce size via minify
Breaking Scrollbar switched to css animation
New Added cleanup function to remove everything rondell specific
New Rondell options can be updated with a new rondell call. Maybe this leads to a wizard :)
Change Some performance improvements
1.0.4
New onUpdateLightbox callback can be defined in the options.
1.0.3
FIX No image when opening the lightbox, closing it and opening it again with another image.
FIX Lightbox pops up when closing it and resizing the window.
1.0.2
New The lightbox now contains a 'more' link when the rondell item is a link and the lightbox is enabled. See the 'strings' option to customize the text.
 Just wrap an image with an image link to the big image.
New A close button for the lightbox ;-)
Change Better auto resize for the lightbox.
CHANGE Lightbox now has a default dark theme. New themes for the lightbox will be added eventually.
1.0.0
New Integrated lightweight lightbox to reduce 3rd party lightbox difficulties
Change Using grunt for building, compass for sass mixins and QUnit for testing
FIX Blur and focus problems in IE
0.9.3
New Asynchronous image loading has been added and will be further improved in the next versions
Change New optimized item rendering technique and refactoring for improved performance and flexibility
Change CSS classes are now using hyphens instead of camelcase. Please check your custom styles!
Change Preset 'products' is now called 'scroller'
FIX Fancybox samples now show working navigation arrows and item title
FIX Example for the 'size' option is now correct
0.9.1
New awesome preset thumbgallery which uses all the new options and features.
New Integrated my standalone scrollbar plugin (beta) into the rondell. See the options for setting it up.
New Items absolute index as parameter for the animation functions.
New Option cropThumbnails for image cropping to allow uniform size of thumbnails
New Option switchIndices which enables switching the index of the last and new focused items.
New Option keyDelay which sets minimum time between keypress events are registered.
New Option wrapIndices allowing to disable item index wrapping used in the carousels.
New Opacity is now animated when hovering items.
Change Improved performance
Fix Bugfixes for items fading out or in
Fix Disabled autorotation when rondell is not visible.


Image Not found
{{message}}
This is the email
Your twitter username
eg. https://www.linkedin.com/in/yourname


nips nips2006 nips2006-125 nips2006-125-reference knowledge-graph by maker-knowledge-mining
Source: pdf
Author: Peter Auer, Ronald Ortner
Abstract: We present a learning algorithm for undiscounted reinforcement learning. Our interest lies in bounds for the algorithm’s online performance after some ﬁnite number of steps. In the spirit of similar methods already successfully applied for the exploration-exploitation tradeoff in multi-armed bandit problems, we use upper conﬁdence bounds to show that our UCRL algorithm achieves logarithmic online regret in the number of steps taken with respect to an optimal policy. 1 1.1
[1] Michael J. Kearns and Satinder P. Singh. Near-optimal reinforcement learning in polynomial time. Mach. Learn., 49:209–232, 2002.
[2] Ronen I. Brafman and Moshe Tennenholtz. R-max – a general polynomial time algorithm for near-optimal reinforcement learning. J. Mach. Learn. Res., 3:213–231, 2002.
[3] Sham M. Kakade. On the Sample Complexity of Reinforcement Learning. PhD thesis, University College London, 2003.
[4] Alexander L. Strehl and Michael L. Littman. A theoretical analysis of model-based interval estimation. In Proc. 22nd ICML 2005, pages 857–864, 2005.
[5] Alexander L. Strehl, Lihong Li, Eric Wiewiora, John Langford, and Michael L. Littman. Pac model-free reinforcement learning. In Proc. 23nd ICML 2006, pages 881–888, 2006.
[6] Claude-Nicolas Fiechter. Efﬁcient reinforcement learning. In Proc. 7th COLT, pages 88–97. ACM, 1994.
[7] Peter Auer and Ronald Ortner. Online regret bounds for a new reinforcement learning algorithm. In Proc. ¨ 1st ACVW, pages 35–42. OCG, 2005.
[8] Peter Auer. Using conﬁdence bounds for exploitation-exploration trade-offs. J. Mach. Learn. Res., 3:397– 422, 2002.
[9] Peter Auer, Nicol` Cesa-Bianchi, and Paul Fischer. Finite-time analysis of the multi-armed bandit probo lem. Mach. Learn., 47:235–256, 2002.
[10] Alexander L. Strehl and Michael L. Littman. An empirical evaluation of interval estimation for Markov decision processes. In Proc. 16th ICTAI, pages 128–135. IEEE Computer Society, 2004.
[11] Leslie P. Kaelbling. Learning in Embedded Systems. MIT Press, 1993.
[12] Eyal Even-Dar, Shie Mannor, and Yishay Mansour. Action elimination and stopping conditions for reinforcement learning. In Proc. 20th ICML, pages 162–169. AAAI Press, 2003.
[13] Apostolos N. Burnetas and Michael N. Katehakis. Optimal adaptive policies for Markov decision processes. Math. Oper. Res., 22(1):222–255, 1997.
[14] Eyal Even-Dar, Sham M. Kakade, and Yishay Mansour. Experts in a Markov decision process. In Proc. 17th NIPS, pages 401–408. MIT Press, 2004.
[15] Martin L. Puterman. Markov Decision Processes. Discrete Stochastic Programming. Wiley, 1994.
[16] Grace E. Cho and Carl D. Meyer. Markov chain sensitivity measured by mean ﬁrst passage times. Linear Algebra Appl., 316:21–28, 2000.


Soldier! Thank you for defending our Castle! You are going to be teleported inside, in %teleportIn% seconds!


Caitlyn Jenner reveals the sweet nickname her grandchildren have for her
The reality star has almost 20 grandchildren
by Kendra BeckerCaitlyn Jenner has revealed the sweet nickname her grandchildren have for her.
The transgender star, formerly known as Bruce, split from Kardashian matriarch Kris Jenner back in 2013 – but she still sees herself as a grandparent to the Kardashian kids.
During a chat with her campmates in the jungle, Caitlyn revealed she’ll have 20 grandchildren in December.
Kate Garraway then asked what her grandkids call her, and she said: “They came up with Boom Boom. It kinda stuck, it was easy for them to say.”
“So, little Stormi [Kylie Jenner’s daughter], yeah, she’s like, ‘Ah Boom Boom’s here,” Caitlyn explained.
Caitlyn also explained why all her kids still call her ‘Dad’, despite her transition.
She said: “My kids all call me Dad, Kendall asked me first and I said ‘Dad’, I’m your Dad and I’ll always be your Dad till the day I die.”
“But what they’re really good at which shocks me all the time is when they’re talking about me, my Dad she and it’s tough to change the pronoun in the middle of it.”
I’m A Celebrity…Get Me Out Of Here! airs on Virgin Media One at 9pm.


{% extends "base.html" %} {% block title %}Upload Failed | {% endblock %} {% block content %} There was an error with the input. Please check your file again. Return to front page {% endblock %}


Circus : Posters
Posters
About
Posters
Barnum & Bailey greatest show on Earth: The Apollo Trio
The Barnum & Bailey greatest show on earth : Charles 1st
The Barnum & Bailey latest and greatest thriller the balloon horse Jupiter : In his sensational ascension act with a gorgeous pyrotechnic display at every performance of the greatest show on earth
The Barnum & Bailey greatest show on earth : Baby Bumbeno, only American born giraffe, cutest thing alive
Courtesy of the Boston Public Library
Richard Dale McMullan Collection


Warn about possible truncation (or roundoff) errors. Most of these
are related to integer arithmetic. By default, all warnings are
turned on.
This setting provides detailed control over the warnings about
possible truncation errors. The list consists of keywords
separated by commas or colons.
Since all warnings are on by default, include a keyword prefixed by
no- to turn off a particular warning.
There are three special keywords: all to turn on all the
warnings about truncation, none to turn them all
off, and help to print the list of all the keywords with a brief
explanation of each.
If list is omitted, -truncation is equivalent to
-truncation=all, and -notruncation is equivalent to
-truncation=none.
The warning keywords with their meanings are as follows:
- int-div-exponent:
-
use of the result of integer division as an exponent.
This suggests that a real quotient is intended.
An example would be writing X**(1/3) to evaluate the cube root
of X. The correct expression is X**(1./3.).
- int-div-real:
-
Conversion of an expression involving an integer division to real.
This suggests that a real quotient is intended.
- int-div-zero:
-
division in an integer constant expression that
yields a result of zero.
- int-neg-power:
-
exponentiation of an integer by a negative
integer (which yields zero unless the base integer is 1 in magnitude).
This suggests that a real base is intended.
- promotion:
-
automatic conversion of a lower precision quantity to one of higher
precision. The loss of accuracy for real variables in this process is
comparable to the corresponding demotion. No warning is given for
promotion of integer quantities to real since this is ordinarily
exact.
- real-do-index:
-
use of a non-integer DO index in a
loop with integer bounds.
An integer DO index with real bounds is always
warned about regardless of this setting.
- real-subscript:
-
use of a non-integer array subscript.
- significant-figures:
-
overspecifying a single precision constant. This may indicate that a
double precision constant was intended.
- size-demotion:
-
automatic conversion of a higher precision quantity to one of lower
precision of the same type. This warning only occurs when an explicit
size is used in declaring the type of one or both operands in an
assignment. For example, a warning wil be issued where a REAL*8
variable is assigned to a REAL variable, if the default wordsize
of 4 is in effect. A warning is also issued if a long integer is
assigned to a shorter one, for example, if an INTEGER
expression is assigned to an INTEGER*2 variable. There is one
exception to this last case, namely if the right hand side of the assignment
is a small literal constant (less than 128).
type-demotion:
automatic conversion of a higher precision quantity to one of lower
precision of different type. This warning includes conversion of real
quantities to integer, double precision to single precision real, and
assignment of a longer character string to a shorter one.
The warnings about promotion and demotion also apply to complex
constants, considering the precision to be that of the real or
imaginary part.
Warnings about promotions and demotions are given only when
the conversion is done automatically, e.g. in expressions of mixed
precision or in an assignment statement. If intrinsic
functions such as INT are used to perform the conversion, no warning
is given.
See also: -portability, -wordsize.


Privacy Policy
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.
Contrary to popular belief, Lorem Ipsum is not simply random text.
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.
- It is a long established fact that a reader will be distracted by the readable.
- Contrary to popular belief, Lorem Ipsum is not simply random text.
- There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration.
- Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
- But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system.
- At vero eos et accusamus et iusto odio dignissimos ducimus.
- On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized.
- web sites still in their infancy. Various versions have evolved over the years.
- These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled.
- There are many variations of passages of Lorem Ipsum available, but the majority.
- Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition.
- It is a long established fact that a reader will be distracted by the readable.
- The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.


Chi Kung, Mental Clarity and Intelligence
03-05-2018
Some years ago, a friend that doesn’t practice chi kung asked me if practicing chi kung could raise your IQ. I gave her a somewhat brief answer explaining that I didn’t think practicing chi kung would alter the level of intelligence a person is born with, but it would certainly allow a person to make better use of the IQ they have. A longer explanation is as follows.
I believe that the main reason chi kung can improve a person’s thinking and allow them to make better use of their natural intelligence is because practicing chi kung increases their mental clarity. Mental clarity is a topic we discuss a lot in Shaolin Wahnam and is a benefit many practitioners reportedly enjoy. In my experience, I can say that practicing chi kung indeed has improved my mental clarity. For someone who has never practiced Shaolin Cosmos Chi Kung or has not experienced mental clarity, they might be wondering what mental clarity is.
To be concise, mental clarity is when the mind is quiet and peaceful, free of unwanted thoughts. This does not mean a person has become incapable of thinking; it means thoughts arise only when they want them or need them. A person with mental clarity can find solutions to problems very easily, can quickly make choices that seem difficult to others, can react to unexpected circumstances without hesitation, can learn with ease and can carry out their work or play without getting distracted by something irrelevant. This might sound abnormal these days, as many people generally feel overwhelmed by their own thinking.
I shall paraphrase an example of mental clarity I have heard Sifu Wong give on various occasions:
“Let’s say you are in a gymnasium with three other people, and you want to find which one of those three people is wearing a watch. It will be very easy to find that person. But now let’s say you are in the same gymnasium with 200 people, only one of them is wearing a watch and you want to find them. Now it will be quite difficult. In the same way, when you have mental clarity you can easily find the solution you want or pinpoint the thought you want to focus on. For people with no mental clarity, it can be very difficult to find the solution or pinpoint one thought.”
One of the first experiences I had of improved mental clarity was after starting chi kung as a senior in high school. During my previous school years, whenever I had to read for homework, every now and then I would read half a page or so, but my thoughts would be elsewhere. Once my attention came back to the page I would have no memory of what I’d just read. This went away within a few months of practicing chi kung. Not only was my focus better but my retention of what I’d read had gone way up, without making anymore effort than I had before. My reading ability hadn’t changed. Practicing chi kung had flushed away a lot of mental rubbish, leaving my mind clearer and my focus better.
I’ve always naturally been better at abstract, creative thinking, and I wasn’t that great in math. What I’ve found over the years in this regard is that, while my natural math logic hasn’t changed, as my mental clarity has improved I’m better able to do the math I’m capable of. For example, in the past I would often make small detail mistakes in a math problem. The number of mistakes I make is now greatly reduced, despite making very little effort to improve my math skills. My natural mathematics intelligence has not changed, but I can learn better and think more clearly, creating sort of an illusion that I’m now smarter in math.
So, no, I would not say chi kung will increase a person’s IQ, but their newfound mental clarity will definitely improve their thinking. The benefits from having increased mental clarity carry over to everything they do, whether it’s learning to draw, making an excel spreadsheet, helping someone “solve” a life “problem,” reacting to angry drivers on the highway or meditating. Enjoying mental clarity is one of the greatest benefits you’ll receive from practicing genuine chi kung.


Click here to send a GET request to /my-data-url.
Fill out this form to send a POST request to /my-data-url:


|
Perl Weekly
Issue #106 - 2013-08-05 - Perl is so difficult, it took Zhao Bowen a whole afternoon to learn it...
latest | archive | by Gabor Szabo
|
|
Hi,
So Perl was mentioned in the Wired magazine. - If you find other mention of Perl, please let me know.
Enjoy!
|
|
|
|
Sponsors
|
We're Hiring Telecommuters - Grant Street Group
Grant Street Group is a growing software company using open source software/modern Perl practices to build innovative e-payment, auction, and tax collection web applications. We are looking for talented, motivated professionals committed to flawless work and customer service. Email resume<EMAIL_ADDRESS>|
|
Announcements
|
|
|
Carton 1.0 is released
Carton, another beautiful creation of Tatsuhiko Miyagawa, is a tool to bundle CPAN modules with your application. To make sure all the developers use the same version of the modules and that you can then release your application relying on a specific set of CPAN module/version pairs.
|
|
New Dancer 2 release: 0.07
SawyerX, now reporting from Amsterdam, tells the short history of Dancer 2 releases. I don't think there is any information about Dancer 2 on the main Perl Dancer web site, so I am happy to see that it is being developed, and that new releases appear. At this point it is still unclear to me who is using Dancer 2, and whether there is a clear upgrade path from Dancer 1 to Dancer 2.
|
|
Articles
|
Why I use cpanfile (and you should too)
cpanfile allows you to describe the list of dependencies your module/application has and installing them using cpanm, without creating a CPAN distribution. This can be useful for new developers on GitHub, or inside corporations. See how Mark Allen explains it and then read the comments, including the ones from Miyagawa, who created the cpanfile format.
|
|
Technical Debt Strategies
I found this article of Buddy Burden to be very good. It describes what is technical debt, why is it called that way, and how to handle it. He shows 4 methods for you to implement.
|
|
A Marpa-powered C parser
With all the text processing capabilities of Perl, I am surprised there are no parsers for all the major languages and grammars written in Perl. Maybe Marpa will change this starting with MarpaX::Languages::C::AST released by Jean-Damien Durand.
|
|
Mapping the MOP to Moose
This is the log of Stevan Little as he is thinking about the implementation of MOP in core perl. Especially discussion on how attributes can be lazy in Moose and in the perl5-MOP. I can take away two things from this post. 1) The perl5-MOP implementation is progressing, and we might have a built-in MOP in the next major release of Perl. 2) The whole discussion is way over the top of my head. I am glad some people can think through it.
|
|
Testing
|
Misconceptions & Misunderstandings
What is the difference between CPANTS and CPAN Testers? Who are the CPAN Testers? Why do they report failures? A few weeks ago there was a post complaining about the CPAN Testers (I did not link to it as I don't like posts attacking other people.) Now Barbie, the main person behind the CPAN Testers explains everything you might want to know about CPAN Testers! Well, almost.
|
|
Code
|
|
|
Fun
|
|
|
|
|
|
|
Grants
|
|
|
|
|
CPAN
|
CPAN candidates for adoption
I wanted to do something like this for ages, I am glad Neil Bowers had the same idea and went for it. He created a metric that after some more tweaking will help identify which CPAN modules need some help, maybe even adoption. If you were wondering where could you contribute to Perl, look at the list and try to pick a module from there.
|
|
I've been patching Config::Tiny
Ron Savage already reacting to the above post of Neil Bowers is planning to become the maintainer of Config::Tiny. I am glad this is happening, and I am glad this is happening in public. I hope this will encourage you too to take action. BTW specifically with Config::Tiny, just a few days ago I bumped into one of its issues - not handling UTF-8 files correctly. As I needed a quick solution I created a locally patched version of the module. This works on the short-run, but having this fixed in the official version of Config::Tiny is much better in the long run.
|
|
Perl 6
|
Rakudo performance
In a nutshell: Rakudo-JVM was 40 times faster than Rakudo-Parrot. This sounds very exciting. I guess you can expect more announcements at YAPC::EU.
|
|
Other
|
Three month after domain name change
Once in a while I collect numbers from various sources trying to see how the Perl Maven site does and compare that with other Perl-related sites, and with sites related to PHP, Python and Ruby. It is unfortunate we don't have the visitor count of the major Perl community sites, but at least you might be able to interpolate from these numbers.
|
|
Weekly collections
|
|
|
|
|
|
|
Interview
|
Dave Miller, the leader of the Bugzilla project
Dave was lucky as a project leader: in the past couple of years he had two assistant project managers who basically ran the Bugzilla project while he only had to help out once in a while. Now that those two have moved on, he steps up his efforts again. In this interview you can hear about his work at the Mozilla Foundation and the challenges the Bugzilla project faces.
|
|
Perl Startups: Recollect.net
Ovid continues his weekly interviews with Perl-based start-up companies. This week it was with Luke Closs, the CTO of recollect.net.
|
|
Perl Maven Tutorial
|
Always use strict!
There are 3 very good reasons to use strict. This article collected the articles explaining each one of the cases.
|
|
|
|
Events
I usually list the next 3-4 events here. The list of all the events can be found on the web site. If your Perl event is not listed there, please let me know.
|
|
|
|
|
YAPC::Asia Tokyo
September 19-21, 2013, Keio University Hiyoshi Campus, Tokyo, Japan
|
|
You know, you could get the Perl Weekly right in your mailbox. Every Week. Free of charge!
|


For more information on Plastic SCM you can visit their website.
Refer to the Plastic SCM documentation if you encounter any problems with the set up process on the version control page.
Plastic SCM automatically checks files out if they have been modified, this makes it more convenient for you. The only files that require specific checking out instructions are Project Settings files otherwise you can’t change them.
A merge is likely to happen when you have edited something in your project locally which has also been edited remotely (a conflict). This means you will need to review the changes before the merge can be performed. If Unity recognises that a merge must be completed before changes can be submitted then you will be prompted by Unity to complete the merge, this will take you to the Plastic SCM client.
If incoming changes conflict with local changes then a question mark icon will appear on conflicting files in the incoming changes window. Here is a quick guide to resolving conflicts and merging with Plastic SCM:
In order to lock files using Plastic SCM there are a few steps to follow:
The first thing you must do is create a lock.conf file and make sure it is placed within your server directory. You can find your server directory from “../PlasticSCM/server”.
In your lock.conf file you must specify the repository you are working on and the server that will complete the lock checks. Here is an example:
rep:default lockserver:localhost:8087
*.unity
*.unity.meta
In this case all .unity and .unity.meta files are going to be locked for checkout on repository ‘default’.
./plasticsd restart
cm listlocks
If the steps have been followed correctly the terminal/command line window should now display a list of locked files. You can also test if this has worked by trying to check out the same file using a different user, an error will appear in Unity’s console saying the file is already checked out by another user.
For more information you can visit the Plastic SCM lock file documentation.
To find more about working in distributed mode (DVCS) and offline with Plastic SCM check the Distributed Version Control Guide.


KKBOX Open API Developer SDK for iOS/macOS/watchOS/tvOS
Copyright © 2016-2018 KKBOX All Rights Reserved.
About
The SDK helps to access KKBOX’s Open API. You can easily add the SDK to your Xcode project, and start an app powered by KKBOX. You may obtain information about song tracks, albums, artists and playlists as well.
The SDK is developed in Objective-C programing language, but you can still bridge the SDK to your Swift code. You can use the SDK on various Apple platforms such as iOS, macOS, watchOS and tvOS.
If you are looking for a pure Swift SDK, please take a look at KKBOX Open API Swift SDK.
For further information, please visit KKBOX Developer Site.
Requirement
The SDK supports
- 📱 iOS 7.x or above
- 💻 Mac OS X 10.9 or above
- ⌚ watchOS 2.x or above
- 📺 tvOS 9.x or above
Build ⚒
You need the latest Xcode and macOS. Xcode 10 and macOS 10.14 Mojave are recommended.
Installation
The SDK supports CocoaPods. Please add pod 'KKBOXOpenAPI'
to your Podfile, and then call pod install
.
Usage
To start using the SDK, you need to create an instance of KKBOXOpenAPI.
let API = KKBOXOpenAPI(clientID: "YOUR_CLIENT_ID", secret: "YOUR_CLIENT_SECRET")
Then, ask the instance to fetch an access token by passing a client credential.
API.fetchAccessTokenByClientCredential { token, error in ... }
Finally, you can start to do the API calls. For example, you can fetch the details of a song track by calling ‘fetchTrack’.
self.API.fetchTrack(withTrackID: trackID, territory: .taiwan) { track, error in ... }
You can develop your app using the SDK with Swift or Objective-C programming language, although we have only Swift sample code here.
The project contains a demo project. Please open KKBOXOpenAPI.xcodeproj
located in the ExampleIOS
folder with Xcode and give it a try.
API Documentation 📖
- Documentation for the SDK is available at https://kkbox.github.io/OpenAPI-ObjectiveC/ .
- KKBOX’s Open API documentation is available at https://developer.kkbox.com/ .
License
Copyright 2016-2018 KKBOX Technologies Limited
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.


By default the tool creates the mock server into the server
sub-folder under the project root.
The original setup is the following:
server/
├── api.js
├── config.js
├── config.yml
├── monitoring.js
├── package.json
├── Readme.md
└── server.js
Where
Readme.md
A short readme file about how to use the server.
server.js
The mock server itself.
config.yml
Configuration parameters of the mock server.
config.js
Helper module to load the configuration parameters.
package.json
Module dependencies of the server. By default this file contains all the required dependencies, but the package.json
file in the parent folder also contains them, so you do not need to install them in the server's folder, because it will access them from it parent's node_modules
folder.
You can extend this file, if you need additional modules installed to implement dynamic behavior. In this case you have changed this file, you have install the packages, so run the npm install
command in the server folder.
api.js
A boilerplate module to implement your own implementation functions. If you want to implement only a couple a functions, it is enough to define them in this module, and just refer to them. In case of more complex logic, you'd better create your own modules.
monitoring.js
A sample module, which demonstrates how an implementation should be written.
In a newly created API project the server is configured to work immediately. The default config.yml
looks like this:
# Use this environment by default,
# if server is started without the <env> parameter
useEnvironment: development
#useEnvironment: production
environments:
# This is the default configuration set
default:
documentRoot: .
port: 3007
restapiRoot: ..
remoteServices: []
# Override the default config parameters
# with values specific to the development environment
development:
port: 3007
documentRoot: ../webui
# A development environment with proxying
# the 'serviceUrlPrefix' requests to the local host
devProxy:
port: 3006
documentRoot: ../webui
remoteServices:
-
uri: /monitoring
active: true
host: localhost
port: 3007
-
uri: /*
active: true
host: localhost
port: 3008
# A second development environment with proxying the
# 'serviceUrlPrefix' requests also to the local host
# but with some exceptions.
devProxyWithExceptions:
port: 3006
documentRoot: ../webui
proxyException:
active: true
urlPrefixList:
- /monitoring/isAlive
- /Flight/legs/.*/closeLeg
remoteServices:
-
uri: /*
active: true
host: localhost
port: 3008
# production environment specific values
production:
port: 3008
documentRoot: ../webui/build/crm-api/production
In general the configuration file can contain any property, but should contain at leas two mandatory properties. These are: environments
and useEnvironment
.
The configuration parameters are grouped into environments which are described under the environments
array propery. Each environment is identified by its name and describe a specific server configuration. The configuration file must define at least one environment, that is the default.
The useEnvironment
tells the server that which environment should be used by default, if it was not specified explicitly when the it is started.
An environment usually has the following configuration properties:
documentRoot: (string | Array) Defines the path to the folder, which is used as the document root to the static content provided by the server. This content can be anything: static HTML pages, Fontend JavaScript application (Backbone, ExtJs, etc.), or anything. This parameter can be an individual string or an array of strings. For example: ../webui
port:
(integer)
The port where the server is listening.
For example: 3007
restapiRoot:
(string)
Path of the project root folder. server needs this in order to be able to access to the service descriptions and mock data files.
For example: ..
remoteServices:
(Array)
An array of server-side forwarding rules used by the proxy middleware. If the proxy middleware is used, it iterates through this array, and try to match the requested URI with the uri
property of each item of this array. Each rule contains the following properties: active, uri, host and port respectively. These properties are described below. The items are matched in order, and the first matching uri
will be used. If none of the uri
is matching, then no forwarding happens.
uri:
(boolean)
A regular expression which fully or partially matches an existing service defined under the services
folder. For example: /monitoring/isAlive
identifies exactly one service. /monitoring/*
stands for any service starting with /monitoring/
. /*
means all services.
active:
(boolean)
If true, the server acts as a proxy server, and forwards the service requests to a remote host.
For example: false
host:
(string)
The host name of the remote host. Used only if the server is in proxy mode with the given service (uri
matches and active: true
).
For example: localhost
port:
(integer)
The port of remote host. Used only if the server is in proxy mode with the given service (uri
matches and active: true
).
For example: 3008
proxyException:
(Array)
Defines exceptions of remote services which should NOT be proxied.
active:
(boolean)
If true, the exception rules are active. Default value is: false.
For example: true
urlPrefixList:
(Array)
Provides uri
patterns to match against requests, which should not by proxied.
Example items: /monitoring/isAlive
, /Flight/legs/.*/closeLeg
.
Beside the parameters listed above, you can add further ones to the config file, if you want to extend the functionalities of the server.
To start the mock server with the default configuration, execute the following command:
$ node server/server.js
This will start a web server, which will listen on the localhost, and the port specified in the config.yml
file (3007 by default).
After starting the server, you can can try it with a browser, or the curl
command line tool:
$ curl http://localhost:3007/rest/monitoring/isAlive
true
If you want to start the server with an other configuration (devProxy
for example), define it as a parameter in the following format:
$ node server/server.js devProxy
register service GET /monitoring/isAlive
/monitoring/isAlive
register service GET /customers
/customers
register service POST /customers
/customers
Express server listening on port 3006 in devProxy mode
As you can see, the server is listening now on port 3006, and proxying the HTTP requests to the localhost:3008
.
The following code fragment shows how the middle-ware is configured for the mock server:
// Configure the middle-wares
server.configure( function() {
server.use( proxy(servicesConfig.serviceUrlPrefix, config.remoteServices) );
server.use( express.bodyParser() );
server.use( express.methodOverride() );
server.use( express.cookieParser() );
server.use( express.session( {secret: 'keyboard cat'} ) );
server.use( server.router );
server.use( '/data', express.static( __dirname + '/' + '../data' ) );
server.use( '/docs', express.static( __dirname + '/' + '../docs' ) );
server.use( '/services', express.static( __dirname + '/../services' ) );
server.use( express.static( __dirname + '/' + config.documentRoot ) );
});
The order of processing is the following:
server.use(proxy(servicesConfig.serviceUrlPrefix, config.remoteServices));
config.remoteServices
array. If any one of them is matching, and the proxying is activated with that matching uri
, then forwards the request to the remoteService.host:remoteService.port
. In other words, every matching service call is proxied to the remote server.server.use(server.router);
server.router
, so in this phase the service are provided on the normal way, if the proxy is not enabled.server.use('/data', express.static(__dirname + '/' + '../data'));
<project-root>/data
folder is provided by this middle-ware. You can place additional data files into this folder. server.use('/docs', express.static(__dirname + '/' + '../docs'));
<project-root>/docs
folder is provided by this middle-ware. Actually this is the HTML format documentation, generated by the rest-tool docs --update
command. So you can read it off-line and on-line as well, provided by the mock server itself.server.use('/services', express.static(__dirname + '/../services'));
<project-root>/services
folder is provided by this middle-ware. These are the folders that describe the services, and contain the additional mock data and other files. In normal cases you do not need this, however you might want to write special service modules, that might want to access these files through HTTP requests.server.use(express.static(__dirname + '/' + config.documentRoot));
documentRoot
config parameter. Typically it points to the source, or distribution folder of the the front-end application under development.As it is described in the previous section, the HTTP middle-ware is configured to process the incoming request in the following order:
service.yml
files.docs
, data
, etc.The the mock server is providing generated documentation by default. You also can configure a so called document root folder, for your web UI.
The next setup is typical for a UI development project:
documentRoot
configuration parameter.In the service.yml
file, every method's request
object can have an optional property, which can identify an implementation function in the following format: <module>.<function>
.
In order to use this feature, you must have a module written in JavaScript placed into the server
folder named <module>.js
, which contains an exported function with the name of <function>
. For example the following file is named monitoring.js
and contains the implementation of the response logic which will be called when the referring method is activated:
function isAlive( request, response, serviceDescriptor )
{
response.header( 'Content-Type', 'application/json' );
response.header( 'X-Application-API-Version', 'v0.0.0' );
response.write( 'true' );
response.end( '\n' );
};
exports.isAlive = isAlive;
As you can see, the function gets all the request parameters, as well as the response object, which is used to compose the response.
In order to be able to behave the expected way, the function gets a third parameter (serviceDescriptor
), which holds all the data found in the corresponding service.yml
file. This object also provides methods to access to the mock files situated beside the service descriptor.
The mock server implementation is built on top of the express.js web framework. In order to learn more about how to use the request
and response
parameters, visit its API documentation pages.
Note that you have to export those functions you would like to use externally. This is done by the
exports.isAlive = isAlive;
line of the code fragment above.You must add a line to the
server.js
which tells the server to load this module when starts. In case of the previous example the following line must be added:
var monitoring = require('./monitoring.js');
If you are not familiar with how to create modules, and how to use exports
, etc. read the Node.js documentation.
The rest-tool
creates the following empty extension module with the new project that is called api.js
.
/**
* Implementation of method calls defined in `service.yml` files
* This file is generated by the rest-tool tool.
*/
var services = require('rest-tool-common').services;
var server = require('./server.js');
//=============================================================================
// Put your mock method implementations here
In case you only want to add a couple of simple function, and do not want to bother with creating ad require
-ing your own module, you should just simple define these functions in this api.js
(export the functions), and refer to them from the service.yml
files, with the implementation
property. This server is loading this api.js
by default, so you do not need to modify that.
By default rest-tool returns with only one response, described in the service.yml that is:
name: OK
statusCode: 200
Each method must have at least one OK
response. All the other codes listed under the responses provide documentation purposes by default.
In order to decide which (other) code the server should response you have to built some logic into the server, so you have to make a module inside the server folder, and implement the function that the given method will call. You can refer to this method with the 'implementation' property of each method in the service.yml
file.
Also, you have to require
the newly created module in the server/server.js
file.
Below I will explain how can you respond with 400
:
After the creation of a new project, the rest-tool automatically creates a service, that is called monitoring/isAlive
. You can find its descriptor in the services/monitoring/isAlive/service.yml
.
This file contains a GET method, and that has an implementation, that is:
implementation: monitoring.isAlive
So there is an implementation module, under the server folder, that is: monitoring.js
.
function isAlive( request, response, serviceDescriptor )
{
response.header( 'Content-Type', 'application/json' );
response.header( 'X-Application-API-Version', 'v0.0.0' );
response.write( 'true' );
response.end( '\n' );
};
exports.isAlive = isAlive;
So, if the server is running, you will get the response of true
is you call this service:
$ curl http://localhost:3007/rest/monitoring/isAlive
true
If you want to response a different status-code (400 for example), replace the body of the isAlive
function with the following code:
function isAlive( request, response, serviceDescriptor )
{
response.status(400).send('Bad Request');
};
Restart the server, and call again the service. The result will be the following:
$ curl http://localhost:3007/rest/monitoring/isAlive
Bad Request
To see also the code, call the curl
with -v
:
$ curl http://localhost:3007/rest/monitoring/isAlive -v
* About to connect() to localhost port 3007 (#0)
* Trying <IP_ADDRESS>...
* connected
* Connected to localhost (<IP_ADDRESS>) port 3007 (#0)
> GET /rest/monitoring/isAlive HTTP/1.1
> User-Agent: curl/7.27.0
> Host: localhost:3007
> Accept: */*
>
* additional stuff not fine transfer.c:1037: 0 0
* HTTP 1.1 or later with persistent connection, pipelining supported
< HTTP/1.1 400 Bad Request
< X-Powered-By: Express
< Vary: Accept-Encoding
< Content-Type: text/html; charset=utf-8
< Content-Length: 11
< X-Response-Time: 1ms
< Set-Cookie: connect.sid=s%3As8tJdvyopZnjRndqPrh1U_Qh.N8Eln3hIcweFei1r6gkVeSr7f%2F3iKV3gxFI4Y44P8qo; Path=/; HttpOnly
< Date: Sat, 20 Dec 2014 14:54:30 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
Bad Request* Closing connection #0
As you can see, the implementation function gets the whole service descriptor as its third parameter. So you can access to any proerty you have defined in the service.yml
.
It is very likely that your server implementation will be written in a different language, not in JavaScript, and developed by an other team.
However one of the advantages of using rest-tool is to let the development teams working parallel with each other, you have to integrate your front-end with the back-end, for several reasons, but the most obvious one is, to see how the two parts work together, and do bug-fixing.
In such situations you need your independent front-end environment as well as you should be able to connect to the real implementation instead of the mock server. For security reasons, in such cases you usually should deploy your front-end to the application server, that can be rather time consuming. This is the case, when the proxy comes into the picture. You can continue using your mock server as static content provider, to load your front-end application, but you can switch on its proxy function to forward the service calls to a remote server, that is the application server your front-end should be tested with.
In order to use this feature, create a configuration of the server (according to the The mock server configuration section) to enable the proxy function that forwards the requests to the test application server, and continue using the mock to provide its static content that you have been used so far for development. This way, you can connect to the real, or test application server without the long-lasting deployment process, and easily switch back and forth between the mock and the other back-end implementation.
Using an array of forwarding rules, it is possible to proxy different services toward differend servers. For example you can use the original mock server to provide the frontend code under development provided as static content directly by the mock server. Then you can also provide some basic REST services also by the mock server (/monitoring/isAlive
, etc.). At the same time you can add some rules to forward the REST calls to an other Node.js, PHP or JEE backend server. Moreover you can add an other proxy rule to forward REST calls to a third party messaging middleware (RabbitMQ, HornetQ, etc.).
You can individually enable/disable the forwarding of each service call, using the active
field in the configuration. This way, you can first use the mock services, until the final implementation gets ready to use. Then you can switch out to the real backend service one-by-one.
In some cases it is not easy to control the proxy-ing of individual services under development, meanwhile we want to forward all the other requests to a remote server.
For such cases you can use the proxyException
patterns. This is a different approach. Here you can allow the remote services in general, and add the exceptions one-by-one to the proxyException
list.


Daddy, (AKA adeh desandies) was a boung boy born in Newark, california in 1977,the same year jimmy carter became the us resident and the artificial heart was invented.
he had a lot of fun growing up in lake blvd, newark, as he thrively grew in 35167 charmwood court, a lovely house. he lived in a room that is now a half of a new room.
he was known to be a deep thinker:
and he loved to play with toys.
he really loved to climb(like me)...
but not as much as he loves his brother(like me)
he was starting to grow up
so he went to school. he went to key's school since kind gardens, then went to JFK school since 3rd grade.
he wanted to become a crazy scientist,
and he smiled like that too.....(ya right)
he graduated from primary and went to highschool. he played soccer there.
then he went to play track in senior highschool.
as he was growing, so was his hair.
growing...
and growing!
he went to uni anyways....
and then, after coming to china, he had jinyao.
then he had rere...


[gecode-users] AllInterval Series
Nick Hindle
nick.hindle at tesco.net
Tue Jun 5 19:51:51 CEST 2007
Hi,
In the All-Interval series example, I cannot work out how values for the private member IntVarArray x are initialised.
According to the specification in www.CSPLib.org, this var array holds the numbers 0,1,...11 to represent the pitch-classes c, c#, d, etc.
Could someone help me understand how they are initialised in this example?
Thankyou in advance,
Nick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.ps.uni-sb.de/pipermail/users/attachments/20070605/7cb5b963/attachment.htm>
More information about the gecode-users
mailing list


Cashuna Marshall
About
Portfolio
Contact
Contact
Your name:
Subject:
Send a message:
E-mail me
Connect Using:
Links curentlly unavailable.


A Light in the ...
£51.77
In stock
£51.77
In stock
£53.74
In stock
£50.10
In stock
£47.82
In stock
£54.23
In stock
£22.65
In stock
£33.34
In stock
£17.93
In stock
£22.60
In stock
£52.15
In stock
£13.99
In stock
£20.66
In stock
£17.46
In stock
£52.29
In stock
£35.02
In stock
£57.25
In stock
£23.88
In stock
£37.59
In stock
£51.33
In stock
£45.17
In stock


Before Change
if restore:
self.restore()
avg_loss, n_batches = 0.0, 0.0
coord = tf.train.Coordinator()
n_samples = 0
if self.use_queue:
enqueue_thread = threading.Thread(
target=_enqueue_batch,
After Change
// we try to read more batches than the total number that get queued,
// this thread will hang indefinitely.
while n_enqueued[0] <= n_samples:
if n_samples == final_sample[0]:
break
time.sleep(0)
if n_samples == final_sample[0]:
break
fetched_values = self.session.run(fetches, feed_dict=feed_dict)


Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
This is bold text
This is italic text
Strikethrough
I’m an inline-style link with hover title
“This is a cool quote. Below is a separator line.”
//this is CSS. Other options are javascript, json, yml and more
#header h1 {
color: #fff;
}
No language indicated, so no syntax highlighting.
Inline code
has back-ticks around
it.
Full Width Image
Regular Image
Unordered list
- Donec non tortor in arcu mollis feugiat
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit
Here is an ordered list of items
- Donec non tortor in arcu mollis feugiat
- Lorem ipsum dolor sit amet, consectetuer adipiscing elit
Tables
| Title | Title |
|---|---|
| Text | Text |
| Text | Text |
| Text | Text |


Before Change
if restore:
self.restore()
avg_loss, n_averaged_batches = 0.0, 0.0
coord = tf.train.Coordinator()
n_samples = 0
n_enqueued = [0]
final_sample = [None]
if self.use_queue:
After Change
if n_averaged_batches > 0:
avg_loss = float(avg_loss) / n_averaged_batches
if checkpoint_interval > 0:
if n_averaged_batches > 0:
print("Ending global_step %d: Average loss %g" % (self.global_step,
avg_loss))
saver.save(self.session, self.save_file, global_step=self.global_step)
time2 = time.time()
print("TIMING: model fitting took %0.3f s" % (time2 - time1))
return avg_loss


myapp/src/main/web/.*\.html myapp/src/main/web/.*\.jpeg myapp/src/main/web/.*\.gifThe example above illustrates that a build will only occur, if html/jpeg/gif files have been committed to the SCM. Exclusions take precedence over inclusions, if there is an overlap between included and excluded regions.


Driver:
all
Temperature
Precipitation
Impact:
all
Coastal and marine Ecosystems
Human and managed
Mountains, snow and ice
Rivers, lakes, and soil moisture
Terrestrial ES
Other systems
Variable:
Population
Area


This app is scaffolded by
slush-ng
This app uses Bootstrap
for styling. If you are looking to add functional Bootstrap components, refer UI Bootstrap.
This app is baked in with
This app comes integrated with
angular-route
,
controllers
, a sample
directive
and a sample
filter
This app also has a sample factory
layer, that can be used to interact with RESTful services (includes an example too).


nips nips2008 nips2008-234 nips2008-234-reference knowledge-graph by maker-knowledge-mining
Source: pdf
Author: Jurgen V. Gael, Yee W. Teh, Zoubin Ghahramani
Abstract: We introduce a new probability distribution over a potentially inﬁnite number of binary Markov chains which we call the Markov Indian buffet process. This process extends the IBP to allow temporal dependencies in the hidden variables. We use this stochastic process to build a nonparametric extension of the factorial hidden Markov model. After constructing an inference scheme which combines slice sampling and dynamic programming we demonstrate how the inﬁnite factorial hidden Markov model can be used for blind source separation. 1
[1] L. R. Rabiner, “A tutorial on hidden markov models and selected applications in speech recognition,” Proceedings of the IEEE, vol. 77, pp. 257–286, 1989.
[2] Z. Ghahramani and M. I. Jordan, “Factorial hidden markov models,” Machine Learning, vol. 29, pp. 245– 273, 1997.
[3] P. Wang and Q. Ji, “Multi-view face tracking with factorial and switching hmm,” in Proceedings of the Seventh IEEE Workshops on Application of Computer Vision, pp. 401–406, IEEE Computer Society, 2005.
[4] B. Logan and P. Moreno, “Factorial hmms for acoustic modeling,” 1998.
[5] K. Duh, “Joint labeling of multiple sequences: A factorial hmm approach,” in 43rd Annual Meeting of the Association of Computational Linguistics (ACL) - Student Research Workshop, 2005.
[6] T. L. Grifﬁths and Z. Ghahramani, “Inﬁnite latent feature models and the indian buffet process,” Advances in Neural Information Processing Systems, vol. 18, pp. 475–482, 2006.
[7] R. M. Neal, “Bayesian mixture modeling,” Maximum Entropy and Bayesian Methods, 1992.
[8] Y. W. Teh, D. G¨ r¨ r, and Z. Ghahramani, “Stick-breaking construction for the indian buffet process,” ou Proceedings of the International Conference on Artiﬁcial Intelligence and Statistics, vol. 11, 2007.
[9] A. Hyvarinen and E. Oja, “Independent component analysis: Algorithms and applications,” Neural Networks, vol. 13, pp. 411–30, 2000.
[10] D. Knowles and Z. Ghahramani, “Inﬁnite sparse factor analysis and inﬁnite independent components analysis,” Lecture Notes in Computer Science, vol. 4666, p. 381, 2007.
[11] S. L. Scott, “Bayesian methods for hidden markov models: Recursive computing in the 21st century,” Journal of the American Statistical Association, vol. 97, pp. 337–351, Mar. 2002.
[12] J. Van Gael, Y. Saatci, Y. W. Teh, and Z. Ghahramani, “Beam sampling for the inﬁnite hidden markov model,” in The 25th International Conference on Machine Learning, vol. 25, (Helsinki), 2008.
[13] M. J. Beal, Z. Ghahramani, and C. E. Rasmussen, “The inﬁnite hidden markov model,” Advances in Neural Information Processing Systems, vol. 14, pp. 577 – 584, 2002.
[14] Z. Ghahramani, T. L. Grifﬁths, and P. Sollich, “Bayesian nonparametric latent feature models,” Bayesian Statistics, vol. 8, 2007. 8


OmniAuth::Basic
OmniAuth stratgies for APIs that have HTTP Basic authentication (such as Campfire and Basecamp).
Installation
To get just HTTP Basic functionality:
gem install oa-basic
For the full auth suite:
gem install omniauth
Stand-Alone Example
Use the strategy as a middleware in your application:
require 'omniauth/basic' use OmniAuth::Strategies::Campfire
Then simply direct users to ‘/auth/campfire’ to prompt them for their Campfire credentials. You may also pre-set the credentials by POSTing to the URL with appropriate parameters (in the case of Campfire and Basecamp, the parameters are subdomain, user, and password).
OmniAuth Builder
If you want to allow multiple providers, use the OmniAuth Builder:
require 'omniauth/basic' use OmniAuth::Builder do provider :campfire provider :basecamp end


Demon rankings made possible thanks to Pointercrate! All demons and rankings are managed by their list staff.
Usernames may differ from what is used in GD


StackOverflow-lite is a platform where people can ask questions and provide answers.
These are all the questions asked in all forums.


Frequently Asked Questions:
How do I get involved with the FAANG project?
Please register at the FAANG website to become part of the FAANG community and join the working commitees.
How do I submit sample and experimental data to FAANG data portal?
The FAANG data portal displays sample, experiment and analysis data for livestock animals. There are detailed instructions on how to prepare and submit your data at our dedicated web page. These pages will guide you through the preparation of your data to meet the FAANG metadata standards and in the use of the tools that we have developed to support your submission.
How to access FAANG data?
We provide two ways of accessing the data: one is through this data portal, the other is through APIs to access programmatically. More details can be found on our API help page.
Is there a way to access data programmatically?
Certainly. We provide APIs to access data programmatically. The details can be found on our API help page.
Does FAANG have a Data Sharing Policy?
FAANG is committed to sharing data rapidly, before publication. All members have agreed to the FAANG Data Sharing Statement for pre-publication data release.
FAANG is also committed to making regular public releases of primary and secondary analysis results to provide access to the wider community.
I still have questions, how do I contact you?
Please contact the FAANG Data Coordination Centre, we are happy to help.


Description
{{family.description}}
Classification and Taxa
Classification:
{{family.display_classification.path}}
Curation Details
Status: {{family.curation_state_name}}
Method: {{family.source_method}} {{family.source_method_description}}
Source Assembly:
{{family.source_assembly.label}}
Length: {{family.length}}
Target Site Duplication: {{family.target_site_cons || "Unknown"}}
Citations
-
{{cit.title}}
{{cit.authors}}
{{cit.journal}} Pubmed
Aliases and External Links
- {{alias.database}}: {{alias.alias}}
Source
Submitter: {{family.submitter}}
Author: {{family.author || "Unknown"}}
Created On: {{family.date_created | date: 'medium'}}
Modified On: {{family.date_modified | date: 'medium'}}


Attempting to connect to a database in a Java program (getting a Connection object) is a time-consuming task. If you create a certain amount of connection in advance and store it in the repository, you can save time if the program provides a connection from the repository if there is a request. This programming technique is called connection pooling. When using JDBC, you have to return the connection to the repository instead of returning the resource using the Connection's close() method.
Log is a class for outputting log messages to a file.
DBConnectionPool is a class that puts database connections into a pool and manages it.
DBConnectionPoolManager is a class that manages DBConnectionPool objects.
The ConnectionManager is an abstract class that asks the DBConnectionPoolManager class for a connection. The reason for the abstract class is that it considers multiple databases. Depending on the database you are using, create a class that inherits this class.
OracleConnectionManager is a class that inherits the ConnectionManager class to manage connections for Oracle.
Oracle.properties is the connection pool configuration file for Oracle. In oracle.properties, the string "oracle" is used as the distinguished name of the connection pool object for Oracle. It is advantageous for reuse and maintenance to manage the configuration as a file rather than to implement it in Java code.
package net.java_school.util; import java.io.*; import java.util.Date; public class Log { public String logFile = "C:/jdbc/connection-pool.log"; FileWriter fw = null; public static final String LINE_SEPARATOR = System.getProperty("line.separator"); public Log() { try { fw = new FileWriter(logFile, true); } catch (IOException e){} } public void close() { try { fw.close(); } catch (IOException e){} } public void close(FileWriter fw) { try { fw.close(); } catch (IOException e){} } public void debug(String msg) { try { fw.write(new java.util.Date()+ " : "); fw.write(msg + LINE_SEPARATOR); fw.flush(); } catch (IOException e) { System.err.println("IOException.......!!"); } } public static void out(String msg) { System.out.println(new Date() + ": " + msg); } public static void err(String msg) { System.out.println(new Date() + ": " + msg); } public static void err(Throwable e, String msg) { System.err.println(new Date() + ": " + msg); e.printStackTrace(System.out); } }
package net.java_school.db.dbpool; import java.util.*; import java.sql.*; import java.util.Date; import net.java_school.util.Log; class DBConnectionPool { //Number of connections currently in use private int checkedOut; // Free Connection List private Vector<Connection> freeConnections = new Vector<Connection>(); //Maximum number of connections private int maxConn; //Initial number of connections private int initConn; //Waiting time (maximum time to wait when there is no connection in the pool) private int maxWait; //Connection Pool Name private String name; //DB Password private String password; //DB URL private String URL; //DB UserID private String user; //Constructor public DBConnectionPool(String name, String URL, String user, String password, int maxConn, int initConn, int waitTime) { this.name = name; this.URL = URL; this.user = user; this.password = password; this.maxConn = maxConn; this.maxWait = waitTime; for (int i = 0; i < initConn; i++) { freeConnections.addElement(newConnection()); } } //Returning Connection //@param con : Connection to return public synchronized void freeConnection(Connection con) { freeConnections.addElement(con); checkedOut--; //Notify thread waiting to get Connection notifyAll(); } //Get Connection public synchronized Connection getConnection() { Connection con = null; //If Connection is in Free List, get the first of List if (freeConnections.size() > 0) { con = (Connection) freeConnections.firstElement(); freeConnections.removeElementAt(0); try { //If the connection is closed by the DBMS, request again if (con.isClosed()) { Log.err("Removed bad connection from " + name); con = getConnection(); } } //If strange connection occurs, request again catch (SQLException e) { Log.err(e, "Removed bad connection from " + name); con = getConnection(); } } //If Connection is not in Free List, create new else if (maxConn == 0 || checkedOut < maxConn) { con = newConnection(); } if (con != null) { checkedOut++; } return con; } //Get Connection //@param timeout : Maximum Wait Time to Obtain a Connection public synchronized Connection getConnection(long timeout) { long startTime = new Date().getTime(); Connection con; while ((con = getConnection()) == null) { try { wait(timeout * maxWait); } catch (InterruptedException e) {} if ((new Date().getTime() - startTime) >= timeout) { //Wait timeout return null; } } return con; } //Get Connection private Connection newConnection() { Connection con = null; try { if (user == null) { con = DriverManager.getConnection(URL); } else { con = DriverManager.getConnection(URL, user, password); } Log.out("Created a new connection in pool " + name); } catch (SQLException e) { StringBuffer sb = new StringBuffer(); sb.append("Can't create a new connection for "); sb.append(URL); sb.append(" user: "); sb.append(user); sb.append(" passwd: "); sb.append(password); Log.err(e, sb.toString()); return null; } return con; } }
package net.java_school.db.dbpool; import java.sql.*; import java.util.*; import net.java_school.util.Log; public class DBConnectionPoolManager { //To apply the singleton pattern to the DBConnectionPoolManager (keep only one instance), declare it as static static private DBConnectionPoolManager instance; private Vector<String> drivers = new Vector<String>(); private Hashtable<String, DBConnectionPool> pools = new Hashtable<String, DBConnectionPool>(); //Obtaining instance of DBConnectionPoolManager // @return DBConnectionManger static synchronized public DBConnectionPoolManager getInstance() { if (instance == null) { instance = new DBConnectionPoolManager(); } return instance; } // Default Constructor private DBConnectionPoolManager() {} //Send current Connection to Free Connection List //@param name : Pool Name //@param con : Connection public void freeConnection(String name, Connection con) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { pool.freeConnection(con); } Log.out("One Connection of " + name + " was freed"); } //Obtain Open Connection. Creates a new connection if there are no open connections and the maximum number of connections has not been reached. //Waits for the default wait time when there are no open connections currently and the maximum number of connections is in use. //@param name : Pool Name //@return Connection : The connection or null public Connection getConnection(String name) { DBConnectionPool pool = (DBConnectionPool) pools.get(name); if (pool != null) { return pool.getConnection(10); } return null; } // Create a Connection Pool // @param poolName : Name of Pool to create // @param url : DB URL // @param user : DB UserID // @param password : DB Password private void createPools(String poolName, String url, String user, String password, int maxConn, int initConn, int maxWait) { DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, maxConn, initConn, maxWait); pools.put(poolName, pool); Log.out("Initialized pool " + poolName); } //Initialization public void init(String poolName, String driver, String url, String user, String passwd, int maxConn, int initConn, int maxWait) { loadDrivers(driver); createPools(poolName, url, user, passwd, maxConn, initConn, maxWait); } //JDBC Driver Loading //@param driverClassName : The JDBC driver for the DB you want to use. private void loadDrivers(String driverClassName) { try { Class.forName(driverClassName); drivers.addElement(driverClassName); Log.out("Registered JDBC driver " + driverClassName); } catch (Exception e) { Log.err(e, "Can't register JDBC driver: " + driverClassName); } } public Hashtable<String,DBConnectionPool> getPools() { return pools; } public int getDriverNumber() { return drivers.size(); } }
package net.java_school.db.dbpool; import java.sql.*; import java.io.*; import java.util.*; import net.java_school.util.Log; public abstract class ConnectionManager { protected DBConnectionPoolManager connMgr; protected String poolName, dbServer, dbName, port, userID, passwd; protected int maxConn,initConn, maxWait; private Properties dbProperties; private String configFile; public ConnectionManager(String pool) { poolName = pool; //Specifying the directory for the Property file configFile = "C:/jdbc/"+poolName+".properties"; try { dbProperties = readProperties(); dbServer = getProperty("dbServer"); port = getProperty("port"); dbName = getProperty("dbName"); userID = getProperty("userID"); passwd = getProperty("passwd"); maxConn = Integer.parseInt(getProperty("maxConn")); initConn = Integer.parseInt(getProperty("initConn")); maxWait = Integer.parseInt(getProperty("maxWait")); } catch (IOException ioe) { Log.err("Error reading properties of " + configFile); } } public Connection getConnection() { return (connMgr.getConnection(poolName)); } public void freeConnection(Connection conn) { connMgr.freeConnection(poolName, conn); } private String getProperty(String prop) throws IOException { return (dbProperties.getProperty(prop)); } protected synchronized Properties readProperties() throws IOException { Properties tempProperties = new Properties(); FileInputStream in = new FileInputStream(configFile); tempProperties.load(in); return tempProperties; } public int getDriverNumber() { return connMgr.getDriverNumber(); } }
package net.java_school.db.dbpool; public class OracleConnectionManager extends ConnectionManager { public OracleConnectionManager() { super("oracle"); String JDBCDriver = "oracle.jdbc.driver.OracleDriver"; //Oracle JDBC thin driver String JDBCDriverType = "jdbc:oracle:thin"; String url = JDBCDriverType + ":@" + dbServer + ":" + port + ":" + dbName; connMgr = DBConnectionPoolManager.getInstance(); connMgr.init(poolName, JDBCDriver, url, userID, passwd, maxConn, initConn, maxWait); } }
############################################ # Database Connection Properties for Oracle ############################################ # Database Server Name OR IP address dbServer = <IP_ADDRESS> # The port number your DB server listents to. port = 1521 # Database Name dbName = XE # Database User userID = scott # Database Password passwd = tiger # Maximum Connection Number maxConn = 20 # Inital Connection Number initConn = 5 # Maximum Wait Time maxWait = 5
Create an empty file named connection-pool.log in C:/jdbc according to the following code in Log.java:
public String logFile = "C:/jdbc/connection-pool.log"
Create a file named oracle.properties in C:/jdbc according to the following code in ConnectionManager.java:
configFile = "C:/jdbc/" + poolName + ".properties";
If compilation is complete, apply it to GetEmp.java.
package net.java_school.jdbc; import java.sql.*; import net.java_school.util.Log; import net.java_school.db.dbpool.*; public class GetEmp { public static void main(String[] args) { ConnectionManager conMgr = new OracleConnectionManager(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String query = "SELECT * FROM emp"; try { conn = conMgr.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(query); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); System.out.println(empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm + " : " + depno); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conMgr.freeConnection(conn); } catch (SQLException e) {} } } }
DBCP is Apache's open source connection pool library.
More information is available at:
http://commons.apache.org/proper/commons-dbcp/
An example we will practice is BasicDataSourceExample.java at the following address: http://svn.apache.org/viewvc/commons/proper/dbcp/trunk/doc/ I will test BasicDataSourceExample.java with a little modification. To practice the example, add the commons-dbcp, commons-pool, and commons-logging libraries to the Build Path.
Note that DBCP 2 runs only in the JDK 7 environment. You have to use DBCP 1.4 in JDK 6 and DBCP 1.3 in JDKs 6 and below.
package net.java_school.dbcp; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 javax.sql.DataSource; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; // // Here are the dbcp-specific classes. // Note that they are only used in the setupDataSource // method. In normal use, your classes interact // only with the standard JDBC API // import org.apache.commons.dbcp2.BasicDataSource; // // Here's a simple example of how to use the BasicDataSource. // // // Note that this example is very similiar to the PoolingDriver // example. // // To compile this example, you'll want: // * commons-pool-1.5.6.jar // * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+) // * j2ee.jar (for the javax.sql classes) // in your classpath. // // To run this example, you'll want: // * commons-pool-1.5.6.jar // * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+) // * j2ee.jar (for the javax.sql classes) // * the classes for your (underlying) JDBC driver // in your classpath. // // Invoke the class using two arguments: // * the connect string for your underlying JDBC driver // * the query you'd like to execute // You'll also want to ensure your underlying JDBC driver // is registered. You can use the "jdbc.drivers" // property to do this. // // For example: // java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \ // -classpath commons-pool-1.5.6.jar:commons-dbcp-1.4.jar:j2ee.jar:oracle-jdbc.jar:. \ // PoolingDataSourceExample // "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" // "SELECT * FROM DUAL" // public class BasicDataSourceExample { public static void main(String[] args) { // First we set up the BasicDataSource. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up data source."); DataSource dataSource = setupDataSource("jdbc:oracle:thin:@<IP_ADDRESS>:1521:XE"); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery("SELECT * FROM dept"); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while(rset.next()) { for(int i=1;i<=numcols;i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch(SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch(Exception e) { } try { if (stmt != null) stmt.close(); } catch(Exception e) { } try { if (conn != null) conn.close(); } catch(Exception e) { } } } public static DataSource setupDataSource(String connectURI) { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); ds.setUsername("scott"); ds.setPassword("tiger"); ds.setUrl(connectURI); return ds; } public static void printDataSourceStats(DataSource ds) { BasicDataSource bds = (BasicDataSource) ds; System.out.println("NumActive: " + bds.getNumActive()); System.out.println("NumIdle: " + bds.getNumIdle()); } public static void shutdownDataSource(DataSource ds) throws SQLException { BasicDataSource bds = (BasicDataSource) ds; bds.close(); } }
Let's create a class that gets a connection from the connection pool by referring to the example above.
package net.java_school.dbcp; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; public class Test { private static final String URL = "jdbc:oracle:thin:@<IP_ADDRESS>:1521:XE"; private static final String USER = "scott"; private static final String PASS = "tiger"; private DataSource dataSource; public Test() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); ds.setUsername(USER); ds.setPassword(PASS); ds.setUrl(URL); this.dataSource = ds; } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
Apply the above class to GetEmp.java.
package net.java_school.jdbc; import java.sql.*; import net.java_school.dbcp.*; public class GetEmp { public static void main(String[] args) { Test test = new Test(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String query = "SELECT * FROM emp"; try { conn = test.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(query); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); System.out.println(empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm + " : " + depno); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) {} } } }
Note that the connection is returned by the conn.close();. Would not it be a problem to return resources like this when using a connection pool? To solve this question, you have to look at the DataSource interface. The DataSource is the connection factory. There are three kinds of implementations of DataSource.
DBCP implements the javax.sql.DataSource interface. The connections we have used so far are different from those for connection pooling. The close() method of the connection object for connection pooling returns itself to the pool.
We will create an example similar to the connection pool we already used. First, create a ConnectionManager abstract class. The constructor of this abstract class reads the configuration file and sets the object's members. This abstract class has a method that is called to get a connection.
package net.java_school.dbcp; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; public abstract class ConnectionManager { protected String poolName, dbServer, dbName, port, userID, passwd; protected int maxConn, initConn, maxWait; protected DataSource dataSource; public ConnectionManager(String pool) { String configFile = pool + ".properties"; Properties properties = readProperties(configFile); dbServer = properties.getProperty("dbServer"); port = properties.getProperty("port"); dbName = properties.getProperty("dbName"); userID = properties.getProperty("userID"); passwd = properties.getProperty("passwd"); maxConn = Integer.parseInt(properties.getProperty("maxConn")); initConn = Integer.parseInt(properties.getProperty("initConn")); maxWait = Integer.parseInt(properties.getProperty("maxWait")); } protected synchronized Properties readProperties(String configFile) { Properties properties = new Properties(); FileInputStream in = null; try { in = new FileInputStream(configFile); properties.load(in); } catch (IOException e) { e.printStackTrace(); return null; } return properties; } public Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
Next, create an OracleConnectionManager class that inherits ConnectionManager.
package net.java_school.dbcp; import org.apache.commons.dbcp2.BasicDataSource; public class OracleConnectionManager extends ConnectionManager { public OracleConnectionManager() { super("oracle"); String driverClassName = "oracle.jdbc.driver.OracleDriver"; String driverType = "jdbc:oracle:thin"; String url = driverType + ":@" + dbServer + ":" + port + ":" + dbName; BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(driverClassName); ds.setUsername("scott"); ds.setPassword("tiger"); ds.setUrl(url); this.dataSource = ds; } }
MaxConn, initConn, maxWait If not set, the default value is applied. To set it as a property file, add the following code:
ds.setInitialSize(initConn); ds.setMaxTotal(maxConn); ds.setMaxWaitMillis(maxWait);
For instructions on how to set it in BasicDataSource, see the official site documentation. Copy the oracle.properties file to the root directory of your Eclipse project.
############################################ # Database Connection Properties for Oracle ############################################ # Database Server Name OR IP address dbServer = <IP_ADDRESS> # The port number your DB server listents to. port = 1521 # Database Name dbName = XE # Database User userID = scott # Database Password passwd = tiger # Maximum Connection Number maxConn = 20 # Inital Connection Number initConn = 5 # Maximum Wait Time maxWait = 5
Let's apply them to GetEmp.java again.
package net.java_school.jdbc; import java.sql.*; import net.java_school.dbcp.*; public class GetEmp { public static void main(String[] args) { ConnectionManager conMgr = new OracleConnectionManager(); Connection conn = null; Statement stmt = null; ResultSet rs = null; String query = "SELECT * FROM emp"; try { conn = conMgr.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(query); while (rs.next()) { String empno = rs.getString(1); String ename = rs.getString(2); String job = rs.getString(3); String mgr = rs.getString(4); String hiredate = rs.getString(5); String sal = rs.getString(6); String comm = rs.getString(7); String depno = rs.getString(8); System.out.println(empno + " : " + ename + " : " + job + " : " + mgr + " : " + hiredate + " : " + sal + " : " + comm + " : " + depno); } } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) {} } } }References