The settings tag allows access to site settings.
Returns a setting value. Most are simply text strings edited via the settings tab in PyroCMS. Some, however, are boolean and use 1 for true and 0 for false.
| Setting | Notes |
|---|---|
| activation_email | 1 or 0. Send out an e-mail when a user signs up with an activation link |
| akismet_api_key | |
| comment_order | ASC (Oldest First) or DESC (Newest First) |
| contact_email | |
| currency | |
| dashboard_rss | |
| dashboard_rss_count | |
| default_theme | Folder name of the default theme |
| enable_profiles | 1 or 0 |
| frontend_enabled | 1 or 0 |
| ga_email | Google Analytics email |
| ga_password | Google Analytics password |
| ga_profile | Google Analytics profile ID |
| ga_tracking | Google Analytics tracking ID |
| mail_protocol | |
| mail_sendmail_path | |
| mail_smtp_host | |
| mail_smtp_pass | |
| mail_smtp_port | |
| mail_smtp_user | |
| meta_topic | |
| moderate_comments | 1 or 0 |
| records_per_page | Number |
| require_lastname | 1 or 0 |
| rss_feed_items | Number |
| server_email | |
| site_name | |
| site_slogan | |
| twitter_cache | Number |
| site_slogan | |
| twitter_consumer_key | |
| twitter_consumer_key_secret | |
| twitter_feed_count | Number |
| twitter_blog | 1 or 0 |
| twitter_username | |
| unavailable_message | |
| version | Current version of PyroCMS |


Mathematics of Machine Learning
LMS-Bath Symposium, 3-7 August 2020, University of Bath
Back
Talks
Posters
Public Lecture
To be confirmed


YouTube is a social media company and website where people upload videos to share with other people and comment on other people's videos.
 They are great sources of entertainment. They also cure boredom and help relieve stress after I have had a rough moment or a bad day.
I think that working as a YouTube content creator would be a great job for me. YouTube content creators are basically the same as YouTubers. They create videos and then upload them onto YouTube to share with others. I think that it is a good job for me because not only am I good at making videos but I am also good at editing and even adding effects to them. I am also good at photo editing. I use computers, iPads, and phones on a daily basis. I mainly use them for entertainment and for doing homework sometimes. I would like to spend my time learning more about computers and software, especially multimedia software. The hardest part about this is the coding. Codes have a lot of content that can mean different things, but look very similar, so it can be very confusing at times. I like to edit photos and videos because it allows me to be creative. I don't find any of the industry boring. I just find the coding difficult and frustrating because it is not only time-consuming, but it is also very confusing.
The assignment tells you to pick a job in the technology industry you would like to work at and why you would like to work there. I chose YouTube because it is interesting. I learned that not all aspects of a job will be easy and that coding is involved with nearly any job that involves technology.


--- layout: default title: ICHTD'17 - PayPal Payment Successful meta: Your payment has been successful! keyword: heat transfer, heat transfer devices, cfd, boilers, compact heat exchangers, heat transfer enhancement, mechanical design, heat transfer conference, heat transfer devices conference, cfd conference, boilers conference, compact heat exchangers conference, heat transfer enhancement conference, mechanical design conference, fluid flow, fluid flow conference, fluid mechanics, fluid mechanics conference, fluid dynamics, fluid dynamics conference ---
Your payment has been successful!
We thank you very much for registering for ICHTD'17. An email has been sent to you confirming your payment to ICHTD'17. Please keep this email for your reference.
Please make sure you fill out and submit the registration form. Failing to fill out this form will result in the elimination of your registration.
You may find the registration form by following the link below:
Should you have any concerns, questions or comments, please do not hesitate to contact us at:
We are looking forward to seeing you at ICHTD'17!


A list of books
There are many books that provide a great insight into decision making. Some of them are:
- Seneca, translated by R. Campbell (c. 65 AD) Letters from a Stoic
- R. Hagstrom (2013) Investing. The last liberal art
- P. Kalanithi (2016) When breath becomes air
- R. Fisher & D. Shapiro (2005) Beyond reason
- L. Bernstein (1998) Against the Gods: The remarkable story of risk
- D. Ariely (2010) Predictable irrational. The hidden forces that shape our decisions
- D. Kahneman (2012) Thinking, fast and slow
- P. Tetlock & D. Gardner (2016) Superforecasting: The art and science of prediction
- P. Belevin (2003) Seeking for wisdom: From David to Munger
- N. Taleb (2012) Antifragile: Things that gain from disorder
- V. Voss & T. Raz (2017) Never split the difference: Negotiating as if your life depended on it
- A. Schopenhauer (1831) The art of always being right
- R. Dalio (2017) Principles: Life and work
- J. Hallinan (2009) Why we make mistakes: How we look without seeing. Forget things in seconds, and are all pretty sure we are way above average
- M. Peterson (2009) An introduction to decision theory
- J. Boutand & M. Lara (2015) The biased mind: How evolution shaped our psychology including anecdotes and tips for making sound decisions
- R. Emerson (1841) Self-reliance and other essays


|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object com.izforge.izpack.util.Log
public class Log
This class handles informing the user about unusual events during the installation process and therefore about the possibility that the installation may not have succeeded at all or may have succeeded only partially. Because the logger represents a single resource it is implemented as singleton.
addMessage()
methods, using
the appropriate message index. If the message contains placeholders for variables, provide a
String
array that supplies the necessary variable text. Calling
addMessage()
will add an informative message to the log. These may be used to
indicate actions taken by the installer throughout the progression of the install. Calling
addWarning()
will not only add the requested warning message to the log but also
cause the user to be alerted about the fact that the install might not have succeeded completely.
addError()
goes one step further, by alerting the user that the installation has
failed.
LogMessage
,
LogWarning
and LogError
.
To derive a correct integer value for the message index add a new value to either
MESSAGE_BASE
, WARNING_BASE
or ERROR_BASE
,
depending on the message category. Next, increment the MAX_ constant for the message category, to
ensure that the add... methods actually allow the message to be added. The key for the text
resource must be named either log.message_
, log.warning_
or
log.error_
in accordance with the chosen index base. In addition, the key must be
appended by the message index (without the base, since this implementation will automatically
subtract the base). Variable place holders must conform to the specification for
java.text.MessageFormat
.
-DIzPack.debug=on
-DIzPack.debug.channel=<channelA,channelB,...>The parameter is a comma separated list of one or more channel identifiers.
-DIzPack.debug.dumpList=onTo turn debug messages on
| Nested Class Summary | |
|---|---|
private class |
Log.Record
|
| Field Summary | |
|---|---|
private static java.lang.String |
CHANNEL_LIST
System property to enable dumping of the list of debug channels that did record messages |
private static java.lang.String |
CHANNEL_SPEC
System property to set the debug channels to trace |
private java.util.Vector<java.lang.String> |
channels
The list of channels requested for debug output. |
private static java.lang.String |
DATE_FORMAT
The formatting used for the report time stamp |
private java.util.ArrayList<Log.Record> |
debug
The collection of debug messages |
private static java.lang.String |
DEBUG_SWITCH
System property to turn debug output on |
private boolean |
debugActive
This flag signals if debug messages should be recorded |
private boolean |
dumpChannels
This flag signals that the identifiers of the recorded debug channels should be dumped |
private static java.lang.String |
ERROR_PREFIX
The prefix for building error message keys |
private java.util.ArrayList<Log.Record> |
errors
The collection of error messages |
private AutomatedInstallData |
installData
Access to the installation information and the localized text resources |
private static Log |
me
The only instance of Messenger |
private static java.lang.String |
MESSAGE_PREFIX
The prefix for building message keys |
private java.util.ArrayList<Log.Record> |
messages
The collection of installation messages |
private java.lang.String |
newline
The system dependent newline character sequence |
private java.util.Hashtable<java.lang.String,java.lang.String> |
recordedChannels
This map keeps track of all channels that are recorded. |
private static java.lang.String |
RESOURCE_PREFIX
The prefix for all text resources related to this class |
private static java.lang.String |
WARNING_PREFIX
The prefix for building warning message keys |
private java.util.ArrayList<Log.Record> |
warnings
The collection of warning messages |
| Fields inherited from interface com.izforge.izpack.util.LogError |
|---|
COULD_NOT_WRITE_FILE, ERROR_BASE, MAX_ERROR |
| Fields inherited from interface com.izforge.izpack.util.LogWarning |
|---|
MAX_WARNING, WARNING_BASE |
| Fields inherited from interface com.izforge.izpack.util.LogMessage |
|---|
MAX_MESSAGE, MESSAGE_BASE |
| Constructor Summary | |
|---|---|
private |
Log()
This class is installed as singleton. |
| Method Summary | |
|---|---|
void |
addCustomError(java.lang.String template,
java.lang.String[] detail,
java.lang.Throwable exception)
This method records an error message, using a custom text template. |
void |
addCustomMessage(java.lang.String template,
java.lang.String[] detail)
This method records a general installation message, using a custom text template. |
void |
addCustomWarning(java.lang.String template,
java.lang.String[] detail,
java.lang.Throwable exception)
This method records a warning message, using a custom text template. |
void |
addDebugMessage(java.lang.String template,
java.lang.String[] detail,
java.lang.String channel,
java.lang.Throwable exception)
This method provides a channel for debugging messages in IzPack development. |
void |
addError(int message,
java.lang.String[] detail,
java.lang.Throwable exception)
This method records an error message to the list of messages |
void |
addMessage(int message,
java.lang.String[] detail)
This method records general installation message |
void |
addWarning(int message,
java.lang.String[] detail,
java.lang.Throwable exception)
This method records a warning message to the list of messages |
private java.lang.String |
buildDebug(int index)
Builds a debug message from the information contained in the indicated debug record |
private java.lang.String |
buildDebug(Log.Record record)
Builds a debug message from the information contained in a specific debug record |
private java.lang.String |
buildError(int index)
Builds an error message from the information contained in the indicated error record |
private java.lang.String |
buildMessage(int index)
Builds a general installation message from the information contained in the indicated record |
private java.lang.String |
buildWarning(int index)
Builds a warning message from the information contained in the indicated warning record |
private java.lang.String |
compileReport()
Prepares an installation report from the recorded information |
void |
dumpRecordedChannels()
Dumps the list of debug channels to stdout that have recorded messages |
boolean |
errorsRecorded()
Reports if any errors have been recorded. |
static Log |
getInstance()
Returns the only instance of Log |
void |
informUser()
Displays a dialog that informs the user about the fact that one or more unusual events have occurred during installation. |
boolean |
messagesRecorded()
Reports if any messages have been recorded. |
boolean |
warningsRecorded()
Reports if any warnings have been recorded. |
void |
writeReport()
Presents the user with a dialog to select a file and location for the installation report and writes a report contianing all messages to the user selected file. |
void |
writeReport(java.lang.String file)
Writes a report contianing all messages to the indicated file. |
| Methods inherited from class java.lang.Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Field Detail |
|---|
private static final java.lang.String RESOURCE_PREFIX
private static final java.lang.String DATE_FORMAT
private static final java.lang.String MESSAGE_PREFIX
private static final java.lang.String WARNING_PREFIX
private static final java.lang.String ERROR_PREFIX
private static final java.lang.String DEBUG_SWITCH
private static final java.lang.String CHANNEL_SPEC
private static final java.lang.String CHANNEL_LIST
private static Log me
Messenger
private java.lang.String newline
private AutomatedInstallData installData
private java.util.ArrayList<Log.Record> messages
private java.util.ArrayList<Log.Record> warnings
private java.util.ArrayList<Log.Record> errors
private java.util.ArrayList<Log.Record> debug
private java.util.Vector<java.lang.String> channels
Vector
must be used for
this purpose, since this is the only class that explicitly specifies that the
equals()
method is used for determining if a particular object is contained.
private java.util.Hashtable<java.lang.String,java.lang.String> recordedChannels
private boolean debugActive
private boolean dumpChannels
| Constructor Detail |
|---|
private Log()
getInstance()
to get an instance.
| Method Detail |
|---|
public static Log getInstance()
Log
Log
public void addMessage(int message, java.lang.String[] detail)
message
- the numeric identifier of the message to add, as defined in
LogMessage
detail
- a string array of variable fields that should be inserted into the message textpublic void addCustomMessage(java.lang.String template, java.lang.String[] detail)
template
- the basic template of the messagedetail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.MessageFormat.format(java.lang.String, java.lang.Object[])
public void addWarning(int message, java.lang.String[] detail, java.lang.Throwable exception)
message
- the numeric identifier of the message to add, as defined in
LogWarning
detail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.exception
- the exception associated with the event or null
if there was
none.MessageFormat.format(java.lang.String, java.lang.Object[])
public void addCustomWarning(java.lang.String template, java.lang.String[] detail, java.lang.Throwable exception)
template
- the basic template for the messagedetail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.exception
- the exception associated with the event or null
if there was
none.MessageFormat.format(java.lang.String, java.lang.Object[])
public void addError(int message, java.lang.String[] detail, java.lang.Throwable exception)
message
- the numeric identifier of the message to add, as defined in
LogError
detail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.exception
- the exception associated with the event or null
if there was
none.MessageFormat.format(java.lang.String, java.lang.Object[])
public void addCustomError(java.lang.String template, java.lang.String[] detail, java.lang.Throwable exception)
template
- the basic template for the messagedetail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.exception
- the exception associated with the event or null
if there was
none.MessageFormat.format(java.lang.String, java.lang.Object[])
public void addDebugMessage(java.lang.String template, java.lang.String[] detail, java.lang.String channel, java.lang.Throwable exception)
null
or an empty string is used as channel identifier
the message will be output, regardless of the channel filter applied. Please use this option
sparingly, just for really impotant messages of general interest.
To receive output for select channels, start IzPack with the command line option
-DIzPack.debug.channel=, followed by a comma separated list of channel identifiers.
template
- the basic template for the messagedetail
- a string array of variable fields that should be inserted into the message
text. Each array element will be inserted into the text template, replacing a marker.channel
- the debug channel the message is associated with.exception
- the exception associated with the event or null
if there was
none.public boolean messagesRecorded()
public boolean warningsRecorded()
public boolean errorsRecorded()
public void informUser()
public void writeReport()
public void writeReport(java.lang.String file)
file
- the fully qualifies name of the file to write to.private java.lang.String compileReport()
private java.lang.String buildMessage(int index)
index
- the index of the requested message entryprivate java.lang.String buildWarning(int index)
index
- the index of the requested warning entryprivate java.lang.String buildError(int index)
index
- the index of the requested error entryprivate java.lang.String buildDebug(int index)
index
- the index of the requested debug entryprivate java.lang.String buildDebug(Log.Record record)
record
- the debug recordpublic void dumpRecordedChannels()
|
|||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Site is a single building or other facility.
| lib | phIoT |
|---|---|
| superkind | ph::Entity |
| filter | site |
| Dict |
Dict is a map of tag name/value pairs |
|---|---|
| Entity |
Entity represents top-level dicts with a unique identifier |
| GeoPlace |
Geographic place |
|---|
| area | Number<area> |
Floor area of the building typically measured in ft² or m² |
|---|---|---|
| primaryFunction | Str |
Primary function of site as US Energy Star key |
| site! | Marker | |
| yearBuilt | Number<none> |
Original year of construction such as 1980 |
Geographic place
| geoAddr | Str |
Free form street address |
|---|---|---|
| geoCity | Str |
Geographic city or locality name |
| geoCoord | Coord |
Geographic coordinate as "C(latitude,longitude)" |
| geoCountry | Str |
Geographic country as ISO 3166-1 two letter code |
| geoCounty | Str |
Geographic subdivision of US state |
| geoPostalCode | Str |
Geographic postal code; for US this is a five digit zip code |
| geoState | Str |
State or province name; for US this is two letter state code |
| geoStreet | Str |
Geographic street address and name |
| tz | TimeZoneName |
TimeZone identifier for location |
Entity represents top-level dicts with a unique identifier
| dis | Str |
Display name for humans |
|---|---|---|
| id | Ref |
Defines the unique identifier of an entity in system using a Ref value type |


on Ethereum Private Blockchain Network
as a part of KISA Fintech X Blockchain Academy Curriculum in Nov 2018.
매수요청 주주명부 거래기록
User1 User2 User3 User4
A prototype of OTC/Shareholder Management dApp.
https://github.com/ZHyoKim/Fito


Public key
Private key
Use
characters
with lowercases
with uppercases
with digits
with symbols
Save preset


The first step to run accessibility checks in SKY UX unit tests is to import the SKY UX SDK testing library into your SPA. This library provides methods to interact with SKY UX during Karma unit tests. For accessibility testing, it extends the Jasmine expect function to add the toBeAccessible matcher.
To install the testing library, open the command prompt, cd into your SPA's directory, and run:
After you import the testing library, the next step to run accessibility checks in unit tests is to import the extended Jasmine expect function into .spec.ts files. At the top of the spec files for the components to test, import the function from the testing library:
import {
expect
} from '@skyux-sdk/testing';
After you import expect function, you can use it to run accessibility tests for components. For components that change state, you can insert the function into existing it blocks. And for components that don't change state, the function can stand alone to run accessibility checks from its own it block.
Insert the expect function and toBeAccessible matcher
After you import the expect function into spec files, the next step is to wrap the expect function around the elements to test for accessibility. Accessibility checks are asynchronous, so it's important to wrap your tests in Angular's async method. And to break the linear flow of control when using async, it's also important to wrap toBeAccessible in Angular's whenStable method.
Keep in mind that async is also a native JavaScript declaration, so you need to explicitly import the Angular async method at the top of the unit test spec file.
import { async } from ‘@angular/core/testing’;
Specify parameters for toBeAccessible
Finally, you can specify two optional parameters within the toBeAccessible matcher. The first parameter is a callback that lets you execute code after accessibility checks run. The second parameter is an option that lets you overwrite the default accessibility checks that SkyA11yAnalyzerConfig specifies.
Callback
In the first toBeAccessible parameter, you can specify logic to run after accessibility testing:
it('should pass accessibility', async(() => {
fixture.whenStable().then(() => {
expect(element).toBeAccessible(() => {
// Do something else after the accessibility checks run...
});
});
}));
For example, for components that change state, you can use this parameter to change state after accessibility checks and then run the accessibility checks again.
Overwrite accessibility checks
In the second toBeAccessible parameter, you can adjust configuration settings to turn off accessibility checks. The SkyA11yAnalyzerConfig interface specifies configuration settings, and it turns all checks on by default. To turn off accessibility checks, you set them to false:
You can also use the SKY UX a11y configuration property to overwrite accessibility checks. This option is useful if you need to turn off a set of accessibility checks in multiple spec files.
In the skyuxconfig.json file, you specify the accessibility checks to overwrite and set them to false:
Then in the spec files where you want to overwrite accessibility checks, you import SkyAppConfig and SkyAppTest at the top:
import {
SkyAppConfig
} from '@skyux/config';
import {
SkyAppTestModule
} from '@skyux-sdk/builder/runtime/testing/browser';
Finally, in the it blocks where you run accessibility checks, you inject SkyAppConfig in the async method and then reference the a11y configuration property in the second toBeAccessible parameter:
When you include accessibility rules in your unit tests, you may run into errors that uncover accessibility issues. Here is an example of an error message that appears in the command log when you run skyux test:
info: Starting accessibility checks for https://host.nxt.blackbaud.com/builder-allytest/...
info: Accessibility checks finished with 1 violation.
error: aXe - [Rule: 'label'] Form elements must have labels - WCAG: wcag332, wcag131
Get help at: https://dequeuniversity.com/rules/axe/2.3/label?application=webdriverjs
Elements:
The first line of the error message indicates what failed. It lists the name of the rule that failed and a detailed description that includes the WCAG 2.0 success criteria numbers. On the next line, the error message provides the URL for the rule definition to help address the failure. And finally, the error message lists the DOM elements where the failure was identified.


Anomaly Detection and Recommender Systems
March 5, 2018
Python machine learning matplotlibThis post covers the seventh exercise from Andrew Ng’s Machine Learning Course on Coursera.
Introduction
First, the anomaly detection algorithm will be implemented and applied to detect failing servers on a network. Next, collaborative filtering will be used to build a recommender system for movies.
Anomaly Detection
An anomaly detection algorithm will be implemented to detect anomalous behavior in server computers. The features measure the throughput (mb/s) and latency (ms) of response of each server. While the servers were operating, $m = 307$
examples of how they were behaving were collected, and thus having an unlabeled dataset $\left\{x^{(1)},\dots,x^{(m)}\right\}$
. It is suspected that the vast majority of these examples are “normal” (non-anomalous) examples of the servers operating normally, but there might also be some examples of servers acting anomalously within this dataset.
A Gaussian model will be used to detect anomalous examples in the dataset. First, a 2D dataset will allow to visualize what the algorithm is doing. On that dataset a Gaussian distribution will be fitted in order to find values that have very low probability and hence can be considered anomalies. After that, the anomaly detection algorithm will be applied to a larger dataset with many dimensions.
import numpy as np
from scipy.io import loadmat
import matplotlib.pyplot as plt
# Load dataset.
data1 = loadmat('ex8data1.mat')
for key in data1:
print(key)
X = data1["X"]
Xval = data1["Xval"]
yval = data1["yval"].flatten() # shape must be (307,) to use it in "selectThreshold".
print('\nVisualizing example dataset for outlier detection.')
# Visualize the example dataset.
plt.plot(X[:, 0], X[:, 1], 'bx', markersize=3)
plt.xlabel('Latency (ms)')
plt.ylabel('Throughput (mb/s)')
plt.title('Figure 1: The first dataset.')
plt.show()
__header__
__version__
__globals__
X
Xval
yval
Visualizing example dataset for outlier detection.
Gaussian Distribution
To perform anomaly detection, first a model will be fitted to the data’s distribution. Given a training set $\left\{x^{(1)},\dots,x^{(m)}\right\} \left(\text{ where } x^{(i)} \in \mathbb{R}^n \right)$
, the Gaussian distribution for each of the features $x_i$
have to be estimated. For each feature $i = 1 \dots n$
, the parameters $\mu_i$ and $\sigma_i^2$
that fit the data in the $i-th$
dimension $\left\{x_i^{(1)},\dots,x_i^{(m)}\right\}$
will be found. (the $i-th$
dimension of each example). The Gaussian distribution is given by:
$$p\left(x;\mu,\sigma^2\right)=\frac{1}{\sqrt{2\pi\sigma^2}}e^{-\frac{\left(z-\mu\right)^2}{2\sigma^2}},$$
where $\mu$
is the mean and $\sigma^2$
controls the variance.
Estimating Parameters for a Gaussian
The parameters $\left(\mu_i, \sigma_i^2\right)$
of the $i-th$
feature can be estimated by using the following equations:
$$\mu_i=\frac{1}{m}\sum_{j=1}^{m}x_i^{(j)} \text{ and } \sigma_i^2=\frac{1}{m}\sum_{j=1}^{m}\left(x_i^{(j)}-\mu_i\right)^2$$
The code in estimateGaussian
function will take as input the data matrix $X$
and output an $n$
-dimension vector
mu
that holds the mean of all the $n$ features and another $n$
-dimension vector sigma2
that holds the variances of all the features. This can implemented using a for-loop over every feature and every training example (though a vectorized implementation might be more efficient).
The contours of the fitted Gaussian distribution are visualized in Figure 2. From the plot, it can be seen that most of the examples are in the region with the highest probability, while the anomalous examples are in the regions with lower probabilities.
import scipy.linalg as linalg
# Create a function to compute the parameters of a Gaussian distribution.
def estimateGaussian(X):
"""
Estimates the parameters (mean, variance) of a
Gaussian distribution using the data in X.
Args:
X : array(# of training examples m, # of features n)
Returns:
mu : array(# of features n, 1)
sigma2: array(# of features n, 1)
"""
# Get useful variables.
m, n = X.shape
# Init mu and sigma2.
mu = np.zeros((n, 1))
sigma2 = np.zeros((n, 1))
mu = np.mean(X.T, axis=1)
mu = mu.reshape(mu.shape[0], -1)
sigma2 = np.var(X.T, axis=1)
sigma2 = sigma2.reshape(sigma2.shape[0], -1)
return mu, sigma2
# Create a function to compute the probability.
def multivariateGaussian(X, mu, Sigma2):
"""
Computes the probability density function of the examples X
under the multivariate gaussian distribution with parameters
mu and sigma2. If Sigma2 is a matrix, it is treated as the
covariance matrix. If Sigma2 is a vector, it is treated as the
sigma^2 values of the variances in each dimension (a diagonal
covariance matrix).
Args:
X : array(# of training examples m, # of features n)
mu : array(# of features n, 1)
Sigma2: array(# of features n, # of features n)
Returns:
p : array(# of training examples m,)
"""
k = len(mu)
if (Sigma2.shape[0] == 1) or (sigma2.shape[1] == 1):
Sigma2 = linalg.diagsvd(Sigma2.flatten(),
len(Sigma2.flatten()),
len(Sigma2.flatten()))
X = X - mu.T
p = np.dot(np.power(2 * np.pi, - k / 2.0),
np.power(np.linalg.det(Sigma2), -0.5)) * \
np.exp(-0.5 * np.sum(np.dot(X, np.linalg.pinv(Sigma2)) * X, axis=1))
return p
# Create a function to visualize the dataset and its estimated distribution.
def visualizeFit(X, mu, sigma2):
"""
Visualizes the dataset and its estimated distribution.
This visualization shows the probability density function
of the Gaussian distribution. Each example has a location
(x1, x2) that depends on its feature values.
Args:
X : array(# of training examples m, # of features n)
mu : array(# of features n, 1)
sigma2: array(# of features n, 1)
"""
X1, X2 = np.meshgrid(np.arange(0, 30, 0.5), np.arange(0, 30, 0.5))
Z = multivariateGaussian(np.column_stack((X1.reshape(X1.size),
X2.reshape(X2.size))),
mu, sigma2)
Z = Z.reshape(X1.shape)
plt.plot(X[:, 0], X[:, 1],'bx', markersize=3)
# Do not plot if there are infinities.
if (np.sum(np.isinf(Z)) == 0):
plt.contour(X1, X2, Z, np.power(10,(np.arange(-20, 0.1, 3)).T))
print('Visualizing Gaussian fit.')
# Estimate mu and sigma2.
mu, sigma2 = estimateGaussian(X)
# Return the density of the multivariate normal at each data point (row) of X.
p = multivariateGaussian(X, mu, sigma2)
# Visualize the fit.
visualizeFit(X, mu, sigma2)
plt.xlabel('Latency (ms)')
plt.ylabel('Throughput (mb/s)')
plt.title('Figure 2: The Gaussian distribution contours \
of the distribution fit to the dataset.')
plt.show()
Visualizing Gaussian fit.
Selecting the Threshold, $\varepsilon$
Now that the Gaussian parameters have been estimated, it can be investigated which examples have a very high probability given this distribution and which examples have a very low probability. The low probability examples are more likely to be the anomalies in the dataset. One way to determine which examples are anomalies is to select a threshold based on a cross validation set. An algorithm will be implemented to select the threshold $\varepsilon$
using the $F_1$
score on a cross validation set.
The code in selectThreshold
uses a cross validation set $\left\{\left(x_{cv}^{\left(1\right)}, y_{cv}^{\left(1\right)}\right),\dots, \left(x_{cv}^{\left(m_{cv}\right)}, y_{cv}^{\left(m_{cv}\right)} \right) \right\}$
, where the label $y = 1$
corresponds to an anomalous example, and $y = 0$
corresponds to a normal example. For each cross validation example, $p\left(x_{cv}^{\left(i\right)}\right)$
will be computed. The vector of all of these probabilities $p\left(x_{cv}^{\left(1\right)}\right), \dots, p\left(x_{cv}^{\left(m_{cv}\right)} \right)$
is passed to selectThreshold
in the vector pval
. The corresponding labels $y_{cv}^{\left(1\right)},\dots,y_{cv}^{\left(m_{cv}\right)}$
is passed to the same function in the vector yval
.
The function selectThreshold
returns two values; the first is the selected threshold $\varepsilon$
. If an example $x$ has a low probability $p(x) < \varepsilon$
, then it is considered to be an anomaly. The function also returns the $F_1$
score, which tells how well it is doing on finding the ground truth anomalies given a certain threshold. For many different values of $\varepsilon$
, the resulting $F_1$
score will be computed by computing how many examples the current threshold classifies correctly and incorrectly.
The $F_1$
score is computed using precision $(prec)$
and recall $(rec)$
:
$$ F_1 = \frac{2\cdot prec \cdot rec}{prec + rec}, $$
Precision and recall are computed by:
$$ prec = \frac{tp}{tp + fp} $$
$$ rec = \frac{tp}{tp + fn}, $$
where
$tp$
is the number of true positives: the ground truth label says it’s an anomaly and the algorithm correctly classified it as an anomaly.$fp$
is the number of false positives: the ground truth label says it’s not an anomaly, but the algorithm incorrectly classified it as an anomaly.$fn$
is the number of false negatives: the ground truth label says it’s an anomaly, but the algorithm incorrectly classified it as not being anomalous.
In the code selectThreshold
, a loop will try many different values of $\varepsilon$
and select the best $\varepsilon$
based on the $F_1$
score. The computation of the $F_1$
score can be implemented using a for-loop over all the cross validation examples $\left(\text{to compute the values }tp, fp, fn\right)$
. The
value for $\varepsilon$
should be about $8.99e-05$
. Figure 3 plots the anomalies in a circle.
# Create a function to find the best threshold epsilon.
def selectThreshold(yval, pval):
"""
Finds the best threshold to use for selecting outliers
based on the results from a validation set (pval) and
the ground truth (yval).
Args:
yval : array(# of cv examples,)
pval : array(# of cv examples,)
Returns:
bestEpsilon: float
bestF1 : float
"""
# Init values.
bestEpsilon = 0
bestF1 = 0
F1 = 0
stepsize = (max(pval) - min(pval)) / 1000
for epsilon in np.arange(min(pval), max(pval), stepsize):
# Use predictions to get a binary vector of
# 0's and 1's of the outlier predictions.
predictions = pval < epsilon
tp = sum(((yval == 1) & (predictions == 1)))
fp = sum((yval == 0) & (predictions == 1))
fn = sum((yval == 1) & (predictions == 0))
prec = tp / (tp + fp)
rec = tp / (tp + fn)
F1 = 2 * prec * rec / (prec + rec)
if F1 > bestF1:
bestF1 = F1
bestEpsilon = epsilon
return bestEpsilon, bestF1
pval = multivariateGaussian(Xval, mu, sigma2)
epsilon, F1 = selectThreshold(yval, pval)
print('Best epsilon found using cross-validation: {}'.format(epsilon))
print('Best F1 on Cross Validation Set: {}'.format(F1))
print('(A value epsilon of about 8.99e-05 is expected.)')
# Find the outliers in the training set and plot them.
outliers = p < epsilon
# Draw a red circle around those outliers.
plt.plot(X[outliers, 0], X[outliers, 1], 'ro', markersize=10, fillstyle='none')
visualizeFit(X, mu, sigma2)
plt.xlabel('Latency (ms)')
plt.ylabel('Throughput (mb/s)')
plt.title('Figure 3: The classified anomalies.')
plt.show()
Best epsilon found using cross-validation: 8.990852779269495e-05
Best F1 on Cross Validation Set: 0.8750000000000001
(A value epsilon of about 8.99e-05 is expected.)
High Dimensional Dataset
The anomaly detection algorithm will be applied now on a more realistic and much harder dataset. In this dataset, each example is described by $11$
features, capturing many more properties of the compute servers.
The code will estimate the Gaussian parameters $\left(\mu_i \text{ and } \sigma_i^2\right)$
, evaluate the probabilities for both the training data $X$
from which the Gaussian parameters were estimated, and do so for the the cross-validation set $Xval$
. Finally, the selectThreshold
will be used to find the best threshold $\varepsilon$
. A value epsilon of about $1.38e-18$
, and $117$
anomalies shall be found.
# Load the second dataset.
data2 = loadmat('ex8data2.mat')
X = data2["X"]
Xval = data2["Xval"]
yval = data2["yval"].flatten()
# Apply the same steps to the larger dataset.
mu, sigma2 = estimateGaussian(X)
# Training set.
p = multivariateGaussian(X, mu, sigma2)
# Cross-validation set.
pval = multivariateGaussian(Xval, mu, sigma2)
# Find the best threshold.
epsilon, F1 = selectThreshold(yval, pval)
print('Best epsilon found using cross-validation: {}'.format(epsilon))
print('Best F1 on Cross Validation Set: {}'.format(F1))
print('# Outliers found: {}'.format(sum(p < epsilon)))
Best epsilon found using cross-validation: 1.377228890761358e-18
Best F1 on Cross Validation Set: 0.6153846153846154
# Outliers found: 117
Recommender Systems
The collaborative filtering learning algorithm will be implemented and applied to a dataset of movie ratings. This dataset consists of ratings on a scale of 1 to 5. The dataset has $n_u = 943$
users, and $n_m = 1682$
movies.
The code in the function cofiCostFunc
computes the collaborative fitlering objective function and gradient. The function minimize
will be used to learn the parameters for collaborative filtering.
Movie Ratings Dataset
The variable $Y$
(a num_movies x num_users
matrix) stores the ratings $y^{(i,j)}$
(from 1 to 5). The variable $R$
is a binary-valued indicator matrix, where $R(i, j) = 1$
if user $j$
gave a rating to movie $i$
, and $R(i, j) = 0$
otherwise. The objective of collaborative filtering is to predict movie ratings for the movies that users have not yet rated, that is, the entries with $R(i, j) = 0$
. This will allow to recommend the movies with the highest predicted ratings to the user.
To understand the matrix $Y$
, the average movie rating will be computed for the first movie (Toy Story) and output the average rating to the screen.
The matrices, $X$
and $Theta$
will be also used:
$$X = \begin{bmatrix}
-\left(x^{(1)}\right)^T-\\
-\left(x^{(2)}\right)^T-\\
\vdots\\
-\left(x^{(n_m)}\right)^T-\end{bmatrix}, \quad
Theta = \begin{bmatrix}
-\left(\theta^{(1)}\right)^T-\\
-\left(\theta^{(2)}\right)^T-\\
\vdots\\
-\left(\theta^{(n_u)}\right)^T-\end{bmatrix}.$$
The $i-th$
row of $X$
corresponds to the feature vector $x^{(i)}$
for the $i-th$
movie, and the $j-th$
row of $Theta$
corresponds to one parameter vector $\theta^{(j)}$
, for the $j-th$
user. Both $x^{(i)}$
and $\theta^{(j)}$
are $n$
-dimensional vectors. $n = 100$
will be used, and therefore, $x^{(i)} \in \mathbb{R}^{100}$
and $\theta^{(j)} \in \mathbb{R}^{100}$
. Correspondingly, $X$
is a $n_m \times 100$
matrix and $Theta$
is a $n_u \times 100$
matrix.
Collaborative Filtering Learning Algorithm
First the cost function (without regularization) will be implemented.
The collaborative filtering algorithm in the setting of movie recommendations considers a set of $n$
-dimensional parameter vectors $x^{(1)}, \dots, x^{(n_m)} \text{ and } \theta^{(1)}, \dots, \theta^{(n_u)}$
, where the model predicts the rating for movie $i$
by user $j$
as $y^{(i,j)} = \left(\theta^{(j)}\right)^T x^{(i)}$
. Given a dataset that consists of a set of ratings produced by some users on some movies, the parameter vectors $x^{(1)}, \dots, x^{(n_m)}, \theta^{(1)}, \dots, \theta^{(n_u)}$
that produce the best fit (minimizes the squared error) will be learnt.
Note that the parameters to the function minimize
are $X$
and $Theta$
.
Collaborative Filtering Cost Function
The collaborative filtering cost function (without regularization) is given by
$$ J\left(x^{(1)}, \dots, x^{(n_m)}, \theta^{(1)}, \dots, \theta^{(n_u)} \right) = \frac{1}{2} \sum_{(i, j):r(i, j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)^2.$$
The cofiCostFunc
function will return this cost in the variable $J$
. Note that the cost should be accumulated for user $j$
and movie $i$
only if $R(i,j) = 1$
. An output cost of $22.22$
is expected.
Implementation Note: A vectorized implementation to compute $J$
is strongly recommended, since it will later be called many times by the optimization package minimize
. To come up with a vectorized implementation, the following tip is helpful: The $R$
matrix can be used to set selected entries to 0. For example, $R * M$
will do an element-wise multiplication between $M$
and $R$
; since $R$
only has elements with values either 0 or 1, this has the effect of setting the elements of $M$
to 0 only when the corresponding value in $R$
is 0. Hence, np.sum(error * R)
is the sum of all the elements of $M$ for which the corresponding element in $R$
equals 1.
Collaborative Filtering Gradient
Next the gradient will be implemented in cofiCostFunc
. The code will return the variables X_grad
and Theta_grad
. Note that X_grad
is a matrix of the same size as $X$
and similarly, Theta_grad
is a matrix of the same size as $Theta$
. The gradients of the cost function is given by:
$$\frac{\partial{J}}{\partial{x_k^{(i)}}}=\sum_{j:r(i,j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)\theta_k^{(j)}$$
$$\frac{\partial{J}}{\partial{\theta_k^{(j)}}}=\sum_{j:r(i,j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)x_k^{(i)}$$
Note that the function returns the gradient for both sets of variables by unrolling them into a single vector. A gradient check (checkCostFunction
) will be applied to numerically check the implementation of the gradients. If the implementation is correct, then the analytical and numerical gradients match up closely.
Implementation Note: A vectorized implementation is recommended. The gradient can be implemented with a for-loop over movies (for computing $\frac{\partial{J}}{\partial{x_k^{(i)}}}$
) and a for-loop over users (for computing $\frac{\partial{J}}{\partial{\theta_k^{(j)}}}$
). To perform the vectorization, it must be found a way to compute all the derivatives associated with $x_1^{(i)}, x_2^{(i)},\dots, x_n^{(i)}$
(i.e., the derivative terms associated with the feature vector $x^{(i)}$
) at the same time. The derivatives for the feature vector of the $i-th$
movie can be defined as:
$$\left(X_{grad}\left(i,:\right)\right)^T=\begin{bmatrix}
\frac{\partial{J}}{\partial{x_1^{(i)}}}\\
\frac{\partial{J}}{\partial{x_2^{(i)}}}\\
\vdots\\
\frac{\partial{J}}{\partial{x_n^{(i)}}}\end{bmatrix}=
\sum_{j:r(i,j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)\theta^{(j)}$$
As previously noted, an element-wise multiplication with $R$
is the trick. A similar method can be used to vectorize the derivatives with respect to $\theta^{(j)}$
as well.
print('Loading movie ratings dataset.')
# Load data.
data3 = loadmat('ex8_movies.mat')
# Y is a 1682x943 matrix, containing ratings (1-5)
# of 1682 movies on 943 users.
Y = data3["Y"]
# R is a 1682x943 matrix, where R(i,j) = 1 if and only if
# user j gave a rating to movie i.
R = data3["R"]
# From the matrix, statistics like average rating can be computed.
print('Average rating for movie 1 (Toy Story): {0:.2f}/5'.\
format(np.mean(Y[0, R[0, :]==1])))
# Visualize the ratings matrix by plotting it with imshow.
plt.imshow(Y, aspect='auto')
plt.ylabel('Movies')
plt.xlabel('Users')
plt.show()
# Load pre-trained weights (X, Theta, num_users, num_movies, num_features).
data4 = loadmat('ex8_movieParams.mat')
X = data4["X"]
Theta = data4["Theta"]
# Reduce the data set size so that this runs faster.
num_users = 4
num_movies = 5
num_features = 3
X = X[:num_movies, :num_features]
Theta = Theta[:num_users, :num_features]
Y = Y[:num_movies, :num_users]
R = R[:num_movies, :num_users]
# Create a function to compute the cost J and grad.
def cofiCostFunc(params, Y, R, num_users, num_movies, num_features, lambda_coef):
"""
Returns the cost and gradient for
the collaborative filtering problem.
Args:
params : array(num_movies x num_features + num_users x num_features,)
Y : array(num_movies, num_users)
R : array(num_movies, num_users)
num_users : int
num_movies : int
num_features: int
lambda_coef : float
Returns:
J : float
grad : array(num_movies x num_features + num_users x num_features,)
"""
# Unfold params back into the parameters X and Theta.
X = np.reshape(params[:num_movies * num_features], (num_movies, num_features))
Theta = np.reshape(params[num_movies * num_features:], (num_users, num_features))
# Init values.
J = 0
X_grad = np.zeros(X.shape)
Theta_grad = np.zeros(Theta.shape)
# Compute squared error.
error = np.square(np.dot(X, Theta.T) - Y)
# Compute regularization term.
reg_term = (lambda_coef / 2) * (np.sum(np.square(Theta)) + np.sum(np.square(X)))
# Compute cost function but sum only if R(i,j)=1; vectorized solution.
J = (1 / 2) * np.sum(error * R) + reg_term
# Compute the gradients.
X_grad = np.dot((np.dot(X, Theta.T) - Y) * R, Theta) + lambda_coef * X
Theta_grad = np.dot(((np.dot(X, Theta.T) - Y) * R).T, X) + lambda_coef * Theta
grad = np.concatenate((X_grad.reshape(X_grad.size),
Theta_grad.reshape(Theta_grad.size)))
return J, grad
# Create a list of my X and Theta.
lst_params = [X, Theta]
# Unroll parameters and then merge/concatenate.
unrolled_params = [lst_params[i].ravel() for i,_ in enumerate(lst_params)]
params = np.concatenate(unrolled_params)
# Evaluate cost function.
J, _ = cofiCostFunc(params, Y, R, num_users, num_movies, num_features, 0)
print('Cost at loaded parameters: {:0.2f}'.format(J))
print('(this value should be about 22.22)')
Loading movie ratings dataset.
Average rating for movie 1 (Toy Story): 3.88/5
Cost at loaded parameters: 22.22
(this value should be about 22.22)
Regularized Cost Function
The cost function for collaborative filtering with regularization is given by:
$$ J\left(x^{(1)}, \dots, x^{(n_m)}, \theta^{(1)}, \dots, \theta^{(n_u)} \right) = \frac{1}{2} \sum_{(i, j):r(i, j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)^2 + \left(\frac{\lambda}{2}\sum_{j=1}^{n_u}\sum_{k=1}^n\left(\theta_k^{(j)}\right)^2\right) + \left(\frac{\lambda}{2}\sum_{i=1}^{n_m}\sum_{k=1}^n\left(x_k^{(i)}\right)^2\right).$$
Regularized Gradient
The gradients for the regularized cost function is given by:
$$\frac{\partial{J}}{\partial{x_k^{(i)}}}=\sum_{j:r(i,j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)\theta_k^{(j)} + \lambda x_k^{(i)}$$
$$\frac{\partial{J}}{\partial{\theta_k^{(j)}}}=\sum_{j:r(i,j)=1} \left(\left(\theta^{(j)}\right)^T x^{(i)} - y^{(i,j)} \right)x_k^{(i)} + \lambda \theta_k^{(j)}.$$
# Create a function to compute numerical gradient.
def computeNumericalGradient(J, theta):
"""
Computes the numerical gradient of the function J
around theta using "finite differences" and gives
a numerical estimate of the gradient.
Notes: The following code implements numerical
gradient checking, and returns the numerical
gradient. It sets numgrad(i) to (a numerical
approximation of) the partial derivative of J
with respect to the i-th input argument,
evaluated at theta. (i.e., numgrad(i) should
be the (approximately) the partial derivative
of J with respect to theta(i).)
Args:
J : function
theta : array(num_movies x num_features + num_users x num_features,)
Returns:
numgrad: array(num_movies x num_features + num_users x num_features,)
"""
# Initialize parameters.
numgrad = np.zeros(theta.shape)
perturb = np.zeros(theta.shape)
e = 1e-4
for p in range(theta.size):
# Set the perturbation vector.
perturb.reshape(perturb.size)[p] = e
loss1, _ = J(theta - perturb)
loss2, _ = J(theta + perturb)
# Compute the Numerical Gradient.
numgrad.reshape(numgrad.size)[p] = (loss2 - loss1) / (2 * e)
perturb.reshape(perturb.size)[p] = 0
return numgrad
# Create a function to check the cost function and gradients.
def checkCostFunction(lambda_coef):
"""
Creates a collaborative filering problem
to check the cost function and gradients.
It will output the analytical gradients
and the numerical gradients computed using
computeNumericalGradient. These two gradient
computations should result in very similar values.
Args:
lambda_coef : float
"""
# Create small problem.
X_t = np.random.rand(4, 3)
Theta_t = np.random.rand(5, 3)
# Zap out most entries.
Y = np.dot(X_t, Theta_t.T)
Y[np.random.rand(Y.shape[0], Y.shape[1]) > 0.5] = 0
R = np.zeros(Y.shape)
R[Y != 0] = 1
# Run Gradient Checking.
X = np.random.randn(X_t.shape[0], X_t.shape[1])
Theta = np.random.randn(Theta_t.shape[0], Theta_t.shape[1])
num_users = Y.shape[1]
num_movies = Y.shape[0]
num_features = Theta_t.shape[1]
# Create short hand for cost function.
def costFunc(p):
return cofiCostFunc(p, Y, R, num_users, num_movies,
num_features, lambda_coef)
params = np.concatenate((X.reshape(X.size), Theta.reshape(Theta.size)))
numgrad = computeNumericalGradient(costFunc, params)
J, grad = cofiCostFunc(params, Y, R, num_users, num_movies,
num_features, lambda_coef)
# Visually examine the two gradient computations.
for numerical, analytical in zip(numgrad, grad):
print('Numerical Gradient: {0:10f}, Analytical Gradient {1:10f}'.\
format(numerical, analytical))
print('\nThe above two columns should be very similar.\n')
# Evaluate the norm of the difference between two solutions.
diff = np.linalg.norm(numgrad-grad) / np.linalg.norm(numgrad+grad)
print('If the backpropagation implementation is correct, then \n' \
'the relative difference will be small (less than 1e-9). \n' \
'\nRelative Difference: {:.10E}'.format(diff))
print('Checking Gradients (without regularization)...\n')
# Check gradients by running checkCostFunction.
checkCostFunction(0)
Checking Gradients (without regularization)...

If the backpropagation implementation is correct, then
the relative difference will be small (less than 1e-9).
Relative Difference: 8.7114891286E-13
# Evaluate cost function.
J, _ = cofiCostFunc(params, Y, R, num_users, num_movies, num_features, 1.5)
print('Cost at loaded parameters (lambda_coef = 1.5): {:0.2f}'\
'\n(this value should be 31.34)\n'.format(J))
print('Checking Gradients (with regularization)... \n')
# Check gradients by running checkCostFunction.
checkCostFunction(1.5)
Cost at loaded parameters (lambda_coef = 1.5): 31.34
(this value should be 31.34)
Checking Gradients (with regularization)...
Numerical Gradient: -0.165736, Analytical Gradient -0.165736
Numerical Gradient: 1.398242, Analytical Gradient 1.398242
Numerical Gradient: 0.502167, Analytical Gradient 0.502167
Numerical Gradient: 1.803162, Analytical Gradient 1.803162
Numerical Gradient: -8.327052, Analytical Gradient -8.327052
Numerical Gradient: 0.682292, Analytical Gradient 0.682292
Numerical Gradient: -3.453835, Analytical Gradient -3.453835
Numerical Gradient: -10.457582, Analytical Gradient -10.457582
Numerical Gradient: 2.752216, Analytical Gradient 2.752216
Numerical Gradient: 4.629106, Analytical Gradient 4.629106
Numerical Gradient: -8.648931, Analytical Gradient -8.648931
Numerical Gradient: -2.430226, Analytical Gradient -2.430226
Numerical Gradient: -0.615139, Analytical Gradient -0.615139
Numerical Gradient: -0.961198, Analytical Gradient -0.961198
Numerical Gradient: 0.915409, Analytical Gradient 0.915409
Numerical Gradient: -0.355228, Analytical Gradient -0.355228
Numerical Gradient: -1.244693, Analytical Gradient -1.244693
Numerical Gradient: 2.519143, Analytical Gradient 2.519143
Numerical Gradient: 2.348013, Analytical Gradient 2.348013
Numerical Gradient: 10.832565, Analytical Gradient 10.832565
Numerical Gradient: -7.547379, Analytical Gradient -7.547379
Numerical Gradient: 5.521721, Analytical Gradient 5.521721
Numerical Gradient: -8.935899, Analytical Gradient -8.935899
Numerical Gradient: -0.090028, Analytical Gradient -0.090028
Numerical Gradient: 2.219835, Analytical Gradient 2.219835
Numerical Gradient: -4.729332, Analytical Gradient -4.729332
Numerical Gradient: -1.062867, Analytical Gradient -1.062867
The above two columns should be very similar.
If the backpropagation implementation is correct, then
the relative difference will be small (less than 1e-9).
Relative Difference: 2.2207133250E-12
Learning Movie Recommendations
Now the algorithm can be trained to make movie recommendations. First, an example of movie preferences will be entered, so that later when the algorithm runs, the movie recommendations can be computed based on the preferences. The list of all movies and their number in the dataset can be found listed in the file movie_idx.txt
.
Recommendations
After the additional ratings have been added to the dataset, the collaborative filtering model will be trained. This will learn the parameters $X$
and $Theta$
. To predict the rating of movie $i$
for user $j$
, the $\left(\theta^{(j)}\right)^T x^{(i)}$
need to be computed. Then, the ratings are computed for all the movies and users and the movies that are recommended are displayed, according to ratings that were entered earlier.
# Create a function to load movies.
def loadMovieList():
"""
Reads the fixed movie list in movie_idx.txt
and returns a cell array of the words in movieList.
Returns:
movieList: list
"""
# Read the fixed movieulary list.
with open('movie_ids.txt', encoding = "ISO-8859-1") as f:
movieList = []
for line in f:
movieName = line.split()[1:]
movieList.append(" ".join(movieName))
return movieList
movieList = loadMovieList()
# Initialize ratings.
my_ratings = np.zeros((1682, 1))
# Check the file movie_idx.txt for id of each movie in the dataset.
# For example, Toy Story (1995) has ID 0, so to rate it "4", set:
my_ratings[0] = 4
# Or suppose did not enjoy The Mask (1994), so set:
my_ratings[71] = 1
# Select a few movies and rate them:
my_ratings[8] = 3
my_ratings[12]= 3
my_ratings[32]= 2
my_ratings[44] = 5
my_ratings[60] = 5
my_ratings[63] = 4
my_ratings[67] = 3
my_ratings[85] = 5
my_ratings[117] = 1
my_ratings[153] = 4
my_ratings[155] = 5
my_ratings[164] = 5
my_ratings[174] = 4
my_ratings[178] = 5
my_ratings[193] = 4
my_ratings[354] = 2
my_ratings[442] = 4
my_ratings[478] = 5
my_ratings[514] = 5
my_ratings[606] = 5
my_ratings[633] = 5
my_ratings[639] = 5
my_ratings[649] = 5
my_ratings[954] = 5
my_ratings[1422] = 3
print('User ratings:\n')
for i, rating in enumerate(my_ratings):
if rating > 0:
print('Rated {} for {}'.format(rating[0], movieList[i]))
User ratings:
Rated 4.0 for Toy Story (1995)
Rated 3.0 for Dead Man Walking (1995)
Rated 3.0 for Mighty Aphrodite (1995)
Rated 2.0 for Desperado (1995)
Rated 5.0 for Eat Drink Man Woman (1994)
Rated 5.0 for Three Colors: White (1994)
Rated 4.0 for Shawshank Redemption, The (1994)
Rated 3.0 for Crow, The (1994)
Rated 1.0 for Mask, The (1994)
Rated 5.0 for Remains of the Day, The (1993)
Rated 1.0 for Twister (1996)
Rated 4.0 for Monty Python's Life of Brian (1979)
Rated 5.0 for Reservoir Dogs (1992)
Rated 5.0 for Jean de Florette (1986)
Rated 4.0 for Brazil (1985)
Rated 5.0 for Clockwork Orange, A (1971)
Rated 4.0 for Sting, The (1973)
Rated 2.0 for Sphere (1998)
Rated 4.0 for Birds, The (1963)
Rated 5.0 for Vertigo (1958)
Rated 5.0 for Boot, Das (1981)
Rated 5.0 for Rebecca (1940)
Rated 5.0 for Microcosmos: Le peuple de l'herbe (1996)
Rated 5.0 for Cook the Thief His Wife & Her Lover, The (1989)
Rated 5.0 for Seventh Seal, The (Sjunde inseglet, Det) (1957)
Rated 5.0 for Before Sunrise (1995)
Rated 3.0 for Walking Dead, The (1995)
Learning Movie Ratings
Now, the collaborative filtering model will be trained on a movie rating dataset of 1682 movies and 943 users.
from scipy.optimize import minimize
print('Training collaborative filtering...')
# Load data.
Y = data3["Y"] # array(1682, 943)
R = data3["R"] # array(1682, 943)
# Add my ratings to the data matrix.
Y = np.column_stack((my_ratings, Y)) # array(1682, 944)
R = np.column_stack(((my_ratings != 0), R)) # array(1682, 944)
# Create a function to normalize ratings.
def normalizeRatings(Y, R):
"""
Preprocesses data by subtracting mean rating for every
movie (every row). Normalizes Y so that each movie has
a rating of 0 on average, and returns the mean rating in Ymean.
Args:
Y : array(num_movies, num_users)
R : array(num_movies, num_users)
Returns:
Ynorm: array(num_movies, num_users)
Ymean: array(num_movies, 1)
"""
m, n = Y.shape
Ymean = np.zeros((m, 1))
Ynorm = np.zeros(Y.shape)
for i in range(m):
idx = R[i, :] == 1
# Compute the mean only of the rated movies.
Ymean[i] = np.mean(Y[i, idx])
Ynorm[i, idx] = Y[i, idx] - Ymean[i]
return Ynorm, Ymean
# Normalize ratings.
[Ynorm, Ymean] = normalizeRatings(Y, R)
# Get useful values.
num_users = Y.shape[1]
num_movies = Y.shape[0]
num_features = 10
# Set initial parameters (Theta, X).
X = np.random.randn(num_movies, num_features)
Theta = np.random.randn(num_users, num_features)
initial_parameters = np.concatenate((X.reshape(X.size),
Theta.reshape(Theta.size)))
# Set options.
options = {'maxiter': 100, 'disp': True}
# Set regularization.
lambda_coef = 10
# Create short hand for cost function.
def costFunc(initial_parameters):
return cofiCostFunc(initial_parameters, Y, R, num_users,
num_movies, num_features, lambda_coef)
# Optimize.
results = minimize(costFunc, x0=initial_parameters,
options=options, method='CG', jac=True)
theta = results.x
# Unfold results back into the parameters X and Theta.
X = np.reshape(theta[:num_movies * num_features], (num_movies, num_features))
Theta = np.reshape(theta[num_movies * num_features:], (num_users, num_features))
print('\nRecommender system learning completed!')
Training collaborative filtering...
Warning: Maximum number of iterations has been exceeded.
Current function value: 71999.719327
Iterations: 100
Function evaluations: 150
Gradient evaluations: 150
Recommender system learning completed!
Recommendation for me
After training the model, recommendations can be generated by computing the predictions matrix.
p = np.dot(X, Theta.T)
# Get first column (my predictions) and add Ymean.
my_predictions = p[:, 0] + Ymean.flatten()
movieList = loadMovieList()
# Reverse sort by index.
ix = my_predictions.argsort()[::-1]
print('Top 10 recommendations for me:\n')
for i in range(10):
j = ix[i]
print('Predicting rating {:0.2f} for movie {}'.\
format(my_predictions[j], movieList[j]))
print('\n\nOriginal ratings provided:\n')
for i in range(len(my_ratings)):
if my_ratings[i] > 0:
print('Rated {} for {}'.\
format(int(my_ratings[i]), movieList[i]))
Top 10 recommendations for me:
Predicting rating 8.99 for movie Casablanca (1942)
Predicting rating 8.98 for movie Close Shave, A (1995)
Predicting rating 8.89 for movie Wrong Trousers, The (1993)
Predicting rating 8.87 for movie Rear Window (1954)
Predicting rating 8.85 for movie Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb (1963)
Predicting rating 8.82 for movie Schindler's List (1993)
Predicting rating 8.81 for movie Wallace & Gromit: The Best of Aardman Animation (1996)
Predicting rating 8.79 for movie Usual Suspects, The (1995)
Predicting rating 8.75 for movie One Flew Over the Cuckoo's Nest (1975)
Predicting rating 8.73 for movie 12 Angry Men (1957)
Original ratings provided:
Rated 4 for Toy Story (1995)
Rated 3 for Dead Man Walking (1995)
Rated 3 for Mighty Aphrodite (1995)
Rated 2 for Desperado (1995)
Rated 5 for Eat Drink Man Woman (1994)
Rated 5 for Three Colors: White (1994)
Rated 4 for Shawshank Redemption, The (1994)
Rated 3 for Crow, The (1994)
Rated 1 for Mask, The (1994)
Rated 5 for Remains of the Day, The (1993)
Rated 1 for Twister (1996)
Rated 4 for Monty Python's Life of Brian (1979)
Rated 5 for Reservoir Dogs (1992)
Rated 5 for Jean de Florette (1986)
Rated 4 for Brazil (1985)
Rated 5 for Clockwork Orange, A (1971)
Rated 4 for Sting, The (1973)
Rated 2 for Sphere (1998)
Rated 4 for Birds, The (1963)
Rated 5 for Vertigo (1958)
Rated 5 for Boot, Das (1981)
Rated 5 for Rebecca (1940)
Rated 5 for Microcosmos: Le peuple de l'herbe (1996)
Rated 5 for Cook the Thief His Wife & Her Lover, The (1989)
Rated 5 for Seventh Seal, The (Sjunde inseglet, Det) (1957)
Rated 5 for Before Sunrise (1995)
Rated 3 for Walking Dead, The (1995)


|
135. Drawing Lines Time Limit: 0.1 sec, Memory Limit: 1 MB Little Johnny likes to draw a lot. A few days ago he painted lots of straight lines on his sheet of paper. Then he counted in how many zones the sheet of paper was split by these lines. He noticed that this number is not always the same. For instance, if he draws 2 lines, the sheet of paper could be split into 4, 3 or even 2 (if the lines are identical) zones. Since he is a very curious kid, he would like to know which is the maximum number of zones into which he can split the sheet of paper, if he draws N lines. The sheet of paper is to be considered a very large (=infinite) rectangle. Input The input file will contain an integer number: N (0<=N<=65535). Output You should output one integer: the maximum number of zones into which the sheet of paper can be split if Johnny draws N lines. Sample Input #1 0 Sample Output #1 1 Sample Input #2 1 Sample Output #2 2 | ||||||
|


TOC
Tweaks
Night Light
A Built-in blue light filter.
(Mingw-w64)[https://sourceforge.net/projects/mingw-w64/]
The GNU/GCC compiler on Windows.
(WSL)[https://blogs.msdn.microsoft.com/wsl/]
Built-in Linux sub-systems for Windows 10.
- Now available: Ubuntu
- Upcoming: Fedora and OpenSUSE
(Github Desktop)[https://desktop.github.com/]
Github Desktop client on Windows It’s an alternative if you’re not using Atom
(Dolphin Emulator)[https://dolphin-emu.org/]
The world’s best emulator for Wii and Gamecube.
(Rufus)[https://rufus.akeo.ie/]
Bootable USB creator. Everything you need is here in general use.
(BlueStacks)[http://www.bluestacks.com]
Well-made Android emulator. Now biggest in the world.


Choose A Shipping Method
No valid shipping methods are available for your order. You will be contacted regarding shipping when your order is processed.
Select Your Payment Method


I just installed a Emoncms server in my computer, the server is using Wampserver 2.4. THE emoncms is running and the database. I have a SMS pushing data to the server but I can not received any data. I have the port open in my firewall and I can see the packet going to the server, but there is no action in the inputs at the sever. I test the EMS using the online server and is pushing data to it, I check the IP and the API and they are correct to my server. Any idea what may be happening?
»
Re: No receive data
Is the Wampserver on-line? (If it isn't, you can only access it within the machine it's running on.) Did you follow all the set-up instructions for enabling the required options?
Re: No receive data
Thanks
yes the server is ONLINE and I did follow all the WampServer Modification to all the files. My controller say it connect and pushing the data, I can see in my router that the packet is forwarded to the machine with the server, but I don't see any data in the input page.
Re: No receive data
Here is a the log form the Apache server,
Re: No receive data
Could it be a formatting issue in your script?
from your access log
GET /emoncms/input/post.json?apikey=583dfbef6ac0a135916fba49cf44a97e&node=1&json=[{TRTU1:74.000000},{SRTU1:75.000000},{C11:100.000000}]
Emoncms expects data
http://emoncms.org/input/post.json?apikey=a924b4d95306a55445ea3a96eb17e689&json={power:200,temp:21}
Re: No receive data
Sorry that I ask you, But can you point me to where may be that script? IF you refer to the script that is pushing the data, is working fine because I test it with the emoscms.org server and is pushing data to the server, I can see it on the input page. Something on my side server that is not letting the data in.
Re: No receive data
I make a change to allow my using <IP_ADDRESS> because I am using W8 and I have now this log, there is no error on the Apache error log
Re: No receive data
<IP_ADDRESS> will not work. That address is only good inside the machine running the Wampserver. You must get the proper address of the machine from your router.
Here are my instructions for setting up to work to a local server:
2. To a local server:
The server can be WAMP, LAMP or MAMP. Install it according to the provider's instructions, and any special notes here [link to emcms installation].
To set up emoncms, you must inhabit two worlds – the website and the host machine's world, and you must be clear in your mind which one you are operating in.
Fire up your browser and go to "localhost". You are on a website now. You should see the Wamp home page and phpmyadmin, which is under "Tools". Run phpmyadmin (click it). Click "Databases" in the top banner. In the next screen, think of a name for your database (I used "emondata" – make a note of what you call it) and put that in appropriate box and click "Create".
Then set emoncms up as a user: click on Privileges in the top banner, click on Add a new user, then invent a User name for it, enter "localhost" as the host, and give it a password then click Create the user. Note the user name & password. When it returns to the previous screen, you need to give the new user ALL PRIVILEGES in the database you just created. So click Edit privileges against the new user's name, scroll down to “Database-specific privileges” and select the database from the drop-down list. On the next screen click Check all, then Go to apply them.
Move into the machine's world and copy emoncms into a directory where it will appear in Localhost (Wampserver calls it the “www directory”)
When you've copied emoncms in the machine's world, you'll find you have (in the website world) on your Wamp home page (localhost) a website called something like openenergymonitor-emoncms3. It's that which you click on to run emoncms (but don't do that yet).
N.B. Remember to put your server “online”.
Next tell emoncms how to log in to the database. In the machine's world, in that directory:
Do this by creating settings.php: copy default.settings.php and rename to settings.php. Edit it and set the $username, $password, $server and $database to the values you set in phpmyadmin ($server will be "localhost").
In the website world, run emoncms and register yourself as a user and obtain an APIkey (you need not be the user that you set up in phpmyadmin).
Set up the NanodeRF to send the data. Use the 'static IP' sketch:
a. Invent a MAC address for your NanodeRF. It must be unique within your LAN. Put it in here in the Nanode sketch:
// ethernet interface mac address, must be unique on the LAN
static byte mymac[] = { 0x42,0x31,0x42,0x21,0x30,0x31 };
b. Check your router's admin pages and find the IP address that it has allocated to the machine that your server is running on. Make the router use this IP address always (static) - check the router documentation for how to do this.
Edit the NanodeRF sketch:
c. set website[ ] to blank as you don't have a domain name (it is not “localhost”):
// 1) Set this to the domain name of your hosted emoncms - leave blank if posting to IP address
char website[] PROGMEM = "";
d. Tell the NanodeRF your server's IP address. Enter the IP address you found from your router here:
// or if your posting to a static IP server:
static byte hisip[] = { 192,168,1,10 };
e. Instruct the Nanode to use it:
// change to true if you would like the sketch to use hisip
boolean use_hisip = true;
f. Instruct the Nanode to use a static IP for itself too:
boolean use_staticIP = true;
g. Invent an IP address within the range used by your router, but not used by any device on your local network:
static byte myip[] = { 192,168,1,66 };
h. Set your router's Gateway address (your router's admin pages will tell you this):
static byte gwip[] = { 192,168,1,254 };
i. Tell the Nanode the sub-directory where you installed emoncms (this will be the name you clicked on to run it)
// 2) If your emoncms install is in a subdirectory add details here i.e "/emoncms3"
char basedir[] = "/emoncms-master";
j. Give the Nanode the APIkey:
// 3) Set to your account write apikey
char apikey[] = "YOURAPIKEY";
k. Plug in an Ethernet cable to your router, compile and upload the sketch. On the serial port you should see
(with possibly a wait while it times out and retries):
[webClient]
IP: <IP_ADDRESS>
Gateway: <IP_ADDRESS>
Server: <IP_ADDRESS>
Data sent: /emoncms-dev/input/post.json?apikey=a8bfc828b48860ca24e23cf824718cc5&json={rf_fail:1}
OK recieved
Data sent: /emoncms-dev/input/post.json?apikey=a8bfc828b48860ca24e23cf824718cc5&node=10&csv=0,36,2,33,1,36
OK recieved
Time request sent
Time: t16,34,58
Data sent: /emoncms-dev/input/post.json?apikey=a8bfc828b48860ca24e23cf824718cc5&node=10&csv=0,32,0,43,0,37
OK recieved
Data sent: /emoncms-dev/input/post.json?apikey=a8bfc828b48860ca24e23cf824718cc5&node=10&csv=0,34,0,36,-1,31
OK received
[etc]
Explanation:
IP: <IP_ADDRESS>
This is the content of myip[ ] It will appear in your Router's list against the MAC that you allocated to the NanodeRF
Gateway: <IP_ADDRESS>
The Gateway address of your router - will depend on your router's settings.
Server: <IP_ADDRESS>
The IP address of your server (or the machine that the server is running on, as allocated by your router)
Data sent: /emoncms-dev/input/post.json?apikey=a8bfc828b48860ca24e23cf824718cc5&json={rf_fail:1}
OK received
The data sent by the NanodeRF, and an acknowledgement by emoncms.
Then, when you look at Inputs at emoncms.org, you should have and be able to click on Node 10 and it will expand to show four inputs named 1-4 (depending on the sketch you're using in the emonTx), and if you click [log] you'll see a graph of the data.
It also gets back from the server the current time: "Time: t15,53,13".
Re: No receive data
Robert
First of all THANKS for your time and help. I have the server part as you mention, But there is a different controller sending the data. Let me explain to you; this sis a EMS control made by EASYIO operating under SEDONA. IN the application program we have an Object emonpush. We set the object with the API, Port Number and the ip, with that information the internal script execute and send the input data from our controller to the server. So for testing I use the emoncsm.org server so check that the emoncmspush object is sending the data, and is working because I can get daat from it to the emoncms.org server.
So what we do is find the API under the APIHElP in our server "583dfbef6ac0a135916fba49cf44a97e", find my public ip an enter it in the object server ip and set the port that is 80. With this setting the controller is pushing the data to our server. I can see on my Firewall the the pack are getting to the server as you see it on the Apache Access log. "<IP_ADDRESS> - - [19/Feb/2014:12:07:15 -0400] "GET /emoncms/input/post.json?apikey=583dfbef6ac0a135916fba49cf44a97e&node=1&json=[{TRTU1:76.000000},{SRTU1:77.000000},{C11:0.000000}] HTTP/1.1" 404 221. I check at the web the last HTTPxxxxx and it say is a denied message from a server.
There is my problem that I can find where. I am new to this, on the server side.
Let mw know if you understand or need additional information and one again thanks for your time
Re: No receive data
Somehow, I missed your post. I am not a networking or server expert, but if your server log is reporting that it is blocking the message, then surely that must be a problem with either the server itself or your firewall.


{% if request.user.is_authenticated %}
Logged as {{ request.user.username }}.
There is no content for this key, you can add it:


COVID-19 has created a huge number of impediments for citizens who require medical service due to the risk of contracting the disease from compromised patients in their local healthcare institutions.
Telemedicine brings medicinal treatment to the patient. It was April of 2020 when DOH launched a round-the-clock telemedicine hotline for Metro Manila residents aimed to provide medical advice whether it's COVID-19 related or not, with doctors standing by to answer inquiries (DOH, 2020).
In addition, the DOH’s telemedicine project has been widely recognized as a means of simplifying patient referral systems by eliminating the hand-to-hand transfer of records through the use of electronic transmission; lessening the struggles for a patient who seeks medical care. One of the goals of the health organizations in the Philippines is to limit the number of cases of people acquiring the epidemic disease, thus the need for face-to-face consultations will be minimized through telemedicine as well.
PH Health Department launches telemedicine services in Metro Manila amid Covid-19 pandemic | ANC
Telemedicine has been widely used in various institutions particularly concerning the ones offering health-related services. One of the most popular organizations in the Philippines utilizing the use of telemedicine is the Department of Health providing free teleconsultations. The following institutions also established the use of telemedicine in their health care provision towards their consumers (eCompareMo, 2020; Medical Pinas, 2020):
The Department of Health (DOH) in partnership with the National Privacy Commission (NPC) have created programs boosting the telemedicine services in the region to have a more precise control over the growing number of cases of people acquiring the COVID-19. They have employed medical consultations over phone, chat and short messaging service (SMS) as well as on other audio and video conferencing platforms. The DOH, according to its website, entails that they are maximizing the use of technology on connecting the public to medical professionals for better and more secured medical advice in line with their goals of inhibiting the growing number of COVID-19 cases (DOH, 2020).


Thank you for the information you’ve provided so far. In this section, we’ll be
gathering details about {{NameToUse}}’s military service, education and
work history.
United States Armed Forces?
Please tell us more about {{NameToUse}}'s military service.
Are you interested in more
information about military honors and burial rights?
Wonderful. Our funeral home staff will set aside time during your
arrangement conference to talk about this.
What was {{NameToUse}}'s education level
8th Grade or Less
Some Highschool
Highschool Grad/GED
Some College
Associate Degree
Bachelors Degree
Master Degree
Doctorate Degree
Unknown
What was {{NameToUse}}'s ocupation?
What industry was {{NameToUse}} in?
Is {{NameToUse}} of Hispanic Origin?
No
Yes, Mexican American Chicano
Yes, Puerto Rican
Yes, Cuban
Yes, Other
Unknown
What is {{NameToUse}}'s' Origin?
Race Origin
Mixed Race
Arctic (Siberian, Eskimo)
Caucasian (European)
Caucasian (Indian)
Caucasian (Middle East)
Caucasian (North African, Other)
Indigenous Australian
Native American
North East Asian (Mongol, Tibetan, Korean Japanese, etc)
Pacific (Polynesian, Micronesian, etc)
South East Asian (Chinese, Thai, Malay, Filipino, etc)
West African, Bushmen, Ethiopian
Other Race


public interface LSParserFilter
LSParserFilter
s provide applications the ability to examine
nodes as they are being constructed while parsing. As each node is
examined, it may be modified or removed, or the entire parse may be
terminated early.
At the time any of the filter methods are called by the parser, the
owner Document and DOMImplementation objects exist and are accessible.
The document element is never passed to the LSParserFilter
methods, i.e. it is not possible to filter out the document element.
Document
, DocumentType
, Notation
,
Entity
, and Attr
nodes are never passed to the
acceptNode
method on the filter. The child nodes of an
EntityReference
node are passed to the filter if the
parameter "
entities" is set to false
. Note that, as described by the parameter "
entities", unexpanded entity reference nodes are never discarded and are always
passed to the filter.
All validity checking while parsing a document occurs on the source document as it appears on the input stream, not on the DOM document as it is built in memory. With filters, the document in memory may be a subset of the document on the stream, and its validity may have been affected by the filtering.
All default attributes must be present on elements when the elements are passed to the filter methods. All other default content must be passed to the filter methods.
DOM applications must not raise exceptions in a filter. The effect of throwing exceptions from a filter is DOM implementation dependent.
See also the Document Object Model (DOM) Level 3 Load and Save Specification.
| Modifier and Type | Field and Description |
|---|---|
static short |
FILTER_ACCEPT
Accept the node.
|
static short |
FILTER_INTERRUPT
Interrupt the normal processing of the document.
|
static short |
FILTER_REJECT
Reject the node and its children.
|
static short |
FILTER_SKIP
Skip this single node.
|
| Modifier and Type | Method and Description |
|---|---|
short |
acceptNode(Node nodeArg)
This method will be called by the parser at the completion of the
parsing of each node.
|
int |
getWhatToShow()
Tells the
LSParser what types of nodes to show to the
method LSParserFilter.acceptNode . |
short |
startElement(Element elementArg)
The parser will call this method after each
Element start
tag has been scanned, but before the remainder of the
Element is processed. |
static final short FILTER_ACCEPT
static final short FILTER_REJECT
static final short FILTER_SKIP
static final short FILTER_INTERRUPT
short startElement(Element elementArg)
Element
start
tag has been scanned, but before the remainder of the
Element
is processed. The intent is to allow the
element, including any children, to be efficiently skipped. Note that
only element nodes are passed to the startElement
function.
startElement
for filtering
will include all of the Element's attributes, but none of the
children nodes. The Element may not yet be in place in the document
being constructed (it may not have a parent node.)
startElement
filter function may access or change
the attributes for the Element. Changing Namespace declarations will
have no effect on namespace resolution by the parser.
elementArg
- The newly encountered element. At the time this
method is called, the element is incomplete - it will have its
attributes, but no children.FILTER_ACCEPT
if the Element
should
be included in the DOM document being built.
FILTER_REJECT
if the Element
and all of
its children should be rejected.
FILTER_SKIP
if the
Element
should be skipped. All of its children are
inserted in place of the skipped Element
node.
FILTER_INTERRUPT
if the filter wants to stop the
processing of the document. Interrupting the processing of the
document does no longer guarantee that the resulting DOM tree is
XML well-formed. The Element
is rejected.
short acceptNode(Node nodeArg)
nodeArg
- The newly constructed element. At the time this method
is called, the element is complete - it has all of its children
(and their children, recursively) and attributes, and is attached
as a child to its parent.FILTER_ACCEPT
if this Node
should
be included in the DOM document being built.
FILTER_REJECT
if the Node
and all of its
children should be rejected.
FILTER_SKIP
if the
Node
should be skipped and the Node
should be replaced by all the children of the Node
.
FILTER_INTERRUPT
if the filter wants to stop the
processing of the document. Interrupting the processing of the
document does no longer guarantee that the resulting DOM tree is
XML well-formed. The Node
is accepted and will be the
last completely parsed node.
int getWhatToShow()
LSParser
what types of nodes to show to the
method LSParserFilter.acceptNode
. If a node is not shown
to the filter using this attribute, it is automatically included in
the DOM document being built. See NodeFilter
for
definition of the constants. The constants SHOW_ATTRIBUTE
, SHOW_DOCUMENT
, SHOW_DOCUMENT_TYPE
,
SHOW_NOTATION
, SHOW_ENTITY
, and
SHOW_DOCUMENT_FRAGMENT
are meaningless here. Those nodes
will never be passed to LSParserFilter.acceptNode
.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2015, Oracle and/or its affiliates. All rights reserved.


| DOSE: |
42 mg |
smoked |
AM-2201 |
(powder / crystals) |
I have come into various forums more than once touting my skills as an advanced, mature and responsible researcher. I have also been very harsh when folks basically have what appears to be a panic attack or psychological freak-out, then make dire posts about AM-2201 or similar compounds being the route causative factors of dire physical reactions or ailments, regardless of what else might be in their personal histories or systems at that time.
Last night's research with AM-2201 was the first time I ever felt I got into a space that was uncomfortable with these compounds.
I was on the very tail end of a low MXE dose of 25 mgs. A friend had told me he smoked 50 mgs of AM-2201 and tripped so hard he 'joined the carpet.' I knew this was a precipitously high dose for this compound, but I also had my skill set and decades of cannabinoid tolerance . . .
I was already stoned.
I loaded 42 mgs (A favorite dose for me of many things . . . ) into my spoon pipe on top of a bed of Casey Jones weed. I took one single small hit. Nice. Then a huge, massive rip - definate chemical flavor to my exhale.
Effects came on hard, fast, aggressive and overwhelming. I could no longer effectively communicate either via keyboard or verbally with my husband. My open eyed vision was significantly distorted, even 'hazy.' I couldn't stand up straight and be stable. Sitting up I kept falling over and 'nodding off' into full blown tripping.
Other than feeling positively bowled over this felt okay.
But, then the midlife thing that haunts me sometimes hit hard - I started overheating. It was very difficult to manage. I shed all clothes, poured water over my head and finally gave in, sat down in the bathtub and in that position took a quick cool rinse off, kind of combo shower and very shallow bath. Even coming out of that I still felt very hot, but no longer like I might be in some sort of overheating trouble.
I lay back down and again was nailed - every time I tried to sit up it was a no go and I felt more than a bit dizzy and nauseaus.
I remember laying there hot, tripping with my eyes closed. I did a quick, internal self-assessment. Ego intact and not too panicky - knew who I was, where I was, what day it was and why I was in this situation - 25 grams MXE + most of 42 mgs AM-2201.  Heh - typical! Body just fine, mind completely OD'd overwhelmed. I started chuckling out loud - only one single person to blame for this mess!
My husband asked me if I wanted to smoke a bowl - he didn't realize how deep I already was. I replied, 'No I'm utterly OD'd on synthetic cannabinoids and just need to go to bed.' He understood but was a bit dismayed - it's pretty bad when Pandora decided not to smoke a bowl . . . .By the time I lay down for bed, having done my teeth and other bathroom chores, I felt super high/stoned but a lot better.
 I don't feel like I am stoned or have a residual high but I definately have that squeeky-clean, golden feeling that sometimes comes after a heavy experience, be it glowing or difficult.
I'm glad I finally got a bit of a taste of the tip of the iceberg - now I know what folks are talking about when they say they OD on these compounds and no doubt for them it feels much worse and more panicky. I've had a lot of trips, including bad ones in my life. I tend to deal with difficult experiences very calmly, not moving or saying much, mostly telling folks around me I'm freaking out or OD'd . . . .Last night was pretty much my norm for when I feel I've gotten into a bit of personal trouble.
If it had gotten worse, I would have asked my husband to assess me and maybe even have considered a hospital trip. NOT because I felt I was poisoned or dying but for a significant time I felt I could not get my body temperature/vaso-dilation under control and was in danger of significant over-heating. . . .
Just thought this might be worth sharing to indicate, a.) Even she up on the high horse gets bitched slapped down on occasion and b.) Getting into personal trouble does NOT mean one needs to freak-out. My response of basically just calmly letting it run its course, communicating basics to those around me and managing noxious physical symptoms (e.g. overheating) paid off in spades AND I cannot believe how GOOD I feel today. Time is my (and your) ally when things get sketchy. What goes up must come down. Everything with a beginning has a middle and end.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


testlibraw(1) Linux IEEE 1394 testlibraw(1) NAME testlibraw - run basic functionality tests on libraw1394 SYNOPSIS testlibraw DESCRIPTION testlibraw attaches to the Linux IEEE 1394 subsystem through libraw1394 and tries to read data from all connected nodes. It therefore acts as a check that: * libraw1394 is installed correctly * the IEEE 1394 subsystem is loaded in the kernel and of a supported version * libraw1394 and kernel side raw1394 can communicate * connected nodes can be reached and do respond. The read transactions are of a form that all powered up nodes conforming to the IEEE 1394 standard have to be able to respond to. The source of this program also acts as a demonstration of libraw1394 programming, including initialization, transactions and the event loop. EXAMPLE RUN FIXME: insert example here BUGS None known. SEE ALSO http://linux1394.sourceforge.net/ AUTHOR Andreas Bombe<EMAIL_ADDRESS>libraw1394 2.0.9 testlibraw(1)


FRIDAY OF THE THIRD WEEK
Entrance Antiphon
Behold, the Lord will come descending with splendour to visit his people with peace,
and he will bestow on them eternal life
Collect
May your grace, almighty God, always go before us and follow after,
so that we, who await with heartfelt desire the coming of your Only-Begotten Son,
may receive your help both now and in the life to come. Through our Lord. . .
FIRST READING
Isaiah 56:1-3a.6-8 A reading from the Book of Isaiah Thus says the LORD: "Keep justice, and do
righteousness, for soon my salvation will come, and my deliverance be revealed. Blessed is the man who does this, and the son
of man who holds it fast, who keeps the sabbath,
not profaning it, and keeps his hand from doing any evil." Let not the
foreigner who has joined himself to the LORD say, "The LORD will surely
separate me from his people". For thus says the LORD: The foreigners who
join themselves to the LORD, to minister to him, to love the name of the LORD,
and to be his servants, every one who keeps the sabbath,
and does not profane it, and holds fast my covenant-- these I will bring to my
holy mountain, and make them joyful in my house of prayer; their burnt
offerings and their sacrifices will be accepted on my altar; for my house shall
be called a house of prayer for all peoples. Thus says the Lord GOD, who
gathers the outcasts of The word of the Lord
RESPONSORIAL PSALM
Psalm
67:2-3.5.7-8(R.4) R.  O God, be gracious and bless us and let your face
shed its light upon us. So will your ways be known upon earth and all nations
learn your salvation. R.  Let the nations be glad and shout for joy, with
uprightness you rule the peoples; you guide the nations on earth. R.  The earth has yielded its fruit for God, our God,
has blessed us. May God still give us his blessing that all the ends of the
earth may revere him. R.  ALLELUIA Alleluia. Come, Lord, visit us in peace, that we may rejoice in your presence with hearts
made new. Alleluia. GOSPEL
John 5:33-36 A reading from the holy Gospel according to John At that time: Jesus said to the Jews, “You sent to
John, and he has borne witness to the truth. Not that the testimony which I
receive is from man; but I say this that you may be saved. He was a burning and
shining lamp, and you were willing to rejoice for a while in his light. But the
testimony which I have is greater than that of John; for the works which the
Father has granted me to accomplish, these very works which I am doing, bear me witness that the Father has sent me.” The Gospel of the Lord
Prayer over the Offerings
Be pleased with our humble prayers and offerings,
O Lord, we pray, and since we have no merits to plead our cause,
come to our rescue with the protection of your mercy. Through Christ our Lord.
Communion Antiphon
We await a saviour, the Lord Jesus Christ, who will change our mortal bodies,
to conform with his glorified body.
Prayer after Communion Replenished by the food of spiritual nourishment,
we humbly beseech you, O Lord, that, through our partaking in this mystery,
you may teach us to judge wisely the things of earth and hold firm to the things of heaven. Through Christ our Lord.


Dec. 7, 2014
On Asking Questions
|
Nov. 30, 2014
Pairing Project: Cheatsheet for Ruby Enumerables
|
Nov. 29, 2014
On Learning from Conflict
|
Nov. 28, 2014
Ruby Recursions: Recognizing Patterns and Repetition
|
Nov. 23, 2014
On Personal Values
|
Nov. 20, 2014
JavaScript Objects: Understanding Data Structures in JavaScript
|
Oct. 26, 2014
On Stereotype Threat and the Nuances of Equality
|
Oct. 27, 2014
Blocks, Procs and Lambdas: More on Object Oriented Programming
|
Oct. 16, 2014
On Peer Pairing and Self Improvement
|
Oct. 15, 2014
Classes: Bringing Together Objects and Methods
|
Oct. 12, 2014
On Free Speech and Social Media
|
Oct. 11, 2014
Enumerables: Iterating with Finer Control
|
Oct. 5, 2014
On Thinking Styles and Learning Philosophies
|
Oct. 4, 2014
Data Structures: An Introduction to Arrays and Hashes
|
Sept. 29, 2014
Guided Pairing Session 1.2: Pairing for a Website
|
Sept. 27, 2014
CSS Positioning: The Difference between Relative, Absolute and Fixed Positioning
|
Sept. 19, 2014
On Embracing Challenges
|
Sept. 18, 2014
Git, GitHub and the Command Line: Tools For Getting Started
|


_Your_Friends_&_Neighbors_ (R) *** 1/2 (out of ****)
_Your_Friends_&_Neighbors_, writer-director Neil LaBute's follow-up to his incendiary debut, _In_the_Company_of_Men_, does not have the sensational "men are monsters" hook of the previous film, but it is every bit as caustic--and the effect is nearly as fascinating.
The six central characters' names rhyme: Mary, Barry, Terri, Cheri, Cary, and Jerry. But any point to this bit of cutesy preciousness is moot, for the characters' names (or, for that matter, the city name) are never spoken throughout the entire film, adding a discomforting intimacy--it's as if we, the audience, are witnessing our "friends" and "neighbors." Why the quotes? Because while these six interact within the same overlapping households and social circles under the guise of friendship, what they do is distinctly unneighborly. Amy Brenneman and Aaron Eckhart's characters are unhappily married; he isn't getting the job done in bed, and he'd much rather pleasure himself, anyway. Brenneman (since the character names assigned in the end credits are never used, neither will I) seeks something "different" in the arms of one of Eckhart's best "friends", Ben Stiller, who himself is having trouble with his live-in girlfriend, the "unfeminine" Catherine Keener. So it is not terribly surprising when Keener, who hates Stiller's habit of talking during the act, seeks--and finds--silent sex with another woman, Nastassja Kinski. Kinski is an "artist's assistant" at a gallery that is visited at various points by nearly each individual member of the group, which is rounded out by the brash, egotistical, misogynistic Jason Patric.
It sounds like a mess, and it is; there's no rhythm or recognizable structure to the entire film, jumping between characters and situations in seemingly random fashion. Ironically, though, LaBute's fractured style heightens the reality of the events, which roughly assemble with the imperfect coherence of strung-together memories. Nonetheless, the jumble is jarring, but the rough mosaic is made consistently engrossing by LaBute's acidly comic dialogue, the intriguingly amoral (and well-rounded) characters, and the crack acting ensemble.
The clear standout in the cast is Patric. While his character is an even more extreme version of Eckhart's notorious Chad in _Men_, Patric's earnestness prevents him from becoming a complete cartoon--which makes him more all the more frightening. Speaking of Eckhart, he is barely recognizable here--and completely convincing--as slick, confident Chad's complete opposite: fat, unkempt, and completely emasculated. Brenneman may betray her husband, but she makes the audience never lose sight of the purehearted loneliness that drives her character to act in such a way; the same, but to a lesser degree, goes for Keener, whose character is much harder around the edges; and Stiller. If one character remains a cipher, it is Kinski's, who is mainly seen as an aloof object of desire (she is, however, given some emotional gumption in her final scene).
As funny as _Your_Friends_&_Neighbors_ often is, I wouldn't exactly call it an _entertaining_ film. As surreally exaggerated as some of the characters and situations appear to be, the emotional fallout is painfully genuine. Long after the film is over, you may find yourself in deep discussion about _Your_Friends_&_Neighbors_ with your friends and neighbors--at least, those whom you _believe_ to be your friends and neighbors. (opens August 19)
Michael Dequina
<EMAIL_ADDRESS>|<EMAIL_ADDRESS>Mr. Brown's Movie Site: http://welcome.to/mrbrown
CompuServe Hollywood Hotline: http://www.HollywoodHotline.com
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


About Me
Now that you've answered my questions, here are a few related details:
-
I am 6'4", which is tall enough that people often comment on it, like I had no idea. Though, to be fair, sometimes I forget myself when I reach for something and realize that my arms extend out as far as they do.
-
I was born in Washington State, and if I have my way, I'll never leave permanently. We're all spoiled by the grandeur of Mother Nature here, and I try not to take it for granted.
-
Gloomy weather can have its effect on me, but for the most part I actually enjoy the rain. Falling asleep to the sound of it is very soothing, and a reminder that even when it's miserable outside, there are still benefits (in addition to keeping everything so green!)
-
I've always enjoyed going to Seahawks games, but I didn't become a serious fan until after the team's first Super Bowl run in 2005/2006. I watched the playoffs with my roommates at the time, and really enjoyed the experience, so I decided to watch the regular season games, too. Because of this, I find the idea of "fair weather" fans to be kind of silly. We're all fair weather fans until we're not!
-
While I've always lived in Washington, I've moved around quite a bit, spending elementary school in Federal Way, junior high and high school in Sumner, and college up in Bellingham, and that's far from a comprehensive list of everywhere I've lived. In fact, I've moved so often that whenever anyone I know asks for help moving, I'm always up for it, because it's something I've done so much of myself (and I've always appreciated the help I've received!)


*Note:There are boundary issues within the container.The object may get lost when it hits certain points.Just adjust the slider && it will return into view.


--- layout: post status: publish published: true title: Interact with REST Services from the Command Line author: display_name: Geoff Lane login: admin email<EMAIL_ADDRESS>url: http://www.zorched.net author_login: admin author_email<EMAIL_ADDRESS>author_url: http://www.zorched.net date: '2007-08-10 21:32:32 -0400' date_gmt: '2007-08-11 03:32:32 -0400' categories: - Web - Ruby tags: - rails - rest comments: - id: 10895 author: Tristen author_email<EMAIL_ADDRESS>author_url: http:// date: '2007-08-18 18:57:58 -0400' date_gmt: '2007-08-19 00:57:58 -0400' content: hi i enjoyed the read - id: 11092 author: Jarrod author_email<EMAIL_ADDRESS>author_url: http://jarrodspillers.com date: '2007-12-07 10:52:14 -0500' date_gmt: '2007-12-07 16:52:14 -0500' content: this was extremely helpful - thanks for writing this! - id: 15598 author: Tristan author_email<EMAIL_ADDRESS>author_url: http://netzrauschen.tknetwork.de date: '2009-08-26 03:50:11 -0400' date_gmt: '2009-08-26 09:50:11 -0400' content: "Thanks for the writeup!\r\n\r\nOne should note that Rails (since June 27, 2008) ignores the Accept header, see: http://github.com/rails/rails/commit/2f4aaed7b3feb3be787a316fab3144c06bb21a27" ---
REST is becoming more popular as a means of implementing Service Oriented Architectures (SOA) as well as merely providing simple remote APIs for interacting with systems. The main reason for this is that it provides a very simple means of creating and consuming Services. Contrasted to SOA implementations like SOAP and REST can be a relief of simplicity.
One of the main advantages of REST is that it requires no tooling to use. Unlike SOAP, it is very easy to construct ad-hoc clients to consume a RESTful service. These examples use curl a command-line utility available on Unix systems or using Cygwin on Windows. The same concepts can be translated to anything that can send HTTP requests.
To get started with this example you can generate a Rails project and the Order object with the following commands: {% highlight bash %} rails order_example cd order_example ./script generate resource order name:string {% endhighlight %}
Then you can implement a RESTful controller with the following code: {% highlight ruby %} class OrdersController < ApplicationController # GET /orders # GET /orders.xml def index @orders = Order.find(:all) respond_to do |format| format.html # index.rhtml format.xml { render :xml => @orders.to_xml } end end
# GET /orders/1 # GET /orders/1.xml def show @order = Order.find(params[:id]) respond_to do |format| format.html # index.rhtml format.xml { render :xml => @order.to_xml } end end
# POST /orders # POST /orders.xml def create @order = Order.new(params[:order]) respond_to do |format| if @order.save flash[:notice] = 'Order was successfully created.' format.html { redirect_to order_url(@order) } format.xml { head :created, :location => order_url(@order) } else format.html { render :action => "new" } format.xml { render :xml => @order.errors.to_xml } end end end
# PUT /orders/1 # PUT /orders/1.xml def update @order = Order.find(params[:id]) respond_to do |format| if @order.update_attributes(params[:order]) flash[:notice] = 'Order was successfully updated.' format.html { redirect_to order_url(@order) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @order.errors.to_xml } end end end
# DELETE /orders/1 # DELETE /orders/1.xml def destroy @order = Order.find(params[:id]) @order.destroy respond_to do |format| format.html { redirect_to orders_url } format.xml { head :ok } end end end {% endhighlight %}
This controller allows you respond to all of the Actions that can be taken on a Resource: GET, POST, PUT and DELETE.