text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
From: dariomt_at_[hidden]
Date: 2008-06-26 03:35:45
> Why not to introduce an additional level of indirection ;)
> Just wrap the 3d-Party lib in a DLL (or Shared Object under Linux),
> than you should be find to use 2 libs with each other...
Thanks for the idea. I'll give it a try, but ideally the application should
be distributed as a single executable file.
About versioning the boost namespace, I suppose you mean something like
changing boost namespace to e.g. boost_1_35_0. Any thoughts on how much work
it would take me to patch a given version of boost to do that? Is it even
possible?
.
>
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net | https://lists.boost.org/boost-users/2008/06/37522.php | CC-MAIN-2020-16 | refinedweb | 136 | 77.33 |
RDF has always had the appeal of a Grand Unification Theory of
the Internet, promising to create an information backbone into
which many diverse information sources can be connected. With
every source representing information in the same way, the
prospect is that structured queries over the whole Web become
possible.
That's the promise, anyway. The reality has been somewhat
more frustrating. RDF has been ostracized by many for a complex and
confusing syntax, which more often than not obscures the real
value of the platform. One also gets the feeling, RDF being
the inaugural application of namespaces, that there's a certain
contingent who will never forgive it for that!
As an RDF-advocate, I am dismayed when some emerging Web metadata
applications reject RDF -- the reason given usually being "it's too
hard." I tend to think that a rather weak reason, especially as many of
the same people are attempting deployment of XML schemas!
However, I can't dispute that the current RDF syntax isn't the best, and
as long as there is metadata on the Web that can be converted to RDF by
means of a simple transform, we retain our hope of a "semantic web" of
information.
Some of the most important factors in XML's success have been
the ready availability of tools (in particular, parsers) and
ubiquitous APIs (SAX, DOM). RDF has
not matched that level of support, with the
consequence that it has felt a lot more like a research project
than an immediately applicable technology. However, some folks
have been committing their time to developing tools for
manipulating RDF, and also moving toward standardized APIs.
One tool in particular, R.V. Guha's RDFDB, caught my
attention. It's an RDF database server, based on top of the Sleepycat Berkeley
Database. The source code is in C, but more importantly, it
supports interrogation via TCP/IP sockets, meaning integration is
possible with any programming language. For me, this is an
advantage over previous RDF libraries in Java and Perl, neither of
which are my platforms of choice.
After spending a little while with RDFDB, I began to see that
it offers what I'm looking for in an RDF store. Let me explain a
little further about my criteria. My personal RDF
dream centers around the integration of all my information. I
want to be able to traverse the relationships between
my surfing, e-mail, schedule, and document data. The hierarchy of
e-mail folders and the file system just doesn't reflect the way I
work.
That reality of this dawned on me as I found myself using the
Unix tools find, grep, and locate to connect and
cross-reference documents and e-mail. The way I was traversing my
data was task-centric. If I'm working on a particular topic, I
want to see all previous correspondence on that issue. If I
visit someone's web page, I might want to see all the mail that
person has sent me recently.
find
grep
locate
So began my dream of integrating all my metadata. Somewhere
there would be a large database into which my e-mail, web
browser, file system, and so on would enter metadata. I'd then be
able to, with relative ease, query the database to make
connections between data items on my computer. On top of that
database, graphical clients could be written to maintain and
annotate it, and hooks written back into the browser, file
manager, and e-mail client to allow the use of this extra
information.
RDFDB appears to be the first stage of this plan, a database
tuned for storing and querying descriptions of resources. (Note that there
are existing approaches to RDF storage
using a relational database, but RDFDB takes a specialist
approach to storing RDF data).
Although an early stage project, RDFDB offers enough
functionality to do useful work immediately. Guha has tried to
keep the interface similar to that of SQL, in order to make the
learning curve easier. With RDFDB, you can:
create database testdb </>
insert into testdb (editor) </>
select ?p from testdb where (editor ?p) </>
(Note the </> line terminator). Facilities also exist for loading entire modules of data in
from an RDF file, and for assigning prefixes to namespaces.
</>
Both binaries for Linux and source code are available. You'll
need Sleepycat's Berkeley
DB3.1 installed in order to compile RDFDB. The
RDFDB server itself runs as a TCP/IP server, and just
sits there waiting for connections. You can use telnet as
a trivial command-line interface to the server -- this is one of
Guha's design goals, that RDFDB access should be as easy as HTTP
access.
Once a couple of environmental variables are set and the server
is running, it's easy to
start working with RDFDB, by inserting simple relationships into
the database and querying them. RDFDB also offers a facility to
perform batch import of RDF data, via the load ... file
construct.
load ... file
A good source of example data can always be found in one's
mailbox.
To take the first step toward my dreams of
integration, we first need to invent a vocabulary for describing
the data. This is where the prototype nature of my project
becomes apparent: a well-designed vocabulary is probably 80 percent of
the work in an effort like this. Particularly when integration
with disparate sources is required, a common vocabulary is
essential, and using standards such as Dublin Core becomes a very good idea.
Here are the properties I settled on:
A basic use of these properties would be simply to scrape all
the names and addresses from my in-box in order to create an
address book. With a small bit of Python, I generated a document
looking something like this:
<?xml version='1.0'?>
<rdf:RDF xmlns:rdf=''
xmlns:
<rdf:Description
<m:realName>Edd Dumbill</m:realName>
</rdf:Description>
<rdf:Description
<m:realName>Liora Alschuler</m:realName>
</rdf:Description>
<rdf:Description
<m:realName>Lisa Rein</m:realName>
</rdf:Description>
</rdf:RDF>
The file was placed in a suitable place on my machine and
imported into a database:
create database mailstore </>
load XML_RDF file into mailstore </>
A few simple queries (user input in bold, lines broken for
convenience, queries should be written all on one line):
select ?x from mailstore where
( ?x 'Lisa Rein') </>
?x = mailto:lisarein@finetuning.com
select ?x from mailstore where
(
mailto:simonstl@simonstl.com ?x) </>
?x = Simon St.Laurent
select ?x from mailstore where
(?x mailto:edd@usefulinc.com 'Edd Dumbill') </>
?x =
You can see that the property, subject, and object (the components
of an RDF description) can all be queried
by the database server. Although trivial in this example, querying
properties could have some very useful purposes, such as
determining the relationship between two people.
Writing out the
qualified names of the properties each time is a little
cumbersome, so RDFDB allows you to do this instead:
enter namespace xmlns:m </>
select ?x from mailstore where
(m:realName mailto:simonstl@simonstl.com ?x) </>
Now let's take things a little further and include some more
data from the mailbox. I wrote a simple
Python script to parse my mailbox and extract some message
data. In addition to the addressbook entries above, I also
include a description for each message:
<rdf:Description
<m:subject>Re: Submitting an article to xml.com</m:subject>
<m:timestamp>Tue, 08 Aug 2000 17:29:13 -0700</m:timestamp>
<m:author rdf:
</rdf:Description>
Note that for the e-mail message identification itself, I'm
using the mid: URI scheme
(more on URI
schemes). Having imported the RDF again into my database,
I can now answer questions like "Which e-mail messages were written by
Simon St. Laurent?":
mid:
select ?a from mailstore where
(m:realName ?a 'Simon St.Laurent') </>
?a = mailto:simonstl@simonstl.com
select ?i from mailstore where
(m:author ?i mailto:simonstl@simonstl.com) </>
?i = mid:200008022049.QAA05551@hesketh.net
?i = mid:200008030436.AAA29373@hesketh.net
?i = mid:200008030444.AAA29581@hesketh.net
?i = mid:200008061638.MAA09311@hesketh.net
?i = mid:200008081347.JAA04357@hesketh.net
?i = mid:200008090020.UAA06745@hesketh.net
I tried a few more exotic queries, using conjunctions, but
RDFDB currently seems a little flaky in its processing of
these. Using this form the above query could be reduced to:
select ?i from mailstore where
(m:realName ?a 'Simon St.Laurent')
(m:author ?i ?a) </>
RDF at the W3C
RDF FAQ
RDF and
Metadata (XML.com)
XMLhack RDF
news
RDF Interest
Group
Semantic Web Road Map
RDFDB offers a great backbone -- storage and query
facilities -- for integrating diverse information sources. In its
early stages now, it's a project that deserves to get more
mindshare. The SQL-like syntax brings a familiarity to querying
that other, more Prolog-like, mechanisms don't.
Architecturally, I find the implementation of RDFDB as a database server
a great advantage. It immediately makes multiple data sources
and clients a reality, and makes cross-platform
implementation easy
(writing a language client to RDFDB is pretty trivial, I managed
a workable first cut in 10 lines of Perl).
RDF is slowly getting more use in the field, but it needs
more ubiquitous, easy-to-use technology and APIs to
be an obvious first-stop for metadata and resource
discovery applications. RDFDB can
make an important contribution in this area.
Post to del.icio.us
This article has been tagged:
Articles that share the tag rdf:
What Is RDF (56 tags)
Screenscraping the Senate (31 tags)
Converting XML to RDF (27 tags)
Building Metadata Applications with RDF (21 tags)
An Introduction to FOAF (18 tags)
View All | http://www.xml.com/pub/a/2000/08/09/rdfdb/index.html | crawl-001 | refinedweb | 1,613 | 53.61 |
sizeof operator
Queries size of the object or type
Used when actual size of the object must be known
Syntax
Both versions return a constant of type std::size_t.
Explanation
1) returns size in bytes of the object representation of type.
2) returns size in bytes of the object representation of the type, that would be returned by expression, if evaluated.
Notes
Depending on the computer architecture, a byte may consist of 8 or more bits, the exact number being recorded in CHAR_BIT.
sizeof(char), sizeof(signed char), and sizeof(unsigned char) always return 1.
sizeof cannot be used with function types, incomplete types, or bit-field l.
Keywords
Example
The example output corresponds to a system with 64-bit pointers and 32-bit int.
#include <iostream> struct Empty {}; struct Bit {unsigned bit:1; }; int main() { Empty e; Bit b; std::cout << "size of empty class: " << sizeof e << '\n' << "size of pointer : " << sizeof &e << '\n' // << "size of function: " << sizeof(void()) << '\n' // compile error // << "size of incomplete type: " << sizeof(int[]) << '\n' // compile error // << "size of bit field: " << sizeof b.bit << '\n' // compile error << "size of array of 10 int: " << sizeof(int[10]) << '\n'; }
Output:
size of empty class: 1 size of pointer : 8 size of array of 10 int: 40 | http://en.cppreference.com/mwiki/index.php?title=cpp/language/sizeof&oldid=66856 | CC-MAIN-2015-32 | refinedweb | 209 | 57.91 |
ClockAdjust(), ClockAdjust_r()
Adjust the time of a clock
Synopsis:
#include <sys/neutrino.h> int ClockAdjust( clockid_t id, const struct _clockadjust * new, struct _clockadjust * old ); int ClockAdjust_r( clockid_t id, const struct _clockadjust * new, struct _clockadjust * old );
Since:
BlackBerry 10.0.0
Arguments:
- id
- The ID of the clock you want to adjust. This must be CLOCK_REALTIME; this clock maintains the system time.
- new
- NULL or a pointer to a _clockadjust structure that specifies how to adjust the clock. Any previous adjustment is replaced.
The _clockadjust structure contains at least the following members:
- long tick_nsec_inc — the adjustment to be made on each clock tick, in nanoseconds.
- unsigned long tick_count — the number of clock ticks over which to apply the adjustment.
- old
- If not NULL, a pointer to a _clockadjust structure where the function can store the current adjustment (before being changed by a non-NULL new).
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
These kernel calls let you gradually adjust the time of the clock specified by id. You can use these functions to speed up or slow down the system clock to synchronize it with another time source – without causing major discontinuities in the time flow.
The ClockAdjust() and ClockAdjust_r() functions are identical except in the way they indicate errors. See the Returns section for details.
The total time adjustment, in nanoseconds, is:
(new->tick_count * new->tick_nsec_inc)
If the current clock is ahead of the desired time, you can specify a negative tick_nsec_inc to slow down the clock. This is preferable to setting the time backwards with the ClockTime() kernel call, since some programs may malfunction if time goes backwards.
Picking small values for tick_nsec_inc and large values for tick_count adjusts the time slowly, while the opposite approach adjusts it rapidly. As a rule of thumb, don't try to set a tick_nsec_inc that exceeds the basic clock tick as set by the ClockPeriod() kernel call. This would change the clock rate by more than 100% and if the adjustment is negative, it could make the clock go backwards.
You can cancel any adjustment in progress by setting tick_count and tick_nsec_inc to 0.
In order to adjust the clock, your process must have the PROCMGR_AID_CLOCKSET ability enabled. For more information, see procmgr_ability().
Blocking states:
These calls don't block.
Returns:
The only difference between these functions is the way they indicate errors:
Errors:
- EFAULT
- A fault occurred when the kernel tried to access the buffers provided.
- EINVAL
- The clock ID isn't valid.
- EPERM
- The process tried to adjust the time without having the required permission; see procmgr_ability().
Classification:
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/c/clockadjust.html | CC-MAIN-2015-32 | refinedweb | 463 | 64.71 |
import "github.com/mailru/easyjson/jlexer"
Package jlexer contains a JSON lexer implementation.
It is expected that it is mostly used with generated parser code, so the interface is tuned for a parser that knows what kind of data is expected.
bytestostr.go error.go lexer.go
type Lexer struct { Data []byte // Input data given to the lexer. UseMultipleErrors bool // If we want to use multiple errors. // contains filtered or unexported fields }
Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice.
Bool reads a true or false boolean keyword.
Bytes reads a string literal and base64 decodes it into a byte slice.
Consumed reads all remaining bytes from the input, publishing an error if there is anything but whitespace remaining.
Delim consumes a token and verifies that it is the given delimiter.
FetchToken scans the input for the next token.
func (r *Lexer) GetNonFatalErrors() []*LexerError
Interface fetches an interface{} analogous to the 'encoding/json' package.
IsDelim returns true if there was no scanning error and next token is the given delimiter.
IsNull returns true if the next token is a null keyword.
IsStart returns whether the lexer is positioned at the start of an input string.
JsonNumber fetches and json.Number from 'encoding/json' package. Both int, float or string, contains them are valid values
Null verifies that the next token is null and consumes it.
Ok returns true if no error (including io.EOF) was encountered during scanning.
Raw fetches the next item recursively as a data slice
Skip skips a single token.
SkipRecursive skips next array or object completely, or just skips a single token if not an array/object.
Note: no syntax validation is performed on the skipped data.
String reads a string literal.
StringIntern reads a string literal, and performs string interning on it.
UnsafeBytes returns the byte slice if the token is a string literal.
UnsafeFieldName returns current member name string token
UnsafeString returns the string value if the token is a string literal.
Warning: returned string may point to the input buffer, so the string should not outlive the input buffer. Intended pattern of usage is as an argument to a switch statement.
WantColon requires a colon to be present before fetching next token.
WantComma requires a comma to be present before fetching next token.
LexerError implements the error interface and represents all possible errors that can be generated during parsing the JSON data.
func (l *LexerError) Error() string
Package jlexer imports 13 packages (graph) and is imported by 1197 packages. Updated 2020-04-26. Refresh now. Tools for package owners. | https://godoc.org/github.com/mailru/easyjson/jlexer | CC-MAIN-2020-29 | refinedweb | 432 | 58.58 |
Home » Support » Index of All Documentation » How-Tos » How-Tos for Modeling, Rendering, and Compositing Systems »
Using Wing IDE with Autodesk Maya
Wing IDE is an integrated development environment that can be used to develop, test, and debug Python code written for Autodesk Maya, a commercial 3D modeling application. Maya, the debug process is initiated from outside of Wing IDE, and must connect to the IDE. This is done with wingdbstub according to the instructions in the Debugging Externally Launched Code section of the manual.
Because of how Maya sets up the interpreter, be sure to set kEmbedded=1 in your copy of wingdbstub.py and use the debugger API to ensure the debugger is connected to the IDE before any other code executes as follows:
import wingdbstub wingdbstub.Ensure()
Then click on the bug icon in lower left of Wing's window and make sure that Accept Debug Connections is checked. After that, you should be able to reach breakpoints by causing the scripts to be invoked from Maya.
To use the mayapy executable found in the Maya application directory to run Wing's Python Shell tool and to debug standalone Python scripts, enter the full path of the mayapy file (mayapy.exe on Windows) in the Python Executable field of the Project Properties dialog.
Better Static Auto-completion
Maya's Python support scripts do not come with source code, but rather only with pyc files. Because Wing cannot statically analyze those files, it will fail to offer auto-completion for them unless .pi files are used. A set of .pi files generated by the PyMEL project can be found in Maya 2011 or in the PyMEL distribution.
- Maya 2011 ships with .pi files in the devkit/pymel/extras/completion/pi subdirectory of the Maya 2011 install directory.
- For other Maya versions, .pi files from the PyMEL distribution at may be used. PyMEL does not need to be installed or used to make use of the .pi files; it's enough to simply unpack the source distribution. The pi directory within the PyMEL 1.0.2 distribution is extras/completion/pi
Add the pi directory to the list of interface file directories that Wing uses by adding it to the Interface File Path preference in the Source Analysis -> Advanced preference page. After adding the directory to the path, Wing will offer auto-completion if you import xxx and then type xxx.
Additional Information
Some additional information about using Wing IDE with Maya can be found in For Python: Maya 'Script Editor' Style IDE. This includes extension scripts for more closely integrating Wing Pro and Maya and some additional details. For example, sending Python and MEL code to Maya from Wing is explained here
See also the section Using Wing IDE with Maya in Autodesk Maya Online Help: Tips and tricks for scripters new to Python.
Related Documents
Wing IDE provides many other options and tools. For more information:
- Wing IDE Reference Manual, which describes Wing IDE in detail.
- Wing IDE Quickstart Guide which contains additional basic information about getting started with Wing IDE. | https://wingware.com/doc/howtos/maya | CC-MAIN-2016-40 | refinedweb | 514 | 62.68 |
Important: Please read the Qt Code of Conduct -
Read data and add it to a chart
Hi everyone. Here is a code script that can write and read data from txt and show it on display in a time interval. I want to convert the screen in a real time chart. I want to add my datas to chart in real time. For example, read data in 0,2 sec and add chart in an order. How can i do such thing?
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QTimer> #include <QList> #include <qlist.h> #include <QDebug> QTimer *timer = new QTimer(); MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); connect(timer, SIGNAL(timeout()), SLOT(Timer_Slot())); } void MainWindow::Timer_Slot() { QString line = allLines[curIndex]; ui->plainTextEdit->setPlainText(line); if (curIndex < allLines.size() - 1 ) { curIndex++; } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_2_clicked() //write { QFile file("C:/Users/ilknu/Documents/QFileDemo/abc.txt"); if(!file.open(QFile::WriteOnly | QFile::Text )) { QMessageBox::warning(this, "title", "file not open"); } QTextStream out (&file); QString text = ui->plainTextEdit->toPlainText(); out << text; file.flush(); file.close(); } void MainWindow::on_pushButton_clicked() //read { QFile file("C:/Users/ilknu/Documents/QFileDemo/abc.txt"); if(file.open(QIODevice::ReadOnly)) { QTextStream in (&file); while (!in.atEnd()) { QString line = in.readLine(); allLines.append(line); } file.close(); } file.close(); curIndex=0; timer->start(200); }
@suslucoder From where do you want to read the data?
@suslucoder Then I'm not sure what exactly you want to do. What do you mean by "real time"? You can simply read the whole file at once and update the chart.
@jsulm I don't want it to read all the data and add it to the chart. It can read the entire file in once, but I want it to add the data to the chart every 0.2 seconds. It should always proceed by adding the most recently read data to the chart
@suslucoder said in Read data and add it to a chart:
but I want it to add the data to the chart every 0.2 seconds
Then this is not "realtime".
You already have the file content in allLines and you already have Timer_Slot() slot. So, what prevents you from adding next data line to your chart in that slot?
@suslucoder There are many examples:
Take time to see how data is added to a chart.
@jsulm as you said, I already have the file content in allLines. When i do series.append(allLines) to adding chart I get an error. Thank you I will analyze the examples
@suslucoder I told you in that other thread from you that you can't use a string list there. Please also read documentation...
@suslucoder
@jsulm already answered this last question in. You cannot add a a string (or string list) to a chart, you have to parse it to generate the actual desired numbers.
For adding data every few seconds: whether you read the lines from the file as you go or you read them all into a list in memory, either way on a
QTimer::timeout()signal read the next however-many from the file/list and add them to the chart.
@suslucoder
Well it's not another "struct". You presumably have a file containing the text of numbers, perhaps separated by commas or new lines or something. You need to convert those to X,Y numeric values, and then pass those (or
QPointFs) to add to the chart series. It doesn't matter whether you do that at the time of reading in the file or just before adding them to the series, but you will need to do so at one of those two stages.
@suslucoder said in Read data and add it to a chart:
I should use another struct instead of string list, right?
You should use what the method to set the data expects. That's why I suggested to read the documentation: it is documented quite clearly.
- jsulm Lifetime Qt Champion last edited by jsulm
@suslucoder I already posted a link to charts examples.
For example:
And you still did not tell us what data you actually want to show and what type of chart you need...
- mrjj Lifetime Qt Champion last edited by
Hi
Please show one line from the "C:/Users/ilknu/Documents/QFileDemo/abc.txt"
so we know how data is. else it's impossible to give any hints on how you can show that in a chart.
1991 01 213.5 136.9 0.64 220.5 147.6 229.4 205.5 8 17.4
1991 02 270.2 167.5 0.62 221.5 147.6 243.0 206.3 10 18.4
QString line = read_one_line_from_file(); QStringList list = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); for (const QString &entry : list) { double num = entry.toDouble(); // or `unsigned num = entry.toUInt()` for the first 2 numbers on each line, by the look of it // do whatever is necessary with each `double` number retrieved // such as adding pairs directly to the chart, or building a `QLineSeries`, or whatever }
@suslucoder said in Read data and add it to a chart:
Where should I place the code script?
Come on. Place is where you read the data from the file...
@jsulm I know but i have, QString line = in.readLine();
allLines.append(line);
I couldnt get the idea about it. When i do it i get out of index error .And after doing all this things, how can i add my datas to a chart?
@suslucoder I did this part. After that, how can i add it to a chart? Like the way create a new chart, append series and it goes like this?
@suslucoder said in Read data and add it to a chart:
And after doing all this things, how can i add my datas to a chart?
I already provided links to examples several times.
"When i do it i get out of index error" - then post your code...
@jsulm ```
QString line = in.readLine();
allLines.append(line);
QStringList list = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
for(const QString &entry : list) {
double num = entry.toDouble();
}
series->append(num)
``
Says use of undeclared identifier num
- mrjj Lifetime Qt Champion last edited by mrjj
Hi
You want like
QStringList list = line.split(QLatin1Char(' '), Qt::SkipEmptyParts); for(const QString &entry : list) { double num = entry.toDouble(); series->append(X,Y); // use num for either xor y or both depending on what you want }
- SGaist Lifetime Qt Champion last edited by
@mrjj said in Read data and add it to a chart:
series->append(num); // add each number from the line
This cannot work as QLineSeries does not have such an overload.
Currently discussed here.
- mrjj Lifetime Qt Champion last edited by mrjj
@SGaist
Good catch.
yes its x,y.
It was more about num being undeclared at that point in time :)
Changed as not to confuse future readers. | https://forum.qt.io/topic/122319/read-data-and-add-it-to-a-chart | CC-MAIN-2021-04 | refinedweb | 1,153 | 74.29 |
Proper Tail Calls, a definition.
Great article. I think that PTC has something to do with the continuations present in functional languages. For example, you can call a function adding the name of another function as its last parameter, and such function will be called with the result of the first one. As far as I know, this is called Continuation Passing Style (CPS) in the context of functional programming. Not exactly the same, but pretty close. Interesting. What do you think?
Posted by: ruben | February 5, 2008 7:27 AM
Thanks. PTC definitely helps with Continuation Passing Style (CPS). If you use CPS in a language that does not have PTC, you run the risk of a stack overflow error because the call to the continuation doesn't return to the original function.
Posted by: Francis Cheng | February 5, 2008 9:03 PM
This is great news, Francis. PTC is one of the things I've been wanting in Actionscript for a while. Thanks for the info.
Posted by: Austin Haas | February 6, 2008 10:19 AM
Therefore, I'm wondering how PTC is used (if so) in relation to a recursive implementation of a function (e.g. factorial). Does PTC apply to the function call which is in tail position and its return value its not used? I'm thinking of:
def fact(n):
if (n == 1) return 1
return n * fact(n-1)
I'll have to read Clinger's paper and catch up with this language. :)
Posted by: ruben | February 6, 2008 1:32 PM
For more information about PTC and recursion, see my January 30th post Proper Tail Calls and Recursion. As for your example, the call to fact(n-1) is not in tail position because you are multiplying the return value of fact(n-1) by n, so that multiplication operation is the last thing the function does. See the link above for a lengthier discussion about that very function.
Posted by: Francis Cheng | February 7, 2008 9:19 AM
@Francis, came across your blog via Colin Moock's blog. Thanks for posting the ES4 happenings.
I found the description of proper-tail calls in "Programming in Lua" to be quite good. Though I did come in knowing about functions on the stack, something you did a good job of expounding here for the uninitiated.
Posted by: Nathan Youngman | February 8, 2008 4:13 PM | http://blogs.adobe.com/fcheng/2008/01/proper_tail_calls_a_definition.html | crawl-002 | refinedweb | 402 | 71.65 |
manage a neo4j server installation
manage a neo4j server installation
npm install neo4j-supervisor
var supervise = require('neo4j-supervisor');var neo = supervise('/potato/neo4j');neo.clean(function(err) { ... }); // purge all data from the databaseneo.running(function(yep) { ... }); // check if instance is runningneo.start(function() { ... }); // start an instance//... etc - see below for a list of available functions
doesn't work on windows. :~~[
Neo4j 3 has problems starting up inside tmux on OS X. To get this working, you'll
need to run
brew install reattach-to-user-namespace. It should just work on its
own after this.
all the callbacks are in the format
function(err, output) unless otherwise
specified
runningwill return true and
attachedwill return false.
neo.attachedreturns true, then call
cb.
cbis called.
cbis called
portis specified, set the port of the server to
port. otherwise, get the port of the server.
port, but with hostname.
server—the location of the server with protocol and port, and
endpoint—the path of the api endpoint on top of
server. this conveniently fits straight into seraph. | https://www.npmjs.com/package/neo4j-supervisor | CC-MAIN-2017-09 | refinedweb | 175 | 52.76 |
Opened 6 years ago
Closed 5 years ago
#3728 closed enhancement (wontfix)
os.popen3 usage cause lags in launch() function
Description
Commands launched by launch() function are working, but a lag of 20/30 sec occur after when using apache2+mod_python
Here is my fix, don't know if it's good or not, but it's working for me :
def launch(self, cmd, input): """Launch a process (cmd), and returns exitcode, stdout + stderr""" p = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (p_in, p_out, p_err) = (p.stdin, p.stdout, p.stderr) if input: p_in.write(input) p_in.close() out = p_out.read() err = p_err.read() p.wait() p_err.close() p_out.close() return out, err
Attachments (0)
Change History (3)
comment:1 Changed 6 years ago by cboos
comment:2 Changed 6 years ago by franck34
comment:3 Changed 5 years ago by cboos
- Resolution set to wontfix
- Status changed from new to closed
Works fine in the 0.11 version.
The maintenance of the 0.10 version of the plugin is up for adoption...
Note: See TracTickets for help on using tickets.
subprocess is now used for the 0.11 version of the plugin.
I don't know really, but it seems unlikely that the 0.10 version will adopt this change.
Closing as worksforme? | http://trac-hacks.org/ticket/3728 | CC-MAIN-2014-23 | refinedweb | 221 | 75.91 |
51764/how-can-i-get-all-the-pods-on-a-node
You can use the following command to get all the pods on a node in kubernetes Cluster -
$ kubectl get po --all-namespaces -o jsonpath='{range .items[?(@.spec.nodeName =="nodename")]}{.metadata.name}{"\n"}{end}'
Run the following commands:
This command will create ...READ MORE
I have followed the link which you have ...READ MORE
Here is a solution to your problem:
You ...READ MORE
Make sure your imagePullPolicy is set to Always(this is
Make sure your imagePullPolicy is set to ...READ MORE
Just do port forward.
kubectl port-forward [nginx-pod-name] 80:80
kubectl ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/51764/how-can-i-get-all-the-pods-on-a-node | CC-MAIN-2020-16 | refinedweb | 115 | 68.26 |
PyCells: The Python SpreadSheet redux
In 2004 I saw a recipe about how to make a "spreadsheet" in python in 10 lines of code:
class SpreadSheet: _cells = {} tools = {} def __setitem__(self, key, formula): self._cells[key] = formula def getformula(self, key): return self._cells[key] def __getitem__(self, key ): return eval(self._cells[key], SpreadSheet.tools, self)
It's shocking. And it works, too:
>>> from math import sin, pi >>> SpreadSheet.tools.update(sin=sin, pi=pi, len=len) >>> ss = SpreadSheet() >>> ss['a1'] = '5' >>> ss['a2'] = 'a1*6' >>> ss['a3'] = 'a2*7' >>> ss['a3'] 210 >>> ss['b1'] = 'sin(pi/4)' >>> ss['b1'] 0.70710678118654746 >>> ss.getformula('b1') 'sin(pi/4)'
I was so awed, I wrote a PyQt version . Of course there is a catch in that code: it sucks if you are trying to write a spreadsheet with it.
Why? Because it doesn't store results, but only formulas.
For example:
A1=2 A2=A1*2
If you ask for the value of A2, you get 4. If you set A1 to 7, what's the value of A2?
Well, it's nothing yet, because it's only calculated when you ask for it. But suppose you are trying to display that sheet... you need to know A2's value changed when you set A1!
That's cell dependencies, and while that simple code handles them in a way, it totally sucks in another.
So, I went ahead and coded around it successfully. Of course the code was not so pretty anymore (although a large part of the uglyness is just for making it work with Python 2.3 and relative cells).
Then yesterday, while looking at the excel formula parser madness I saw a reference to PyCells, a python port of Cells from CLOS.
Here is a blog commenting on Pycells:).
Almost everyone uses that analogy... however, no matter how hard I looked, I couldn't find anyone who had actually tried writing a spreadsheet using PyCells! Not even as an example!
So here it is:
import cells class Cell(cells.Model): formula=cells.makecell(value='') @cells.fun2cell() def value(self,prev): print "eval ",self.formula return eval(self.formula, {}, self.ss) def __init__(self, ss, *args, **kwargs): self.ss=ss cells.Model.__init__(self, *args, **kwargs) class ssDict: def __init__(self): self.ss={} def __getitem__(self,key): return self.ss[key].value def __setitem__(self,key,v): if not self.ss.has_key(key): c=Cell(self) c.formula=v self.ss[key]=c else: self.ss[key].formula=v if __name__ == "__main__": ss=ssDict() ss['a1'] ='5' ss['a2']='2*a1' print "a1: ", ss['a1'] print "a2: ", ss['a2'] ss['a1'] = '7' print "a1: ", ss['a1'] print "a2: ", ss['a2']
And here you can see it running:
[ralsina@monty cells]$ python ctest.py a1: eval 5 5 a2: eval 2*a1 10 eval 7 eval 2*a1 a1: 7 a2: 14
See how when I set a1 to 7 I get "eval 7" and "eval 2*a1"? That's because it's propagating changes the right way. And that's why this would work as a basis for a spreadsheet.
UPDATE
It seems there is a bug wither in PyCells, or in my example, or something, because it breaks pretty easily, if the dependency chain is even two cells:
a1: eval 5 5 a2: eval 2*a1 10 a3: eval 2*a2 20 eval 7 eval 2*a1 a1: 7 a2: 14 a3: 20
In this example, I am setting A3 to 2*A2, and when I update A1, A3 is not updated. Further research is needed.
Sweet use of self.ss as local namespace for "eval". Well done !
I can't take credit for that, it's from Raymond Hettinger's original recipe.
You can solve dependencies using Tarjan's algorithm. If you can build a dictionary like this:
{ 0 : [1], # 1 depends on 0
1 : [2], # 2 depends on 1
2 : [1,3], # 1 and 3 depends on 2
3 : [], # Nothing depends on 3
}
Tarjan's will give you a list back like so:
[(0,), (1, 2), (3,)]
If you calculate in that order you will not have a problem. It also shows you that 1 and 2 have to be solved simultaneously.
There is a nice, liberally licensed, implementation available here:...
It will work with any hashable type for the indexes, not just numbers.
JT
Thanks, I'll try to take a look
This is cool! And so interested! Are u have more posts like this? Plese tell me, thanks
this is really interesting viewpoint on the subject i might add
great post
Your blog has the same post as another author but i like your better | https://ralsina.me/weblog/posts/BB585.html | CC-MAIN-2020-45 | refinedweb | 782 | 74.9 |
Troubleshooting and Limitations - .NET
This section describes troubleshooting and limitations for .NET Vuser scripts.
Tip: For general VuGen troubleshooting and limitations, see Troubleshooting and Limitations for VuGen.
Replay Limitations
- Exceptions in .NET scripts generated by vts functions, may cause the replay to abort, even when the Continue on error Runtime setting is enabled.
Workaround: Use
tryand
catchstatements for error handling of the vts functions.
- .NET scripts that contain UI objects can behave unexpectedly during replay in VuGen, the Controller, or on a load generator machine.
Recording Limitations
The following limitations apply to the VuGen recording of a Microsoft .NET application:
.NET Vuser scripts support only single-protocol recording in VuGen.
Direct access to public fields is not supported—the AUT must access fields through methods or properties.
VuGen does not record static fields in the applications—it only records methods within classes.
Multi-threaded support is dependent on the client application. If the recorded application supports multi-threading, then the Vuser script will also support multi-threading.
In certain cases, you may be unable to run multiple iterations without modifying the script. Objects that are already initialized from a previous iteration, cannot be reinitialized. Therefore, to run multiple iterations, make sure to close all of the open connections or remoting channels at the end of each iteration.
- Recording is not supported for Enterprise Services communication based on MSMQ and Enterprise Services hosted in IIS.
The .NET version should be the same on the record and replay machines.
VuGen partially supports the recording of WCF services hosted by the client application.
Recording is not supported for Remoting calls using a custom proxy.
Recording is not supported for ExtendedProperties property of ADO.NET objects, when using the default ADO.NET filter.
Applications created with .NET Framework 1.1 which are not compatible with Framework 2.0, cannot be recorded. To check if your Framework 1.1 application is compatible, add the following XML tags to your application's .config file:
<configuration> <startup> <supportedRuntime version="v2.0.50727"/> </startup> </configuration>
Invoke the application (without VuGen) and test its functionality. If the application works properly, VuGen can record it. Remove the above tags before recording the AUT with VuGen. For more information regarding this solution, see the MSDN Knowledge Base.
- are configured through the runtime settings and using the filters mechanism.
- When McAfee antivirus is active, it may issue the following message when recording a .NET script: "The solution has been changed externally".
Workaround: Add the VuGen.exe process to the Low-Risk processes in the McAfee antivirus On-Access Scan Properties.
VuGen does not record a method that gets a private class as an argument. For example:
public class A { private class P {
… } private void MethodUsingPrivateClass(P p) { … } }
- References added to a .NET script during recording, by means of the .NET Recording Filter, are not removed from the script by removing them in the References List dialog box.
Script Editing Limitations
Disable FIPS if you want to open or debug a .NET Vuser script in Visual Studio 2015. | https://admhelp.microfocus.com/vugen/en/12.60/help/WebHelp/Content/VuGen/140750_tl_dotnet.htm | CC-MAIN-2018-39 | refinedweb | 505 | 52.05 |
In Part 1 of this series, you already learned how to extend the Add New Class template file already shipped with Visual Studio .NET 2003. But when you are creating test classes using NUnit or TestDriven.NET, you might want to have a skeleton class, which adds the [TestFixture] attribute to the class declaration and which defines a method already having the [Test] attribute added to it. Additionally you would appreciate that you can select this template from the "Add new element" wizard page.
[TestFixture]
[Test]
This article will explain how you can easily create your own wizards doing just a few steps. Again, I want to refer the really good article Creating project item code templates for Visual Studio .NET by Emil Aström. I suggest that you read this article carefully because I will crosslink to it, whenever I feel it is necessary.
The background - or intention - this time will be to create a skeleton class for NUnit test cases. This skeleton class is based on the template we created in Part 1 and extends it. So if you have passed Part 1, then I suggest to read this article now.
The first step you'll have to do is to create a new .vsdir file. The format of the file is explained in Emil's article. If you installed Visual Studio .NET 2003 using default options, you will find the directory where to create the .vsdir file at:
C:\Program Files\Microsoft Visual Studio .NET 2003\VC#
\CSharpProjectItems\LocalProjectItems
for C# projects. If you changed the installation path, you can look at Emil's article to get the correct path to your project items directory. If you want to, you can add a new category by simply creating a new directory at this location. Try it and add the new directory:
C:\Program Files\Microsoft Visual Studio .NET 2003\VC#
\CSharpProjectItems\LocalProjectItems\Wizardry
In the new directory, add a file called called wizardry.vsdir. Open the file in an editor and add the following pipe delimited string to it:
..\..\CSharpAddNunitTestClass.vsz|0|NUnit Testclass|1|Creates
a new NUnit Testclass|0|0|0|TestClass.cs
Please ignore the line break above that has been added here to avoid text from scrolling.
Here's a brief description of the content (thanks Emil). You will also find a complete documentation in MSDN:
RelPathName
(clsidPackage)
LocalizedName
SortPriority
Description
DllPath
(clsidpackage)
IconResourceId
Flags
SuggestedBaseName
The .vsz files shipped with Visual Studio .NET 2003 are normally kept in the CSharpProjectItems directory, so I decided to put mine there too. But you can place them anywhere you want, all you have to do is to setup the parameter RelPathName correctly to point to the location of the file.
Important note: Don't put a line break in the middle of the pipe delimited set of parameters. Otherwise this will cause your wizard not to work!
The .vsz file directed to by the RelPathName parameter contains information about the component to use to create the project item. In this article, we will create a project item using the standard engine called VsWizard.VsWizardEngine.7.1. But in the last part of this series you will learn how to create your own engines.
In the directory,
C:\Program Files\Microsoft Visual Studio .NET 2003\VC#\CSharpProjectItems\
add a new file called CSharpAddNUnitTestClass.vsz. If you change the relative path in the .vsdir file, you will have to add the file at the directory you pointed to. Open the file in an editor and add the following content:
VSWIZARD 7.0
Wizard=VsWizard.VsWizardEngine.7.1
Param="WIZARD_NAME = CSharpAddNunitTestClassWiz"
Param="WIZARD_UI = FALSE"
Param="PROJECT_TYPE = CSPROJ"
The parameter VSWIZARD 7.0 identifies the expected version, so you should not change it. The other parameters are covered in Emil's article and there is nothing more to tell about them.
VSWIZARD 7.0
A lot more other parameters can be changed in the .vsz file, but we can ignore them right now. I just want to mention two interesting things:
ABSOLUTE_PATH
RELATIVE_PATH
Documentation for all already available parameters can be found in MSDN.
Remember, back in Part 1, we edited the template file of the Add New Class wizard. We added some code comments and regions to it, saved it, and after restarting Visual Studio .NET 2003, we got the expected result. As I already mentioned before, the path to the template files is defined by two variables (when not adding the ABSOLUTE_PATH parameter to the .vsz file):
WIZARD_NAME
So our files are expected (if you installed Visual Studio .NET 2003 at the default location) at:
c:\Program Files\Microsoft Visual Studio .NET
2003\VC#\VC#Wizards\CSharpAddNUnitTestClassWiz\
Create this directory and copy the contents of CSharpAddClassWiz directory from Part 1 into the new directory. Open the file NewCSharpFile.cs and change its contents:
using System;
using System.Diagnostics;
using NUnit.Framework;
namespace [!output SAFE_NAMESPACE_NAME]
{
/// <summary>
/// </summary>
/// <remarks>
/// <para>created: [!output CREATION_DATE]</para>
/// <para>Author : Michael Groeger</para>
/// </remarks>
[TestFixture]
public class [!output SAFE_CLASS_NAME]
{
#region [!output SAFE_CLASS_NAME] Testcases
/// <summary>
/// </summary>
[Test]
public void Test()
{
// TODO: add test instructions here
}
#endregion
}
}
Save the file and run a new instance of Visual Studio .NET 2003. Open a project, right click on its project name in Solution Explorer and click "Add > Add class". The wizard dialog opens and you should see the following:
If you click Open, the following class should be generated for you:
using System;
using System.Diagnostics;
using NUnit.Framework;
namespace Wizardry2
{
/// <summary>
/// </summary>
/// <remarks>
/// <para>created: 10. May 2005</para>
/// <para>Author : Michael Groeger</para>
/// </remarks>
[TestFixture]
public class TestClass1
{
#region TestClass1 public members
/// <summary>
/// </summary>
[Test]
public void Test()
{
}
#endregion
}
}
Unfortunately, I don't have an English version of Visual Studio .NET. So the screenshots in this article are kept in German. If somebody wants to, he can send me English screenshots. The paths in this article should be correct for English versions, if not, just leave me a note.
This time I have shown you that it is very easy to create your own wizards which produce skeleton classes for simple purposes. It has just taken a few steps:
The next article will cover, how you can add a simple user interface to your custom wizard, which allows you to add your own symbols. This will help you in creating typed collections and dictionaries. Interested? Coming. | http://www.codeproject.com/Articles/10707/Building-VS-NET-Wizards-Part-2 | CC-MAIN-2015-11 | refinedweb | 1,060 | 57.06 |
Welcome to the robot version of the Justice League. Where Rosie will team up against a band of baddies, and in general, bring much needed calm and order to the world. Justice for precisely what, you ask? Actually, we don't quite know. But as we now have a logo, let's pretend that this is all for a righteous cause.
So far, our greatest creation has been a... (semi)-autonomous moving plastic box. Good for carrying a basket of fruits. However, not so good at defeating fruit cakes, intent on taking over the world.
The master plan? As with all good plans to defend all that's precious to humanity (Guardians of the Samsung Galaxy) it begins with the requisition of more random kit that we can attach to our Pi. Then, some equally random Python code to make use of those gizmos. Yes, we'll battle unpleasant invaders one if statement at a time, and scare them away with more bits of electronics than you'd find in your local car boot sale.
Ladies and gentlemen. Let us introduce to you the greatest superhero of them all. ™Rosie™ ™Patrol™.© ™.© ™.
Electricity is dangerous. It can zap you. It can cause fires. Never tamper with any devices that are connected to, or will be connected to the mains (AC). Stick to stuff with normal household batteries. They are much more appropriate for robot use anyway.
Always ask for help from someone more qualified than you if you are unsure about any of this. And - sorry kids - always have adult supervision.
Always ask for help from someone more qualified than you if you are unsure about any of this. And - sorry kids - always have adult supervision.
All superheroes need:
- Raspberry Pi 3 (kitted out with wheels and sensors and stuff), and Raspbian running on SDHC card
- Computer from which you are connecting to the Raspberry Pi remotely
- An electrical relay. We are using a 4-channel relay by Kuman. Same principles apply to all other relays, although always check up to what current (A) and voltage (V) the relay supports in relation to the device that you are trying to control.
- A random assortment of torches to hack
- Gear for some soldering, and drill, if you are intend on doing some serious gadgetry surgery
Already completed these missions?You'll need to have completed the Rosie series.
Your mission, should you accept it, is to:
- Hack a torch, attach it to a relay, and connect it to Pi's GPIO pins
- Graduate to Python 3 (from 2) and start using IPython for the interactive Python shell
- Modify the Python code to create our own class for a light
- Create a Flask function to allow light to be switched using HTTP requests
- Create a button in Flask's HTML template for the light button
- Make Rosie cruise around at night, looking all sparkly. Defeat evil.
The brief:Let's get straight to the point. Have you ever wanted to hack an electronic head torch? Have you? Has this always been on your bucket list? Admit it, it has! Well, even if you don't under interrogation by an evil mastermind, you've got no choice. You see, all bad things happen at night, when everyone is asleep. And in most parts of the world, it gets dark at night (something to do with the sun, rotation of the earth... blah, blah, blah). So, in order to do some patrolling past bed time, Rosie Patrol requires a light. A bright light.
And Rosie would like one of those bright lights that humans use, not those titchy, embarrassing LEDs designed for remote controls and mobile phones. See, she's seen humanoids in ugly fluorescent jackets and Lycra shorts run and cycle with them at night. They look so comfortable to wear (the torch, not the Lycra). Perfect for a midnight patrol to track down delinquents in the middle of a misdemeanour.
But you can already see the problem coming. They aren't designed for a Raspberry Pi, or robots for that matter. People are expected to turn things on and off, using a very much human-friendly (but not so machine-friendly) mechanical switch. But we don't want to let Rosie down. And she needs the tools to do her job properly (you know, saving the world and stuff).
This is why we suddenly find ourselves on an urgent (but not so top secret) mission to hack apart an electronic head torch or two. Make them robot-friendly. And for this, we welcome into our team of superheroes, the Relay (yes, not a very good superhero name we realise). It's an electrical device that can be used to connect the Pi's GPIO pins to electronic stuff not normally expected to be controlled by a little red marauder of justice.
All this for a robot... with a torch.
The devil is in the detail:We start by exploring a timeless question that philosophers have grappled with since the dawn of mankind:
Thee shall not has't light, if thy head torch hast nay electricity
But thee shall has't light, if thy head torch hast electricity..?
Thankfully, we can answer this age-old mystery once and for all. Yes. Your head torch (and electrical devices generally!) works only when there is electrical current flowing through it from its batteries. It will not, when there is none. So one crude way of controlling the lightbulb in the head torch would be to start and stop the flow of electrical current to it, much like if you were plugging and unplugging batteries, manually. This is basically what a mechanical switch does. So far so good.
But we want to control this switching using simple signals from the Pi's GPIO pins. So we need a device that effectively allows us to control a small mechanical switch, using only (small) electrical signals. Meet the Relay. Relays are electrically operated switches, which allow a small electrical signal to control a larger flow of electrical current. So in short, it will allow signals from our Pi's GPIO pins to turn on and off electricity travelling through devices. Perfect for a head torch.
But this is important. Before we totally obliterate our torch to inject into it our relay, we need to understand how our particular torch works. Does it have a simple on / off switch that closes / opens the circuit? Or does it have a switch that only momentarily closes a part of the circuit, which in turn, sends a signal to a microchip. A chip that probably coordinates the change in the status of the light between on, off and other states (like beam strength, flashing, etc). In order to hack it, we need to understand what is expected. And reproduce this behaviour using our Pi and relay. After all, the less of the working parts of the torch we touch the better. If it's not broken, don't fix it. We are only interested in the switch.
You're probably bored by now. Let's whip out some examples and do this for real.
Arise our three lights in shining armour!
Name: Eric.
Name: Electron 2000.
Name: Elsa (or possibly it's Anna?)
What does it do: It's an
annoying amazing wand that plays Let it Go when a button is pressed..
What does it do: It's an.
We've spoken about it. But what does it look like? Relays look like... another piece of electronic circuitry. Why? What did you think it would look like?
...And this is how you cable it. It needs a small amount of power itself to operate the switches. For this, we can use the 5V and 0V (Ground) supplies on the Pi. Remember, this is not used to power any devices attached to it. It is simply used to operate the switches. All devices therefore need to continue to have their own power supplies (batteries).
There is also a GPIO pin assigned per channel (ours has 4). This is where we send signals to from Pi's GPIO pins, to open / close that particular switch (channel). We'll use GPIO pin 33 (BCM 13) for the test.
And of course, there are some terminals for where you connect the actual devices. Depending on which terminals you use, you can have a normally open or normally closed setup. This is where actual current of the device is passing (or not). And this is why it's important to check that your relay's switches can handle the voltage and current that the device actually handles. You should have no problem if your devices are powered by a couple of AA or AAA batteries, unless of course, you have a Tesla motor you'd like to hook up to your relay.
The idea is to mimic the behaviour of the switch the torch is currently equipped with, using the relay. For Eric, we simply want to instruct the relay to open / close the circuit. This allows current to not flow / flow to the light-bulb, like with the mechanical sliding switch which makes two metal plates break or make contact.
There are many potential places that we can do this, with an 'old-school' torch like this. We interrupted the torch's existing circuit where the positive terminal of the battery normally makes contact with the bottom of the lightbulb, and replaced it with two cables. When the ends of the two cables meet, the circuit is complete and the light comes on. Great, because this is so easily controllable using the relay.
But our brainy friend Electron 2000 - being the sophisticated piece of tech that it is (light years ahead of Eric) - appears to have a microchip which is expecting momentary pulses of electricity to signal changes in its lights. Here, we need to reproduce the behaviour of a switch closing and opening quickly using the relay (more on this later, with Python).
Looking at the circuit board inside, the existing push to close (normally open) momentary switch is soldered to the board. This is perfect, as we can simply un-solder it, and replace it with... you should know this by now... two ominous-looking cables. Testing reveals that the two ends of these cables meeting momentarily kicks the microchip (and the torch) into action.
Once the cables are connected to the terminals on the relay, we are ready to unleash some Python code to start our very own robot disco.
Before we do, though, let's do some housekeeping we have been forgetting to do. Let's graduate to Python version 3. We've been using Python version 2 until now, as the RasPiRobot v3 libraries required it. But now that we have our very own motor controller code, we can move onto using the latest and greatest version of Python.
Python 3 should already be installed on Raspbian OS. And it can be called using python3, instead of python. Let's check that it exists, and its version. While we're at it, let's check that Pip 3 (for Python 3) is also installed, and up to date. We need Pip to install Python packages, remember?
python3 --version pip3 --version sudo pip3 install --upgrade pip...checks version of Python 3, Pip 3 and upgrades Pip 3 if out of date
You should always try to use Python 3 if you can help it*. Python 2 won't be around for much longer.
*Not always possible, as so much stuff that you'll want to use has been written in Python 2.
Then, because for testing we want to turn our lights on and off interactively, we want to use the Python shell. But quite frankly, the default Python shell you get when you type python / python3 isn't very pretty, or helpful. So we'll install a Python shell on steroids - IPython.
sudo pip3 install ipython...downloads and installs IPython using Pip 3
Once it's installed, we should now be able to launch it, using ipython in the Linux shell. Check that it is using Python 3. You don't have to look very far. It tells you. There.
IPython is exactly like the standard Python shell, except there are lots of helpful features like line numbering, colour coding, etc. We've also found that it is good at coping with code being copied and pasted in over the SSH session. Useful, when you are
Before we proceed with modifying our rosie application, let's interact with the relay (and the torch) using a new class that we'll set up.
class Light: def __init__(self, relay_pin = None, momentary = False): self.relay_pin = relay_pin self.momentary = momentary gpio.setmode(gpio.BCM) gpio.setwarnings(False) gpio.setup(relay_pin, gpio.OUT) self.switch_closed = False def switch(self): if self.momentary == False: if self.switch_closed == False: gpio.output(self.relay_pin, 0) self.switch_closed = True elif self.switch_closed == True: gpio.output(self.relay_pin, 1) self.switch_closed = False elif self.momentary == True: gpio.output(self.relay_pin, 0) self.switch_closed = True time.sleep(0.1) gpio.output(self.relay_pin, 1) self.switch_closed = False
See how it looks infinitely better in IPython now that there is some colour coding and formatting? You can also define entire blocks of code, like we are doing with our class, before submitting it. Execution is done using the 'Enter' key.
Our class Light represents our lights. It will be initialised with a specific GPIO pin that is connected to the relevant channel of the relay. We'll also have two modes: a momentary switch and one that isn't. This should allow it to interact with both Eric and Electron 2000 using this one single class.
The switch() method is there to simply allow us to send the relevant signals to the relay. When the flag is False for momentary, we simply open or close the circuit, one of those actions at a time. When it is True, we close and open quickly (with a delay of 0.1 second).
We'll use an instance variable self.switch_closed to keep track of the current state of the light's switch.
All we need to do now is instantiate a Light object, and call its method.
For Eric, we don't need the switching to be momentary:
l1 = Light(13, False)
And when we call the l1.switch() method, we see that we can turn Eric on / off! We've successfully bridged the world of code, with a physical object that we use (perhaps) every day.
l1.switch()
You know what we're now going to do. Because let's face it. That torch on Rosie? No way. We'll do the same, but with Electron 2000 connected to the relay (using the same GPIO pin). 4 channels on the relay means you could have 4 torches on the go. But that's silly.
We'll instantiate Electron 2000 as l2.
l2 = Light(13, True)
Guess what? We're now in control of the head torch. With each call to l2.switch(), we can cycle through the different light settings. Pretty chaotic, and kind of cool, at the same time.
l2.switch()
So what is there left to do? In true Rosie style, we'll return to our rosie application and call it rosie-web-lights.py. And here it is:
Besides the new Light class we need to add to the code, we will add a little Flask function to respond to HTTP POST requests on the '/light' web address by switching the lights.
def rosie_light(): _light = request.form.get("light") if _light == "l1": l1.switch() return redirect(url_for("index"))
And because - for now - we want to have our web browsers make this POST request, we'll modify Flask's Jinja2 template for 'index.html' to have a new form and button.
<form action="/light" method="post"> <button class="button-mode" type="submit" name="light" value="l1">Light 1</button> </form>
This simply makes a new HTML button appear, which when pressed, sends a HTTP POST request from the browser to Flask running on Rosie. And because that request routes through to the rosie_light() function, and ultimately leads to l1.switch() method being called, it switches through the lights, on-demand.
And of course, somewhere in the code, we've instantiated our super-duper light as l1. GPIO pin 13 has the honours here to instruct the relay.
l1 = Light(13, True)
Incidentally, we do revisit this code in a later episode, to make a little more advanced.
One little gotcha. Whenever you now run rosie-web-lights.py or use Supervisor, don't forget to use python3, not python.
python3 rosie-web-lights.py
And stop / start rosie using Supervisor's supervisorctl command.
sudo supervisorctl stop rosie sudo supervisorctl start rosie...stops and starts the rosie application using Supervisor
Clearly, in futuristic dystopia, we don't want the lights to be controlled by Rosie's clumsy human operator. We want Rosie to control the lights herself, depending on the things that she observes in the world. But that's just stuff that we can do with some logic and code, right? For now, you have permission to feel pleased with yourself that you've hacked a head-torch. All in the name of law and order...
Now... where were we with hacking that Frozen wand..? | https://www.rosietheredrobot.com/2017/10/lights-in-shining-armour.html | CC-MAIN-2019-04 | refinedweb | 2,904 | 75.3 |
Pas2JS Version Changes
Contents
- 1 Releases
- 1.1 Next Version
- 1.2 Version 2.0.0
- 1.3 Version 2.0.0RC8
- 1.4 Version 2.0.0RC7
- 1.5 Version 2.0.0RC6
- 1.6 Version 2.0.0RC5
- 1.7 Version 2.0.0RC4
- 1.8 Version 2.0.0RC3
- 1.9 Version 2.0.0RC2
- 1.10 Version 2.0.0RC1
- 1.11 All changes of version 2.0.0
- 1.12 Version 1.4.34
- 1.13 Version 1.4.32
- 1.14 Version 1.4.30
- 1.15 Version 1.4.28
- 1.16 Version 1.4.26
- 1.17 Version 1.4.24
- 1.18 Version 1.4.22
- 1.19 Version 1.4.20
- 1.20 Version 1.4.18
- 1.21 Version 1.4.16
- 1.22 Version 1.4.14
- 1.23 Version 1.4.12
- 1.24 Version 1.4.10
- 1.25 Version 1.4.8
- 1.26 Version 1.4.6
- 1.27 Version 1.4.4
- 1.28 Version 1.4.2
- 1.29 Version 1.4.0
- 1.30 Version 1.4.0RC7
- 1.31 Version 1.4.0RC6
- 1.32 Version 1.4.0RC5
- 1.33 Version 1.4.0RC4
- 1.34 Version 1.4.0RC3
- 1.35 Version 1.4.0RC2
- 1.36 Version 1.4.0RC1
- 1.37 All changes of version 1.4.0
- 1.38 Version 1.2.0
- 1.39 Version 1.2.0RC1
- 1.40 Version 1.0.4
- 1.41 Version 1.0.3
- 1.42 Version 1.0.2
- 1.43 Version 1.0.1
- 1.44 Version 1.0.0
- 1.45 Version 1.0.0rc1
- 1.46 Version 0.9.32
- 1.47 Version 0.9.31
- 1.48 Version 0.9.30
- 1.49 Version 0.9.29
- 1.50 Version 0.9.28
- 1.51 Version 0.9.27
- 1.52 Version 0.9.26
- 1.53 Version 0.9.25
- 1.54 Version 0.9.24
- 1.55 Version 0.9.23
- 1.56 Version 0.9.22
- 1.57 Version 0.9.21
- 1.58 Version 0.9.20
- 1.59 Version 0.9.19
- 1.60 Version 0.9.18
- 1.61 Version 0.9.17
- 1.62 Version 0.9.16
- 1.63 Version 0.9.15
- 1.64 Version 0.9.14
- 1.65 Version 0.9.13
- 1.66 Version 0.9.12
- 1.67 Version 0.9.11
- 1.68 Version 0.9.10
- 1.69 Version 0.9.9
- 1.70 Version 0.9.8
- 1.71 Version 0.9.7
- 1.72 Version 0.9.6
- 1.73 Version 0.9.5
- 1.74 Version 0.9.4
- 1.75 Version 0.9.3
- 1.76 Version 0.9.2
- 1.77 Version 0.9.1
- 1.78 Version 0.9.0
- 1.79 Version 0.8.45
- 1.80 Version 0.8.44
- 1.81 Version 0.8.43
- 1.82 Version 0.8.42
- 1.83 Version 0.8.41
- 1.84 Version 0.8.40
- 1.85 Version 0.8.39
- 1.86 Version 0.8.38
- 1.87 Version 0.8.37
- 1.88 Version 0.8.36
- 1.89 Version 0.8.35
- 1.90 Version 0.8.34
- 1.91 Version 0.8.33
- 1.92 Version 0.8.32
- 1.93 Version 0.8.31
- 1.94 Version 0.8.30
- 1.95 Version 0.8.29
- 1.96 Version 0.8.28
- 1.97 Version 0.8.27
- 1.98 Version 0.8.26
- 1.99 Version 0.8.25
- 1.100 Version 0.8.24
- 1.101 Version 0.8.23
- 1.102 Version 0.8.22
- 1.103 Version 0.8.21
- 1.104 Version 0.8.20
- 1.105 Version 0.8.19
- 1.106 Version 0.8.18
- 1.107 Version 0.8.17
- 1.108 Version 0.8.16
- 1.109 Version 0.8.15
- 1.110 Version 0.8.14
- 1.111 Version 0.8.13
- 1.112 Version 0.8.12
- 1.113 Version 0.8.11
- 1.114 Version 0.8.10
- 1.115 Version 0.8.9
- 1.116 Version 0.8.8
- 1.117 Version 0.8.7
- 1.118 Version 0.8.6
- 1.119 Version 0.8.5
- 1.120 Version 0.8.4
- 1.121 Version 0.8.3
- 2 Trunk
- 3 Navigation
Releases
Next Version
- fixed freeing temporary class interface, if it is nil.
- removed obsolete TTypeInfoDynArray.DimCount
- fixed TTypeInfoStaticArray.Dims
- fixed obj as COMIntfType, when obj is nil': for FPC and Delphi compatibility nil returns nil and does not raise an exception.
- fixed checking statement after except-on
- fixed if then asm a;b end
- fixed ord(integer)
Version 2.0.0
11th Jan 2021
All changes of version 2.0.0
- fixed TDictionary with procedural type
- fixed TTypeInfoRecord.RecordType
Version 2.0.0RC8
31th Dec 2020
- fixed UTF-16 char literal #128..#255
- fixed using invalid UTF-16 but valid string #$DC00'b'
- fixed checking class method modifiers match class interface (as in IUnknown)
- fixed typecast specialized array to specialized type
- fixed implicit call of specialized method
- added separate hints 4501 field "x" not used and 4502 field "x" assigned but never used. Delphi/FPC do not have these hints, as they treat records as one memory block and can't omit fields. pas2js can omit fields.
- The param in await(param) must now be an async function, to avoid accidentally calling the wrong function or not a function at all.
- Allowing await(T,jsvalue), because jsvalue could be a promise.
- fixed typecast implicit function call passing to arg, e.g. aFunc(aType(obj.bFunc))
- fixed delayed init specialized class interface
Version 2.0.0RC7
13th Dec 2020
- fixed optimization shortrefglobals and enum value
- fixed filer storing unix line ending and writing precompiled code with platform line ending
- fixed unit without implementatiom
- fixed record member type
Version 2.0.0RC6
8th Dec 2020
- the binary snapshot now use same directories as "make all". E.g. bin\i386-win32 for the Windows 32bit executables.
- the binary snapshot now contains the makestub utility
- fixed filer, call type helper of unit, which unit implementation has not been parsed.
- fixed catching load file exceptions and turn into regular errors
- fixed generating typeinfo for classes with published members, but not referenced via typeinfo
Version 2.0.0RC5
4th Dec 2020
- fixed skipping non fully specialized types
- fixed filer, storing reference to await and debugger
- fixed filer, specialize signature of implementation of methods
- fixed filer, skipping generic reference to generic type
- fixed filer, reading inline specialize expression
- fixed filer, checking signatures needing indirect units of implementation
Version 2.0.0RC4
30th Nov 2020
- fixed await on as operator
- fixed await(ProcArgument)
- fixed hint Await needs a promise
- fixed calling async function with result type COM interface
- fixed checking 'await(T,callasyncfunc) type match
- fixed async procedure modifier not needed in implementation of a procedure
- added FormData js keyword
- fixed shortrefglobals optimization of new/free instance fields
- fixed crash on parser error in inline specialize expression, issue 38111
- fixed typeinfo path of inline specialize type
- fixed -OoShortRefGlobals
- fixed error when using generic type without parameters
- fixed shortrefglobals when unit initialization uses unit of otherwise empty implementation section
Version 2.0.0RC3
13th Nov 2020
- fixed typeinfo unicodestring and widechar
- fixed passing widechar to var argument char and unicodestring to string and vice versus.
- rtl: system.pas: removed obsolete UnicodeString=string and WideChar=char type alias. They are normal compiler types.
- fixed typecast integer to widechar
- fixed ord(widechar)
- added overload TryStrToInt64 with int64, TryStrToQWord with QWord, TryStrToUInt64 with UInt64
Version 2.0.0RC2
11th Nov 2020
- fixed shortrefglobals for minimal class interface, issue 38042
- fixed disable optimization using fpc syntax e.g. -OoNoShortRefGlobals, issue 3804
- fixed shortrefglobals for procedure without args, issue 38043
- -JRnone now skips resource directives
Version 2.0.0RC1
5th Nov 2020
All changes of version 2.0.0
- the binary snapshots now use same directories as "make all". E.g. bin\i386-win32 for the Windows 32bit executables.
- Generics
- Attributes:
- Incompatibility: $modeswitch ignoreattributes was removed
- base class System.TCustomAttribute
- $modeswitch prefixedattributes: enabled by default in $mode Delphi
- declare in front of any type, type member
- the Delphi compiler attributes like ref, weak, volatile, etc are not supported.
- query attributes of a type:
- use either typinfo function GetRTTIAttributes(typeinfo(SomeType).Attributes):
- or use RTTI unit r:=TRTTIContext, r.GetType(typeinfo(SomeType)).GetAttributes
- class constructors:
- for classes, records, class helpers, record helpers and type helpers.
- Called in initialization section
- Optimizer removes attributes if type is not used.
- VarArg.Free, e.g. procedure DoIt(var Arg: TObject); begin Arg.Free end; setting Arg to nil
- range checking for type helpers
- range checking for var/out arguments
- fixed low/high(nativeint) for 53 significand bits instead of only 52 explicit bits, increasing high to $1fffffffffffff = 9007199254740991
- float literal: removing unneeded 0 in front of E e.g. 1.20E1 as 1.2E1
- Overflow checks for integers -Co {$overflowchecks on} {$Q+} for integer operators +, -, *. Checks if result is outside nativeint and raises EIntOverflow.
- class abstract modifier
- type helper for classtype, same as FPC
- type helper for interfacetype, no constructors, same as FPC
- Dispatch messages:
- method modifier message integer and message string
- directive {$DispatchField fieldname} and {$DispatchStrField fieldname}
Insert these directives in front of your dispatch methods to let the compiler check all methods with message modifiers if they pass a record with the right field.
TMyComponent = class {$DispatchField Msg} procedure Dispatch(var aMessage); virtual; {$DispatchStrField MsgStr};
- added rtti utility functions GetInterfaceProp, SetInterfaceProp, GetMethodProp, SetMethodProp
- TStream with TBytes
- TBytesStream
- convert ord(const) to a const
- Resource strings:
- TJSFunction(@obj.methodname) is now converted to classtype.methodname
- Constructors of external classes are now supported in four ways:
- constructor New is translated to new ExtClass(params). Note the missing JS path.
- constructor New; external name 'GlobalFunc' is translated to new GlobalFunc(). Note the missing JS path.
- constructor SomeName; external name '{}' is translated to {} - a basic, empty JS object
- Otherwise it is translated to new ExtClass.FuncName(params)
- You can now specify a type for the procedure modifier varargs: varargs of SomeType . For example
procedure SumWords(); varargs of Word; ... SumWords(1,2,3); // this works SumWords(1,98765); // this gives a range check error
- Srcmap for pju files
- allowing using a unit twice, with different names, e.g. uses ns.unit1, unit1; or uses foo in 'unit1.pas', unit1;
- option -Sj to allow/disallow typed const to be writable
- option -im to show available modeswitches
- option -M<modeswitch> to enable or disable a modeswitch, see option -im
- typecasting unrelated classes now gives only a warning "Class types are not related" instead of an error, Reason: FPC/Delphi compatibility
- mode ObjFPC now checks procedural types in procedure arguments by signature, reason: FPC compatibility. Note: FPC does that too in $mode delphi, pas2js only in mode ObjFPC.
- type helper for bytebool, wordbool, longbool
- ArrayOfChar:=String and pass string to ArrayOfChar
- safecall calling convention and rtl catch uncaught exceptions.
- Async procedure modifier and await functions:
- function await(AsyncFunctionOfResultT): T; // implicit promise
- function await(aType; p: TJSPromise): aType; // explicit promise requires the resolved type
- function await(aType; v: jsvalue): aType; // explicit optional promise requires the resolved type
- Descending a Pascal class from a JS Function
- The makestub utility converts a Pascal import unit for importing Pascal classes to a unit that is compilable by Delphi
- fcl-json JSON interface from FPC.
- New units for Javascript libraries:
- libjitsimeet interface to jitsi video conferencing.
- libopentok interface to opentok video conferencing.
- libkurento interface to kurento video conferencing.
- libfullcalendar(4/5) interface to fullcalendar.io JS library
- libdatatables interface to datatables.net JS library
- pushjs interface to browser Push Notifications
- libbootstrap interface to bootstrap classes.
- gmaps interface to google maps interface.
- added separate hints 4501 field "x" not used and 4502 field "x" assigned but never used. Delphi/FPC do not have these hints, as they treat records as one memory block and can't omit fields. pas2js can omit fields.
- Optimizations:
- -O2 : Level 2 optimizations (Level 1 + not debugger friendly)
- -OoShortRefGlobals[-]: Insert a JS local var for each module, type and static function. Default enabled in -O2.
2.0.0 Incompatibilities
Signature for event handlers TEventListenerEvent and TJSEvent
The signature for event handlers has been corrected. The class TEventListenerEvent is now an alias for TJSEvent
- That means that the 2 event handler types
TJSEventHandler = reference to function(Event: TEventListenerEvent): boolean; TJSRawEventHandler = reference to Procedure(Event: TJSEvent);
- are now equivalent.
TJSEvent type definition
The TJSEvent type definition has been corrected
- The currentTarget and Target properties of TJSEvent are now of type TJSEventTarget, as they are in the official specs:
property currentTarget : TJSEventTarget Read FCurrentTarget; property target : TJSEventTarget Read FTarget;
- For convenience, a targetElement and CurrentTargetElement property have been added which are of type TJSElement:
property currentTargetElement : TJSElement; property targetElement : TJSElement;
modeswitch ignoreattributes was removed
The workaround {$modeswitch ignoreattributes} was removed. Attributes are now implemented.
Version 1.4.34
28th Oct 2020
- fixed passing in mode delphi a proc address to a proc type argument.
- fixed searching pju file, when uses-in-file missing
- fixed a div b for negative results
- fixed aCurrency/bCurrency for negative results
Version 1.4.32
15th Oct 2020
- fixed crash on class function
- fixed array shrink using SetLength
- fixed try except on ExternalClass do ; end;
- fixed dynamic array function a:=concat(b); // marking b as referenced
- fixed dynamic array function c:=concat(a,b);
- fixed $ancestor of all root classes is null instead of undefined
- fixed rtl.spaceLeft return value
Version 1.4.30
8th July 2020
- fixed assign record with field of dynamic array
- fixed SysUtils.AnsiSameText comparing strings with umlauts.
Version 1.4.28
3rd Jul 2020
- fixed system.inc()
- fixed namespace search order
- Reason: Delphi/FPC compatibility.
- Old behaviour: search default namespace (aka prepend program namespace), prepend command line namespaces, no namespace (i.e. as written in uses section)
- New behaviour: search no namespace (i.e. as written in uses section), prepend command line namespaces, prepend default namespace (aka program namespace)
- For example program that uses "classes" and units classes.pas and system.classes.pas are in unit search path.
- fixed try exit(value) finally read Result end
Version 1.4.26
6th Jun 2020
- fixed RTTI of record/class field with shared anonymous array, e.g. type t = record a,b:array of byte; end;
Version 1.4.24
11th May 2020
- fixed assign array
Version 1.4.22
10th May 2020
- fixed allowing member with same name as an ancestor member in $mode delphi
- fixed allow static directive repetition in method implementation
- fixed type helper for NativeInt and NativeUInt
- fixed type helper Self in nested procedure
- fixed (i*i).helperfunc
- fixed SetLength(array,..) using resize instead of clone, when not shared. Assign marks an array with a hidden property $pas2jsrefcnt.
Version 1.4.20
11th April 2020
- fixed stack overflow on long procedures
- fixed class helper in with-do
Version 1.4.18
15th Dec 2019
- access modifier constref: works as const, gives a warning for non records, arrays
- omit not used resourcestrings
- fixed sourcemap for Firefox
Version 1.4.16
15th Oct 2019
- fixed helper for type alias type
- fixed selecting last declared helper
- replaced rtl.setArrayLength with faster non recursive version
- fixed external static class method
- fixed check for helper class method for external class must be static
- fixed marking implicit call in property parameter
Version 1.4.14
30th Aug 2019
- source map: when using -Jmabsolute -Jmsourceroot=file:// prepend the absolute source files with file://. Needed by Firefox.
- fixed longword bitwise operations not, and, or, xor, shl, shr for numbers > $7fffffff
- fixed creating relative paths without shared based directory, e.g. in source maps C:\foo\project1.js.map C:\bar\project1.pas
Version 1.4.12
28th Aug 2019
- fixed get method reference of Self inside anonymous method without self
- fixed typecast nil to class, interface, dynamic array
- fixed endless loop on type TArr = array of TArr
- no warning "function result not set" for fieldless record
- fixed check for duplicate unit, when names differ
- fixed ComInterfaceInstance is/as InterfaceType to use QueryInterface
- fixed passing dynamic array to open array var parameter
Version 1.4.10
10th Jul 2019
- added separate error message duplicate published method
- fixed allowing reintroduce published method
- fixed high(dynarrayvar with expr)
- fixed class var a:t; b:t;
- fixed type helper in other unit
Version 1.4.8
24th June 2019
- fixed var a: somearray = nil
- fixed fixed assignment inside anonymous proc inside for-loop
- fixed ArcTan definition (bug ID 35655)
- setlength(arr) now always clone for FPC/Delphi compatibility. Formerly it merely resized the array.
Version 1.4.6
20th Apr 2019
- fixed advanced records
- fixed linux rtl.js
Version 1.4.4
19th Apr 2019
- fixed duplicate identifier when redefining a procedure.
- fixed escaping string literals in asm blocks
Version 1.4.2
11th Apr 2019
- fixed optimization of NewInstance function
- fixed filer class helper
- fixed passing TExt.new as parameter
- fixed writing workingdirectory
- fixed advanced record constructor
- handling environment options PAS2JS_OPTS
- fixed nodejs GetEnvironmentVariable returning empty string for non existing variables
Version 1.4.0
24th Mar 2019
- fixed supporting older node.js (<7.0.0) using Math.pow instead of newer exponential operator **.
Version 1.4.0RC7
16th Mar 2019
- fixed accessing Self in anonymous function
- fixed UntypedArg:=recordvar and RecordType(UntypedArg)
- an external method of a helper is treated like an external method of the helped type
- updated examples
- fixed hint method hides identifier with same signature
- fixed hint argument not used, with array argument and only writing an element
- fixed hint argument not used, with array argument passed as argument
Version 1.4.0RC6
8th Mar 2019
- fixed passing class var to var argument
- fixed reading precompiled units by default
Version 1.4.0RC5
6th Mar 2019
- fixed overload var arg and type alias
- added overload TryStrToFloat with type extended
- nativeint shr int
- nativeint shl int
- no hint when hiding private method
- fixed passing multiple -vm parameters
- fixed include file search in module directoy
- allow typecast external class to unrelated external class in $mode delphi, e.g. TJSEventTarget(aJSWindow). Normally you need TJSEventTarget(TJSObject(aJSWindow)).
Version 1.4.0RC4
3rd Mar 2019
- fixed {$warn identifier error}
- fixed and/or/xor with nativeint
- warn on nativeint shl/shr int using only 32bit
- fixed type helper call as arg
- fixed (f*f).helpercall
- fixed info message macro name set to "value"
- make all now creates a default bin/targetcpu-targetos/pas2js.cfg, so that pas2js.exe works out-of-the box.
Version 1.4.0RC3
27th Feb 2019
- renamed $modeswitch multiplescopehelpers to multihelpers, same as FPC
- fixed TAliasOfEnumType.EnumValue
- fixed emitting hints for not used units
- fixed SetBufListSize
Version 1.4.0RC2
18th Feb 2019
- fixed typecast jsvalue(anobject/interface), not doing getObject,
- fixed obj.Free set to nil if already nil
- added unit websvg.pas providing API to SVG elements
- fixed getdelimitedtext, quoting was wrong
- fixed array-of-const references in precompiled units
- Added some missing routines in strutils (containstext, containsstr)
Version 1.4.0RC1
16th Feb 2019
- Highlights:
- class helpers
- record helpers
- type helpers
- advanced records
- array of const
- added locate to JSONdataset, as well as lookup and support for lookup fields.
- Added Indexes (sorting) to JSONDataset.
- Incompatibilities:
- pas2js now searches units first in the folder of the current module as Delphi does.
- JSArguments declaration was changed from an array of jsvalue to TJSFunctionArguments.
All changes of version 1.4.0
- some user types like enumeration, set, range and array types. It cannot extend interfaces or helpers.
- Type helpers are available.
- built-in function concat (string1,string2,...)
- local types (declared inside functions) are now created in the global scope
- added locate to JSONdataset, as well as lookup and support for lookup fields.
- Added Indexes (sorting) to JSONDataset.
- Added unit fpexprpars.pas, an expression parser unit (needed for dataset filtering...)
- omit unnecessary brackets on associative operations (a||b)||(c||d), (a&&b)&&(c&&d), (a|b)|c, (a&b)&c, (a^b)^c, (a+b)+c, (a-b)-c, (a*b)*c
- records are now created as Object, instead of JS function
- records now have hidden (not enumerable) functions $new, $assign, $clone, $eq
- passing records to var argument now passes the record directly instead of creating a temporary setter
- Assigning a record, e.g. aRecord:=value, now copies the values, while keeping the JS object. This makes pointer of record Delphi/FPC compatible.
- Advanced records: enabled in $mode delphi, disabled im $mode objfpc, enable with {$modeswitch AdvancedRecords}
- visibility private, strict private, public, default is public
- methods, class methods (must be static like in FPC/Delphi), constructors
- class vars
- const
- property, class property, array property, default array property
- nested types
- RTTI
- Records can now have external fields with '[2]', '["a b"]'
- In $mode objfpc forward class-of and pointer declarations can now refer to types even if there are other const/var/resourcestring sections in between. Same a FPC. For example:
type TClassOfBird = class of TBird; const k = 1; type TBird = class end;
- lo(), hi() in $mode delphi returning the lo/hi byte, in $mode objfpc returning the lo/hi byte|word|longword.
- char range with non ascii literals: 'Б'..'Я'
- typecast char to word and other integers
- added option -Jmabsolute to store absolute filenames in sourcemaps
- JSArguments declaration was changed from an array of jsvalue to TJSFunctionArguments.
- fixed expr[][] with default properties
- fixed assigning class vars
- pas2js now searches units first in the folder of the current module as Delphi does.
- fixed case-of with non ascii literals
- implemented ProcVar:=StaticClassMethod
- implemented ProcVar:=ClassMethod inside static class method
- class property getter/setter can now be static or non static.
- array of const:
- Works the same: vtInteger, vtBoolean, vtPointer, vtObject, vtClass, vtWideChar, vtInterface, vtUnicodeString
- longword is converted to vtNativeInt instead of mangling to vtInteger
-
- fixed o.ProcVar() when ProcVar is typeless property
- fixed const evaluation float - currency
- fixed reading #$00xx as widechar, bug 34923
- fixed relative paths in srcmap in Windows
- nicer error message on invalid set element type
Version 1.2.0
- 23th Dec 2018
- SVN release tag is
- added dataabstract: support for Remobjects Data Abstract: The TDAConnection and TDADataset classes
- set rtl.js version to 10200
- fixed parsing comment in $IFDEF, $IFNDEF, issue 34711
- fixed searching unit
Version 1.2.0RC1
- 16th Dec 2018
- SVN release tag is
- Anonymous Functions:
type TRefProc = reference to procedure; TProc = procedure; procedure DoIt(arg: TRefProc); var ref: TRefProc; proc: TProc; begin ref:=procedure begin end; // assign to "reference of procedure" type ref:=procedure // note the omitted semicolon var i: integer; // var, types, const, local procedures begin end; DoIt(procedure begin end); // pass as argument refproc:=procedure assembler asm // embed JavaScript console.log("foo"); end; // Note that typecasting to non "reference to" does not make a difference // because in JS all functions are closures: proc:=TProc(procedure begin end); end;
- added variable rtl.version, which corresponds to the compiler version Major*10000+Minor*100+Release
- added option -JoCheckVersion:
- -JoCheckVersion- : do not add rtl version check, default.
- -JoCheckVersion=main : insert rtl.checkVersion() into main.
- -JoCheckVersion=system : insert rtl.checkVersion() into system unit.
- -JoCheckVersion=unit : insert rtl.checkVersion() into every unit.
- moved classtopas function to a class2pas unit, improved the interface so it uses a stringlist. Adapted the demo.
- Fix System.Int() so it also works on IE (where Math.trunc is missing).
- allow typecasting string(apointer) and pointer(astring)
- asm-block now skips Pascal comments //... and Pascal string literals with single quotes. It no longer stops at end in such comments and string literals.
- Fix FormatFloat() rounding logic (actually FloatToDecimal)
- Fix stringofchar for count<=0
- Fix quotestring and add quotedstr
- implemented special includes like {$i %date%}:
- string literal, e.g. '1.0.2'
- If param is none of the above it will use the environment variable. Keep in mind that depending on the platform the name may be case sensitive. If there is no such variable an empty string is inserted.
- implemented pred(char), succ(char)
- allow typecasting TypedPointer(UntypedPointer)
- allow assign UntypedPointer:=TypedPointer
- skip double quotes in asm-blocks, e.g. s = "end"+"'";
- added {$modeswitch OmitRTTI}: treat class section 'published' as 'public' and typeinfo() does not work on symbols declared with this switch. This allows to easily disable generating RTTI and allows the optimizer to omit unused published properties.
- added option -Jpcmd<command>: Run postprocessor. For each generated js execute command passing the js as stdin and read the new js from stdout. This option can be added multiple times to call several postprocessors in succession. Quote the <command> to add options for the postprocessor. For an example see minifier.
- Added built-in procedure Debugger;, which is converted to the JavaScript statement debugger;. If a debugger is running it will break on this line just like a break point.
- Changed operator precedence level of is to same as and, or, xor. Same as fpc/delphi.
- fixed assert to raise on false, bug 34643
- built-in procedure val(const string; out enum; out int)
- added option -JoRTL-<x>=<y> to change the name of a autogenerated identifier. See the list of available identifiers with -iJ.
Version 1.0.4
- 14th Nov 2018
- SVN release tag is
- fixed calling destructor after exception in constructor
- fixed initializing static array of record
- fixed parsing if expr then raise else
- fixed local record and enum types
- fixed for e in set do
- fixed for-in of shared sets
- fixed inc(classvar)
- fixed assigning class var of descendant classes
- fixed error position on include file not found
- fixed loading include file from cache
- fixed range check of o.aString[index] and o.aArray[index]
- fixed Result:=inherited;
- fixed escaping invalid UTF-16 in string literals
- fixed not generating octal literals in ECMAScript5, it bites strict mode
- fixed IsNaN on ECMAScript6
- fixed error on method in record
- fixed name clash published property and external
- fixed str(aCurrency)
- catch ECompilerTerminate while parsing params
- sLineBreak and LineEnding are now var under platform NodeJS
Version 1.0.3
- 28th Oct 2018
- SVN release tag is
- fixed char(#10)
- fixed: allow array property accessor argument mismatch const/default for simple types, e.g.:
function GetItems(const i: integer): byte; property Items[i: integer]: byte read GetItems;
- fixed high(intvar)
- fixed WPO when using record constants
- fixed include(FuncResultSet,enum)
- fixed if then <empty> else <something>;
- fixed p^.x:=
- fixed acurrency:=aninteger to become acurrency:=aninteger*10000
- fixed integer(acurrency) to become Math.floor(acurrency/10000)
- fixed calling $final, clearing references on destroy
- fixed not calling BeforeDestruction on exception in constructor
- fixed $class be a property of the class, not the object
- fixed local var modifier absolute in method
- fixed using external const in const expression, e.g. const tau = 2*pi;
- fixed selecting procedure overload, preferring lossy int over int to float
- fixed calling Free inside method
- fixed System.Int() so it also works on IE (where Math.trunc is missing).
- fixed FormatFloat() rounding logic (actually FloatToDecimal)
- fixed stringofchar for count<=0
- fixed quotestring and add quotedstr
Version 1.0.2
- 26 Sep 2018
- SVN release tag is
- fixed multiple class interface maps
Version 1.0.1
- 19 Sep 2018
- SVN release tag is
- fixed generating srcmap for precompiled javascript
Version 1.0.0
- 9 Aug 2018
- SVN release tag is
- SVN fixes branch is
- fixed override method of class interface
- fixed crash on checking body element of empty proc
- use default source filename in pcu/pju files
Version 1.0.0rc1
- 24 Jul 2018
- fixed TObject.Create()
- -vd shows stacktraces
Version 0.9.32
- 17 Jul 2018
- fixed memory leaks and double frees
Version 0.9.31
- 10 Jul 2018
- fixed aIntSet:=[0]
- fixed crash on List.Items.Dummy
- fixed some mem leaks
- fixed -MDelphi + $mode objfpc + overloads withouts overload keyword
- TGUIDString is now type string
- RTL: added websockets
Version 0.9.30
- 4 Jul 2018
- fixed calling COM interface _Release function for expressions.
- fixed catching exception in pju variant of pas2js
- split reserved words into two categories: the compiler now checks global JS identifiers like "Date" only for identifiers without path. That means a local variable Date will be renamed, a property Date will not, keeping the RTTI name of properties. Identifiers like apply are still renamed.
- fixed property RTTI for alias type in other unit
- fixed default value of integer variables, using 0 even if it is outside range. Reason: Delphi/FPC compatibility.
Version 0.9.29
- 29 Jun 2018
- fixed pcu reading alias type
- fixed analyzer: element needing typeinfo marks indirect elements as used normally
- hint for text after final "end.", disable with $warn GARBAGE off
- $warn BOUNDS_ERROR off: disable range check warnings at compile time
- $warn MESSAGE_DIRECTIVE off: disable $message notes
Version 0.9.28
- 27 Jun 2018
- fixed static array of char = stringlit+stringlit
- fixed libpas2js disk full error
- $warn directive: {$warn identifier on|off|default|error}, identifier can be a message number as shown with -vq or one of the following. Note, that some hints like "Parameter %s not used" are currently using the enable state at the end of the module, not the state at the hint source position.
-
Version 0.9.27
- 26 Jun 2018
- mode delphi: fixed passing static array to open array
- allow assigning aTypeInfo:=pointer, needed by units with and without using unit typinfo
Version 0.9.26
- 25 Jun 2018
- typecast function address to JS function, e.g. TJSFunction(@IntToStr)
- typecast function reference to JS function, e.g. TJSFunction(OnClick)
- typecast method address to JS function, e.g. TJSFunction(@List.Sort). Note that a method address creates a function wrapper to bind the Self argument.
- changed some types to type alias: TDateTime, TDate, TTime, Single, Real, Comp, UnicodeString, WideString. This only effects typinfo and some compiler error messages. Reason: Delphi/FPC compatibility.
- In mode delphi dynamic array initializations must now use square brackets instead of round brackets. For example var a: array of integer = [1,2];. Reason: Delphi compatibility.
- Assignation using constant array. For instance Arr:=[1,2,3], where Arr is a dynamic array.
- + operator for arrays: This concatenation operator is available using the new modeswitch arrayoperators, which is enabled by default in mode delphi.
- unit webgl updated
- unit webaudio added
- unit webbluetooth added
- db unit: ftDataset field type added (not supported)
- JSONDataset unit: TField.OldValue now works for TJSONDataset
- webidl2pas tool added. A command line tool to create Pascal units from idl specs.
- allow external record fields.
- hint 5024 'Parameter "%s" not used' was split into two:
- 4501 for virtual/override methods
- 5024 for others
Version 0.9.25
- 7 Jun 2018
- TComponent now supports IInterface
- -o is now always relative to working directory, even if -FU or -FE is given. Reason: FPC compatibility
- fixed typeinfo(typeintegerrange)
- fixed using interface ancestor methods
- fixed 'make' building with fpc 3.0.4
Version 0.9.24
- 2 Jun 2018
- fixed precompiled js formatting to same options as compiled js
- fixed unit analyzer private method used by protected property
- fixed class-of RTTI
- fixed precompiled resolve pending scopes before pending units
Version 0.9.23
- 28 May 2018
- added webgl demos from Ryan Joseph
- for value in jsarray do - where jsarray is any external class with a matching length and default property. This enumerates similar to other arrays the values, not the index.
- allow typecast array to TJSObject
- allow typecast TJSObject to array
- Unicode character constants outside of BMP, e.g. #$10437
- allow {$H+}, error on {$H-}
- added intrinsic procedure WriteStr(out s: string; params...), which works similar to str(param,s), except it can take any amount of parameters, which are concatenated.
- added option -Sm to enable macro replacements
Version 0.9.22
- 17 May 2018
- Fixed $00ff00
Version 0.9.21
- 16 May 2018
- added option -FE: set the main output path, used for the main .js file, if there is no -o option or the -o option has no folder.
- fixed WPO typeinfo of inherited property
- for easier FPC integration the following message IDs were changed:
- nVirtualMethodXHasLowerVisibility = 3250; // was 3050
- nConstructingClassXWithAbstractMethodY = 4046; // was 3080
- nNoMatchingImplForIntfMethodXFound = 5042; // was 3088
- nSymbolXIsDeprecated = 5043; // was 3062
- nSymbolXBelongsToALibrary = 5065; // was 3061
- nSymbolXIsDeprecatedY = 5066; // 3063
- nSymbolXIsNotPortable = 5076; // was 3058
- nSymbolXIsNotImplemented = 5078; // was 3060
- nSymbolXIsExperimental = 5079; // was 3059
Version 0.9.20
- 11 May 2018
- fixed passing typecasted alias type to var parameter
- forbid typecast rectordtype to other recordtype
- remove leading zeroes in number literals
- added namespace option -FN<x>, marked -NS as obsolete. Reason: fpc compatibility.
- added option -vz : write messages to stderr, -o. still uses stdout.
- added option -ic : Write list of supported JS processors usable by -P<x>
- added option -io : Write list of supported optimizations usable by -Oo<x>
- added option -it : Write list of supported targets usable by -T<x>
- added option -SIcom, -SIcorba interface style
- added option -vv : Write pas2jsdebug.log with lots of debugging info
- fixed option -va including option -vt
- fixed combination of -Jc -o.
- option -vt now writes used unit scopes
- external class fields with brackets. e.g. X: nativeint external name '[0]'
- autogenerated interface GUIDs now consider the unitname
Version 0.9.19
- 2 May 2018
- type alias type, e.g. type TCaption = type string;
- record const, e.g. const p: TPoint = (x:1; y:2);
- {$WriteableConst on|off}: treat typed constants as readonly, e.g. const i:byte=3;... i:=4; creates a compile time error.
- forbid assignment of for-loop variable
- nested classes
- property specifier nodefault
- default(type) returning the initial value of the type, e.g. default(recordtype).
- external typed const: e.g. const NaN: Double; external name 'NaN';
- case string of support for ranges
- fixed typecast shortint(integer)
Version 0.9.18
- 26 Apr 2018
- Fixed rcArrR in rtl.js
Version 0.9.17
- 25 Apr 2018
- Fix recno calculation for TJSONDataset
- Fix initializing next buffers in TDataset.
- Implemented Currency as double, values are multiplied by 10000 and truncated, so a 2.7 is stored as 27000.
- Implemented pointer of record. It's simply a reference.
- p:=@r translates to p=r
- p^.x becomes p.x
- intrinsics new(PointerOfRecord), dispose(PointerOfRecord). dispose(p) sets p to null if possible.
- enumerator for jsvalue: e.g. var v: jsvalue; key: string; for key in jsvalue do translates to for (key in jsvalue){}
- enumerator for external class: e.g. var o: TJSObject; key: string; for key in o do translates to for (key in o){}
- range checking $R+
- compile time: warnings become errors
- run time: int:=, int+=, enum:=, enum+=, intrange:=, intrange+=, enumrange:=, enumrange+=, char:=, charrange:=
- run time: parameters: int, enum, intrange, enumrange, char, charrange
- run time: array[index], string[index]
- type cast integer to integer, e.g. byte(aLongInt)
- with range checking enabled: error if outside range
- without range checking: emulates the FPC/Delphi behaviour: e.g. byte(value) translates to value & 0xff, shortint(value) translates to value & 0xff <<24 >>24.
- case-of statement: error on duplicate values
- fixed error on int:=double
Version 0.9.16
- 21 Apr 2018
- mode delphi: allow "ObjVar is IntfType" and "ObjVar as IntfType" with unrelated types.
- TVirtualInterface - create an implementation at runtime. rtl unit rtti.pas
- typecast a class type to JS Object, e.g. TJSObject(TObject)
- typecast an interface type to JS Object, e.g. TJSObject(IUnknown)
- typecast a record type to JS Object, e.g. TJSObject(TPoint)
- not jsvalue is converted to !jsvalue
- "=" operator for records with static array fields
- changed TGuid to record
- TGUID record
- GuidVar:='{guid}', StringVar:=GuidVar, GuidVar:=IntfTypeOrVar, GuidVar=IntfTypeOrVar, GuidVar=string
- pass IntfTypeOrVar to GuidVar parameter
- added new type TGuidString to system unit
- GuidString:=IntfTypeOrVar, GuidString=IntfTypeOrVar
- pass IntfTypeOrVar to GuidString parameter
- added option -JoUseStrict, to enable or disable adding "use strict"
Version 0.9.15
- 8 Apr 2018
- fixed crash when ancestor implements more interfaces than current class.
Version 0.9.14
- 8 Apr 2018
- fixed duplicates in rtl/strutils.pas
- fixed reference counts on reading element lists
- implemented using function result variable in for-loop. e.g. for Result:=..., for Result in ...
- fixed for string in arrayofstring do
- fixed $scopedenums with anonymous enumtype. e.g. type TSet = set of (A,B);
- implemented class interfaces:
-
- GUIDs are simple string literals, TGUID = string.
- An interface without a GUID gets one autogenerated from its name and method names.
- - mode delphi: types must be related, objfpc: can be unrelated, nil if not found, COM: uses _AddRef
- typecast:
- IntfType(IntfVar) - must be related
- ClassType(IntfVar) - can be unrelated, nil if invalid
- IntfType(ObjVar) - mode delphi: must be related, objfpc: can be unrelated, nil if not found, COM: if ObjVar has delegate uses _AddRef
- TJSObject(intfvar)
- Assign operator:
- IntfVar:=nil
- IntfVar:=IntfVar2 - IntfVar2 must be same type or a descendant
- IntfVar:=ObjVar - nil if unsupported
- jsvalue:=IntfVar
- Assigned(IntfVar)
- RTTI
- $modeswitch ignoreinterfaces was removed
- Not supported: array of interface, interface as record member
Version 0.9.13
- 21 Mar 2018
- fixed keeping methods AfterConstruction, BeforeDestruction
- fixed modeswitch ignoreinterfaces
Version 0.9.12
- 19 Mar 2018
- fixed parsing procedure p(var a; b: t)
- fixed checking duplicate implementation of unit interface procedure
Version 0.9.11
- 16 Mar 2018
- fixed loading files encoded in non UTF-8, e.g. UTF-8 with BOM. This was a regression.
Version 0.9.10
- 13 Mar 2018
- fixed renaming overloads of unit interface at end of interface, not at end of module. Needed for unit cycles.
Version 0.9.9
- 13 Mar 2018
- Fixed libpas2js to use WorkingDir parameter instead of GetCurrentDir
- Fixed static array clone function.
Version 0.9.8
- 9 Mar 2018
- fixed optimizer keep overrides
Version 0.9.7
- 7 Mar 2018
- fixed pass local variable v as argument to a var parameter.
Version 0.9.6
- 6 Mar 2018
- static arrays are now cloned on assignment or when passed as argument to a function (no const, var, out)
- Fixed array[enum..enum] of
- pas2jslib: fixed checks of directoryexists to use cache
- uses with'.
Version 0.9.5
- 12 Feb 2018
- Error on duplicate forward class
- Error on method class in other unit
- Fixed index property override
Version 0.9.4
- 8 Feb 2018
- Removed debug writeln, fixing Disk Full errors in libpas2js.
- Nicer error messages on illegal qualifier.
Version 0.9.3
- 4 Feb 2018
- Fixed number literals outside int64.
- Shorten float numbers, e.g. 1.00000E+001 to 10
- unexpected exception now sets ExitCode to 1
Version 0.9.2
- 4 Feb 2018
- Fixed -constant, when constant is a negative number
Version 0.9.1
- 3 Feb 2018
- Fixed class const evaluating expression.
Version 0.9.0
- 31 Jan 2018
- Fixed srcmap header. It must be )]}' to work in Firefox. Added option -JmXSSIHeader to exclude or include the XSSI protection header.
- Ignore procedure modifier "inline"
- Char(int)
- search units and include files case insensitive by default. Enable FPC like search with parameter -JoSearchLikeFPC.
- Const in external classes:
- const c: type = value, const c = value are translated to the value.
- const c: type, class const c: type are treated like readonly variables.
Version 0.8.45
- 23 Jan 2018
- is-operator: jsvalue is class-type, jsvalue is class-of-type
- assertions: -Sa, $C+|-, $Assertions on|off, Assert(boolean), Assert(boolean,string)
- object checks: -CR, $ObjectChecks on|off, check method calls, check object type casts
- some bugfixes for alias types
- multi dimensional static array const, e.g. array[1..2,3..4] of byte = ((5,6),(7,8))
- fixed overloads when skipping class interface
- fixed s[i]:= when s is a var parameter
Version 0.8.44
- 15 Jan 2018
- State of directives $Hints|Notes|Warnings on|off at end of procedure is used for analyzer hints, e.g. "local variable x not used".
- Fixed re-reading directories after Reset.
Version 0.8.43
- 4 Jan 2018
- Fixed -Fi include path
- Read directories instead of checking every single file. Added hooks for ReadDir to libpas2js.
Version 0.8.42
- 25 Dec 2017
- var absolute modifier for local variables
- $scopedenums
- $hint, $note, $warn, $error, $fatal, $message text
- $message hint|note|warn|error|fatal text
- $hints, $notes, $warnings on|off
Version 0.8.41
- 25 Dec 2017
- Enumerators:
- ordinal types: char, boolean, byte, ..., longword, enums, sets, static array, custom range
- const set
- variables: set, string, array
- class GetEnumerator
- It does not support operator enumerator, IEnumerator, member modifier enumerator.
Version 0.8.40
- File read callback for pas2jslib
Version 0.8.39
- 14 Dec 2017
- fixed circular unit dependencies
Version 0.8.38
- 12 Dec 2017
- support for * and ? in search paths
- fixed converting a typecast to an alias proc type
- fixed inherited-identifier-as-expr
- emit warning method-hides-method-in-base-type only for virtual methods
- reduced function hides identifier from level hint to info
- fixed unit contnrs to always use mode objfpc.
Version 0.8.37
- 5 Dec 2017
- Bugfixed a combination of overload/override
Version 0.8.36
- 5 Dec 2017
- fixed missing brackets in binary expression and left side has a call (a-f(b)) / (c-d)
Version 0.8.35
- 20 Nov 2017
- fixed a bug in the overload code
Version 0.8.34
- 19 Nov 2017
- fixed skipping attributes behind procedure declarations.
- Procedures/methods now properly hides procs with same name.
- In mode delphi overloads now always require the 'overload' modifier.
- In mode objfpc the modifier is required when using different scopes.
- hints for hiding identifiers of other units.
- implemented system.built-in-identifier.
Version 0.8.33
- 14 Nov 2017
- srcmaps with included sources now ignores untranslatable local paths and simply uses the full local path.
- custom enum ranges, e.g. TBlobType = ftBlob..ftBla
- custom integer ranges, e.g. TSome = 1..5
- custom char ranges
- set of custom enum/integer/char ranges
- the conversion of the for-to-do loop has changed. If the loop is never executed, the loop variable is not touched. And the start expression is now executed before the end expression.
Version 0.8.32
- 8 Nov 2017
- some bug fixes for warnings
Version 0.8.31
- 29 Oct 2017
- bugfix for implicit function calls of parameters of some built in functions.
Version 0.8.30
- 19 Oct 2017
- nicer "can't find unit" position
- fixed a crash parsing uses clause
Version 0.8.29
- 16 Oct 2017
- bugfixes
- it now supports directive $M alias $TypeInfo
Version 0.8.28
- fixed passing static array
Version 0.8.27
- 4 Oct 2017
- implemented resourcestrings
- implemented logical xor
- fixed class-of-typealias
- fixed property index modifier expression
Version 0.8.26
- 3 Oct 2017
- fixed RTTI for static arrays
- implemented property modifier index
- implemented FuncName:=
Version 0.8.25
- 1 Oct 2017
- bugfixes
- a new modeswitch ignoreattributes to ignore attributes.
Version 0.8.24
- 28 Sep 2017
- implemented multi dimensional SetLength
- fixed keeping old values when using SetLength
- fixed method override of override
Version 0.8.23
- 27 Sep 2017
- property default value for sets
- custom integer ranges, like TValueRelationship
- typecast enums to integer type (same as ord function)
- new modeswitch ignoreinterfaces to parse class interfaces, but neither resolve nor convert them. Using them will cause an error.
Version 0.8.22
- 24 Sep 2017
- fixed loading dotted units
- implemented property stored and default modifiers
Version 0.8.21
- 21 Sep 2017
- fixed aString[index]:=
- fixed analyzer to mark default values of arguments
- many improvements for sourcemaps making step-over/into nicer in Chrome.
- new tool fpc/packages/fcl-js/examples/srcmapdump to dump the produced sourcemap.
- unicodestring and widechar are now declared by the compiler instead of system.pas
Version 0.8.20
- 14 Sep 2017
- Static array const are now implemented. For example:
- array['a'..'d'] of integer = (1,2,3,4);
- array[1..3] of char = 'pas';
Version 0.8.19
- 12 Sep 2017
- several bug fixes
- started static arrays:
- array[2..6] of char
- array['a'..'z'] of char
- array[boolean] of longint
- array[byte] of string
- array[enum] of longint
- array[char] of boolean // Note that char is widechar!
- low(), high()
Version 0.8.18
- 6 Sep 2017
- Anonymous arrays in record members are now supported:
TFloatRec = Record ... Digits: Array Of Char; End;
Version 0.8.17
- 3 Sep 2017
- checks for semicolons between statements
- fixed proc type of procedure in Delphi mode
- implemented @@ operator for proc types in Delphi mode.
- compile time evaluation, range and overflow checking for boolean, base integer types, enums, sets, custom integer ranges, char, widechar, string, single and double.
Version 0.8.16
- 28 Jul 2017
- bugfix release.
Version 0.8.15
- 8 Jul 2017
- compiler can now generate source maps when passing option -Jm
Version 0.8.14
- 17 May 2017
- now supports TObject.Free.
In Delphi/FPC obj.Free works even if obj is nil. In JavaScript this would crash. And to free memory JS requires to clear all references, which is not required in Delphi/FPC. Therefore the compiler adds code to check for null, call the destructor and sets the variable to null.
It does not support freeing properties and function results. For example: List[i].Free; will give a compiler error. The property setter might create side effects, which would be incompatible to Delphi/FPC.
Version 0.8.13
- 11 May 2017
- $IF
- $ELSEIF
- $IFOPT
- $Error
- $Warning,
- $Note
- $Hint
- And in the config files it supports #IF, #IFDEF, #IFNDEF, #ELSEIF, #ELSE, #ENDIF.
Version 0.8.12
- 5 May 2017
- dotted unit names and namespaces.
Version 0.8.11
- 23 Apr 2017
- dynamic arrays can now be initialized with a constant. Same syntax as static arrays: const a: array of string = ('one', 'two');
- Classes can now be declared in the unit implementation.
- Unit nodejs now has a console class TNJSConsole.
- I added the fpcunit package. Successful tests already work. A fail is not yet caught.
Version 0.8.10
- 22 Apr 2017
- you can now use "if aJSValue then", which works just like the JS "if(v)".
- added ParamCount, ParamStr, GetEnvironment* functions. The default is not doing much.
- new package fcl_base_pas2js, containing custapp and nodejsapp: - TCustomApplication is the known class from the FCL, but with abstract methods.
- TNodeJSApplication is a TCustomApplication using nodejs to read command line params and environment variables.
Version 0.8.9
- 21 Apr 2017
- The compiler now has the types 53bit NativeInt and 52bit NativeUInt. Keep in mind that there is still no range checking.
Current aliases:
JSInteger = NativeInt; Integer = LongInt; Cardinal = LongWord; SizeInt = NativeInt; SizeUInt = NativeUInt; PtrInt = NativeInt; PtrUInt = NativeUInt; ValSInt = NativeInt; ValUInt = NativeUInt; ValReal = Double; Real = Double; Extended = Double; Int64 = NativeInt unimplemented; QWord = NativeUInt unimplemented; Single = Double unimplemented; Comp = Int64 unimplemented; UnicodeString = String; WideString = String; WideChar = char;
Version 0.8.8
- 20 Apr 2017
- bugfix release.
Version 0.8.7
- 18 Apr 2017
- $mod: the current module
- Self: in a method with nested functions this holds the class or class instance.
- overloads are now chosen like FPC/Delphi not only by type, but also by precision. This means if there are several compatible overloads, and none fits exactly it will choose the next higher. Formerly it gave an error.
- cardinal is no longer a base type, but longword is. Same as FPC.
Version 0.8.6
- 17 Apr 2017
- bugfix release.
Version 0.8.5
- 15 Apr 2017
- bugfix for the analyzer.
- supports published array properties and published records.
- array properties for external classes.
Version 0.8.4
- 14 Apr 2017
- bugfix release.
Version 0.8.3
- 4 Apr 2017
- pas2js now has code navigation in Lazarus
Trunk
- New command line option: -Ja<x>: Append JS file <x> to main JS file. E.g. -Jamap.js. Can be given multiple times. To remove a file name append a minus, e.g. -Jamap.js-.
- Back to pas2js
- Back to lazarus pas2js integration | https://wiki.freepascal.org/index.php?title=Pas2JS_Version_Changes&oldid=142541 | CC-MAIN-2021-10 | refinedweb | 7,915 | 50.43 |
table of contents
other sections
NAME¶
fork—
create a new process
LIBRARY¶Standard C Library (libc, -lc)
SYNOPSIS¶
#include <unistd.h>
pid_t
fork(void);
DESCRIPTION¶The parent's descriptors, except for descriptors returned by kqueue(2), which are not inherited from the parent process.).
-.
RETURN VALUES¶Upon¶The
fork() system call will fail and no child process will be created if:
- [
EAGAIN]
- The system-imposed limit on the total number of processeswould be exceeded (see getrlimit(2)).
- [
ENOMEM]
- There is insufficient swap space for the new process.
SEE ALSO¶execve(2), rfork(2), setitimer(2), setrlimit(2), sigaction(2), vfork(2), wait(2)
HISTORY¶The
fork() function appeared in Version 1 AT&T UNIX. | https://manpages.debian.org/testing/freebsd-manpages/fork.2freebsd.en.html | CC-MAIN-2020-45 | refinedweb | 114 | 52.39 |
Introduction: Augmented Reality Vuforia 7 Ground Plane Detection.
Vuforia's augmented reality SDK for Unity 3D uses ARCore and ARKit to detect ground planes in AR. Today's tutorial will use their native integration in Unity to make an AR app for Android or IOS. We will have a car fall out of the sky onto the ground, and it's doors will open automatically when we get close. We will also go over doing video in AR. To follow along you will need Unity 3D installed on your computer (it's free). These instructions are for total beginners so we will go over everything in detail!
The best part about Vuforia's SLAM is the amount of IOS and Android devices that it supports. A full device list can be found here:...
Step 1: Start a New Project.
Download Unity 3D from here if you don't already have it:
Make sure to install support for Vuforia Augmented Reality and Android or IOS depending on which device you have.
Open up Unity and start a new Unity project, call it whatever you want.
First lets get out app set up to build out so we don't forget. So, save the scene and call it "main".
Go to file, build settings, and switch your build platform to Android or IOS. Navigate to the XR settings in player settings and check Vuforia Augmented Reality Supported.
If your on Android you won't have to do anything else, but on IOS go to other settings and make sure to put in something for your bundle identifier. Use the format "com.YourCompanyName.YourAppName."
Put in anything for the camera usage description and change the target minimum build version to at least 9.0.
Close out of that and now let's get everything else set up.
Step 2: Let's Set Up Vuforia.
Now let's get everything set up.
Go to gameobject in the top menu and click ARCamera. Now delete the main camera from your scene.
Select the ARCamera and on the right side in the inspector click on Open Vuforia Configuration. Click the datasets collection and uncheck everything because we aren't using any image targets here.
Click on device tracker and click track device pose. Change the tracking from rotational to positional.
Now go back to the game object tab and click Vuforia, Ground Plane, and Plane finder. This houses the scripts that find our ground plane.
The last thing we need is the ground plane stage, so go to game object again in the top menu, and click Vuforia, Ground Plane, and choose Ground Plane Stage. Now anything that we child to this will show up in AR.
Step 3: Add a New Script.
The default behavior of this ground plane detection is to place a new object every time you press on the screen. What we want is to just reposition the object every time you press on the screen. So right click in your assets folder and create a new C# script. Call it "DeployStageOnce" and replace everything with this code:
using System; using UnityEngine; using Vuforia; public class DeployStageOnce : MonoBehaviour { public GameObject AnchorStage; private PositionalDeviceTracker _deviceTracker; private GameObject _previousAnchor; public void Start () { if (AnchorStage == null) { Debug.Log("AnchorStage must be specified"); return; } AnchorStage.SetActive(false); } public void Awake() { VuforiaARController.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted); } public void OnDestroy() { VuforiaARController.Instance.UnregisterVuforiaStartedCallback(OnVuforiaStarted); } private void OnVuforiaStarted() { _deviceTracker = TrackerManager.Instance.GetTracker<PositionalDeviceTracker>(); } public void OnInteractiveHitTest(HitTestResult result) { if (result == null || AnchorStage == null) { Debug.LogWarning("Hit test is invalid or AnchorStage not set"); return; } var anchor = _deviceTracker.CreatePlaneAnchor(Guid.NewGuid().ToString(), result); if (anchor != null) { AnchorStage.transform.parent = anchor.transform; AnchorStage.transform.localPosition = Vector3.zero; AnchorStage.transform.localRotation = Quaternion.identity; AnchorStage.SetActive(true); } if (_previousAnchor != null) { Destroy(_previousAnchor); } _previousAnchor = anchor; } }
In order to make sure this script gets used we need to call the OnInteractiveHitTest() function so go back to Unity and click the plane finder game object. Change the mode from Automatic to Interactive. Drag the script we just made onto the plane finder game object. Remove the ContentPositioningBehavior script. You will see a spot for a game object on the DeployStageOnce script, drag the plane finder into there, and find this script, choose the OnInteractiveHitTest function from the top of the list. Now our function will get called whenever the user clicks on the screen!
Step 4: Let's Add the Car.
Download this free car 3D model from here(Make sure to get the .obj version):-...
Also, download this sound because we are gonna play it when the car hits the ground:...
Unzip both of those files and drag them into your assets folder.
Click on the car and look to the right, change Use Embedded Materials to Use External Materials(Legacy) from the drop down menu at the top. Now we will be able to change the color of all the materials on the car.
Drag the car onto your ground plane stage making it a child. Change the scale to .035 on the x, y, and z.
Now go through each of the cars child game objects and change their materials to whatever color you want.
Add a rigid body component to the car's root game object and also add a box collider, scale it so it covers the whole car. Also add a box collider to the ground plane stage and scale it so its a few times wider than the ground plane stage. This way we can drop the car out of the sky and it will hit the ground using Unity's built in physics engine.
Step 5: Put the Car in the Sky.
Add an audio source component to the car's root game object, drag the car crash sound into it's audio clip spot.
Now we need to make a script that will put the car into the air when the user presses on the screen and then plays the crash sound when the car hits the ground. So, right click in the assets folder and create a new C# script and call it "CarController."
Replace all the code there with this:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CarController : MonoBehaviour { private bool soundPlayed = false; // Update is called once per frame void Update () { if (!soundPlayed && transform.localPosition.y < .05f) { soundPlayed = true; StartCoroutine (DelayPlaySound ()); } } public void MoveCar(){ transform.localPosition += new Vector3 (0, 10, 0); transform.eulerAngles += new Vector3 (5, 20, 5); soundPlayed = false; } IEnumerator DelayPlaySound(){ yield return new WaitForSeconds (.2f); GetComponent<AudioSource> ().Play (); } }
Add the MoveCar function to the OnInteractiveHitTest event like in the picture above. Now it will get called when the user clicks on the screen.
Step 6: Lambo Doors.
So if you expand the car game object and find the doors, you will notice both doors are one single mesh. If we want to open the doors our only option is going to be Lambo doors that open vertically. To make this work we need to first change their pivot point.
Make an empty game object that is a child of the car. Drag the doors in and make them a child of this new game object. Move the parent game object to where the pivot point should be, by the door hinges. Now move the child doors back into place. Now when we rotate the doors parent, the pivot point is in the right place.
We are going to make a script that opens the doors when you get close to the car but before we do that we need a way to "trigger" the event. Add a box collider to your door parent game object and scale it so it goes a little ways over the car in both directions. Check "isTrigger". Now add a box collider to the main camera and scale it appropriately. Also check "isTrigger". Add a Rigid Body component to your camera and uncheck "useGravity". With your camera selected, change it's tag to "MainCamera" in the top of the inspector.
Add a new script called "LamboDoorBehavior" and add the code below. Drag the script onto your door's parent.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LamboDoorBehavior : MonoBehaviour { private float currAngle = 0; private float desiredAngle = 0; // Update is called once per frame void Update () { currAngle = Mathf.LerpAngle (currAngle, desiredAngle, Time.deltaTime * 3f); transform.localEulerAngles = new Vector3 (currAngle, 0, 0); } public void OpenDoors(){ desiredAngle = 60f; } public void CloseDoors(){ desiredAngle = 0; } void OnTriggerEnter(Collider col){ if (col.CompareTag ("MainCamera")) { OpenDoors (); } } void OnTriggerExit(Collider col){ if (col.CompareTag ("MainCamera")) { CloseDoors (); } } }
This script will cause your doors to open slowly when you get close the them in AR by using the Lerp() function in unity which interpolates between two points (or in this case two angles).
Step 7: Playing Video in AR.
The last thing we need to do is get video playing in AR.
Right click on any game object that is a child of your car and create a 3D object, Quad. This will make sure the quad is a child of your car. Position and resize this quad such that it fits inside the dash of your car and looks like it supposed to be there. This is what we are going to play the video on.
Add a video player component to your quad. Change the source to URL and find a hard link to an .MP4 file or drag a video file into your assets folder and then drag that clip into the empty slot. If you want to stream in a video from a URL, Instragram is a great source. Right click on any Instagram video in Google Chrome and click inspect. Find the div containing the video and copy the link from there (I have this method pictured above).
Make sure to check loop if you want it to play more than once. Add an audio source component to this game object and change the output source to audio source on the video player. Drag in your newly created audio source into that slot.
Finally we are done!
Step 8: Put the App on Your Phone!
If you are building for Android you can just go to file and.
You may have to move the camera around a little bit but give it a second and tap the screen and you should see your car fall out of the sky onto the ground! Now you can walk inside and watch your video play in the dashboard!
Have fun and let me know if you have any questions in the comments!
Participated in the
Epilog Challenge 9
Be the First to Share
Recommendations
3 Comments
1 year ago
Well I am having Unity 2018.4.19f1 and neither above nor the procedure from Unity website worked. It seems like ground detection doesn't work. However object tracking with a license key worked the first time.
Question 2 years ago
Well the first script DeployOnceStage.cs doesnt work in unity and has errors and hence the Provided tutorial is meaningless ,kindly update this page !!
Question 3 years ago
Hi.. thank you very much for the tutorial.. But when i try this out in 2017.4.1, which uses Vuforia 7.0.5, there is no error log but I am not able to place the car in the desired location.. both the cam and the car are positioned in the 0,0,0.. so the car is placed at overt the head.. I need support to close this.. | https://www.instructables.com/Augmented-Reality-Vuforia-7-Ground-Plane-Detection/ | CC-MAIN-2022-05 | refinedweb | 1,918 | 66.13 |
In some minigames in the original Mario Party for Nintendo 64, players must move the joystick in a circular motion (think Zangief's moves on steroids) to build up power. Many try moving the joystick with their left thumb, or between the fingers of their dominant hand, but it's never fast enough; in most minigames, you need 5 Hz just to survive, and it's tough. Others try moving the joystick with their palms; this gives more Hz and more points but causes blisters. Enough cases were reported to the media that Nintendo was investigated by the U.S. Attorney General (), issued a warning about rototorture (), began to supply free gloves with Mario Party, and removed the rototorture from Mario Party 2, replacing it with straight torture.
The only other game I've seen that uses rototorture as such is Bomberman 64, where you have to spin the joystick to wake up from being stunned, but it only lasts about two seconds at a time as opposed to the one-minute rototorture marathons of the original Mario Party.
Some of the games in WarioWare, such as "eat the spaghetti" and "raise the flag", are based on rototorture of the Control Pad. Luckily, these games are much less demanding in terms of Hz than Mario Party was.
All you need for many hours of fun (compile with Allegro):
#include <allegro.h>
#include <stdio.h>
int joypos, spins;
void joyloop ()
{
poll_joystick ();
switch (joypos)
{
case 0: if (joy[0].stick[0].axis[0].d2 && joy[0].stick[0].axis[1].d1) joypos++; break;
case 1: if (joy[0].stick[0].axis[0].d2 && joy[0].stick[0].axis[1].d2) joypos++; break;
case 2: if (joy[0].stick[0].axis[0].d1 && joy[0].stick[0].axis[1].d2) joypos++; break;
case 3:
if (joy[0].stick[0].axis[0].d1 && joy[0].stick[0].axis[1].d1)
{
joypos = 0;
spins++;
}
}
}
int main ()
{
printf ("Spin the joystick as fast as you can!\n");
allegro_init ();
install_joystick (JOY_TYPE_AUTODETECT);
install_timer ();
joypos = spins = 0;
rest_callback (15000, joyloop);
printf ("You spun the joystick %d times!\n", spins);
return 0;
}
And there you have it - your own personal blister generator.
Log in or registerto write something here or to contact authors.
Need help? accounthelp@everything2.com | http://everything2.com/title/rototorture | CC-MAIN-2017-04 | refinedweb | 378 | 61.97 |
25 September 2009 13:13 [Source: ICIS news]
SINGAPORE (ICIS news)--China linear low density polyethylene (LLDPE) and polyvinyl chloride (PVC) futures traded as much as 1.5% lower on Friday as sharp falls in the physical markets dampened sentiment, industry sources said.
The November LLDPE contact closed at CNY9,520/tonne on Friday, CNY145/tonne or about 1.5% lower from the previous day’s settlement price, according to data from the Dalian Commodity Exchange (DCE).
Imported LLDPE was discussed below $1,200/tonne CFR (cost and freight) ?xml:namespace>
November PVC futures meanwhile fell by 1.4% from Thursday’s settlement level to close at CNY6,440/tonne on the back of persistently poor demand in the physical market, a local PVC trader said. The number of open positions also fell to its lowest since late-July, reflecting the sluggish trading sentiment in the futures market, the trader added.
($1 = CNY6.83)
Additional reporting by Ng Hun Wei
For more on PE, | http://www.icis.com/Articles/2009/09/25/9250482/chinas-plastics-futures-fall-further-on-weak-physical-trade.html | CC-MAIN-2015-06 | refinedweb | 164 | 54.93 |
Difference between revisions of "OSEE/BLAM"
From Eclipsepedia
Revision as of 19:13, 14 May 2010
OSEE contains an Eclipse extension point that allows features to be added to OSEE without having to rebuild the application.
This is similar to "scripts" for other tools that you may have encountered but, in OSEE's case, the scripts are actually written in the same Java language as that used to develop the application.
This section of the Wiki, which is work in progress, will describe what is needed to create a new BLAM.
What do I need to know?
- Because BLAMs are added using an Eclipse extension point, you need to understand Java syntax to be able to create a new BLAM
- BLAMs use an extension point called AbstractBlam defined in the package org.eclipse.osee.framework.ui.skynet.blam. It is therefore wise to look at the OSEE source for this package to understand how your code extends OSEE
- The "built-in" BLAMs supplied in OSEE by default are located in the package org.eclipse.osee.framework.ui.skynet.blam.operation. Looking at the source for this package will give hints on BLAM construction
How to create a BLAM
In Eclipse select File-> New Project. From the list select "Plug-In Project".
Put a suitable name in the "Project name" box and leave everything else with default settings. Click Next to move to the Content dialog.
In the Content dialog, clear the following options:
- Generate an activator
- This plug-in will make contributions to the UI
- Enable API analysis
Select the "No" box for "Would you like to create a rich client application?" Click Next to move to the "Template" dialog.
Do not select a template, just click on Finish.
Open Manifest.MF in the new project and go to the "Dependencies" tab. Add "org.eclipse.osee.framework.ui.skynet.blam" as a required imported package. Go to the "Extension tab" and select "Add". Select the extension point "org.eclipse.osee.framework.ui.skynet.BlamOperation"
Add a new class with the name of your BLAM
Modify the code to read something like
[code format="java"] package marktestblam;
import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.osee.framework.ui.skynet.blam.AbstractBlam; import org.eclipse.osee.framework.ui.skynet.blam.VariableMap;
/**
* Put your description here. * * @author Put your name here */
public class DoBlam extends AbstractBlam {
@Override public Collection<String> getCategories() { // TODO Auto-generated method stub return null; }
@Override public void runOperation(VariableMap variableMap, IProgressMonitor monitor) throws Exception { // TODO Auto-generated method stub
} } [code] | http://wiki.eclipse.org/index.php?title=OSEE/BLAM&diff=200791&oldid=200789 | CC-MAIN-2014-41 | refinedweb | 426 | 55.24 |
Our Benefits
All topics; questions; ideas; problems; praise; updates; new topic myspace has a mood option with their status update i don t want to have to go to the website. Status coding or movie? mood posts: joined hah ce ideas man but i dunno, it feels more or less ready in some areas but i don t know what the hell to fix now most. Ideas, requests, problems regarding system status development site? send feedback. Reeldigger is perfectly happy having no status my mood: earliest horror memory, any ideas?.
Hide status and mood date myspace myspace a place for friends neuer dj termin im februar new dj documentation; plugins; suggest ideas; support forum; themes; wordpress .
I checked my friends "status and mood" section on myspace, and one of my friends had a strange type ityou dont hafta make it match the preset moodstheyrr just there for ideas.
I notice that when i click the status and mood button (to disable), it does nt stay highlihted it seems to "un-select" iself before i can hit the publish button any ideas about.
I would like my phone to automatically adapt to my mood eg re: mobile active profile status expression (apse) posted by about symbi deas; contact us symbian foundation. The mental status exam is the basis for understanding the loose associations, confabulations, flight of ideas, ideas mood and affect. Waiting for the "mood bus" to arrive by meloney hall how many times have your heard i keep adding ideas from the above list, and soon you ll be feeling better about your. Big figure is disinterested in status my mood: i think he came to some sticky end any ideas? thanks in.
At the meantime user are able to customize their status expression according to their mood or things they check out the latest ideas!. Order status; wish lists; view cart led & mood lighting store christmas present ideas; contact us; shipping & returns. Status and mood bright ideas website. I m out of ideashelp sponsor pare dsl "side by side" parison on cable . In rehearsal: ways in: ways of speaking: putting a scene together: status choices: choosing a mood the starting ideas: see the scene run-through: the actors work on sections of.
Christmas gifts and gadgets, gift ideas, fathers day gifts home > lifestyle > mood lighting mood lighting create the right your order order status delivery shipping rates & policies.
Mood of the nation - the iphone app that lets you share how attitude ( out of ), and has a strong emotional status ( to make your friends feel better, so submit your ideas.
The status and menting api lets third party sites use myspace status and mood updates works blamed for $225b in lost productivity > some brands have good ideas. Extend home; plugins developer center; themes; ideas; kvetch! search plugins this plugin is used to show off your current "status" and "mood" on blog.
Order status; wish lists; view cart x24" usb upgrade tubes forambient mood lighting kits with remote control. Order status; contact us usb type port for recharging your mood light accessory directly from the floating ideas base unit. Action replay code sites christmas concert ideas how do i remove the myspace icon on blac pogb smhs hide mood and status on myspace gp memek jilbab. Copy and paste myspace status and mood you have sudden mood changes out ideas name for myspace display hudab display name ideas for myspace avs code video status and mood.
Free videos silent auction bid templates xem lon to hide status dirty one liners hiding code for myspace activity stream allen make my baby willy wonka game ideas for myspace mood. The mental status examination (or mental state examination in mood is described using the patient s own words, and can tempo of thought, some people may experience flight of ideas. Since the "mood and status" feature is new people have questions about i was dumb enough to put a pic in my mood status and i cannot clear the image any ideas?.
Creative, mad ideas to help you get the most mood changer a real creative jigsaw puzzle ideas is for a puzzle that could possibly status symbol wooden jigsaw puzzles already. Ideas, requests, problems regarding system status? send feedback. I bored of the boring stuff lol and now tht you c. Mood and affect mood describes the subjective state of the patient visual hallucinations, phobias, obsession themes, and overvalued ideas references: how to do a mental status exam..
status and mood ideas
Who We Are
import export data england :: pain and muscle spasm in throat :: lower back pain with leg numbness and up :: ajit jal :: status and mood ideas ::
| http://djiler.i8it.net/crysis-w23/rongoonanawn.html | crawl-003 | refinedweb | 776 | 65.25 |
Opened 9 years ago
Last modified 8 years ago
#12157 new Cleanup/optimization
FileSystemStorage does file I/O inefficiently, despite providing options to permit larger blocksizes
Description
FileSystemStorage contains the following:
def _open(self, name, mode='rb'): return File(open(self.path(name), mode))
..which is used to open files which are stored as FileFields in Django models.
If the programmer decides to hack through the file by using (for instance) the django.core.files.base.File.chunks() method:
def chunks(self, chunk_size=None): """ Read the file and yield chucks of ``chunk_size`` bytes (defaults to ``UploadedFile.DEFAULT_CHUNK_SIZE``). """ if not chunk_size: chunk_size = self.__class__.DEFAULT_CHUNK_SIZE if hasattr(self, 'seek'): self.seek(0) # Assume the pointer is at zero... counter = self.size while counter > 0: yield self.read(chunk_size) counter -= chunk_size
...the programmer would expect self.read() - which drops through to django.core.files.base.File.read() - to honour its arguments and for the I/O to occur in DEFAULT_CHUNK_SIZE blocks, currently 64k; however Dtrace shows otherwise:
29830/0xaf465d0: open_nocancel("file.jpg\0", 0x0, 0x1B6) = 5 0 29830/0xaf465d0: fstat(0x5, 0xB007DB60, 0x1B6) = 0 29830/0xaf465d0: fstat64(0x5, 0xB007E1E4, 0x1B6) = 0 0 29830/0xaf465d0: lseek(0x5, 0x0, 0x1) = 0 0 29830/0xaf465d0: lseek(0x5, 0x0, 0x0) = 0 0 29830/0xaf465d0: stat("file.jpg\0", 0xB007DF7C, 0x0) = 0 0 29830/0xaf465d0: write_nocancel(0x1, "65536 113762\n\0", 0xD) = 13 0 29830/0xaf465d0: mmap(0x0, 0x11000, 0x3, 0x1002, 0x3000000, 0x0) = 0x7C5000 0 29830/0xaf465d0: read_nocancel(0x5, "\377\330\377\340\0", 0x1000) = 4096 0 29830/0xaf465d0: read_nocancel(0x5, "\333\035eS[\026+\360\215Q\361'I\304c`\352\v4M\272C\201\273\261\377\0", 0x1000) = 4096 0 ... ...(many more 4kb reads elided)... ... 29830/0xaf465d0: sendto(0x4, 0x7C5014, 0x10000) = 65536 0
...reading blocks in chunks of 4Kb (on OSX) and writing them in 64Kb blocks.
The reason this is occurring is because "open(self.path(name), mode)" is used to open the file, invoking the libc() stdio buffering which is much smaller than the 64kb requested by the programmer.
This can be kludged-around by hacking the open() statement:
def _open(self, name, mode='rb'): return File(open(self.path(name), mode, 65536)) # use a larger buffer
...or by not using the stdio file()/open() calls, instead using os.open()
In the meantime this means that Django is not handling FileSystemStorage reads efficiently.
It is not easy to determine whether this general stdio-buffer issue impacts other parts of Django's performance.
Change History (6).
#9632 has a patch which may or may not affect this issue. | https://code.djangoproject.com/ticket/12157 | CC-MAIN-2019-18 | refinedweb | 422 | 67.04 |
In the not too distant past, I have had to implement solutions for generating PDF documents, based on dynamic data and a document template to be defined by the end-user. The approach we took was to allow the end user to create the document layout in MS Word, embedding simple tags to indicate the position of dynamic data elements. The Word document had to be saved as HTML, was cleansed into proper XHTML by JTidy was subsequently turned into an XSLT stylesheet that consisted largely of XSL-FO statements with small pieces of XSLT embedded to inject the dynamic data elements. The resulting proper XSL-FO document was finally transformed into PDF using Apache FOP. The XSLT that turned XHTML into XSLT-with-a-lot-of-XSL-FO was really the essence of the solution. Translating HTML into XSL-FO was key.
Yesterday I came across a very interesting article on MSDN, discussing a way of turning Word Document directly into an XSL-FO document: Transforming Word Documents into the XSL-FO Format (feb 2005). It shows how you can save a Word document as XML and specify a stylesheet to be applied when saving. I had not known before that my Word 2003 also was an XSLT processor! The article introduces a stylesheet – Word2FO.xsl – that can be used for the transformation into XSL-FO. I decided to give it a spin.
.
A short intro on XSL-FO: XSL-T, XPath and XSL-FO..
Converting Word documents to XSL-FO
As per the instructions in the MSDN article, I download the Word2FO.xsl stylesheet – with several supporting templates – and install them on my local hard drive. I then open Word 2003, create a simple document with several layout features that are bound to pose a challenge on the conversion to XSL-FO. I then select Save As from the File Menu.
The document type is XML. This brings up a checkbox Apply Transform. When checked, the Transform button is enabled. When I press it, I can browse the file system to locate an XSL(T) stylesheet. It turns out Word is also an XSLT transformation engine! That was news to me. Well, I select the Word2FO.xsl stylesheet. When finally I press Save, the document is saved, as XSL-FO:
Thus I have found a very rapid way of turning a layout created by an end-user in Word into XSL-FO format. It is certainly an easy way to find out the XSL-FO syntax for certain layout features: it beats googling for the exact XSL-FO syntax for certain layout properties. It would also give me an interesting alternative for the solution I described above: instead of saving Word as HTML, tiyding it to XHTML and XSLT transforming it into an XSLT stylesheet, riddled with XSL-FO -heavily relying on the custom XHTML-to-XSLFO stylesheet – I could pick up the XSL-FO created by Word and embed it in a prepared XSLT.
Transforming onwards to PDF
I am not able to quickly gather from this XSL-FO content whether the conversion was successful and complete. That is something I would typically leave to XSL-FO render-engines, like Antenna House or Apache FOP (open source). I typically make use of Apache FOP, see, an open source implementation of a FO renderer. FOP can render to PDF as well as SVG, PS, RTF.
The result of rendering the XSL-FO document created by Word as PDF, using the stable 0.20.5 FOP release (July 2003!), looks as follows:
Well, not bad. However we lost a couple of details. Most notable the column layout in the original Word document. Also a couple of fonts – no arial (or any sans-serif for that matter) is created into the PDF. Of course we cannot tell from this example whether the FOP renderer is limited or the XSL-FO was faulty. I will give it a try with the latest (beta) 0.9 release op FOP (december 2005).
I have tried with FOP 0.91 and the result is very similar. Still no column layout, still no sans-serif font types. I get warnings about the fonts that allow we to correct the situation (it seems that proper, exact matchting font definitions need to be configured with FOP):
WARNING: Warning(1/6184): fo:table, table-layout="auto" is currently not supported by FOP Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'TimesNewRoman,normal,400' not found. Substituting with default font. Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'Arial,normal,700' not found. Substituting with default font. Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'Arial,italic,700' not found. Substituting with default font. Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'TimesNewRoman,italic,400' not found. Substituting with default font. Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'TimesNewRoman,italic,700' not found. Substituting with default font. Mar 22, 2006 11:32:12 AM org.apache.fop.fonts.FontInfo notifyFontReplacement WARNING: Font 'CourierNew,normal,400' not found. Substituting with default font.
Note that it is very simple to write a Java class that can convert XSL-FO to PDF using Apache FOP. The code looks like this (derived from the example ExampleFO2PDF.java that is shipped with FOP):
package nl.amis.fop092; /* * Copyright 1999: ExampleFO2PDF.java 332791 2005-11-12 15:58:07Z jeremias $ */ // Java import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; //JAXP import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Source; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.sax.SAXResult; // FOP import org.apache.fop.apps.Fop; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FormattingResults; import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.PageSequenceResults; /** * This class demonstrates the conversion of an FO file to PDF using FOP. */ public class ExampleFO2PDF { /** * Converts an FO file to a PDF file using FOP * @param fo the FO file * @param pdf the target PDF file * @throws IOException In case of an I/O problem * @throws FOPException In case of a FOP problem */ public void convertFO2PDF(File fo, File pdf) throws IOException, FOPException { OutputStream out = null; try { // Construct fop with desired output format Fop fop = new Fop(MimeConstants.MIME_PDF); // Setup output stream. Note: Using BufferedOutputStream // for performance reasons (helpful with FileOutputStreams). out = new FileOutputStream(pdf); out = new BufferedOutputStream(out); fop.setOutputStream(out); // Setup JAXP using identity transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity transformer // Setup input stream Source src = new StreamSource(fo); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); // Result processing FormattingResults foResults = fop.getResults(); java.util.List pageSequences = foResults.getPageSequences(); for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) { PageSequenceResults pageSequenceResults = (PageSequenceResults)it.next(); System.out.println("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : " id") + " generated " + pageSequenceResults.getPageCount() + " pages."); } System.out.println("Generated " + foResults.getPageCount() + " pages in total."); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } finally { out.close(); } } /** * Main method. * @param args command-line arguments */ public static void main(String[] args) { try { System.out.println("FOP ExampleFO2PDF\n"); System.out.println("Preparing..."); //Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); //Setup input and output files File fofile = new File(baseDir, "exampleWordbasedXSLFO.fo"); File pdffile = new File(outDir, "ResultFO2PDF.pdf"); System.out.println("Input: XSL-FO (" + fofile + ")"); System.out.println("Output: PDF (" + pdffile + ")"); System.out.println(); System.out.println("Transforming..."); ExampleFO2PDF app = new ExampleFO2PDF(); app.convertFO2PDF(fofile, pdffile); System.out.println("Success!"); } catch (Exception e) { e.printStackTrace(System.err); System.exit(-1); } } }
Also note that it is good to see that after two years of apparent comatose existence, FOP has regained consciousness with this 0.91 release late 2005!
Hey nice post,
until now I didn’t noticed that word documents can be safed as xsl:fo. Thanks for that!
Greetings
jpee
Hey, really great blog. Seriously I made search for a week. Finally I got a way through xsl fo and apache fop apis. Over all is fine learning journey again ends with AMIS Technology blog. Thanks to you all.
Thanks,
Rajesh
Hey all, interesting forum. Try googling ooo2xslfo, it’s the Open Office implementation of saving a doc as xsl:fo. I tested similar components in Word, AbiWord and Open Office and found that with Apache FOP the PDF turned out best with the Open Office solution, but it really depends on what you need to do. I think AbiWord comes with the feature built in.
Sorry, mistake. I mean i dont want virtualy printers neither terciary softwares.
I’m looking for some sample code to get PDF from Word, i want virtualy printers or terciary sotfwares. I was thinking about Word–>XSL:FO–>PDF
Do you know how get XSL:FO from Word by code and without open winword process???
No, do you know any other way to get that?
Thanks you.
I’m looking for a solution for following requirement.
We have RTF-documents loaded into Oracle 9i CLOB on HP-UX. The user wants to view these CLOB via a JEE-application using Acrobat Reader. The printing functionality within the reader will then be used. They also ask for the possibility of loading the PDF (as a result of the RTF conversion) as a BLOB in Oracle 9i.
The best way to do this would be using PL/SQL to convert the CLOB containing RFT to the BLOB containing the PDF.
If this isn’t possible the next solution would be doing the conversion somewhere in the Oracle iAS (JEE).
I didn’t understand Lucas article all the way. But maybe it contains an answer to my question. Could anyone comment on that?
Thanks in advance!
Hello.. I am not able to open any word file. i have got Windows XP and Office XP installed in my laptop. I have tried repairing, reinstalling and every possible stuff i could. I also have Acrobat Writer 7 installed in it. is their any solution to this? is Acrobat writer linked with the problem?? Kindly suggest some alternative or solution…
How can we convert XSL-FO document to HTML and after some format changes can we convert the HTML doc back to XSL-FO without loosing the formatting info ?
Any suggestion/comment on this would be of great help
Great article. Very informative.
Your page displays fine in Safari 1.3.2 on the Mac. You really ought to switch your browser compatability code to test for specific DOM and JavaScript functionality instead of detecting the browser name and version number. Your Javascript alert that says that my browser (which it identifies as Mozilla) might not be supported is annoying and excludes thousands of people that refuse to use MSIE.
Again, great article. Just clean up that browser support code! Thanks.
Leo,
The original problem Lucas described is not how to convert a Word Document (or Open Office document) to a PDF, we all agree that’s easy. The problem is how to programmatically create a PDF from a user-defined form. For example, say the legal department wants to come up with a template that the sales people in the field can fill out on the fly, and keep all the nicities like headers, footers, pagination, inline images, and so forth.
One might say to simply use Adobe Acrobat, but solution that has it’s own share of problems: most people are comfortable with a Word or Word-like interface which Acrobat does not have, Acrobat fields do not “grow and shrink” with the text (you have to pre-define the field size, and if the text is longer than what you anticipated, you get to choose either truncation or shrunken font size), variable length tables are difficult to deal with, Acrobat costs several hundred (US) dollars, etc.
This is actually a pretty tough problem. Thanks for the article, Lucas.
Why not just open the Word Document in Open Office and click on the “PDF” button ?
You didn’t delve into to this deep enough.
Using XML-FO to get from WordML to PDF works only sort-of. There are many things that fail, because FO doesn’t live in the same world as Word. Try some more complex documents (hint: one with a Table of contents, or one that uses Tabs, or bullets, or line numbers, or …).
If you are going to use this technique, you better research it more. There are a number of commercial companies trying to crack this, and with all of their work, still have problems with true fidelity.
I need to know is this converting word to xls to pdf thingi is free… if so can u give me this software.
kishoreyc@gmail.com.
If its not free.. then make this software freely available.
We use OpenOffice.org as well, since OOo 2 came out the support for a huge
amount of Word’s features is quite excellent and for the past year or so
quite stable.
In conjuciton with iText for further PDF work it becomes a very powerful of automating
Doc -> PDF workflow for not too much money and with users having to do anything XML.
As a matter of fact Tim, we had a Knowledge Center session on XML Publisher just yesterday. It does indeed cover a lot of the functionality we require. My colleague Marcos had prepared demonstrations and clarficiations and I was very impressed.
However, the current pricing & licensing strategy for XML Publisher is very prohibitive. At the current quotes rates of $40.000 – or $30.000 if you already have a Enterprise Edition of
the Oracle Application Server -, we will find few customers interested.
We very much hope prices will come down once the product has mattured somewhat. It seems that Oracle is not ready to do much work on Oracle Reports so XML Publishers
seems to be its logical successor. For that to really be a viable option however, the price simply must come down!
regards,
Lucas
Did you folks check out Oracle XML Publisher, you can use an RTF document as
a report template and not only convert the RTF doc contents but also embed data tags
that are merged in from an XML datasource at runtime. You can then generate PDF,
HTML, RTF and Excel as output formats.
Currently available in the Oracle E Business Suite and as a standalone library.
You could use OpenOffice for conversion on IAS. It has a great PDF renderer and can
also open DOC files. ODF is open to public (zipped XML). So, we made a simple
java program which calls OO service and makes conversion on IAS (kind of odt2pdf).
I found this document a while ago, while searching for a way to go the other direction – from XSL-FO to Word (really, to .RTF). Ironically, I never did find a handy way to do that – instead, I’m looking at generating PDF from XSL-FO, then using a third-party proprietary tool for PDF->RTF conversion. Clumsy, but it seems to be what I’m stuck with for now. I did try Apache’s FOP with RTF specified as the output format, but got show-stopping cryptic Java errors. That was a few months ago, when the RTF output functionality was new; perhaps it’s been smoothed out since then.
I had mistakenly used code tags instead of pre. Our WYSISWG editor let us down. Thanks for the hint.
Great Post, it looks very good, only a little thing… the code will be look more nice
formated, but i supose that was a mistake. | http://technology.amis.nl/2006/03/22/converting-word-documents-to-xsl-fo-and-onwards-to-pdf/ | CC-MAIN-2014-15 | refinedweb | 2,672 | 59.19 |
Blog Map
This blog post introduces a small command line utility (OpenXmlDiff.Exe, code attached to this page) that compares two Open XML documents and produces a textual report of the differences in markup between them. This utility was born out of sheer frustration. I've been needing this utility for months. I've always accomplished my goals without it, but it would have been a time-saver several times in the past. I've heard rumors of this existing elsewhere, but it has always eluded me.
This blog is inactive.New blog: EricWhite.com/blogBlog TOC(Oct 27, 2008 - The Open XML SDK development team has built an Open XML Diff program that's very nice - find out about it here.)
Using this utility, we can create two documents with a very small difference between them, and see the exact changes that the difference caused. Sometimes this alone is enough to explain the markup. But if further explanation is necessary, the diff makes it easy to find the relevant places in the Open XML specification. For our purposes, the currently published Ecma 376 specification works just fine.
This utility is a small (350 line) program written in C# 3.0. Any edition of Visual Studio 2008 will compile it. OpenXmlDiff uses another program, XmlDiff.exe, and another DLL, XmlDiffPatch.dll. These files are included in a download from the MSDN XML Developer's Center.
To build and run this utility:
We now have assembled all three files that we'll need to execute the diff. Another approach is to add C:\Program Files\XmlDiffPatch\bin to your path, and copy OpenXmlDiff.Exe to C:\Program Files\XmlDiffPatch\bin. Or whatever.
Next, use Word 2007 to create a document with some content, and name it, say, "Doc1.docx".
Close Word, and copy Doc1.docx to Doc2.docx.
Edit Doc2.docx with Word, and make a small change. For this blog post, I'll highlight the second word, and make it bold. Save Doc2.docx, and close Word.
At the command prompt:
C:\OpenXmlDiff>OpenXmlDiff Doc1.docx Doc2.docx >Report.txt
Open Report.txt in an editor.
The report tells us that the documents have the same set of parts, and it lists the parts that are identical:
Comparison ReportOriginal File: Doc1.docxModified File: Doc2.docx Documents have the same parts Identical Parts===============/docProps/app.xml/word/theme/theme1.xml/word/endnotes.xml/word/fontTable.xml/word/footnotes.xml/word/styles.xml/word/webSettings.xml
The report then lists something called a diffgram for the parts that have changed. More on what a diffgram is in a moment. We can see that three parts were changed:
When we look at the changes to settings.xml and core.xml, it is apparent that these changes are some housekeeping changes injected by Word, and not relevant. However, the changes to /word/document.xml are what we're looking for. We see something like the following. I've formatted a bit to make it more readable on a blog: the original diffgram includes lots of namespace declarations, but I've deleted them from the following listings.
Part Comparison===============Uri: /word/document.xmlContentType: application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml<xd:xmldiff <xd:node <xd:node <xd:node <xd:add> <w:r> <w:t xml:On</w:t> </w:r> </xd:add> <xd:node <xd:add> <w:rPr> <w:b /> </w:rPr> </xd:add> <xd:node <xd:changethe</xd:change> </xd:node> </xd:node> > </xd:node> </xd:node> </xd:node></xd:xmldiff>
The diffgram isn't really the differences between the two files. It is a definition of a set of changes that when applied to the first file will result in the second file. (The XmlPatch.Exe is a utility that can do this, not relevant.) Instead, we'll use the diffgram to figure out exactly the changes that occurred to our doc as a result of bolding the second word in the first paragraph.
The diffgram schema is documented in a CHM that is installed with the XML diff and patch utilities:
The <xd:node element (the first child element of the root element of the diffgram) specifies that to find the relevant change, we need to find the second node at the root level of Doc1.xml. The match attribute is a "1" based index into nodes at the relevant hierarchical level in the XML. Using Visual Studio (and the Power Tools for Visual Studio, which includes the very cool Open XML editor), we can open the main document part (/word/document.xml) for Doc1.docx and see:
<807E1B" w: <w:r> <w> </w:p>
The first node is the XML declaration:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
The second node is the <w:document> node:
="">
This is the node that the previously mentioned diffgram element is referring to.
The next element of the diffgram is <xd:node, so this indicates that we should look at the first child element of the previously selected element, so this refers to the <w:body> element, which is the first child of the <w:document> element.
And so on.
Then in the diffgram, we see the following. (namespaces were deleted)
<xd:add> <w:r> <w:t xml:On</w:t> </w:r></xd:add>
This is the markup that indicates the addition of a run and text node in the relevant spot. Because I bolded the second word, this caused the markup to be split into three text runs, with formatting on the middle run. The above indicates the addition of the first run.
And we see the new, formatted middle run. This is where we see the addition of the <w:rPr> element and its child <w:b/> element, which indicate that this run is bolded: (namespaces deleted)
<xd:node <xd:add> <w:rPr> <w:b /> </w:rPr> </xd:add>
And then we see the change of this text run to contain just the bolded word.
<xd:node <xd:changethe</xd:change> </xd:node></xd:node>
And then we see the rest of the paragraph, not bolded: (namespaces deleted)
>
This is a very simple scenario, but I've used this in a more complicated scenario. I had a situation where I knew that there was a change to markup *somewhere* else in the document that I needed to know about. I didn't even know what part the change might be in. This utility found what I needed to know, and pointed me to the right place in the spec.
Possible enhancements: it would be cool if this were a GUI, and when you clicked on a part that had differences, it opened a window that displayed the differences graphically in an HTML viewer. Converting a diffgram to HTML has been done before, so maybe it wouldn't be too hard. Any volunteers?
You've been kicked (a good thing) - Trackback from DotNetKicks.com
I found the documentation for the diffgram. I've udated the original post with the location. Also, I
When learning about Open XML or developing Open XML solutions, it's very common to find yourself wondering
In my enthusiasm to move the extraneous namespaces from the middle of the diffgram, I introduced a bug
Eric, I'm still using VS 2005, and so I can't compile OpenXmlDiff.
Any chance of a pre-built executable?
thanks .. Jason
Hi Jason, I wish I could. But since this is a blog that is hosted on a Microsoft server, to post a pre-built executable is a long, drawn out process. This won't happen unless there is a compelling business reason. One approach - VS 2008 will run side-by-side with 2005 - you could install the express edition to build. Also would give you the chance to play with some cool technologies, such as LINQ :) Or if there are any volunteers who want to build an executable and post a link as a comment here, I'd be appreciative.
-Eric
This post presents some code to remove personal information from an Open XML word processing document.
(July 16, 2008: This approach has been replaced with a better version .) I had a thought that the instructions
Hi Eric,
good work. There is an error in the with the following line:
if (partList.Contains(part) || !part.ContentType.EndsWith("xml"))
return;
Nice Comparison between open XML Documents.
Thanks
<a href="">Litera Corp</a> | http://blogs.msdn.com/b/ericwhite/archive/2008/06/14/openxmldiff-exe-a-utility-to-find-the-differences-between-two-open-xml-documents.aspx | CC-MAIN-2014-15 | refinedweb | 1,402 | 65.01 |
# How I discovered an easter egg in Android's security and didn't land a job at Google
 Google loves easter eggs. It loves them so much, in fact, that you could find them in virtually every product of theirs. The tradition of Android easter eggs began in the very earliest versions of the OS (I think everyone there knows what happens when you go into the general settings and tap the version number a few times).
But sometimes you can find an easter egg in the most unlikely of places. There’s even an urban legend that one day, a programmer Googled “mutex lock”, but instead of search results landed on foo.bar, solved all tasks and landed a job at Google.
**Reconstruction**
The same thing (except without the happy ending) happened to me. Hidden messages where there definitely couldn’t be any, reversing Java code and its native libraries, a secret VM, a Google interview — all of that is below.
### DroidGuard
One boring night I factory-reset my phone and got to setting it up again. First things first, a fresh Android install asked me to log into the Google account. And I wondered: how does the process of logging into Android even work? And the night suddenly became less boring.
I use PortSwigger’s Burp Suite to intercept and analyze network traffic. The free Community version is enough for our purposes. To see the https requests we first need to install PortSwigger’s certificate onto the device. As a testing device I picked an 8-year-old Samsung Galaxy S with Android 4.4. Anything newer than that and you might have issues with certificate pinning and stuff.
In all honesty, there’s nothing particularly special with Google API requests. The device sends out information about itself and gets tokens in response… The only curious step is a POST request to the anti-abuse service.

After the request is made, among numerous very normal parameters there appears an interesting one, named **droidguard\_result**. It’s a very long Base64 string:

DroidGuard is Google’s mechanism for detecting bots and emulators among real devices. SafetyNet, for example, also uses DroidGuard’s data. Google has a similar thing for browsers, too — Botguard.
But what’s that data? Let’s find out.
### Protocol Buffers
What generates that link (*[www.googleapis.com/androidantiabuse/v1/x/create?alt=PROTO&key=AIzaSyBofcZsgLSS7BOnBjZPEkk4rYwzOIz-lTI](https://www.googleapis.com/androidantiabuse/v1/x/create?alt=PROTO&key=AIzaSyBofcZsgLSS7BOnBjZPEkk4rYwzOIz-lTI)*) and what inside Android makes this request? After a short investigation, it turned out that the link, in this exact form, is located inside one of Google Play Services’ obfuscated classes:
```
public bdd(Context var1, bdh var2) {
this(var1, "https://www.googleapis.com/androidantiabuse/v1/x/create?alt=PROTO&key=AIzaSyBofcZsgLSS7BOnBjZPEkk4rYwzOIz-lTI", var2);
}
```
As we’ve already seen in Burp, POST requests on this link have **Content-Type** — **application/x-protobuf** (Google Protocol Buffers, Google’s protocol for binary serialization). It’s not json, though — it’s difficult to uncover what exactly is being sent.
Protocol buffers work like this:
* First we describe the structure of the message in a special format and save it into a .proto file;
* Then we compile .proto files, and the protoc compiler generates source code in a chosen language (in Android’s case it’s Java);
* Finally, we use the generated classes in our project.
We have two ways to decode protobuf messages. The first one is to use a protobuf analyzer and try to recreate the original description of .proto files. The second is to rip out the protoc-generated classes out of Google Play Services, which is what I decided to do.
We take Google Play Services’ .apk file of the same version that’s installed on the device (or, if the device is rooted, just take the file straight from there). Using dex2jar we convert the .dex file back into .jar and open in a decompiler of choice. I personally like JetBrains’ Fernflower. It works as a plugin to IntelliJ IDEA (or Android Studio), so we simply launch Android Studio and open the file with the link we’re trying to analyze. If proguard wasn’t trying too hard, the decompiled Java code for creating protobuf messages could just be copy-pasted into your project.
Looking at the decompiled code, we see that Build.\* constants are being sent inside the protobuf message. (okay, that wasn’t too hard to guess).
```
...
var3.a("4.0.33 (910055-30)");
a(var3, "BOARD", Build.BOARD);
a(var3, "BOOTLOADER", Build.BOOTLOADER);
a(var3, "BRAND", Build.BRAND);
a(var3, "CPU_ABI", Build.CPU_ABI);
a(var3, "CPU_ABI2", Build.CPU_ABI2);
a(var3, "DEVICE", Build.DEVICE);
...
```
But unfortunately, in the server’s reply all protobuf fields turned into alphabet soup after obfuscation. But we can discover what’s in there using an error handler. Here’s how data coming from the server is checked:
```
if (!var7.d()) {
throw new bdf("byteCode");
}
if (!var7.f()) {
throw new bdf("vmUrl");
}
if (!var7.h()) {
throw new bdf("vmChecksum");
}
if (!var7.j()) {
throw new bdf("expiryTimeSecs");
}
```
Apparently, that’s how fields were called before obfuscation: **byteCode**, **vmUrl**, **vmChecksum** and **expiryTimeSecs**. This naming scheme already gives us some ideas.
We combine all the decompiled classes from Google Play Services into a test project, rename them, generate test Build.\* commands and launch (imitating any device we want). If someone wants to do it himself, here’s [the link to my GitHub](https://github.com/amankevich/antiabuse-request).
If the request is correct, the server returns this:
> 00:06:26.761 [main] INFO d.a.response.AntiabuseResponse — byteCode size: 34446
>
> 00:06:26.761 [main] INFO d.a.response.AntiabuseResponse — vmChecksum: C15E93CCFD9EF178293A2334A1C9F9B08F115993
>
> 00:06:26.761 [main] INFO d.a.response.AntiabuseResponse — vmUrl: [www.gstatic.com/droidguard/C15E93CCFD9EF178293A2334A1C9F9B08F115993](https://www.gstatic.com/droidguard/C15E93CCFD9EF178293A2334A1C9F9B08F115993)
>
> 00:06:26.761 [main] INFO d.a.response.AntiabuseResponse — expiryTimeSecs: 10
Step 1 complete. Now let’s see what’s hidden behind the **vmUrl** link.
### Secret APK
The link leads us directly to an .apk file, named after its own SHA-1 hash. It’s rather tiny — only 150KB. And it’s quite justified: if it’s downloaded by every single one of the 2 billion Android devices, that’s 270TB of traffic on Google’s services.

`DroidGuardService` class, being part of Google Play Services, downloads the file onto the device, unpacks it, extracts .dex and uses the `com.google.ccc.abuse.droidguard.DroidGuard` class through reflection. If there’s an error, then `DroidGuardService` switches from DroidGuard back to Droidguasso. But that’s another story entirely.
Essentially, `DroidGuard` class is a simple JNI wrapper around the native .so library. The native library's ABI matches what we sent in the `CPU_ABI` field in the protobuf request: we can ask for armeabi, x86 or even MIPS.
The `DroidGuardService` service itself doesn’t contain any interesting logic for working with the `DroidGuard` class. It simply creates a new instance of `DroidGuard`, sends it the **byteCode** from the protobuf message, calls a public method, which returns a byte array. This array is then sent to the server inside the **droidguard\_result** parameter.
To get a rough idea of what’s going on inside `DroidGuard` we can repeat the logic of `DroidGuardService` (but without downloading the .apk, since we already have the native library). We can take a .dex file from the secret APK, convert it into .jar and then use in our project. The only issue is how the `DroidGuard` class loads the native library. The static initialization block calls the `loadDroidGuardLibrary()` method:
```
static
{
try
{
loadDroidGuardLibrary();
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
```
Then the `loadDroidGuardLibrary()` method reads library.txt (located in the root of the .apk file) and loads the library with that name though the `System.load(String filename)` call. Not very convenient for us, since we’d need to build the .apk in a very specific way to put library.txt and the .so file into its root. It would be much more convenient to keep the .so file in the lib folder and load that through `System.loadLibrary(String libname)`.
It’s not hard to do. We’ll use [smali/baksmali](https://github.com/JesusFreke/smali) — assembler/disassembler for .dex files. After using it, classes.dex turns into a bunch of .smali files. The `com.google.ccc.abuse.droidguard.DroidGuard` class should be modified, so that the static initialization block calls the `System.loadLibrary("droidguard")` method instead of `loadDroidGuardLibrary()`. Smali’s syntax is pretty simple, the new initialization block looks like this:
```
.method static constructor ()V
.locals 1
const-string v0, "droidguard"
invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V
return-void
.end method
```
Then we use backsmali to build it all back into .dex, and then we convert it into .jar. At the end we get a .jar file that we can use in our project — [here it is](https://github.com/amankevich/droidguard-lib-test), by the way.
The entire DroidGuard-related section is a couple of strings long. The most important part is to download the byte array we got in the previous step after addressing the anti-abuse service and hand it off to the `DroidGuard` constructor:
```
private fun runDroidguard() {
var byteCode: ByteArray? = loadBytecode("bytecode.base64");
byteCode?.let {
val droidguard = DroidGuard(applicationContext, "addAccount", it)
val params = mapOf("dg_email" to "test@gmail.com", "dg_gmsCoreVersion" to "910055-30",
"dg_package" to "com.google.android.gms", "dg_androidId" to UUID.randomUUID().toString())
droidguard.init()
val result = droidguard.ss(params)
droidguard.close()
}
}
```
Now we can use Android Studio’s profiler and see what happens during DroidGuard’s work:

The initNative() native method collects data about the device and calls Java methods `hasSystemFeature(), getMemoryInfo(), getPackageInfo()`… that’s something, but I still don’t see any solid logic. Well, all that remains is to disassemble the .so file.
### libdroidguard.so
Fortunately, analyzing the native library isn’t any more difficult that doing it with .dex and .jar files. We’d need an app similar to Hex-Rays IDA and some knowledge of either x86 or ARM assembler code. I chose ARM, since I had a rooted device lying around to debug on. If you don’t have one, you could take an x86 library and debug using an emulator.
An app similar to Hex-Rays IDA decompiles the binary into something resembling C code. If we open the `Java_com_google_ccc_abuse_droidguard_DroidGuard_ssNative` method, we’ll see something like this:
```
__int64 __fastcall Java_com_google_ccc_abuse_droidguard_DroidGuard_initNative(int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9)
...
v14 = (*(_DWORD *)v9 + 684))(v9, a5);
v15 = (*(_DWORD *)v9 + 736))(v9, a5, 0);
...
```
Doesn’t look too promising. First we need to make a couple of preliminary steps to transform that into something more useful. The decompiler doesn’t know anything about JNI, so we install Android NDK and import the jni.h file. As we know, the first two parameters of a JNI method are `JNIEnv*` and `jobject (this)`. We can find out the types of other parameters from DroidGuard’s Java code. After assigning the correct types, meaningless offsets turn into JNI method calls:
```
__int64 __fastcall Java_com_google_ccc_abuse_droidguard_DroidGuard_initNative(_JNIEnv *env, jobject thiz, jobject context, jstring flow, jbyteArray byteCode, jobject runtimeApi, jobject extras, jint loggingFd, int runningInAppSide)
{
...
programLength = _env->functions->GetArrayLength)(_env, byteCode);
programBytes = (jbyte *)_env->functions->GetByteArrayElements)(_env, byteCode, 0);
...
```
If we have enough patience to trace the byte array received from the anti-abuse server, we’ll be… disappointed. Unfortunately, there’s no simple answer to “what’s happening here?”. It’s pure, distilled byte code, and the native library is a virtual machine. Some AES encryption sprinkled on top and then the VM reads the byte code, byte by byte, and executes commands. Every byte is a command followed by operands. There aren’t many commands, only around 70: read int, read byte, read string, call Java method, multiply two numbers, if-goto etc.
### Wake up, Neo
I decided to go even further and figure out the structure of the byte code for this VM. There’s another problem with the calls: sometimes (once every couple weeks) there’s a new version of the native library where byte-command pairs are scrambled. It didn’t stop me and I decided to recreate the VM using Java.
What the byte code does is do all the routine work on collecting info about the device. For example, it loads a string with the name of a method, gets its address through dlsym and executes. In my Java version of the VM I recreated only 5 or so methods and learned to interpret the first 25 commands of the anti-abuse service’s byte code. On the 26th command the VM read another encrypted string from the byte code. It suddenly turned out that it’s not a name of another method. Far from it.
> Virtual Machine command #26
>
> Method invocation vm->vm\_method\_table[2 \* 0x77]
>
> Method vmMethod\_readString
>
> index is 0x9d
>
> string length is 0x0066
>
> (new key is generated)
>
> encoded string bytes are EB 4E E6 DC 34 13 35 4A DD 55 B3 91 33 05 61 04 C0 54 FD 95 2F 18 72 04 C1 55 E1 92 28 11 66 04 DD 4F B3 94 33 04 35 0A C1 4E B2 DB 12 17 79 4F 92 55 FC DB 33 05 35 45 C6 01 F7 89 29 1F 71 43 C7 40 E1 9F 6B 1E 70 48 DE 4E B8 CD 75 44 23 14 85 14 A7 C2 7F 40 26 42 84 17 A2 BB 21 19 7A 43 DE 44 BD 98 29 1B
>
> decoded string bytes are 59 6F 75 27 72 65 20 6E 6F 74 20 6A 75 73 74 20 72 75 6E 6E 69 6E 67 20 73 74 72 69 6E 67 73 20 6F 6E 20 6F 75 72 20 2E 73 6F 21 20 54 61 6C 6B 20 74 6F 20 75 73 20 61 74 20 64 72 6F 69 64 67 75 61 72 64 2D 68 65 6C 6C 6F 2B 36 33 32 36 30 37 35 34 39 39 36 33 66 36 36 31 40 67 6F 6F 67 6C 65 2E 63 6F 6D
>
> decoded string value is (**You're not just running strings on our .so! Talk to us at droidguard@google.com**)
That’s strange. A virtual machine have never talked to me before. I thought that if you start to see secret messages directed to you, you’re going crazy. Just to make sure I was still sane, I ran a couple hundred of different answers from the anti-abuse service through my VM. Literally every 25-30 commands there was a message hidden within the byte code. They often repeated, but below are some unique ones. I edited the email addresses, though: each message had a different address, something like «droidguard+tag@google.com», with the tag being unique for each one.
> droidguard@google.com: Don't be a stranger!
>
> You got in! Talk to us at droidguard@google.com
>
> Greetings from droidguard@google.com intrepid traveller! Say hi!
>
> Was it easy to find this? droidguard@google.com would like to know
>
> The folks at droidguard@google.com would appreciate hearing from you!
>
> What's all this gobbledygook? Ask droidguard@google.com… they'd know!
>
> Hey! Fancy seeing you here. Have you spoken to droidguard@google.com yet?
>
> You're not just running strings on our .so! Talk to us at droidguard@google.com
>
>
Am I the Chosen One? I thought that it was time to stop messing with DroidGuard and talk to Google, since they asked me so.
### Your call is very important to us
I told my findings on the email I found. To make results a little more impressive, I automated the analysis process a little bit. The thing is, strings and byte arrays are stored in the byte code encrypted. The VM decodes them using constants inlined by the compiler. Using an app similar to Hex-Rays IDA you could extract them pretty easily. But with every new version constants change and it’s fairly inconvenient to always extract them manually.
But Java-parsing the native library proved surprisingly simple. Using [jelf](https://github.com/fornwall/jelf) (a library for parsing ELF files) we find the offset of the `Java_com_google_ccc_abuse_droidguard_DroidGuard_initNative` method in the binary, and then using [Capstone](https://github.com/aquynh/capstone) (a disassembling framework with bindings for various languages, including Java) we get assembler code and search it for loading constants into registries.
In the end I got an app that emulated the entire DroidGuard process: makes a request to the anti-abuse service, downloads the .apk, unpacks it, parses the native library, extracts the required constants, picks out the mapping of VM commands and interprets the byte code. I compiled it all and sent it off to Google. While I was at it, I started preparing for a move and searched Glassdoor for an average salary at Google. I decided to not agree to anything less than six figures.
The answer didn’t take long. An email from a member of the DroidGuard team simply read: “Why are you even doing this?”

“Because I can” — I answered. A Google employee explained to me that DroidGuard is supposed to protect Android from hackers (you don’t say!) and it would be wise to keep the source code of my DroidGuard VM to myself. Our conversation ended there.
### Interview
A month later I received another email. The DroidGuard team in Zurich needed a new employee. Was I interested in joining? Of course!
There are no shortcuts to get into Google. All my contact could do was forward my CV to the HR department. After that I had to go through the usual bureaucratic rigmarole and a series of interviews.
There’s a lot of stories out there about Google interviews. Algorithms, Olympiad tasks and Google Docs programming aren’t my thing, so I started my preparations. I read through the “Algorithms” course of Coursera dozens of times, solved hundreds of tasks on Hackerrank and learned to get around a graph in both dimensions with my eyes closed.
Two months went by. To say I felt prepared would be an understatement. Google Docs became my favorite IDE. I felt like I knew everything there is to know about algorithms. Of course, I knew my weaknesses and realized I probably wouldn’t pass the series of 5 interviews in Zurich, but going to the programmer’s Disneyland for free was a reward in and of itself. The first step was a phone interview to weed out the weakest of candidates and not waste times of Zurich developers on in-person meetings. The day was set, the phone rang…

… and I immediately failed my first test. I got lucky — they asked a question I’ve seen on the internet before and have already solved. It was about serializing a string array. I offered to code strings in Base64 and save them through a divider. The interviewer asked me to develop a Base64 algorithm. After that the interview turned into sort of a monologue, where the interviewed explained to me how Base64 works and I tried to remember bit operations in Java.
**If anyone at Google is reading this**Guys, you’re bloody geniuses if you got there! Seriously. I can’t imagine how one can clear all the obstacles they put in front of you.
3 days after the call I got an email saying they don’t want to interview me further. And that’s how my communication with Google ended.
Why there are messages in DroidGuard asking to chat, I still have no idea. Probably just for stats. The guy I wrote to in the first place told me that people actually write there, but the frequency varies: sometimes they get 3 replies in a week, sometimes 1 a year.
I believe there are easier ways to get an interview at Google. After all, you could just ask any of the 100,000 employees (though not all of them are developers, admittedly). But it was a fun experience nonetheless. | https://habr.com/ru/post/446790/ | null | null | 3,471 | 66.84 |
Define map with vector argument(s)
(Is it possible to use LaTeX code here in order to get a nice output?)
Let's say I want to put the map phi: Q^3 x Q^3 -> Q defined by (x,y) -> x1y1 - x2y2 + x3*y3 into Sage. How do I do this? I want to have later for example:
sage: x=vector((1,2,3)); y=vector((2,3,1)) sage: phi(x,y)
Then the output should be the value phi(x,y).
Is it only possible via the
def command (with
x[1] etc.)? Or how can you specify the domain of a map? How would you do this? | https://ask.sagemath.org/question/38049/define-map-with-vector-arguments/ | CC-MAIN-2018-13 | refinedweb | 111 | 83.56 |
.NET Service Bus Reverse Web Proxy: Click here to download the source.:
Visual Studio 2008 SP1 with the .NET Framework 3.5 SP1.
A .NET Services project account. The quickest route is to go to and click “Sign up”. The approval/provisioning is pretty much instantaneous (plus 20 seconds for the provisioning to run through) once you provide your Windows Live ID. No more access codes.
The .NET Services SDK for the March 2009 CTP. Click here to get it.:
1: <?xml version=”1.0″ encoding=”utf-8″ ?>
2: <configuration>
3: <configSections>
4: <section name=“reverseWebProxy”
5: type=“Microsoft.Samples.ServiceBusReverseWebProxy.ReverseWebProxySection, ServiceBusReverseWebProxy” />
6: </configSections>
7: <!– Add your .NET Services project account information here –>
8: <!– Create a project at –>
9: <reverseWebProxy netServicesProjectName=“!!myproject!!” netServicesProjectPassword=“!!mypassword!!”
10: enableSilverlightPolicy=“true”>
11: <pathMappings>
12: <add namespacePath=“mysite” localUri=“” />
13: </pathMappings>
14: </reverseWebProxy>
15: </configuration>:
- If your project name were ‘clemensv6’ and you map some local URI to the namespacePath ‘dasBlog’, the resulting .NET Service Bus URI would be.
- The web application should only emit relative paths for links or, otherwise, should have a way to specify the external host address for links. That means that the web application needs to be able to deal with the presence of a reverse proxy. There is no content-level URL rewriter in this sample that would make any corrections to HTML or XML that’s handed upstream. DasBlog allows you to specify the blog site address as some external address and therefore satisfies that requirements.
- Redirects and any other HTTP responses that emit the HTTP ‘Location’ header or any other HTTP headers where URIs are returned are rewritten to map the internal view to the external view.
- If you set enableSilverlightPolicy to true, there will be crossdomain.xml and ClientPolicyAccess.xml endpoints projected into the root of your project’s namespace, ie..
Thank you for submitting this cool story – Trackback from DotNetShoutout
Я всегда чу,
too many requirements are needed to share something from your kitchen.
at you can share with a click of a button and within seconds have your entire picture or video folder available on the web. As an identity you can use your Facebook ID or create an account.
On Facebook this utility is available at
Roboshare tunnel works through any http proxy, no need for ISA client. And btw, only .NET 2.0 is required.
We’ve got a dead-simple file-sharing tool in the samples that shares out a directory as an Atom feed. No client too required, you just use your browser to navigate and download.
This here is about sharing any HTTP endpoint, not a file folder.
We don’t need ISA Firewall client, either. As of M5 there is a full-duplex HTTP tunnel that snaps into place whenever necessary.
make a simple test. Put an mp3 file in your http endoint hosted in the kitchen. Then go to iPhone and listen to that mp3.
Let me know how it works 🙂
I had this working on,
(see)
but I removed this feature in last release for several reasons:
1. chunked posts and chunked responses don’t work. (same for plain responses which are very long)
2. it makes the website really slow, which is ok for development purposes, but doesn’t make sense at all in production.
3. several forum posts and threads with other website owners made me think nobody wants this.
4. there are other ways people can host websites at home, like dyndns. yet people chose to have a hosting plan with 99.9 uptime.
5. your upload speed in your kitchen will be a killer bottleneck for your website.
Well, from my kitchen I can spool HD video to Starbucks via the Service Bus. I’ve got 15 MBit/s symmetric, which means that my upload speed isn’t an issue.
The Service Bus is for ISVs like you. There’s no competition here. I like your app.
You may have a good upload speed, but usually people don’t have it in their kitchens. Not everyone needs such a high tech kitchen as you do 🙂
I added back support for sharing http endpoints on
Follow the steps at and your website can be live in few minutes. If you work at microsoft, try mapping internal to a public address and see what everyone has to say about your paycheck. 🙂
You are right, there is no competition here. Service Bus is for ISVs, while Roboshare.com is for individuals like you, who spend their entire day configuring and deploying files on machines located in different networks and domains. It is easier to copy files directly with roboshare than use a gateway machine, copy them to a common share, and then from there to a final destination. I used to do this a lot and waste a lot of time on this. That’s why I created Roboshare, to help people share and access their files anywhere in a simple and easy to use manner. | https://blogs.msdn.microsoft.com/clemensv/2009/04/05/net-services-march-2009-ctp-host-a-public-website-at-the-kitchen-table-or-from-a-coffee-shop-no-kidding/ | CC-MAIN-2017-17 | refinedweb | 832 | 74.69 |
What’s New In Python 3.8¶
- Editor
Raymond Hettinger
This article explains the new features in Python 3.8, compared to 3.7. For full details, see the changelog.
New Features¶
Assignment expressions¶¶¶¶¶.)
PEP 590: Vectorcall: a fast calling protocol for CPython¶
The Vectorcall Protocol is added to the Python/C API. It is meant to formalize existing optimizations which were already done for various classes. Any static type implementing a callable can use this protocol.
This is currently provisional. The aim is to make it fully public in Python 3.9.
See PEP 590 for a full description.
(Contributed by Jeroen Demeyer, Mark Shannon and Petr Viktorin in bpo-36974.)
Pickle protocol 5 with out-of-band data buffers¶¶ maggie') ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')
¶¶
ast¶¶¶¶¶
The
cProfile.Profile class can now be used as a context manager.
Profile a block of code by running:
import cProfile with cProfile.Profile() as profiler: # code to be profiled ...
(Contributed by Scott Sanderson in bpo-29235.)
csv¶
The
csv.DictReader now returns instances of
dict instead of
a
collections.OrderedDict. The tool is now faster and uses less
memory while still preserving the field order.
(Contributed by Michael Selik in bpo-34003.)
curses¶
Added a new variable holding structured version information for the
underlying ncurses library:
ncurses_version.
(Contributed by Serhiy Storchaka in bpo-31680.)
ctypes¶¶¶¶
get_objects() can now receive an optional generation parameter
indicating a generation to get objects from.
(Contributed by Pablo Galindo in bpo-36016.)
gettext¶
Added
pgettext() and its variants.
(Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in bpo-2504.)
gzip¶¶.).)
New in 3.8.1:
Add option to toggle cursor blink off. (Contributed by Zackery Spytz in bpo-4603.)
Escape key now closes IDLE completion windows. (Contributed by Johnny Najera in bpo-38944.)
The changes above have been backported to 3.7 maintenance releases.
Add keywords to module name completion list. (Contributed by Terry J. Reedy in bpo-37765.)
inspect¶¶
In development mode (
-X
env) and in debug build, the
io.IOBase finalizer now logs the exception if the
close() method
fails. The exception is ignored silently by default in release build.
(Contributed by Victor Stinner in bpo-18748.)
itertools¶¶
Add option
--json-lines to parse every input line as a separate JSON object.
(Contributed by Weipeng Hong in bpo-31553.)
logging¶¶¶
The
mmap.mmap class now has an
madvise() method to
access the
madvise() system call.
(Contributed by Zackery Spytz in bpo-32941.)
multiprocessing¶
Added new
multiprocessing.shared_memory module.
(Contributed by Davin Potts in bpo-35813.)
On macOS, the spawn start method is now used by default. (Contributed by Victor Stinner in bpo-33725.)
os¶¶
pickle extensions subclassing the C-optimized
Pickler
can now override the pickling logic of functions and classes by defining the
special
reducer_override() method.
(Contributed by Pierre Glaser and Olivier Grisel in bpo-35900.)
plistlib¶
Added new
plistlib.UID and enabled support for reading and writing
NSKeyedArchiver-encoded binary plists.
(Contributed by Jon Janzen in bpo-26707.)
pprint¶¶
py_compile.compile() now supports silent mode.
(Contributed by Joannah Nanjekye in bpo-22640.)
shlex¶
The new
shlex.join() function acts as the inverse of
shlex.split().
(Contributed by Bo Bayles in bpo-32102.)
shutil¶¶.)
The
socket.if_nameindex(),
socket.if_nametoindex(), and
socket.if_indextoname() functions have been implemented on Windows.
(Contributed by Zackery Spytz in bpo-37007.)
ssl¶
Added
post_handshake_auth to enable and
verify_client_post_handshake() to initiate TLS 1.3
post-handshake authentication.
(Contributed by Christian Heimes in bpo-34670.)
statistics¶¶()).
(Contributed by Victor Stinner in bpo-36829.)
tarfile¶¶¶
The
tokenize module now implicitly emits a
NEWLINE token when
provided with input that does not have a trailing new line. This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899.)
tkinter¶¶
Added new clock
CLOCK_UPTIME_RAW for macOS 10.12.
(Contributed by Joannah Nanjekye in bpo-35702.)
typing¶¶¶¶
venv now includes an
Activate.ps1 script on all platforms for
activating virtual environments under PowerShell Core 6.1.
(Contributed by Brett Cannon in bpo-32718.)
weakref¶
The proxy objects returned by
weakref.proxy() now support the matrix
multiplication operators
@ and
@= in addition to the other
numeric operators. (Contributed by Mark Dickinson in bpo-36669.)
xml¶¶¶¶¶
gettextmodule:
lgettext(),
ldgettext(),
lngettext()and
ldngettext(). They return encoded bytes, and it’s possible that you will get unexpected Unicode-related exceptions if there are encoding problems with the translated strings. It’s much better to use alternatives which return Unicode strings in Python 3. These functions have been broken for a long time.
Function
bind_textdomain_codeset(), methods
output_charset()and
set_output_charset(), and the codeset parameter of functions
translation()and
install()are also deprecated, since they are only used for the
l*gettext()functions. (Contributed by Serhiy Storchaka in bpo-33710.)
The
isAlive()method of
threading.Threadhas been deprecated. (Contributed by Dong-hee Na in bpo-35283.)
Many builtin and extension functions that take integer arguments will now emit a deprecation warning for
Decimals,
Fractions and any other objects that can be converted to integers only with a loss (e.g. that have the
__int__()method but do not have the
__index__()method). In future version they will be errors. (Contributed by Serhiy Storchaka in bpo-36048.)
Deprecated passing the following arguments as keyword arguments:
func in
functools.partialmethod(),
weakref.finalize(),
profile.Profile.runcall(),
cProfile.Profile.runcall(),
bdb.Bdb.runcall(),
trace.Trace.runfunc()and
curses.wrapper().
function in
unittest.TestCase.addCleanup().
fn in the
submit()method of
concurrent.futures.ThreadPoolExecutorand
concurrent.futures.ProcessPoolExecutor.
callback in
contextlib.ExitStack.callback(),
contextlib.AsyncExitStack.callback()and
contextlib.AsyncExitStack.push_async_callback().
c and typeid in the
create()method of
multiprocessing.managers.Serverand
multiprocessing.managers.SharedMemoryServer.
obj in
weakref.finalize().
In future releases of Python, they will be positional-only. (Contributed by Serhiy Storchaka in bpo-36492.)
API and Feature Removals¶
The following features and APIs have been removed from Python 3.8:
Starting with Python 3.3, importing ABCs from
collectionswas deprecated, and importing should be done from
collections.abc. Being able to import from collections was marked for removal in 3.8, but has been delayed to 3.9. (See bpo-36952.)
The
macpathmodule, deprecated in Python 3.7, has been removed. (Contributed by Victor Stinner in bpo-35471.)
The function
platform.popen()has been removed, after having been deprecated since Python 3.3: use
os.popen()instead. (Contributed by Victor Stinner in bpo-35345.)
The function
time.clock()has been removed, after having been deprecated since Python 3.3: use
time.perf_counter()or
time.process_time()instead, depending on your requirements, to have well-defined behavior. (Contributed by Matthias Bussonnier in bpo-36895.) the
cgimodule. They are deprecated in Python 3.2 or older. They should be imported from the
urllib.parseand
htmlmodules instead.
filemodefunction is removed from the
tarfilemodule. It is not documented and deprecated since Python 3.3.
The
XMLParserconstructor no longer accepts the html argument. It never had an.)
“unicode_internal” codec is removed. (Contributed by Inada Naoki in bpo-36297.)
The
Cacheand
Statementobjects of the
sqlite3module are not exposed to the user. (Contributed by Aviv Palivoda in bpo-30262.)
The
bufsizekeyword argument of
fileinput.input()and
fileinput.FileInput()which was ignored and deprecated since Python 3.6 has been removed. bpo-36952 (Contributed by Matthias Bussonnier.)
The functions
sys.set_coroutine_wrapper()and
sys.get_coroutine_wrapper()deprecated in Python 3.7 have been removed; bpo-36933 (Contributed by Matthias Bussonnier.)
Porting to Python 3.8¶
This section lists previously described changes and other bugfixes that may require changes to your code.
Changes in Python behavior¶
Yield expressions (both
yieldand
yield fromclauses) are now disallowed in comprehensions and generator expressions (aside from the iterable expression in the leftmost
forclause). (Contributed by Serhiy Storchaka in bpo-10544.).)
The CPython interpreter can swallow exceptions in some circumstances. In Python 3.8 this happens in fewer cases. In particular, exceptions raised when getting the attribute from the type dictionary are no longer ignored. (Contributed by Serhiy Storchaka in bpo-35459.)
Removed
__str__implementations from builtin types
bool,
int,
float,
complexand few classes from the standard library. They now inherit
__str__()from
object. As result, defining the
__repr__()method in the subclass of these classes will affect their string representation. (Contributed by Serhiy Storchaka in bpo-36793.)
On AIX,
sys.platformdoesn’t contain the major version anymore. It is always
'aix', instead of
'aix3'..
'aix7'. Since older Python versions include the version number, so it is recommended to always use
sys.platform.startswith('aix'). (Contributed by M. Felt in bpo-36588.)
PyEval_AcquireLock()and
PyEval_AcquireThread()now terminate the current thread if called while the interpreter is finalizing, making them consistent with
PyEval_RestoreThread(),
Py_END_ALLOW_THREADS(), and
PyGILState_Ensure(). If this behavior is not desired, guard the call by checking
_Py_IsFinalizing()or
sys.is_finalizing(). (Contributed by Joannah Nanjekye in bpo-36475.)
Changes in the Python API¶
The
os.getcwdb()function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows. (Contributed by Victor Stinner in bpo-37412.)
subprocess.Popencan now use
os.posix_spawn()in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, the
Popenconstructor using
os.posix_spawn()no longer raises an exception on errors like “missing program”. Instead the child process fails with a non-zero
returncode. (Contributed by Joannah Nanjekye and Victor Stinner in bpo-35537.)
The preexec_fn argument of *
subprocess.Popenis no longer compatible with subinterpreters. The use of the parameter in a subinterpreter now raises
RuntimeError. (Contributed by Eric Snow in bpo-34651, modified by Christian Heimes in bpo-37951.)
The
imap.IMAP4.logout()method no longer silently ignores arbitrary exceptions. (Contributed by Victor Stinner in bpo-36348.)
The function
platform.popen()has been removed, after having been deprecated since Python 3.3: use
os.popen()instead. (Contributed by Victor Stinner in bpo-35345.)
The
statistics.mode()function no longer raises an exception when given multimodal data. Instead, it returns the first mode encountered in the input data. (Contributed by Raymond Hettinger in bpo-35892.).)
The
writexml(),
toxml()and
toprettyxml()methods of
xml.dom.minidom, and the
write()method of
xml.etree, now preserve the attribute order specified by the user. (Contributed by Diego Rojas and Raymond Hettinger in bpo-34160.) emit.
The
PyGC_Headstruct has changed completely. All code that touched the struct member should be rewritten. (See bpo-33597.)
The
PyInterpreterStatestruct has been moved into the “internal” header files (specifically Include/internal/pycore_pystate.h). An opaque
PyInterpreterStateis still available as part of the public API (and stable ABI). The docs indicate that none of the struct’s fields are public, so we hope no one has been using them. However, if you do rely on one or more of those private fields and have no alternative then please open a BPO issue. We’ll work on helping you adjust (possibly including adding accessor functions to the public API). (See bpo-35886.)
The
mmap.flush()method now returns
Noneon success and raises an exception on error under all platforms. Previously, its behavior was platform-dependent: a nonzero value was returned on success; zero was returned on error under Windows. A zero value was returned on success; an exception was raised on error under Unix. (Contributed by Berker Peksag in bpo-2122.)
xml.dom.minidomand
xml.saxmodules no longer process external entities by default. (Contributed by Christian Heimes in bpo-17239.)
Deleting a key from a read-only
dbmdatabase (
dbm.dumb,
dbm.gnuor
dbm.ndbm) raises
error(
dbm.dumb.error,
dbm.gnu.erroror
dbm.ndbm.error) instead of
KeyError. (Contributed by Xiang Zhang in bpo-33106.)
Simplified AST for literals. All constants will be represented as
ast.Constantinstances. Instantiating old classes
Num,
Str,
Bytes,
NameConstantand
Ellipsiswill return an instance of
Constant. (Contributed by Serhiy Storchaka in bpo-32892.)
expanduser()on Windows now prefers the
USERPROFILEenvironment variable and does not use
HOME, which is not normally set for regular user accounts. (Contributed by Anthony Sottile in bpo-36264.)
The exception
asyncio.CancelledErrornow inherits from
BaseExceptionrather than
Exceptionand no longer inherits from
concurrent.futures.CancelledError. (Contributed by Yury Selivanov in bpo-32528.)
The function
asyncio.wait_for()now correctly waits for cancellation when using an instance of
asyncio.Task. Previously, upon reaching timeout, it was cancelled and immediately returned. (Contributed by Elvis Pranskevichus in bpo-32751.)
The function
asyncio.BaseTransport.get_extra_info()now returns a safe to use socket object when ‘socket’ is passed to the name parameter. (Contributed by Yury Selivanov in bpo-37027.)
asyncio.BufferedProtocolhas graduated to the stable API.
DLL dependencies for extension modules and DLLs loaded with
ctypeson Windows are now resolved more securely. Only the system paths, the directory containing the DLL or PYD file, and directories added with
add_dll_directory()are searched for load-time dependencies. Specifically,
PATHand the current working directory are no longer used, and modifications to these will no longer have any effect on normal DLL resolution. If your application relies on these mechanisms, you should check for
add_dll_directory()and if it exists, use it to add your DLLs directory while loading your library. Note that Windows 7 users will need to ensure that Windows Update KB2533623 has been installed (this is also verified by the installer). (Contributed by Steve Dower in bpo-36085.)
The header files and functions related to pgen have been removed after its replacement by a pure Python implementation. (Contributed by Pablo Galindo in bpo-36623.)
types.CodeTypehas a new parameter in the second position of the constructor (posonlyargcount) to support positional-only arguments defined in PEP 570. The first argument (argcount) now represents the total number of positional arguments (including positional-only arguments). The new
replace()method of
types.CodeTypecan be used to make the code future-proof.
Changes in the C API¶
The
PyCompilerFlagsstructure got a new cf_feature_version field. It should be initialized to
PY_MINOR_VERSION. The field is ignored by default, and is used if and only if
PyCF_ONLY_ASTflag is set in cf_flags. (Contributed by Guido van Rossum in bpo-35766.)
The
PyEval_ReInitThreads()function has been removed from the C API. It should not be called explicitly: use
PyOS_AfterFork_Child()instead. (Contributed by Victor Stinner in bpo-36728.)
On Unix, C extensions are no longer linked to libpython except on Android and Cygwin. When Python is embedded,
libpythonmust not be loaded with
RTLD_LOCAL, but
RTLD_GLOBALinstead. Previously, using
RTLD_LOCAL, it was already not possible to load C extensions which were not linked to
libpython, like C extensions of the standard library built by the
*shared*section of
Modules/Setup. (Contributed by Victor Stinner in bpo-21536.)
Use of
#variants of formats in parsing or building value (e.g.
PyArg_ParseTuple(),
Py_BuildValue(),
PyObject_CallFunction(), etc.) without
PY_SSIZE_T_CLEANdefined raises
DeprecationWarningnow. It will be removed in 3.10 or 4.0. Read Parsing arguments and building values for detail. (Contributed by Inada Naoki in bpo-36381.)
Instances of heap-allocated types (such as those created with
PyType_FromSpec()) hold a reference to their type object. Increasing the reference count of these type objects has been moved from
PyType_GenericAlloc()to the more low-level functions,
PyObject_Init()and
PyObject_INIT(). This makes types created through
PyType_FromSpec()behave like other classes in managed code.
Statically allocated types are not affected.
For the vast majority of cases, there should be no side effect. However, types that manually increase the reference count after allocating an instance (perhaps to work around the bug) may now become immortal. To avoid this, these classes need to call Py_DECREF on the type object during instance deallocation.
To correctly port these types into 3.8, please apply the following changes:
Remove
Py_INCREFon the type object after allocating an instance - if any. This may happen after calling
PyObject_New(),
PyObject_NewVar(),
PyObject_GC_New(),
PyObject_GC_NewVar(), or any other custom allocator that uses
PyObject_Init()or
PyObject_INIT().
Example:
static foo_struct * foo_new(PyObject *type) { foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type); if (foo == NULL) return NULL; #if PY_VERSION_HEX < 0x03080000 // Workaround for Python issue 35810; no longer necessary in Python 3.8 PY_INCREF(type) #endif return foo; }
Ensure that all custom
tp_deallocfunctions of heap-allocated types decrease the type’s reference count.
Example:
static void foo_dealloc(foo_struct *instance) { PyObject *type = Py_TYPE(instance); PyObject_GC_Del(instance); #if PY_VERSION_HEX >= 0x03080000 // This was not needed before Python 3.8 (Python issue 35810) Py_DECREF(type); #endif }
(Contributed by Eddie Elizondo in bpo-35810.)
The
Py_DEPRECATED()macro has been implemented for MSVC. The macro now must be placed before the symbol name.
Example:
Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
(Contributed by Zackery Spytz in bpo-33407.)
The interpreter does not pretend to support binary compatibility of extension types across feature releases, anymore. A
PyTypeObjectexported by a third-party extension module is supposed to have all the slots expected in the current Python version, including
tp_finalize(
Py_TPFLAGS_HAVE_FINALIZEis not checked anymore before reading
tp_finalize).
(Contributed by Antoine Pitrou in bpo-32388.)
The functions
PyNode_AddChild()and
PyParser_AddToken()now accept two additional
intarguments end_lineno and end_col_offset.
The
libpython38.afile to allow MinGW tools to link directly against
python38.dllis no longer included in the regular Windows distribution. If you require this file, it may be generated with the
gendefand
dlltooltools, which are part of the MinGW binutils package:
gendef - python38.dll > tmp.def dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a
The location of an installed
pythonXY.dllwill depend on the installation options and the version and language of Windows. See Using Python on Windows for more information. The resulting library should be placed in the same directory as
pythonXY.lib, which is generally the
libsdirectory under your Python installation.
(Contributed by Steve Dower in bpo-37351.).)
The
MAP_ADDnow expects the value as the first element in the stack and the key as the second element. This change was made so the key is always evaluated before the value in dictionary comprehensions, as proposed by PEP 572. (Contributed by Jörn Heissler in bpo-35224.)
Demos and Tools¶
Added a benchmark script for timing various ways to access variables:
Tools/scripts/var_access_benchmark.py.
(Contributed by Raymond Hettinger in bpo-35884.)
Here’s a summary of performance improvements since Python 3.3:
Python version 3.3 3.4 3.5 3.6 3.7 3.8 -------------- --- --- --- --- --- --- Variable and attribute read access: read_local 4.0 7.1 7.1 5.4 5.1 3.9 read_nonlocal 5.3 7.1 8.1 5.8 5.4 4.4 read_global 13.3 15.5 19.0 14.3 13.6 7.6 read_builtin 20.0 21.1 21.6 18.5 19.0 7.5 read_classvar_from_class 20.5 25.6 26.5 20.7 19.5 18.4 read_classvar_from_instance 18.5 22.8 23.5 18.8 17.1 16.4 read_instancevar 26.8 32.4 33.1 28.0 26.3 25.4 read_instancevar_slots 23.7 27.8 31.3 20.8 20.8 20.2 read_namedtuple 68.5 73.8 57.5 45.0 46.8 18.4 read_boundmethod 29.8 37.6 37.9 29.6 26.9 27.7 Variable and attribute write access: write_local 4.6 8.7 9.3 5.5 5.3 4.3 write_nonlocal 7.3 10.5 11.1 5.6 5.5 4.7 write_global 15.9 19.7 21.2 18.0 18.0 15.8 write_classvar 81.9 92.9 96.0 104.6 102.1 39.2 write_instancevar 36.4 44.6 45.8 40.0 38.9 35.5 write_instancevar_slots 28.7 35.6 36.1 27.3 26.6 25.7 Data structure read access: read_list 19.2 24.2 24.5 20.8 20.8 19.0 read_deque 19.9 24.7 25.5 20.2 20.6 19.8 read_dict 19.7 24.3 25.7 22.3 23.0 21.0 read_strdict 17.9 22.6 24.3 19.5 21.2 18.9 Data structure write access: write_list 21.2 27.1 28.5 22.5 21.6 20.0 write_deque 23.8 28.7 30.1 22.7 21.8 23.5 write_dict 25.9 31.4 33.3 29.3 29.2 24.7 write_strdict 22.9 28.4 29.9 27.5 25.2 23.1 Stack (or queue) operations: list_append_pop 144.2 93.4 112.7 75.4 74.2 50.8 deque_append_pop 30.4 43.5 57.0 49.4 49.2 42.5 deque_append_popleft 30.8 43.7 57.3 49.7 49.7 42.8 Timing loop: loop_overhead 0.3 0.5 0.6 0.4 0.3 0.3
The benchmarks were measured on an Intel® Core™ i7-4960HQ processor running the macOS 64-bit builds found at python.org. The benchmark script displays timings in nanoseconds.
Notable changes in Python 3.8.1.8.8.)
Notable changes in Python 3.8.12¶
Starting with Python 3.8.12 the
ipaddress module no longer accepts
any leading zeros in IPv4 address strings. Leading zeros are ambiguous and
interpreted as octal notation by some libraries. For example the legacy
function
socket.inet_aton() treats leading zeros as octal notation.
glibc implementation of modern
inet_pton() does not accept
any leading zeros.
(Originally contributed by Christian Heimes in bpo-36384, and backported to 3.8 by Achraf Merzouki.) | https://docs.python.org/3/whatsnew/3.8.html | CC-MAIN-2021-39 | refinedweb | 3,506 | 53.68 |
More on Custom Ant Tasks
This article is a continuation of the article " Introduction to Custom Ant Tasks." Reading through the previous article is highly recommended because I am just going to pick up where I left off last time. For this reason, my examples in this article will start numbering at five (5). I am assuming you have a moderate level of experience with Ant on your platform-of-choice. (I use Windows 2000 during the day and Mac OS X when I'm at home.) Also, my code examples use some of the newer Java syntax bits such as enhanced-for and generics.
I left off in the first article just shy of mentioning nested elements. My reason for deferring the topic was that I wanted enough material and explanations to be valuable. However, before we get into the actual mechanics of nested elements, let's take a moment to cover custom types.
Topics in this article
- Types versus Tasks
- Custom Condition Types
- Handling Specific Nested Types
- Handling Arbitrary Nested Types
- Task with Nested Tasks
- Nesting Tasks and Conditions
- Custom Selectors
- XML Namespaces
Types versus Tasks
Types are anything that lack an execute() method. This means that Ant will not attempt to call the execute() method when it encounters them. Instead, the parent element will interact with the type via some appropriate method calls which are entirely up to the developer to provide. This being the case, types serve as auxillary helpers for other tasks, usually as nested child elements. You may note that Ant does provide the org.apache.tools.ant.types.DataType class from which many of Ant's own types derive. However, it is perfectly fine for your own tasks to (implicitly) derive directly from java.lang.Object. (Also, although I have yet to personally verify this, I suspect a publicly accessible inner class might also work, provided the typedef is correctly set.)
Ant maintains a distinction between tasks and types to the point that you declare types with a typedef task instead of a taskdef task. For the sake of the example, this means you will list your custom types in a second properties file.
Aside from the setter methods to support attributes in the build file, other methods you provide are at your discretion. Indeed, the whole reason for the type to exist might be limited to the support of exactly one other task or type, or it might be a more generic and flexible type that you use across multiple tasks or types. Ant, for example, has the fairly specific arg element underneath the exec task and the fairly generic fileset element which is supported throughout many Ant tasks which need to deal with files. There are even a few special-purpose categories of types in Ant, the condition type (not to be confused with the <condition> task itself which contains nested condition types) being notable.
Custom Condition Types
Ant has a task called condition, but the various elements which nest underneath it are condition types. Some examples familiar to Ant script writers include isset (for properties) and available (for files and resources) as well as the logicals and and or and the negation not. It may happen that you need some logic to happen based on a condition which is either exceedingly cumbersome to write with the standard condition types, or which is just not possible. Writing a custom condition type is almost identical to writing a custom task:
- Implement org.apache.tools.ant.taskdef.condition.Condition interface
- Implement public boolean eval() method
- Provide standard instance variables and setter methods for attribute support, if needed
Remember when I said the parent element interacts with a type element via some appropriate method? For a condition type, this is the role of the eval() method which returns a boolean value.
Now, once your Java source code is written, create a properties file to map your Java class to an Ant element name. Do not list your custom type in the same properties file you are using for custom tasks; they need to be referenced by separate typedef and taskdef task statements, respectively.
Example 5: A Numerical "Greater Than" Condition
The standard conditions do not support checking numerical-based comparisons such as greater than, less than, or equal to. This is how a numerical greater than condition would work:
//NumGreaterThanCondition.java package org.roblybarger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.condition.Condition; public class NumGreaterThan implements Condition { private double arg1; private double arg2; public double getArg1() { return arg1; } public void setArg1(double arg1) { this.arg1 = arg1; } public double getArg2() { return arg2; } public void setArg2(double arg2) { this.arg2 = arg2; } public boolean eval() throws BuildException { return (arg1>arg2); } }
Create MyAntTypes.properties (if necessary) and add this entry:
numgt=org.roblybarger.NumGreaterThanConditionUpdate your jar file, and then use an Ant script similar to this to put the custom condition to use:
<project name="ex5" default="demo" basedir="."> <typedef resource="MyAntTypes.properties" classpath="myant.jar"/> <target name="demo"> <property name="valueA" value="10.34"/> <property name="valueB" value="9.52"/> <fail message="${valueA} is NOT greater than ${valueB}"> <condition> <not> <numgt arg1="${valueA}" arg2="${valueB}"/> </not> </condition> </fail> <echo message="valueA is greater than valueB"/> </target> </project>
Something like this might be useful if you wanted to verify that you have sufficient disk space before attempting to copy a large file. (The OS-specific details of computing available disk space are left as an exercise to the reader.) You also might employ custom conditions elsewhere to perform sanity checks or enforce business logic rules at various places in your build. Providing a collection of small, focused conditions is better than one monolithic condition: The smaller condition types can be reused more easily, and overall maintenance is reduced to minor updates your ant script should your business rules change slightly.
Page 1 of 4
| http://www.developer.com/lang/article.php/3636196/More-on-Custom-Ant-Tasks.htm | CC-MAIN-2014-10 | refinedweb | 982 | 51.99 |
Fred is a member of the Intelligent Systems Division at NIST. He can be contacted at frederick.proctor@nist.gov.
When dealing with real-time systems, the overhead of interprocess communications (IPC) becomes important. The formalized structures that are used in Linux for IPC can carry with them a significant amount of overhead. This can create timing problems for your applications. In this article, I'll examine two of the best IPC mechanisms available under Linux -- FIFOs and shared memory.
Communication between Linux and Real-Time Linux (RT-Linux) processes is usually accomplished via first-in-first-out (FIFO) connections -- point-to-point queues of serial data analogous to UNIX character devices. FIFOs have the following characteristics:
- FIFOs queue data, so no protocol is required to prevent data overwrites.
- Boundaries between successive data writes are not maintained.
- Applications must detect boundaries between data, particularly if data is of varying size.
- FIFOs support blocking for synchronization. Processes need not poll for the arrival of data.
- FIFOs are a point-to-point communication channel. FIFOs do not support the one writer/several readers model.
You declare the maximum number of FIFOs in rt_fifo_new.c as #define RTF_NO 64. These appear as devices dev/rtf0..63 in the filesystem. This limit can be changed and the rt_fifo_new.o module recompiled. There is no limit to the number of FIFOs an application can use, or to the size of data that can be written to a FIFO (within practical memory limits).
An alternative to FIFOs is shared memory, in which a portion of physical memory is set aside for sharing between Linux and real-time processes. In a nutshell, shared memory is a pool of memory segments reserved at boot time. These segments may be mapped into the address space of more than one application, allowing for fast data sharing, data updates, and handshaking. This allows for low-latency parallel updates.
Shared memory has the following characteristics:
- It does not queue data written to it. Applications requiring handshaking must define a protocol to assure data is not overwritten.
- Because data is not queued, individual items in data structures (megabytes in size) can be quickly updated.
- It has no point-to-point restriction. Shared memory can be written or read by any number of Linux or real-time processes.
- The number of independent shared memory channels is limited only by the size of physical memory.
- Blocking for synchronization is not directly supported. To determine if data is new, the data must contain a count that can be compared against previous reads.
- Mutual exclusion of Linux and RT-Linux processes is not guaranteed. Interrupted reads and writes can be detected, however.
Whether you use FIFOs or shared memory depends on the application's natural communication model. For control applications involving processes that execute cyclically based on the expiration of an interval timer (where data queuing is the exception rather than the rule), shared memory is a good choice for communication.
Setting up the Shared-Memory Pool
The shared-memory pool is a block of physical memory set aside at boot time so that Linux does not use it for processes. To set up the pool, you first determine how much physical memory the system has and how much is to be used for shared memory. Subtracting the size of the shared memory desired from the size of physical memory gives the absolute base address of the pool. The result is passed to the Linux boot loader (LILO) at boot time. This is accomplished by editing /etc/lilo.conf and inserting a line with the append keyword.
Suppose, for example, the system has 32 MB of memory and 1 MB is to be used for the shared-memory pool. The base address for shared memory is 32 MB-1 MB=31 MB. Assuming the original /etc/lilo.conf file contained Example 1(a), the file should be modified like Example 1(b).
Similarly, suppose the system has 16 MB of memory and 512 KB are to be used for the shared-memory pool. The base address for shared memory is 16384 KB-512 KB=15872 KB. The /etc/lilo.conf file should be modified like Example 1(c).
The size of the shared-memory pool must be less than the page size declared in /usr/include/asm/param.h. In Intel Pentium-class machines and above, the page size is 4 MB; on earlier machines, the page size is 1 MB.
Addressing the Shared-Memory Pool in C Programs
The base address of the shared-memory pool needs to be declared in C so that both Linux and RT-Linux code can reference it. For example, you can access shared memory based at 31 MB using the C statement #define BASE_ADDRESS (31 * 0x100000). Similarly, shared memory based at 15872 KB may be accessed using the C statement #define BASE_ADDRESS (15872 * 0x400). This address is used differently in Linux than in RT-Linux. Linux processes need to map this physical address into their virtual address space. RT-Linux processes can reference data located at this address as a pointer directly.
In addition to this declaration, the Linux and RT-Linux C code must agree on the data structures written into shared memory. In Listing One, for example, a Linux process sends a command to an RT-Linux process by filling in the MY_COMMAND structure and writing it into shared memory. The RT-Linux process reads this structure from shared memory to get the command. An RT-Linux process sends status to a Linux process by filling in the MY_STATUS structure and writing it into shared memory. The Linux process reads this structure from shared memory to get the status.
The MY_STRUCT structure is a combination of both the command and status structure, and can be used to ensure that the two structures do not overlap and that their fields are aligned on the proper boundaries. It is also possible to define two base addresses -- one for each structure -- making sure the start of one structure is after the end of the previous one and that all fields are properly aligned. By combining them into a single aggregate structure and letting the compiler allocate storage, the structure will have a valid byte alignment automatically.
In a typical application, the BASE_ADDRESS declaration and shared-structure declarations would be put in a header file shared by both Linux and RT-Linux code.
Accessing the Shared-Memory Pool from Processes other than RT-Linux
Normal Linux processes are required to map physical memory into their private address space to access it. To do this, the Linux processes calls open() on the memory device /dev/mem; see Example 2.
Due to security concerns, the default permissions on /dev/mem allow only root processes to read or write /dev/mem. To access physical memory, the program must be run as root, its permissions must be changed to setuid root, or the permissions on /dev/mem must be changed to allow access to users other than root.
After the file descriptor is opened, the Linux process maps the shared memory into its address space using mmap(); see Listing Two. BASE_ADDRESS is passed to mmap(), which returns a pointer to the shared memory as mapped into the Linux process's address space. Once the shared memory is mapped, it may be accessed by dereferencing the pointer, as in Example 3(a). When the process terminates, you use munmap() to unmap the shared memory by passing the pointer and the size of its object; see Example 3(b).
Accessing the Shared-Memory Pool from RT-Linux
Shared-memory access is much easier in RT-Linux since the real-time code executes in kernel space and thus is not required to map physical addresses to virtual addresses. In Linux kernels 2.0.XX, the pointer can be set directly; see Example 4(a). In Linux kernels 2.1.XX, the pointer needs to be mapped via a call to the __va() macro defined in /usr/include/asm/page.h, as in Example 4(b).
Detecting New Writes
FIFOs have an advantage over shared memory in that reads and writes follow standard UNIX conventions. Processes other than RT-Linux processes can use write() to queue data onto a FIFO, and read() returns the number of characters read. Zero characters read from a FIFO means no new data was written since the last read. On the RT-Linux side, a handler is associated with a FIFO that is invoked after a nonreal-time Linux process writes to the FIFO. Normally the handler calls rtf_get() to dequeue the data from the FIFO.
These functions are not necessary with shared memory. Reads and writes are accomplished by reading and writing directly to pointers. Consequently, the operating system provides no way to detect if the contents of shared memory have been updated. You need to set up this handshaking explicitly.
One way to do this is to use message identifiers that are incremented for each new message. The receiver then polls the shared-memory buffer and compares the current identifier with the previous one. If they are different, a new message has been written. Handshaking to prevent message overrun is implemented by echoing message identifiers in the status structure once they have been received. New messages are not sent until the status echoes the message identifier.
This presumes a time-cyclic polling model on the part of both the Linux and RT-Linux processes. If this is not the natural model for the application, then shared memory may not be a good choice for communication. If shared memory is required for other reasons, and polling is not desirable, other synchronization between Linux and RT-Linux processes can be used. For example, RT-Linux FIFOs can be used only for their synchronization properties. A byte written to a FIFO can be used to wake up a Linux process blocked on a read, or to call the handler in an RT process.
Realizing Mutual Exclusion
It is possible (and therefore a certainty) for a Linux process to be interrupted by a real-time process while in the middle of a read/write to memory they are sharing. If the Linux process is interrupted during a read, the Linux process sees stale data at the beginning and fresh data at the end. If the Linux process is interrupted during a write, the real-time process sees fresh data at the beginning but stale data at the end. Both problems are fatal in general.
The problem of ensuring consistency of data shared between two processes is the subject of operating-systems research, and general solutions exist (see, for instance, An Introduction to Operating Systems, Second Edition, by Harvey M. Dietel, Addison-Wesley, 1990). Our problem is simpler because only the Linux process can be interrupted. In no case can a Linux process interrupt a real-time process during the execution of its task code.
This simplification means that an inuse flag can be used by the Linux process to signal that it is accessing the shared memory. You declare the inuse flag at the beginning of the shared-memory structure, and it is set by the Linux process when it wants to read or write and cleared when the Linux process is finished. The real-time process checks the inuse flag before it accesses shared memory; if set, the process defers the read or write action until it detects that the flag is cleared.
This may lead to the indefinite postponement of the real-time process, if the following conditions are true:
-
- The real-time process runs at the period of the Linux process, or at multiples of this period.
- The accesses are synchronized so that the real-time process always interrupts the Linux process during the critical section when it has set the inuse flag.
The first condition implies that the real-time code is running as slow or slower than the Linux code, and the second implies that the Linux code is running as deterministically as the real-time code. Neither is typically true, and both are rarely true at the same time. If these conditions are true for a system, successive deferrals can be detected by the real-time code and can trigger actions to keep the system under control.
Listing Three illustrates the application of the inuse flag for commands written by the Linux process to the real-time process, and status written by the real-time process and read by the Linux process. Assume that command_ptr has been set up in a Linux process to point to the shared-memory area for commands to the real-time process. To write to shared memory, you must compose the command, set the inuse flag in shared memory directly, write the command, and reset the inuse flag; see Listing Four.
Assuming that the real-time code has set command_ptr to point to the shared memory for commands, it would read commands as in Listing Five. To read status information, the Linux process sets the inuse flag before copying out the data. Assuming that status_ptr has been set up in a Linux process to point to the shared-memory area for status from the real-time process, this would look like Listing Six.
When writing status, the real-time process checks for the inuse flag and defers a status write if it is set. Assuming that the real-time code has set status_ptr to point to the shared memory for status, this would look like Listing Seven.
Queuing Data in Shared Memory Using Ring Buffers
While shared memory is most naturally suited for communications in which data overwrites the previous contents, queuing can be set up using ring buffers. Ring buffers queue 0 or more instances of a data structure, up to a predetermined maximum.
To illustrate the use of ring buffers, consider a system that queues error messages. Errors are declared as strings of a fixed maximum length, and there is a fixed maximum number of errors that can be queued. This is implemented as a two-dimensional array, as in Listing Eight.
Supplementing the actual list of errors are indices to the start and end of the queue, which wrap around from the end of the shared-memory area to the beginning (hence the name "ring buffer"), and a count of the errors queued. As previously described, an inuse flag is also declared to signal that a Linux process is accessing the ring buffer to prevent data inconsistencies in the event a real-time process interrupts Linux process access. The full shared-memory structure declaration is then Listing Nine.
Both Linux and RT-Linux use the same access functions. However, Linux processes need to set the inuse flag before getting an error off the ring, and real-time processes need to check the inuse flag and defer access until the flag is zero. Assuming that errlog is a pointer to the shared-memory area for both Linux and real-time processes, the access functions look like Listing Ten.
For Linux, getting an error off the ring buffer is accomplished by Listing Eleven. For an RT process, writing an error to the ring looks like Listing Twelve.
Sample Code
I've included a sample application that illustrates Linux to real-time commands, real time to Linux status, and real time to Linux error logging.
The application consists of two parts. The first is a real-time process that runs cyclically, reads a command buffer, continually updates a status buffer, and logs some diagnostic messages to the queued error buffer. The second part is a command-line Linux program that handles a few keyboard commands for sending commands and printing the real-time process status and error log.
This application is available electronically; see "Resource Center," page 5. The application is provided as a ZIP file and a gzipped tar file (shmex.tgz). Unpack and compile with:
tar xzvf shmex.tgz
make
You have to set up Linux to boot with shared memory set aside, as detailed previously.
Acknowledgments
Thanks to Rich Bowser, bowser@luz.cs .nmt.edu, for information on the 4-MB memory chunking and the problems with 486 systems; Albert D. Cahalan, acahalan@ cs.uml.edu, for help with memory page and mmap() information; and Daniele Lugli, danlugli@tin.it, for review and comments.
DDJ
Listing One
typedef struct { unsigned char inuse; /* more on this later */ int command; int command_number; int arg1; int arg2; } MY_COMMAND; typedef struct { unsigned char inuse; /* more on this later */ int command_echo; int command_number_echo; int stat1; int stat2; } MY_STATUS; typedef struct { MY_COMMAND command; MY_STATUS status; } MY_STRUCT;
Listing Two
#include <stdlib.h> /* sizeof() */ #include <sys/mman.h> /* mmap(), PROT_READ, MAP_FILE */ #define MAP_FAILED ((void *) -1) /* omitted from Linux mman.h */ #include "myheader.h" MY_STRUCT *ptr; ptr = (MY_STRUCT *) mmap(0, sizeof(MY_STRUCT), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, BASE_ADDRESS); if (MAP_FAILED == ptr) { /* handle error here */ } close(fd); /* fd no longer needed */
Listing Three
typedef struct { unsigned char inuse; int command; int command_number; int arg1; int arg2; } MY_COMMAND; typedef struct { unsigned char inuse; int command_echo; int command_number_echo; int stat1; int stat2; } MY_STATUS;
Listing Four
MY_COMMAND my_command; /* compose command in local structure */ my_command.inuse = 1; /* will overwrite during copy, so set here too */ my_command.command = 123; my_command.command_number++; my_command.arg1 = 2; my_command.arg2 = 3; /* set inuse flag */ command_ptr->inuse = 1; /* copy local structure to shared memory */ memcpy(command_ptr, &my_command, sizeof(MY_COMMAND)); /* clear inuse flag */ command_ptr->inuse = 0;
Listing Five
if (0 != command_ptr->inuse) { /* ignore it, perhaps incrementing a deferral count */ } else { /* okay to access shared memory */ }
Listing Six
MY_STATUS my_status; /* set inuse flag */ status_ptr->inuse = 1; /* copy shared memory to local structure */ memcpy(&my_status, status_ptr, sizeof(MY_STATUS)); /* clear inuse flag */ status_ptr->inuse = 0; /* refer to local struct from now on */ if (my_status.stat1 == 1) { ... }
Listing Seven
if (0 != status_ptr->inuse) { /* defer status write, perhaps incrementing deferral count */ } else { /* okay to write status */ }
Listing Eight
#define ERROR_NUM 64 /* max number of error strings to be queued */ #define ERROR_LEN 256 /* max string length for an error */ char error[ERROR_NUM][ERROR_LEN];
Listing Nine
#define ERROR_NUM 64 /* max number of error strings to be queued */ #define ERROR_LEN 256 /* max string length for an error */ typedef struct { unsigned char inuse; /* flag signifying Linux accessing */ char error[ERROR_NUM][ERROR_LEN]; /* the errors themselves */ int start; /* index of oldest error */ int end; /* index of newest error */ int num; /* number of items */ } MY_ERROR;
Listing Ten
/* initialize ring buffer; done once, perhaps in init_module() */ int error_init(MY_ERROR *errlog) { errlog->inuse = 0; errlog->start = 0; errlog->end = 0; errlog->num = 0; return 0; } /* queue an error at the end */ int error_put(MY_ERROR *errlog, const char *error) { if (errlog->num == ERROR_NUM) { /* full */ return -1; } strncpy(errlog->error[errlog->end], error, ERROR_LEN); errlog->end = (errlog->end + 1) % ERROR_NUM; errlog->num++; return 0; } /* dequeue the error off the front */ int error_get(MY_ERROR *errlog, char *error) { if (errlog->num == 0) { /* empty */ return -1; } strncpy(error, errlog->error[errlog->start], ERROR_LEN); errlog->start = (errlog->start + 1) % ERROR_NUM; errlog->num--; return 0; }
Listing Eleven
char error[ERROR_LEN]; /* place to copy error */ /* set in-use flag in shared memory */ errlog->inuse = 1; /* copy error out */ if (0 != error_get(errlog, error)) { /* empty */ } else { /* handle it */ } /* clear in-use flag in shared memory */ errlog->inuse = 0;
Listing Twelve
char error[ERROR_LEN]; /* place to compose error */ /* check for in-use */ if (0 != errlog->inuse) { /* defer writing, perhaps incrementing deferral count */ } else { /* compose it */ strcpy(error, "your error here"); if (0 != error_put(errlog, error)) { /* full */ } } | http://www.drdobbs.com/open-source/linux-real-time-linux-ipc/184411098 | CC-MAIN-2015-11 | refinedweb | 3,248 | 52.7 |
?
package javax.ws.rs does not exist
validator framework work in Struts
What does COMMIT do?
Does memory for Class or Object?
multiboxes - Struts
java - Struts
import package.subpackage.* does not work
Difference between Struts and Spring
Hello - Struts
Diff between Struts1 and struts 2? - Struts
Regarding struts tag and struts dojo tags.
Struts Projects
sing validator framework work in struts
What does the delete operator do?
Combilation of class - Struts
How to Use Struts 2 token tag - Struts
Does Java support multiple inheritance?
Struts Tutorials
Struts Links - Links to Many Struts Resources
Jquery form validation does not work
STRUTS
Struts
Struts
STRUTS
what does business analyst mean
PHP saying folder does not exist
Object does not support proprty or method
Managing Datasource in struts Application
Package does not exist.. - Java Beginners
struts
post method does not support this url
Duplicate name in Manifest - Struts
Struts 2 Tutorials - Struts version 2.3.15.1
Download Struts
Struts Articles
struts
Dispatch Action - Struts
Struts 1.x Vs Struts 2.x
Struts 2 - History of Struts 2
Struts - Struts
Page Refresh - Struts
Struts Books
what does a technical business analyst do
which part of the cpu does math calculations
Why does Java not support operator overloading?
What does a special set of tags <?= and ?> do in PHP?
Does javaScript have the concept level scope?
What does "1"+2+4 evaluate to?
In netbean jdk, it does not import the file,"java.nio.file.Paths". why?.
What does it mean that a class or member is final?
STRUTS INTERNATIONALIZATION | http://www.roseindia.net/tutorialhelp/comment/38216 | CC-MAIN-2013-48 | refinedweb | 256 | 66.33 |
Implementing member swap() in terms of non-member swap()
std::swap pointers
swap is not a member of std
std::move
c++ swap function implementation
std::swap implementation
swap() in c
c++ swap vector elements
I'm implementing a class with a similar interface to
std::array, which has both the member
swap() and the non-member
swap().
Since I want my class to mimic the standard containers, I would like to implement both kinds of
swap() (the non-member
swap() is implemented via ADL, since specializing
std::swap() isn't permitted):
class A { public: friend void swap(A& a, A& b) { /* swap the stuff */ } void swap(A& other) { swap(*this, other); } };
However, it seems like I can't call the non-member
swap() from inside the class, because it prefers the member
swap() even though it only has a single parameter. Changing it to
::swap(*this, other) doesn't work as well, because the in-class friend function is only findable via ADL. How might I call the non-member
swap() from inside the class?
The problem is that the name of the member function
swap hides the namespace-scope
swap in the body of
A::swap. Unqualified name lookup for
swap in
A::swap will never find namespace-scope
swap and, thus, namespace-scope
swap will not be part of the overload set. One way to get around this would be to simply add a declaration for namespace-scope
swap in the body of
A::swap:
class A { public: friend void swap(A& a, A& b) { /* swap the stuff */ } void swap(A& other) { void swap(A& a, A& b); swap(*this, other); } };
That being said, I'm not sure what this really does for you. The obvious solution is to just implement namespace-scope
swap in terms of
A::swap rather than the other way around. Personally, I would just not have a
swap member function to begin with. The typical way of swapping
aand
b is to just
swap(a, b)…
More C++ Idioms/Non-throwing swap, Although an efficient and exception-safe swap function can be implemented (as shown above) as a member function, non-throwing swap idiom goes further than � If your implementation of swap needs to access the type's privates, then you will either need to call a member function like #3, or declare the non-member function a friend. This is what your examples in #4 do: a friend function can be declared and defined inside the class, but that does not make it a member; it is still scoped within the
The following works for me (it prints blah twice)
#include <utility> #include <iostream> class A { public: friend void swap(A& a, A& b) { std::cout << "blah\n";/* swap the stuff */ } void swap(A& other) { using std::swap; swap(*this, other); } }; int main() { A a, b; swap(a,b); a.swap(b); }
std::swap, Like for example std::begin(x) is better than x.begin(), std::size(x) is better than x. size(). Also functions like swap should be implemented as free functions and not as member I didn't see any uses of member swap that could be improved. Maybe 2020 GitHub, Inc. Terms � Privacy � Security � Status � Help. The launch date for Insolar MainNet was moved a few days forward because the developers need to implement the updated swap terms. Summary of updated swap terms. Become a member.
You can declare your class and your swap function first, then use the global namespace specifier within your member function.
Now you are free to define your swap function outside the class.
#include <algorithm> #include <iostream> class A; void swap(A& a, A& b); class A { int the_stuff; public: A(int a): the_stuff(a) {} friend void swap(A& a, A& b); void print_stuff(){std::cout << "A's stuff is " << the_stuff << std::endl;} void swap(A& other){ ::swap(*this, other); std::cout << "Member swap" << std::endl;} }; void swap(A& a, A& b) { std::swap(a.the_stuff, b.the_stuff); std::cout << "Friend swap" << std::endl; } int main() { A a = 1, b = 2; a.print_stuff(); swap(a, b); a.print_stuff(); return 0; }
Outputs:
//> A's stuff is 1 //> Friend swap //> A's stuff is 2
guideline for preferring free functions over member functions � Issue , The (pointer, count)-style interface leaves increment1() with no realistic way of Note that non- const member functions pass information to other member Consider using swap to implement copy assignment in terms of copy construction ..
C++ Core Guidelines, In computing, sequence containers refer to a group of container class templates in the standard library of the C++ programming language that implement storage of data elements. 3.2 Non-member functions. 4 Usage example; 5 The reserve() operation may be used to prevent unnecessary reallocations. After a call to� Replacement Swap: A substitute for a swap arrangement that is terminated before it matures. A swap may be ended early if there is a termination event or a default. If a swap is terminated early
Sequence container (C++), Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class? Every time we used swap() with a given pair of types, the compiler will go to the above Conceptual only; not C++; case int: // implementation details when T is int; break;; case Terms of Use � Privacy Policy. The expected way to make a program-defined type swappable is to provide a non-member function swap in the same namespace as the type: see Swappable for details.. The following overloads are already provided by the standard library:
Templates, C++ FAQ, Conversely, this is not a problem for the swap member function, as the Here is a typical implementation of std::swap, with comments of we define the free- function swap in terms of the member-function, rather than the other way around. a.swap(b), void, Requires: a.get_allocator() == b.get_allocator()� Swap Documents means each document, instrument or agreement entered into by and between Borrower and the Bank to evidence, confirm, describe, secure, modify or establish the terms of any Swap Transaction effected pursuant to this Agreement, including without limitation any so-called "Master Agreement" concerning any Swap Transaction and each schedule and addendum thereto, together with all
- Why not to implement the non-member
swapin terms of the member
swap?
- @Evg I could, but the symmetry of the non-member
swaplooks nicer.
- Why do you want to add the implementation of the swapping in the friend function
void swap(A& a, A& b)? It should belong to a member function like
void swap(A& other)and the
void swap(A& a, A& b)then could call the member function.
- Also, if you do it the proper way (implement the non-member using the member), you don't need that the non member would be a friend of the class. You are clearly inventing problems...
- @Phil1970 Do you have a reference that says that implementing the non-member using the member is the proper way?
- If your design encourages block-scope function declarations, you’re doing it wrong.
- It might be worth saying why asking for the (non-customizable!)
std::swapfinds the hidden friend.
- Note that friend
swapin the question can benefit from being a hidden friend. | http://thetopsites.net/article/59564137.shtml | CC-MAIN-2020-50 | refinedweb | 1,211 | 55.68 |
jacob deiter wrote:Anyone please share best practice in naming convention in java programming such as
1) Class Name
2) Method name
3) Parameter Name
4) Interface Name
5) Helper Class
6) Wrapper Class
7) Exception class
If I missed any things please address those also
Jilesh Lakhani wrote: . . . you can keep static variable in caps . . .
Campbell Ritchie wrote:
Jilesh Lakhani wrote: . . . you can keep static variable in caps . . .
That only applies to public static final fields.public class Water
{
. . .
/**
* Boiling point of water in °C at normal atmospheric pressure
*/
public static final int BOILING_POINT = 100;
Rusty Shackleford wrote:As long as your names are meaningful and are consistent with your convention, it doesn't really matter what convention you use. | http://www.coderanch.com/t/446758/java/java/practice-naming-convention-java-programming | CC-MAIN-2014-10 | refinedweb | 121 | 62.98 |
:
Publishing Spreadsheets to the Web
Contents
- Introduction
- Spreadsheet to HTML
- What it Does (and Doesn't) Do
- How it Works
Introduction
Spreadsheets are great ways to collect and organise data. However, they are not always the best format for presenting results. They may depend on access to resources not available to people who want to see the results, or they quickly become out of date. How about presenting the finished spreadsheet as a web page? This could be posted on intranet, the internet, or even just saved or emailed.
Fortunately, Resolver spreadsheets are just programs. We can save the spreadsheet as code and then have access to objects that represent the spreadsheet and everything in it. All it takes to turn it into web pages is a little bit more code...
This article presents a little utility that takes a Resolver spreadsheet exported as Python code and saves the worksheets it contains as HTML files (web pages). It supports most of the Resolver formatting, including image worksheets. Each page has a link to all the worksheets in the spreadsheet.
As well as doing a possibly useful task (although you might want to edit the HTML it produces), it is also an example of how to interact with Resolver spreadsheets exported as code.
Note
Thanks to Resolver Systems for permission to use this code. Parts of the HTML generating code were originally developed by William Reade and Michael Foord (me) as part of a demo.
Spreadsheet to HTML
'Spreadsheet to HTML' is a small Windows Forms application that converts Python files created by Resolver into a series of HTML web pages. It generates one web page per worksheet, and will also save images if there are any ImageWorksheets.
How to Install
Install is possibly a bit high-falutin, but this app only works if you run it the right way. The zipfile contains a batch file and a single directory. These must both be placed into your Resolver install directory. This is usually something like C:\Program Files\Resolver. You can then launch the program by double clicking the batch file.
The reason for having to run Resolver from here is that spreadsheets depend on the 'Library' objects, like Workbook, Worksheet, Cell and so on. They need to be executed from the right location in order to be able to import these.
Export a Spreadsheet as Code
When run, this app loads spreadsheets that have been exported as Python files. There is an example one included in the zipfile, but you can test it with any arbitrary spreadsheet by using the File -> Export -> To Python or File -> Export -> To Python Class menu options.
This brings up a save file dialog allowing you to specify the location and name of the Python file that is generated from your spreadsheet.
Load it Into the App
When you run the 'Spreadsheet to HTML' application (from the batch file), you should see a very simple form appear with a 'Choose' button on it. Clicking this should bring up an open file dialog allowing you to choose a Python file.
The zipfile includes an 'rsl' file called 'TheSpreadsheet.rsl'. There are two Python files that have been created by exporting this spreadsheet, one as a class and one as a standard Python file. You can load either of these as an example of what 'Spreadsheet to HTML' can do.
Save the HTML
Once the Python file has been loaded (assuming there are no errors), you should see a folder browse dialog. When you select a folder, the HTML files will be saved there.
The Results
'TheSpreadsheet.rsl' has four worksheets. A cell range with alternate rows colored, an array of colored cells with the grid off and the location of each cell in bold as the value, the same colored array with the grid on and an image worksheet. Each worksheet has a link 'menu bar' at the top to the other worksheets:
As you will be able to see from the examples, the output isn't bad and shouldn't require too much editing to be useful. The nice thing is, the code that produces this output is very simple and easy to customize.
Customizing the HTML
The output web pages are produces by two modules in the 'SpreadsheetToHTML' directory.
- html.py - most of the template for producing the web pages are stored as variables in this file.
- Htmliser.py - this does the actual work of turning spreadsheet objects into web pages. It uses the templates defined in html.py, but unfortunately does contain some HTML in the code as well.
Rather than editing every individual page that is produced, you can change the templates stored in html.py (and some snippets buried in Htmliser.py) to control the output.
For example the look of the whole page is controlled by the page variable at the start of html.py: body { background-color: #fffff0; font-size: 10; } body, td, th { font-family: "Tahome", "Arial"; } .b_left { border-left: solid 2px #000000; }
The link menu for the worksheets is in the worksheetMenuTable variable: <tr> <th colspan="%s"><strong>Worksheets</strong></th> </tr>
Individual cells are written out in the TdFromCell function in Htmliser.py.
What it Does (and Doesn't) Do
Even though the code that generates the webpages is quite small, it actually supports most of the different formatting options for Resolver spreadsheets.
What is Supported?
The following things are supported:
Cell values (wouldn't be much good without this)
ShowGrid
If a worksheet has the grid switched off then the grid won't be shown in the generated webpage, and neither will the column and row headers.
Borders
Cell BackColor
Bold
Dates and numbers are right aligned
Image Worksheets
Worksheet level errors are shown (although not especially gracefully)
Column widths and row heights
Cell errors are shown (again, not particularly well)
Number of Decimal Places
Strip Zeroes
Show Negative Symbol
Show Separators
What isn't Supported?
The following things are not (yet!?) supported by CreateHTML. Contributions welcomed!
FontSize and FontFamily
Show Bounds
CreateHTML only generates HTML for the populated region of a worksheet anyway, so show bounds isn't relevant.
Buttons
They are just ignored. You would need a web application to properly support buttons.
Wrapping
I don't think that wrapping can be done properly from pure HTML (or at least switching wrapping off can't be done). Table cells resize automatically to show their entire contents. It could probably be done with Javascript.
Negative text color
How it Works
Everything we have looked at so far is all very well if you just want to use SpreadsheetToHTML. If you are more interested in how to interact with spreadsheets that have been exported as Python, then we need to look at the code.
Most of the work is done inside CreateHTML.py, which is the main application file. A lot of the code in this file is to do with creating and displaying the GUI components, but there are one or two important parts hidden in there.
RSIronPython
If you look in the batch file SpreadsheetToHTML.bat you will notice that CreateHTML.py is run with an executable called RSIronPython.exe. This is located in the bin directory of your Resolver install.
It is the core of the Resolver executable, but runs arbitrary IronPython scripts instead of just starting Resolver. We use it for testing and developing Resolver, but it means that you can use tools like SpreadsheetToHTML without needing IronPython available separately.
Assemblies and Imports
Like any good IronPython program, the first thing that CreateHTML does is add references to the assemblies that is uses and imports the names it needs.
import SpreadsheetToHTML.CreateHtmlRequiredAssemblies
# Do this import now to speed up loading spreadsheets
from Library.Workbook import Workbook
CreateHTML doesn't just add references to the assemblies that it uses - it adds references to all the assemblies that might be used by spreadsheets. This is done just by importing the SpreadsheetToHTML.CreateHtmlRequiredAssemblies module.
Next it imports Workbook from the Resolver library. Again this is not because CreateHTML itself needs it. The first import of the Resolver library code takes a while, so by doing it before the form is first displayed we can dramatically improve the performance of creating web pages for the first spreadsheet.
Once you have chosen a Python spreadsheet from the file browser, the hard work of executing the file and extracting the spreadsheet object is done by a function called LoadSpreadsheet:
"""
Load and execute a spreadsheet exported as Python.
This function takes a path to the Python file and
returns a workbook instance.
"""
spreadsheetDirectory = Path.GetDirectoryName(path)
sys.path.append(spreadsheetDirectory)
try:
context = {'__name__': '__main__', '__file__': path, '__builtins__': __builtins__}
h = open(path)
code = h.read() + '\n'
h.close()
exec code in context
Spreadsheet = context.get('Spreadsheet')
if Spreadsheet is not None:
# Spreadsheet was exported as a class
workbook = Spreadsheet()
workbook.recalculate()
else:
# Spreadsheet exported as non-class
workbook = context.get('workbook')
if workbook is None:
# Not a spreadsheet at all
raise NoWorkbook("No workbook defined in this code. Are you sure it is a Resolver spreadsheet?")
return workbook
finally:
sys.path.remove(spreadsheetDirectory)
If you want to write a program that can interact with arbitrary spreadsheets exported as code, this is a useful function to understand. I'll take you through it step by step.
Spreadsheet Directory on the Path
One of the things that Resolver does is to add the directory of the currently executing spreadsheet to the 'system path' (sys.path). This ensures that you are able to import from modules kept in the same directory as the spreadsheet file. We need to make sure that this still works when we are running spreadsheets as code, so we do the same:
sys.path.append(spreadsheetDirectory)
The rest of the function is wrapped in a try: ... finally: that removes this directory from the path again after we have done our work - even if an error occurs.
...
finally:
sys.path.remove(spreadsheetDirectory)
Leaving extra directories in sys.path may have unintended consequences (the wrong module being imported from a different directory), this is why we are careful to remove it.
Execute the Code
This is the most important step. We need to read in the spreadsheet file and execute it. Having executed it we need to be able to get access to the objects afterwards. To do this we use the exec statement (which executes code) and provide an explicit 'context' for the code to be executed in.
h = open(path)
code = h.read() + '\n'
h.close()
exec code in context
We need to pre-populate this context with a few basic names that the Python interpreter would provide if the code was being run in the normal way.
We don't do any error handling here. If the spreadsheet fails to execute properly then it will be caught by the code that called LoadSpreadsheet and the error will be reported to the user (you!):
try:
# Load the spreadsheet
print 'Loading spreadsheet'
workbook = LoadSpreadsheet(filePath)
except Exception, e:
MessageBox.Show("An error has occurred:\r\n%s: %s" % (e.__class__.__name__, e),
"An Error has Occurred",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Spreadsheet Exported as Class
There are two ways of exporting spreadsheets as code. You can either export the code exactly as it appears in the codebox, or you can export it as a class. (Exporting as a class is useful if you wish to change the data and recalculate.) Depending on which sort of Python file you are loading, a different object will be in the context after executing the code.
If you exported as a class, then the object in the context will be a class - the Spreadsheet class. To obtain a fully calculated workbook we must create an instance of this class and call recalculate:
if Spreadsheet is not None:
# Spreadsheet was exported as a class
workbook = Spreadsheet()
workbook.recalculate()
Spreadsheet as Code
If the spreadsheet was exported directly, and not as a class, then we can just pull the ready calculated workbook out of the context. If there is no workbook, then it obviously wasn't a Resolver spreadsheet in the first place, and we need to raise an error that will then be reported to the user:
# Spreadsheet exported as non-class
workbook = context.get('workbook')
if workbook is None:
# Not a spreadsheet at all
raise NoWorkbook("No workbook defined in this code. Are you sure it is a Resolver spreadsheet?")
And that is it. One way or another we have got a valid workbook, or we have raised an error. If no error has been raised, LoadSpreadsheet returns the workbook - happy with a job well done.
An Alternative Approach
The code in CreateHTML is designed to work with any spreadsheet, stored in any location on the filesystem. This is why it uses exec and the context to execute the code and extract the workbook.
If you were writing an application designed to interact with specific spreadsheets, then there is a better approach that uses the normal Python import machinery to get access to the workbook.
Place the exported Python file within your application module system. You can then do:
workbook = Spreadsheet()
workbook.recalculate()
Much more straightforward...
Sometime I will write about putting a simple C# facade around this, so that you can interact with spreadsheets from other .NET applications and not just IronPython ones.
HTML from Workbook
Once we have extracted the workbook from our spreadsheet file we have access to the full Workbook and Cell API to work out what is in it and generate the HTML.
I'm not going to go through this code in detail, but it is very simple and contained in the Htmliser module. The important function is HtmlFromWorkBook which takes a workbook and returns a list of (name, html) tuples. It also needs to know the output directory, so that it can save images from image worksheets.
In order to generate HTML it iterates over all the worksheets, and all the cells in each worksheet checking attributes as it goes. If you are interested in understanding how to work with cells and worksheets from code then have a browse and see if you can understand what it is doing.
Last edited Fri Feb 15 13:45:04 2008. | http://www.resolverhacks.net/to_the_web.html | crawl-002 | refinedweb | 2,381 | 63.09 |
Hi All,<?xml:namespace prefix = o<o:p></o:p> <o:p></o:p> I know it's not recommended and no one will support the decision but i would like to convert my Vario to CNG.<o:p></o:p> <o:p></o:p>ppl are getting trany failures and issues with CNG in Vario...<o:p></o:p> <o:p></o:p>Most of you will recommend kay i should sale my ride and buy manual trany.......<o:p></o:p> <o:p></o:p>But i would like to have my ride with me and CNG.....<o:p></o:p> <o:p></o:p>so i request ppl running Vario on CNG please give comments and recommend the best setup<o:p></o:p> <o:p></o:p>Or han friends if anyone from ISLO recommend conversion center (with personal experience) it will be great......... i moved back to Isloo from Karachi this month<o:p></o:p>(H) <o:p></o:p> Ocean<o:p></o:p><o:p> </o:p>
i am sure u r smart enough to use the search optionit will hardly take 2 minutes to come out with 10 topics on cng on vario
AOA
I have my 2006 Vario running on EFI Kit and is working fine. I have no problem with my car. You will have to find a good mechanic to tune your vehicle and believe me there are plenty out there.So do not hesitate and go ahead. Convert your vehicle. Oh yes if you can, buy the better version of Landirenzo kit that is used for 1300 cc cars.Best of luck.
@Hash i know there is a search option but with search u can get 2nd hand information, i just need it first hand. ppl using vario on cng thay can share Do's and Dont's as imran communicated for better version of CNG kit, i definitly need some good convertion center and equipment. fyq is also on his way to help me for this so u ppl suggest too
Following recommendations for CNG:
City Vario & CNG ..not a perfect couple
well my friends are using CNG on it...working good ..but they are not satisfied with it when compared to other cars on CNG ..never asked the reasonbut they are always like ...man get some petrol,CNGs gettin on my nerves:)
The CVT and CNG DONT work together.. if u do some research on CVT.. u will get to know that it is a fairly simple technology..but the problem is that the size of the gear is changes, with speed. The only problem on driving in CNG is that you lose some power on CNG,..and somehow that effects the timing of ur transmission..
in my experince the transmission will start slipping after about 50k kilometers..or u will have to keep it in best tunning all the time..a freind of mine had a 2008 CVT.. and had to sell it coz of the same reason..The transmission literally starts slipping.. u hear the sound of gr gr gr.. wen u park on the signalss.. *** per my experience CVT and CNG. not gud if put together..
your CVT will be ruined soon... | https://www.pakwheels.com/forums/t/city-vario-cng/133016 | CC-MAIN-2017-04 | refinedweb | 540 | 83.05 |
Bogosort in Practice
For whatever reason, there's a lot of humor in programming. From bogus HTTP responses to fun jargon, we're a funny bunch. In practice, the only thing funnier than an idea is an idea that actually runs, so I decided to see how awful Bad Code could really be.
The searching and sorting of arrays is a popular (and central) topic in computer science. There's been a lot of time and effort spent ensuring we can sort array as efficiently as possible. Typically, efficiency in sorting methods is measured as a function of input length vs number of loops. A great sort won't appreciably increase ruznning time as the input gets longer. A bad sort, on the other hand...
When the topic of bad searches come up (at parties or whatever, as it does), a crowd favorite is always the infamous bogosort. The idea is simple: take an array, randomize it, and check if it's sorted. If not, repeat! In the best case, you got really lucky and this sort is very fast. Most of the time, you're less lucky and this is actively awful. Let's see how this would shake out in practice.
The following is a simple implementation of bogosort using Ruby's #shuffle! method (plus some extra code to track how many shuffles it took before the array was sorted). It also adds the
sorted? method to arrays, to help us know when we've (eventually) sorted the array.
class Array def sorted? 1.upto(size - 1) do |i| # if i > i-1, we good return false if self[i] < self[i - 1] end true end end # Performs the bogosort, lets us know how many tries it took def num_shuffles(arr) c = 0 # the sort itself until arr.sorted? arr.shuffle! c += 1 end c end
Since the randomness of the sort begets such a high variance in results, we'll want to do a fair number of trails and take the average.
def bogosort_counter(n) arr = 1.upto(n).to_a res = [] 5000.times do # start in a random order res << num_shuffles(arr.shuffle) end puts "It took an average of #{res.average.round(2)} shuffles to sort an array of length #{n}" end
With our measurement tools in hand, I ran the trials with increasingly long arrays. It's tough to graph numbers that have such a large range (2 element array sorted fairly quickly, large ones... did not), so we used a logarithmic scale. The lines on either side of the dots show the middle 50% of the number of shuffles. As you can see, the number of shuffles scales pretty aggressively with the length of the input.
Each array length follows a remarkably similar pattern, known as a negative binomial distribution (I am told), meaning the number of shuffles is quite variable. For array length 5, it takes 10^5 shuffles. but it's just as likely for it to take many more tries. This causes the (incredibly) long tail you see out to the right.
If you think those numbers are big, it's because they are. Big numbers don't mean anything without context though. To help provide that context, I modified the script to measure the actual clock-on-the-wall time you would spend sorting an array length
n. Note that the table skips the first few values of
n, as they were sorted too fast for Ruby to capture (which is a good thing, I guess).
These results are... not inspiring. Each element added to the array adds roughly a factor of 10 to how long the script takes to run.1 And again, the precious seconds you spend sorting doesn't actually guarantee your array will end up sorted anyway. Unless you're feeling incredibly lucky, I'd stick to something faster and more reliable. Maybe a nice bubble sort.
Huge thanks to Evan Batzer for his time and expertise with chart creation. You can find out more about him and his work here. | https://xavd.id/blog/post/bogosort-in-practice/ | CC-MAIN-2021-21 | refinedweb | 675 | 74.08 |
Speed Up Your Python Using Rust
Speed Up Your Python Using Rust
You might have heard of Rust lately, but did you know it can help you even if you're a Python developer? See how you can make use of Rust in your next Python project!
Join the DZone community and get the full member experience.Join For Free
What Is Rust?
Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.
Featuring:
- Zero-cost abstractions
- Move semantics
- Guaranteed memory safety
- Threads without data races
- Trait-based generics
- Pattern matching
- Type inference
- Minimal runtime
- Efficient C bindings
This description is taken from rust-lang.org.
Why Does It Matter for a Python Developer?
I heard a better description of Rust from Elias (a member of the Rust Brazil Telegram Group):
Rust is a language that allows you to build high level abstractions, but without giving up low-level control – that is, control of how data is represented in memory, control of which threading model you want to use etc.
Rust is a language that can usually detect, during compilation, the worst parallelism and memory management errors (such as accessing data on different threads without synchronization, or using data after they have been deallocated), but gives you a hatch escape in the case you really know what you’re doing.
Rust is a language that, because it has no runtime, can be used to integrate with any runtime; you can write a native extension in Rust that is called by a program node.js, or by a python program, or by a program in ruby, lua etc. and, however, you can script a program in Rust using these languages. — Elias Gabriel Amaral da Silva
There are a bunch of Rust packages out there to help you extending Python with Rust. I can mention Milksnake created by Armin Ronacher (the creator of Flask) and also PyO3, the Rust bindings for Python interpreter (see a complete reference list at the bottom of this article).
Let’s see it in action.
For this post, I am going to use Rust Cpython, the only one I have tested; it is compatible with the stable version of Rust and I found it straightforward to use.
NOTE: PyO3 is a fork of rust-cpython and comes with many improvements, but works only with the nightly version of Rust, so I preferred to use the stable for this post. Anyway, the examples here must work also with PyO3.
Pros: It is easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance.
Cons: The distribution of your project/lib/framework will demand the Rust module to be compiled on the target system because of variation of environment and architecture. There will be a compiling stage which you don’t have when installing Pure Python libraries; you can make it easier using rust-setuptools or MilkSnake to embed binary data in Python Wheels.
Python Is Sometimes Slow
Yes, Python is known for being “slow” in some cases and the good news is that this doesn’t really matter depending on your project goals and priorities. For most projects, this detail will not be very important.
However, you may face the rare case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing.
Example
Let’s say you have a Python function which does a string processing, take the following easy example of
counting pairs of repeated chars, but have in mind that this example can be reproduced with other
string processing functions or any other generally slow process in Python.
# How many subsequent-repeated group of chars are in the given string? abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here} 1 2 3 4 5 6
Python is slow for doing large
string processing, so you can use
pytest-benchmark to compare a
Pure Python (with Iterator Zipping) function versus a
Regexp implementation.
# Using a Python3.6 environment $ pip3 install pytest pytest-benchmark
Then, write a new Python program called
doubles.py
import re import string import random # Python ZIP version def count_doubles(val): total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total # Python REGEXP version double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) # Benchmark it # generate 1M of random letters to test it val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val)
Run pytest to compare:
$ 2 items doubles.py .. --------------------------------------------------------------------------------- benchmark: 2 tests -------------------------------------------------------------------------------- Name (time in ms) Min Max Mean StdDev Median IQR Outliers OPS Rounds Iterations ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- test_regex 24.6824 (1.0) 32.3960 (1.0) 27.0167 (1.0) 1.8610 (1.0) 27.2148 (1.0) 2.9345 (4.55) 16;1 37.0141 (1.0) 36 1 test_pure_python 51.4964 (2.09) 62.5680 (1.93) 52.8334 (1.96) 2.3630 (1.27) 52.2846 (1.92) 0.6444 (1.0) 1;2 18.9274 (0.51) 20 1 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Legend: Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile. OPS: Operations Per Second, computed as 1 / Mean =============================================================================== 2 passed in 4.10 seconds ===============================================================================
Let’s take the
Median for comparison:
- Regexp – 27.2148 <– less is better
- Python Zip – 52.2846
Extending Python with Rust
Create a New Crate
"Crate" is what we call a Rust package.
Have Rust installed ( the recommended way is). I used
rustc 1.21.0.
In the same folder, run
cargo new pyext-myrustlib
It creates a new Rust project in that same folder called
pyext-myrustlib containing the
Cargo.toml (cargo is the Rust package manager) and also a
src/lib.rs (where we write our library implementation).
Edit Cargo.toml
It will use the
rust-cpython crate as dependency and tell cargo to generate a
dylib to be imported from Python.
[package] name = "pyext-myrustlib" version = "0.1.0" authors = ["Bruno Rocha <rochacbruno@gmail.com>"] [lib] name = "myrustlib" crate-type = ["dylib"] [dependencies.cpython] version = "0.1" features = ["extension-module"]
Edit src/lib.rs
What we need to do:
- Import all macros from
cpythoncrate.
- Take
Pythonand
PyResulttypes from CPython into our lib scope.
- Write the
count_doublesfunction implementation in
Rust, note that this is very similar to the Pure Python version except for:
- It takes a
Pythonas first argument, which is a reference to the Python Interpreter and allows Rust to use the
Python GIL.
- Receives a
&strtyped
valas reference.
- Returns a
PyResultwhich is a type that allows the rise of Python exceptions.
- Returns an
PyResultobject in
Ok(total)(Result is an enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a
PyResultthe compiler will take care of wrapping our
Okon that type. (note that our PyResult expects a
u64as return value).
- Using
py_module_initializer!macro, we register new attributes to the lib, including the
__doc__and also we add the
count_doublesattribute referencing our
Rust implementation of the function.
- Attention to the names libmyrustlib, initlibmyrustlib, and PyInit.
- We also use the
try!macro, which is the equivalent to Python’s
try.. except.
- Return
Ok(())– The
()is an empty result tuple, the equivalent of
Nonein Python.
#[macro_use] extern crate cpython; use cpython::{Python, PyResult}; fn count_doubles(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; for (c1, c2) in val.chars().zip(val.chars().skip(1)) { if c1 == c2 { total += 1; } } Ok(total) } py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | { try!(m.add(py, "__doc__", "This module is implemented in Rust")); try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str)))); Ok(()) });
Now Let’s Build It With Cargo
$ cargo build --release Finished release [optimized] target(s) in 0.0 secs $ ls -la target/release/libmyrustlib* target/release/libmyrustlib.d target/release/libmyrustlib.so* <-- Our dylib is here
Now let’s copy the generated
.so lib to the same folder where our
doubles.py is located.
NOTE: on Fedora, you must get a
.so in other system you may get a
.dylib and you can rename it changing extension to
.so.
$ cd .. $ ls doubles.py pyext-myrustlib/ $ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so $ ls doubles.py myrustlib.so pyext-myrustlib/
Having the
myrustlib.so in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module.
Importing From Python and Comparing the Results
Edit your
doubles.py now importing our
Rust implemented version and adding a
benchmark for it.
import re import string import random import myrustlib # <-- Import the Rust implemented module (myrustlib.so) def count_doubles(val): """Count repeated pair of chars ins a string""" total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) def test_rust(benchmark): # <-- Benchmark the Rust version benchmark(myrustlib.count_doubles, val)
Benchmark:
$ 3 items doubles_rust.py ... --------------------------------------------------------------------------------- benchmark: 3 tests --------------------------------------------------------------------------------- Name (time in ms) Min Max Mean StdDev Median IQR Outliers OPS Rounds Iterations -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- test_rust 2.5555 (1.0) 2.9296 (1.0) 2.6085 (1.0) 0.0521 (1.0) 2.5935 (1.0) 0.0456 (1.0) 53;23 383.3661 (1.0) 382 1 test_regex 25.6049 (10.02) 27.2190 (9.29) 25.8876 (9.92) 0.3543 (6.80) 25.7664 (9.93) 0.3020 (6.63) 4;3 38.6285 (0.10) 40 1 test_pure_python 52.9428 (20.72) 56.3666 (19.24) 53.9732 (20.69) 0.9248 (17.75) 53.6220 (20.68) 1.4899 (32.70) 6;0 18.5277 (0.05) 20 1 -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Legend: Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile. OPS: Operations Per Second, computed as 1 / Mean =============================================================================== 3 passed in 5.19 seconds ===============================================================================
Let’s take the
Median for comparison:
- Rust – 2.5935 <– less is better
- Regexp – 25.7664
- Python Zip – 53.6220
Rust implementation can be 10x faster than Python Regex and 21x faster than Pure Python Version. Interesting that the Regex version is only 2x faster than Pure Python.
NOTE: Those numbers makes sense only for this particular scenario; for other cases that comparison may be different.
Conclusion
Rust may not be yet the
general purpose language of choice by its level of complexity and may not be the better choice yet to write common simple
applications such as
web sites and
test automation scripts. However, for
specific parts of the project where Python is known to be the bottleneck and your natural choice would be implementing a
C/C++ extension, writing this extension in Rust seems easy and better to maintain.
There are still many improvements to come in Rust and lots of others crates to offer
Python <--> Rust integration. Even if you are not including the language in your tool belt right now, it is really worth to keep an eye open to the future!
References
The code snippets for the examples showed here are available in this GitHub repo.
The examples in this publication are inspired by this
Extending Python with Rust talk by Samuel Cormier-Iijima in Pycon Canada video, and also by
My Python is a little Rust-y by Dan Callahan in Pycon Montreal (video here).
Other references:
-
-
-
-
-
-
-
-
Join the Community:
Join Rust community, you can find group links here.
If you speak Portuguese, I recommend you join and on .
Published at DZone with permission of Bruno Rocha . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/speed-up-your-python-using-rust | CC-MAIN-2019-30 | refinedweb | 1,990 | 64.51 |
On Mon, 30 Jun 2008 17:54:33 -0500, Nathan <nathan.stocks at gmail.com> wrote: > On Mon, Jun 30, 2008 at 4:20 PM, Terry Jones <terry at jon.es> wrote: >> You're not using deferreds properly. In the simple/typical case, when >> you >> call a function that returns a deferred, you will want to add (at >> least) a > > I don't think that's true. Jean-Paul was the one who told me to do it > that way in the first place: > > > Terry (hi Terry) is correct here. Your interpretation of Jean-Paul Calderone's message is flawed, although I certainly understand how the misinterpretation could occur. There's a big difference between the AMP example in that thread, and the example code you posted to this thread. > If your theory was true, I would be getting garbage everywhere I > return (and use) complicated objects, and I'd be getting True > everywhere that I return booleans. > Not necessarily. I suspect that your real code isn't working the way your posted example does. The bottom line is that the code you posted to this thread does not produce the synchronous behavior that you think it is providing, so it might be more helpful to provide an example of your real code, in order for people here to provide you with some better answers. Hope this helps, L. Daniel Burr | http://twistedmatrix.com/pipermail/twisted-python/2008-June/018005.html | CC-MAIN-2018-05 | refinedweb | 231 | 70.23 |
Shrinath M Aithal wrote:No dude, I too tried the same code, and its not "waiting" 10 seconds before printing y..
I am getting the output as "xy" fine, but not with 10 second gap..
did you get 10 second gap?
Shrinath M Aithal wrote:super confusion now
why isn't it waiting in my system ? I tried running it on another system too, both not giving lag between x and y..
and I tried other programs with "wait()" command, no program is waiting on this command.. ???
why isn't wait working with my system?
avi sinha wrote:
since you haven't overridden run method here the thread t becomed dead as soon as it is started hence there is no lag.
Shrinath M Aithal wrote:
so you mean to say, "t" is a dead thread when we are calling t.wait(10000); ???
and you can acquire synchronization on a dead thread?
and one more thing .. just to bug avi sinha ---> how did you get lag the first time? and why???
and the code you posted above, is infinitely waiting even after printing x and y and is inside your run method forever..
Shrinath M Aithal wrote:I think i found a proper way..
watch this :
public class test{
public static synchronized void main(String[] args) throws Exception {
Thread t=new Thread(new Runnable(){
public void run(){
System.out.print("x");
synchronized(this){
try{
wait(10000);
}catch(Exception e){}
}
System.out.print("y");
}});
t.start();
}
}
that does the job exactly as required.. but is that mature way?
If the wait were placed inside a synchronized(t)
block, then the answer would have been D.
avi sinha wrote:
the original code you posted in you first post & this code is entirely different.
wait method in the first code was being called by the main thread & here it is being called by the thread you ve created. & it is not allowing any other thread to execute because there is no any thread hence it is just waiting for 10 secs
avi sinha
Shrinath M Aithal wrote:so, does it suggest that the answer given in book is wrong? because it says
If the wait were placed inside a synchronized(t)
block, then the answer would have been D.
that didn't happen.. so it doesn't work as said?
>> about bugging Mr avi sinha :
I meant to ask you how you got the "10 second " lag the first time I agree with whatever you said about the thread taking different times to complete printing x and y on different executions.. But usually, its instantaneous.. and you getting proper 10 second lag, is that co incidence ?? ;)
lets drop it.. that'll not help with threads lets talk about the priority of this discussion " is the answer specified in k&b about option "D" wrong? " | http://www.coderanch.com/t/451520/java-programmer-SCJP/certification/synchronized-test | CC-MAIN-2014-10 | refinedweb | 471 | 81.83 |
,
The timerfd() syscall went into 2.6.22. While writing the man page for
this syscall I've found some notable limitations of the interface, and I am
wondering whether you and Linus would consider having this interface fixed
for 2.6.23.
On the one hand, these fixes would be an ABI change, which is of course
bad. (However, as noted below, you have already accepted one of the ABI
changes that I suggested into -mm, after Davide submitted a patch.)
On the other hand, the interface has not yet made its way into a glibc
release, and the change will not break applications. (The 2.6.22 version
of the interface would just be "broken".)
Details of my suggested changes are below. A complication in all of this
is that on Friday, while I was part way though discussing this with Davide,
he went on vacation for a month and is likely to have only limited email
access during that time. (See my further thoughts about what to do while
Davide is away at the end of this mail message.) Our last communication,
after Davide had expressed reluctance about making some of the interface
changes, was a more extensive note from me describing the problems of the
interface.
The problems of the 2.6.22 timerfd() interface are as follows:().
Davide has already submitted a patch to you to make read() from a timerfd
file descriptor return an 8 byte integer, and I understand it to have been
accepted into -mm.
Problem 2
---------
Existing timer APIs (Unix interval timers -- setitimer(2); POSIX timers --
timer_settime()) allow the caller to retrieve the previous setting of a
timer at the same time as a new timer setting is established. This permits
functionality such as the following for userland programs:
1. set a timer to go of at time X
2. modify the timer to go off at earlier time Z; return previous
timer settings (X)
3. When the timer Z expires, restore timer to expire at time X
timerfd() does not provide this functionality.
Problem 3
---------
Existing timer APIs (Unix interval timers -- getitimer(2); POSIX timers --
timer_gettime()) allow the caller to retrieve the time remaining until the
next expiration of the timer.
timerfd() does not provide this functionality.
Solution (proposed interface changes)
-------------------------------------
In response to my "Problem 2", Davide noted in the last message I got from
him before he went on vacation:
> But the old status of the timer is the union of clickid, flags and utmr.
> So, in theory, the whole set should be returned back, forcing a pretty
> drastic API change.
However, I think there is a reasonable solution to this problem, which I
outlined to Davide, but did not yet hear back from him about.
a) Make the 'clockid' immutable: say that it can only be set
if 'ufd' is -1 -- that is, on the timerfd() call that
first creates the timer. This would eliminate the need to
return the previous clockid value. (This is effectively
the limitation that is imposed by POSIX timers: the
clockid is specified when the timer is created with
timer_create(), and can't be changed.)
[In the 2.6.22 interface, the clockid of an existing
timer can be changed with a further call to timerfd()
that specifies the file descriptor of an existing timer.]
b) There is no need to return the previous 'flags' setting.
The POSIX timer functions (i.e., timer_settime()) do not
do this. Instead, timer_settime() always returns the
time until the next expiration would have occurred,
even if the TIMER_ABSTIME flag was specified when
the timer was set.
[The only 'flags' value currently implemented in
timerfd() is TFD_TIMER_ABSTIME, which is the
equivalent of TIMER_ABSTIME.]
With these design assumptions, the only thing that would need
to be added to timerfd() would be an argument used to return the time
until the previous timer would have expired + its interval.
The use cases would be as follows:
ufd = timerfd(-1, clockid, flags, utmr, NULL);
to create a new timer with given clockid, flags, and utmr (intial
expiration + interval).
ufd = timerfd(ufd, 0, flags, utmr, NULL);
to change the flags and timer settings of an existing timer.
ufd = timerfd(ufd, 0, flags, utmr, &old);
to change the flags and timer settings of an existing timer, and retrieve
the time until the next expiration of the timer (and the associated interval).
ufd = timerfd(ufd, 0, 0, NULL, &old);
Return the time until the next expiration of the timer (and the associated
interval), without changing the existing timer settings
Practical details
-----------------
Since Davide is away, my proposal is this: if you are prepared to consider
entertaining this ABI change, then I would try to write the patch. If when
we next hear from Davide (he may have intermittent email access over the
next month), he agrees that it is worth making the change, then I would
submit the change to -mm with the hope that time frames would allow for it
to make it into 2.6.23. (I would guess that delaying things for a month
means the fix might not make it into 2.6.23, and would thus simply make the
fix more painful and less feasible.)
What do you think?
Cheers,
Michael
PS For reference, the timerfd.2 man page describing the 2.6.22 interface is
below.
.TH TIMERFD 2 2007-07-17 Linux "Linux Programmer's Manual"
.SH NAME
timerfd \- create a timer that delivers notifications on a file descriptor
.SH SYNOPSIS
.\" FIXME . This header file may well change
.\" FIXME . Probably _GNU_SOURCE will be required
.\" FIXME . May require: Link with \fI\-lrt\f
.nf
.B #include <sys/timerfd.h>
.sp
.BR "int timerfd(int " ufd ", int " clockid ", int " flags ,
.BR " const struct itimerspec *" utmr );
.fi
.SH DESCRIPTION
.BR timerfd ()
creates and starts a new timer (or modifies the settings of an
existing timer) that delivers timer expiration
information via a file descriptor.
This provides an alternative to the use of
.BR setitimer (2)
or
.BR timer_create (3),
and has the advantage that the file descriptor may be monitored by
.BR poll (2)
and
.BR select (2).
.\" FIXME Davide, a question: timer_settime() and setitimer()
.\" both permit the caller to obtain the old value of the
.\" timer when modifying an existing timer. Why doesn't
.\" timerfd() provide this functionality?
The
.I ufd
argument is either \-1 to create a new timer,
or a file descriptor referring to an existing timerfd timer.
The remaining arguments specify the settings for the new timer,
or the modified settings for an existing timer.
The
.I clockid
argument specifies the clock that is used to mark the progress
of the timer, and must be either
.BR CLOCK_REALTIME
or
.BR CLOCK_MONOTONIC .
.B CLOCK_REALTIME
is a settable system-wide clock.
.B CLOCK_MONOTONIC
is a non-settable clock that is not affected
by discontinuous changes in the system clock
(e.g., manual changes to system time).
See also
.BR clock_getres (3).
The
.I flags
argument is either 0, to create a relative timer
.RI ( utmr.it_interval
specifies a relative time for the clock specified by
.IR clockid ),
or
.BR TFD_TIMER_ABSTIME ,
to create an absolute timer
.RI ( utmr.it_interval
specifies an absolute time for the clock specified by
.IR clockid ).
The
.I utmr
argument specifies the initial expiration and interval for the timer.
The
.I itimer
structure used for this argument contains two fields,
each of which is in turn a structure of type
.IR timespec :
.in +0.5i
.nf
struct timespec {
time_t tv_sec; /* Seconds */
long tv_nsec; /* Nanoseconds */
};
struct itimerspec {
struct timespec it_interval; /* Interval for periodic
timer */
struct timespec it_value; /* Initial expiration */
};
.fi
.in
.PP
.IR utmr.it_value
specifies the initial expiration of the timer,
in seconds and nanoseconds.
Setting both fields of
.IR utmr.it_value
to zero will disable an existing timer
.RI ( ufd
!= \-1),
or create a new timer that is not armed
.RI ( ufd
== \-1).
Setting one or both fields of
.I utmr.it_interval
to non-zero values specifies the period, in seconds and nanoseconds,
for repeated timer expirations after the initial expiration.
If both fields of
.I utmr.it_interval
are zero, the the timer expires just once, at the time specified by
.IR utmr.it_value .
.PP
.BR timerfd (2)
returns a file descriptor that supports the following operations:
.TP
.BR read (2)
.\" FIXME Davide, What I have written below is what
.\" I've determined from looking at the source code
.\" and from experimenting. But is it correct?
If the timer has already expired one or more times since it was created,
or since the last
.BR read (2),
then the buffer given to
.BR read (2)
returns an unsigned 4-byte integer
.RI ( uint32_t )
containing the number of expirations that have occurred.
.\" FIXME Davide, what if there are more expirations than can fit
.\" in a uint32_t? (Why wasn't this value uint64_t, as with
.\" eventfd()?)
.IP
If no timer expirations have occurred at the time of the
.BR read (2),
then the call either blocks until the next timer expiration,
or fails with the error
.B EAGAIN
if the file descriptor has been made non-blocking
(via the use of the
.BR fcntl (2)
.B F_SETFL
operation to set the
.B O_NONBLOCK
flag).
.IP
A
.BR read (2)
will fail with the error
.B EINVAL
if the size of the supplied buffer is less than 4 bytes.
.TP
.BR poll "(2), " select "(2) (and similar)"
The file descriptor is readable
(the
.BR select (2)
.I readfds
argument; the
.BR poll (2)
.B POLLIN
flag)
if one or more timer expirations have occurred.
.IP
The timerfd file descriptor also supports the other file-descriptor
multiplexing APIs:
.BR pselect (2),
.BR ppoll (2),
and
.BR epoll (7).
.SS fork(2) semantics
.\" FIXME Davide, is the following correct?
After a
.BR fork (2),
the child inherits a copy of the timerfd file descriptor.
The file descriptor refers to the same underlying
file object as the corresponding descriptor in the parent,
and
.BR read (2)s
in the child will return information about
expirations of the timer.
.SS execve(2) semantics
.\" FIXME Davide, is the following correct?
A timerfd file descriptor is preserved across
.BR execve (2),
and continues to generate file expirations.
.SH "RETURN VALUE"
On success,
.BR timerfd ()
returns a timerfd file descriptor;
this is either a new file descriptor (if
.I ufd
was \-1), or
.I ufd
if
.I ufd
was a valid timerfd file descriptor.
On error, \-1 is returned and
.I errno
is set to indicate the error.
.SH ERRORS
.TP
.B EBADF
The
.I ufd
file descriptor is not a valid file descriptor.
.TP
.B EINVAL
The
.I ufd
file descriptor is not a valid timerfd file descriptor.
The
.I clockid
argument is neither
.B CLOCK_MONOTONIC
nor
.BR CLOCK_REALTIME .
The
.I utmr
is not properly initialized (one of the
.I tv_nsec
falls outside the range zero to 999,999,999).
.TP
.B EMFILE
The per-process limit of open file descriptors has been reached.
.TP
.B ENFILE
The system limit on the total number of open files has been
reached.
.TP
.B ENODEV
Could not mount (internal) anonymous i-node device.
.TP
.B ENOMEM
There was insufficient memory to handle the requested
.I op
control operation.
.SH VERSIONS
.BR timerfd (2)
is available on Linux since kernel 2.6.22.
.\" FIXME . check later to see when glibc support is provided
As at July 2007 (glibc 2.6), the details of the glibc interface
have not been finalized, so that, for example,
the eventual header file may be different from that shown above.
.SH CONFORMING TO
.BR timerfd (2)
is Linux specific.
.SH EXAMPLE
.nf
.\" FIXME . Check later what header file glibc uses for timerfd
.\" FIXME . Probably glibc will require _GNU_SOURCE to be set
.\"
.\" The commented out code here is what we currently need until
.\" the required stuff is in glibc
.\"
.\" #define _GNU_SOURCE
.\" #include <sys/syscall.h>
.\" #include <unistd.h>
.\" #include <time.h>
.\" #if defined(__i386__)
.\" #define __NR_timerfd 322
.\" #endif
.\"
.\" static int
.\" timerfd(int ufd, int clockid, int flags, struct itimerspec *utmr) {
.\" return syscall(__NR_timerfd, ufd, clockid, flags, utmr);
.\" }
.\"
.\" #define TFD_TIMER_ABSTIME (1 << 0)
.\"
/* Link with -lrt */
#include <sys/timerfd.h> /* May yet change for glibc */
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h> /* Definition of uint32_t */
#define die)
die("clock_gettime");
}
if (clock_gettime(CLOCK_MONOTONIC, &curr) == \-1)
die( utmr;
int max_expirations, tot_exp, tfd;
struct timespec now;
uint32_t exp;
ssize_t s;
if ((argc != 2) && (argc != 4)) {
fprintf(stderr, "%s init\-secs [interval\-secs max\-exp]\\n",
argv[0]);
exit(EXIT_FAILURE);
}
if (clock_gettime(CLOCK_REALTIME, &now) == \-1)
die("clock_gettime");
/* Create a CLOCK_REALTIME absolute timer with initial
expiration and interval as specified in command line */
utmr.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
utmr.it_value.tv_nsec = now.tv_nsec;
if (argc == 2) {
utmr.it_interval.tv_sec = 0;
max_expirations = 1;
} else {
utmr.it_interval.tv_sec = atoi(argv[2]);
max_expirations = atoi(argv[3]);
}
utmr.it_interval.tv_nsec = 0;
tfd = timerfd(\-1, CLOCK_REALTIME, TFD_TIMER_ABSTIME, &utmr);
if (tfd == \-1)
die("timerfd");
print_elapsed_time();
printf("timer started\\n");
.\" exp = 0; // ????? Without this initialization, the results from
.\" // read() are strange; it appears that read() is only
.\" // returning one byte of tick information, not four.
for (tot_exp = 0; tot_exp < max_expirations;) {
s = read(tfd, &exp, sizeof(uint32_t));
if (s != sizeof(uint32_t))
die("read");
tot_exp += exp;
print_elapsed_time();
printf("read: %u; total=%d\\n", exp, tot_exp);
}
exit(EXIT_SUCCESS);
}
.fi
.SH "SEE ALSO"
.BR eventfd (2),
.BR poll (2),
.BR read (2),
.BR select (2),
.BR signalfd (2),
.BR epoll (7),
.BR time (7)
.\" FIXME See: setitimer(2), timer_create(3), clock_settime(3)
.\" FIXME other timer syscalls, and have them refer to this page
.\" FIXME have SEE ALSO in time.7 refer to this page.
Linux is a registered trademark of Linus Torvalds | http://lwn.net/Articles/245544/ | crawl-002 | refinedweb | 2,273 | 68.47 |
As a C# developer you're accustomed to working with interfaces, classes, and subclasses.
C# has the 'as' keyword to cast an object from one type to another. For example:
private void SomeEventHandler(object sender, EventArgs e){ var someThing = sender as SomeClass; // ...}
Furthermore, in C#, the
as type-cast expression returns null if the object and target type are incompatible.
using System;public class Program{ public interface IThing {} public class A : IThing {} public class B : IThing {} public static void Main() { IThing thing = new A(); var a = thing as A; var b = thing as B; Console.WriteLine(a == null); // False Console.WriteLine(b == null); // True }}.
All the type-checking information is discarded when the TypeScript is compiled into JavaScript.
So if you were accustomed to C# and had the following TypeScript code, you might be surprised to find that
b is not
null.
type IThing = {};class A implements IThing {}class B implements IThing {}const thing: IThing = new A();const a = thing as A;const b = thing as B;console.log(a == null); // falseconsole.log(b == null); // false !!!
The TypeScript compiler produces this ES5 JavaScript:
var A = (function () { function A() { } return A;}());var B = (function () { function B() { } return B;}());var thing = new A();var a = thing;var b = thing;console.log(a == null); // falseconsole.log(b == null); // false !!!
Remember,
as is only for telling the type checker to treat something as a different type. | https://decembersoft.com/posts/typescript-vs-csharp-as-keyword/ | CC-MAIN-2018-43 | refinedweb | 232 | 66.84 |
You can find chinese version of this article here : Deferred應用的實例 : retry
—
For grabbing pages from websites with twisted, you can write this:
getPage("").addCallback(printPage)
But what about the HTTP server is too busy to response? Your getPage fails. For reasons, you have to modify your program to retry once the getPage failed. So you might write a method like this:
getPageRetry(5, "")
Well, it seems works fine, but how about you got some other operations to retry? connectToClient, getTime and so on. You have to write
connectToClientRetry(5, "example.com") getTimeRetry(5, "timeserver.com")
You have to write retry-version version of every function that may fail. That’s not a good idea. Twisted provides a very beautiful ansyc callback object named Deferred. It looks like Chain-of-responsibility, but it can also handle errors well. With its beautiful design, I wrote a retry function that can warp all function return Deferred that might fail. That’s no need to modify any exists code of getPage to make it to retry automatically. Here is the recipe:
import logging from twisted.internet import defer log = logging.getLogger('retry') def retry(times, func, *args, **kwargs): """retry a defer function @param times: how many times to retry @param func: defer function """ errorList = [] deferred = defer.Deferred() def run(): log.info('Try %s(*%s, **%s)', func.__name__, args, kwargs) d = func(*args, **kwargs) d.addCallbacks(deferred.callback, error) def error(error): errorList.append(error) # Retry if len(errorList) < times: log.warn('Failed to try %s(*%s, **%s) %d times, retry...', func.__name__, args, kwargs, len(errorList)) run() # Fail else: log.error('Failed to try %s(*%s, **%s) over %d times, stop', func.__name__, args, kwargs, len(errorList)) deferred.errback(errorList) run() return deferred
Here you are! Now you can use it to make your operation to retry automatically!
from twisted.internet import reactor from twisted.web.client import getPage def output(data): print 'output', data def error(error): print 'finall error', error d = retry(3, getPage, '') d.addCallbacks(output, error) d = retry(3, getPage, '') d.addCallbacks(output, error) reactor.run()
Pingback: Tweets that mention An auto-retry recipe for Twisted. » 程式設計 遇上 小提琴 -- Topsy.com | https://blog.ez2learn.com/2009/09/26/an-auto-retry-recipe-for-twisted/ | CC-MAIN-2021-10 | refinedweb | 361 | 62.34 |
I learned that PostgreSQL is written in C. I would like to extend it
by
I feared so far to use PostgreSQL because it is written in C. However,
I've seen on the PostgreSQL about page ()
that they support "library inter
I am learning generics.
I tried below code:
For
HashSet
Set<Object> setOfAnyType = new
HashSet<Object>();setOfAnyType.add(1);setOfAnyType.add("abc");
But When I try same thing
in ArrayList of type Object and try to insert integer and String it gives
me compile time error why?.Please guide.
Li
I was doing my usual "Read a chapter of LYAH before bed" routine,
feeling like my brain was expanding with every code sample. At this point I
was convinced that I understood the core awesomeness of Haskell, and now
just had to understand the standard libraries and type classes so that I
could start writing real software.
So I was reading the
chapter about applicative functors when
I have a method on an object oriented database that creates tables based
on their type.
I want to be able to send a list of types to get
created, but i'm hoping to limit them to only classes derived from a
specific base class (MyBase).
Is there a way i can require this
in the method signature?Instead of
CreateTables(IList<Type> tables)
this is the document link: "Mapping SQL and Java Types"
let's see 8.9.3 JDBC Types Mapped to Java Object Typesat row:
TIMESTAMP - java.sql.Timestamp
but when I use getObject() with
oracle database on a TIMESTAMP column, the return type is
oracle.sql.TIMESTAMP, it can not been cast to java.sql.Timestamp
I know that I can use getTimestamp() but I need ge
I have a project containing POCO entities. A database context has been
created for it using Entity Framework 4.2 and code first. This works fine,
but the context needs to be exposed as an OData service which does not
work.
Browsing to the OData service gives this error:
The property 'DataSubmissionItems' on type
'Lifecycle.ProgramReportSubmission.Model.ProgramRe
Given:
#include <functional>class
world_building_gun;class tile_bounding_box;typedef
std::function<void (world_building_gun, tile_bounding_box)>
worldgen_function_t;void foo() { worldgen_function_t v; worldgen_function_t w(v);}
Should this
compile? My compilers say:
Yes: GCC/stdlibc++ (a
I am trying to figure out how to use the Boost.Preprocessor library to unfold a
"generic" type for different specific types. Below I will ask this for a
simple point class example. Given:
struct
Point##TYPE_SUFFIX_NAME{ TYPE X; TYPE Y;
// Other code};
I want to gene
I often find myself needing to compose a list of items from attributes
of another list of items.An approach I take is often similar to the
following:
public class MyClass {
public Guid Identifier { get; set; } public byte[] Bytes {
get; set; } public int ForeignKey { get; set; }
public static List<MyClass&g
I have a class with a Property called 'Value' which is of type
Object.Value can be of any type, a structure, a class, an array,
IList etc.
My problem is with the setter and determining
whether the value has changed or not.This is simple enough for value
types, but reference types and lists present a problem.
For a
class, would you assume that the Equals metho | http://bighow.org/tags/Types/1 | CC-MAIN-2018-05 | refinedweb | 546 | 62.27 |
“We should make an app”, says your boss while playing with her new smartphone. This statement tends to can get very expensive and scary for developers since there are so many “app” platforms out there. Yet, it is a totally valid request from a product owner. Luckily for us, Microsoft has our back by giving us a solution that can make building multi-platform apps easier with HTML5 and Internet Explorer 9.
The goal with this article is to demonstrate how you can build multi-platform apps by building up a code base in HTML5 and JavaScript that provides different custom user experiences depending on the platform your user prefers. We won’t be going into the intimate details about each step, rather we will be looking at how we can combine a number of techniques discussed thoroughly on the web (see the links throughout the article) build cool “apps” with HTML5. This article comes to us courtesy of.
Author’s Note: A completed version of the app this article talks about is available at for you to download and follow along.
Iteration 0: Ideation and Design Phase
Before starting, think about what multi-platform apps are, such as the Facebook or Twitter app that you use in your browser, your phone, or your desktop. On the technical side, they are very different since each platform uses a different technology (Silverlight, Objective-C, HTML), but to the user they are just different experiences of the same thing.
This idea that we will be able to build multi-platform apps with a single code base of HTML and JavaScript, making it easier to maintain and cheaper to produce. It will be easier to maintain because we’ll only need to know how to use one technology set (HTML5) and it will be cheaper because as we move forward to our other apps,we won’t need to start from scratch.
That’s enough talk. Let’s get started.
The app we are going to build is going to be an Expert Directory app that allows users to browse through contacts for a company, in my case the company is Imaginet. There will be a list of contacts displayed on screen, and when one is selected that contact’s details will appears.
Here is a simple sketch to help visualize what we are going to build.
Keep in mind that this is only a sketch, which is really meant to demonstrate how things are laid out rather than how they will look in the end. The user will be able to select a name on the left and their details on the right.
With our idea clear and our design complete, let’s get to the code.
Iteration 1: The Web App (HTML)
Our first goal will be to build our web app, or web experience. To do this, we are going to use all of the tools in the HTML5 arsenal which consists of HTML5, CSS3, and everybody’s favourite language JavaScript (I’ll talk more about that later). By using HTML5 and starting with the web experience, we get our app out there to the public quickly. HTML5 is also supported a pretty much every modern device you can think of, from phones, to tablets, to your PC. With the multi-platform support of HTML5 and JavaScript we can easily extend that code to support further platforms outside the browser, but more on that later.
To start, we are going to use HTML mark-up with some CSS and get things laid out properly.
Our code is pretty straightforward HTML, except that we are using the new semantic tags like section and nav to provide some metadata to how our app is organized.
The semantic tags make it easier for screen readers to go through our web app and for some web crawlers crawl our site and understand what is what. With that laid out, we apply some CSS floating and positioning, and we are in business.
Author’s Note: This article is not focusing on backwards compatibility, but if you are worried about these new tags working in older browsers like IE7 or IE8, you can include use the Modernizr JavaScript library to make them work properly.
With our UI laid out, we are ready to move onto the logic side of things. For that, we are going to use JavaScript.
Iteration 2: The Web App (JavaScript)
This is the part where developers tend to shy away because they don’t think you can build a full application nothing but JavaScript. If you asked me two years ago, I would agree with you, but now I think it can really hold its own if you know what you’re doing.
Author’s Note: If you need some convincing, check out some articles by Julian M. Bucknall about JavaScript for C# developers, or if you like books on code check out JavaScript: The Good Parts by Douglas Crockford for a clear understanding of the language in a little over 100 pages.
We are going to use JavaScript for two things: our application logic and to create a contact object to encapsulate our contact data. In the src folder, you will see two files where main.js is the application logic and contact.js is the contact object. Let’s start with main.js.
main.js
All of the JavaScript for the application is kept under a JavaScript namespace called SampleApp. By doing this we keep all of our functions and variables out of the global namespace and prevent our variable writing over something else, or someone writing over our own.
You might have also noticed that the images of code are from Visual Studio 2010. I tend to use VS2010 for my web development because: a) I’ve been working with VS since 2005, but not for web and b) the JScript Editor Extensions make the environment feel like my C# environment with code folding and intellisense.
All of the JavaScript code is kicked off with the SampleApp.initialize function (which is called on load because of the parentheses at the end of the function). The other function to check out is SampleApp.showContact which is the majority of our presentation logic, as it display the contact information stored in the second half of our JavaScript code, the contact object.
contact.js
Many developers believe that JavaScript cannot be an object oriented language. Fortunately for all us mutli-platform developers out there, they are wrong. I won’t get into the details here, but there are some great resources like this article from the MSDN or this one from Script Junkie that walk you through how to JavaScript to get things like public and private variables, or inheritance between objects.
For us, we only need one object, the contact object. Our object is pretty simple as it really just contains a number of getter functions and a couple of helper functions that fetch the private variables for us, which I do just like I would in any other OO application.
With our object created, you can see it being used extensively throughout main.js. We create new ones in SampleApp.setupData, and use the object’s functions in SampleApp.showContact.
With all our JavaScript written, and tied together with event handlers, we officially have an app!
…Unfortunately, it doesn’t look to hot, but we can fix that with a little CSS3.
Iteration 3: The Web App (CSS3)
CSS has really been the magic of the web for a long time, but for us it will be the magic for our multi-platform app (in more ways than one). For this bit of magic, we are going to make it look good with our traditional practices, but make some of that painful work easy with some of the new features, like Box Shadow.
Generally, when it comes to implementing drop shadows or rounded corners developers tend to cringe, including me. With CSS3, the new box-shadow and border-radius property makes it easy-peezy lemon squeezy. Check out the class with this code:
And with that, take a look at our app:
The JavaScript we are using on the presentation logic is displaying the contact and making the social media icons fade out if we don’t have that data (click on Ryan to see what I mean). The hover over effect is 100% CSS.
And there you have it! The Web Experience for our Expert Directory App is complete! We can push this out onto the web and get people using it ASAP. But that is only one platform, and one experience. Thanks to IE9, we can take our app experience beyond the web and go further by providing a desktop experience to our users.
Iteration 4: The Desktop App
Our next stop is the desktop experience, which if you think about desktop and web apps, they really aren’t all that different from the user experience side of things.
Web apps live inside of a web browser, which in turn, is a desktop app. One of the major differences in the experience is that when you use a web app, the window in which you view your app is part of the web browser experience, rather than your app’s experience. For example, the taskbar shows the web browser icon and provides web browser functions (in the case of Windows 7), and the look of browser window itself is branded for the developers of the web browser.
If we could change the web browser experience to better reflect our web app when it’s on screen, then we could provide our users with a custom desktop experience, and with Internet Explorer 9 Pinned Sites, we can do that with our existing code base.
I won’t go through the details of the implementation because there is a much better resource than this. Follow the first two steps at and you’ll be done.
In our Expert Directory App, used the Imaginet sphere as my favicon, and added a bit of JavaScript to read query string arguments (see SampleApp.SetupUI to see the code in action). This allowed me to setup custom URLs based on their index in the SampleApp.contact array, and select the appropriate contact to appear when clicked on in the jump list.
Once the user pins the site to their taskbar, we not only get a branded window, but we also get some custom functionality in the taskbar. And with that, we have taken our existing code and expanded it to provide a custom desktop experience.
Author’s Note: I strongly recommend that you complete step 5 in the BuildMyPinnedSite tutorial as you’ll want to make sure your users know they can make your app a desktop app with no work at all.
Future Iterations: Mobile and Windows 8 [Hopefully]
With the web and desktop experiences in the bag, we can take our code back to our boss’ smartphone by using Media Queries in CSS3. Media queries allow you to put some logic around your styling rules in CSS. If you check out the future-style.css you will these examples:
The first query will apply the style wp7 only to devices that have a maximum width of 480px (e.g. Windows Phone 7, iPhones, etc…). If you don’t want to be specific at the device level, you can apply your rules based on the browser width rather than getting device specific.
Microsoft has even announced the HTML5 and JavaScript apps will be able to run natively in the next version of Windows, which opens all kinds of new possibilities for the experiences we can provide for other devices.
In Conclusion…
I really hope that this post demonstrated that HTML5 and JavaScript have really come a long way from the days of Geocities and the infamous blink tag. If you have avoided JavaScript for this long, it just might be the time to start looking into again and see what experiences you can build with HTML5.
The code is not published at codeplex.
I will check with David and see when it will be posted
The Source Code is now on Codeplex for download under the source code tab appswithhtml5.codeplex.com/…/changesets
I got it. Thanks for the post and sample! | https://blogs.msdn.microsoft.com/cdndevs/2011/09/20/multi-platform-apps-with-html5-and-ie9/ | CC-MAIN-2018-09 | refinedweb | 2,059 | 67.49 |
Grzegorz Kossakowski skrev:
> Hi,
>
> It's been three times that I reverted my changes introducing ObjectModel
> interface and using it in Template generator. I must admit that I got
> stuck in unproductive state because I'm constantly unhappy with the
> design.
You are probably striving for perfection and think that you can achieve
it by staying in the design phase just a little bit longer. But it
doesn't work that way. Perfection takes for ever and we don't have that
much time ;) Be happy with what is good enough.
Also you need to start implementing your design. Choose a design (NOW!),
stick with it for a while and implement the important parts of it in the
simplest possible way. By doing this you get *real* experience with the
pros and cons of your design choices and can refactor and redesign if
necessary until it becomes good enough. You will also get better
feedback from the rest of us by committing code.
As a good rule of thumb: when the design phase stops to be stimulating
and has become frustrating it is better to start to implement something ;)
Just as an example, the servlet service framework in its current shape
is the fifth mayor reimplementation since we started to actually
implement it. Before that the community did design for a couple of
years, which in the end was really frustrating for everyone involved.
Also we spent so much time implementing things that would have been
certainly would have been nice to have but that is not part of the
current implementation.
> Let me share my troubles in a hope that someone is much clever
> than me and will give some advise.
>
> As discussed earlier[1][2], Object Model will be simple Map that can
> contain more than item for each key and preserves order in which items
> were added. I found (after several attempts to invent one myslef)
> MultiMap[3] interesting and close to what I want to achieve. It resulted
> in very simple ObjectModelImpl[4]
I'm not convinced. I would prefer to just use an implementation of the
ordinary Map that returns *one* item for each key (respecting the stack
order in the underlying stack based model).
While the MultiMap idea solves the problem of "../1" patterns in the
map: EL, it complicates all the rest of the ELs. Normally, there is no
point in being able to be able to access values for a parameter name
that are shadowed by newer values in a stack based context. The only
reason that this is needed in the map language is that the parameter
naming is automatic 1,2,3,... so that values that you might need are
shadowed automatically. It would have been better if the map language
would have had user named parameters instead, it would have been easier
to understand and we wouldn't have the current problem.
I would propose that we create a new interface that extends Map and
provide a method like:
List getStack(Object key);
or something similar. Then the map language implementation could depend
on this interface for handling its stack access, while the rest of the
ELs only needs to do access on a Map.
> that is only a prototype and will be
> replaced by Spring's, scoped bean that will utilize CallStack as Daniel
> proposed earlier.
I've changed my mind ;) I still believe that using a custom Spring scope
that is similar to the CallStack is a good idea. But I think it might be
overly complicated to evolve the current CallStack implementation so
that it covers all our stack based bean access needs. I think it is
better to have an own stack for the object model. Then we can see at a
later stage if we can find some common abstraction. Right now I'm afraid
that it would just complicate things.
> I wanted to use ObjectModel interface in cocoon-template-impl and
> cocoon-expression-langauge-impl modules. After reading all the code I
> found that current implementation is little unsatisfying. I'll explain
> my concerns.
>
> Let's examine how ExpressionContext[5] class looks like and what's
> purpose.
The design was based on Jex a
whiteboard project in Jakarta commons. Compared to that it was
simplified, Avalon based and adapted to Cocoon's needs. More about the
design can be found here.
> Basically, it's a holder for data passed to expression
> evaluators. It can contain several named variables, context bean and
> namespace table. This class is really vague for me because:
> * it's not clear what's the difference between context bean and named
> variables (you can put everything everywhere)
> * namespace table is very mysterious thing when it comes to general
> data holder and seems to be very specific
>
> To find out what's the purpose for variabales/context bean you must take
> a look at all implementations of Expression interface and find that it's
> rather JXPath-specific feature. If ExpressionContext holds something as
> variable ("variable1") you can access that data by using
> "$variable1/[...]" expression, if the same data is held as context bean
> it's available by "./[...]".
It is a JXPath specific feature.
> Other expression languages implementations
> ignore variables completely so if you happened to rely on this feature
> you are in big trouble. How intuitive...
Might be. But it is not that easy, JXPath is supposed to be applied on a
bean (or DOM) and optionally parameters. Jexl on a map. I felt that
restricting to a common subset of input had been to limiting. You will
be in big trouble if you try to access an XML DOM with Jexl, but it
works fine with JXPath.
For our current use, my design was probably overly generic. We could
remove the contextBean and replace it with a reserved variable name in
the map in the context.
> Namespace table is also very specific to JXPath (because only JXPath has
> concept of namespace implemented) and I'll not discuss in detail how it
> works. It only makes me wonder why it is put in rather general
> ExpressionContext class.
No idea, I was not involved in implementing this part.
> Situation is even more worst because Template
> generator uses this namespace table for its very internal reasons
> (emitting right SAX events, cleaning up namespace declarations and so on).
>
> I'll show you, as an example, execute() method of
> o.a.c.template.script.event.Event class:
>
> public Event execute(final XMLConsumer consumer,
> ExpressionContext expressionContext,
> ExecutionContext executionContext,
> MacroContext macroContext, Event startEvent,
> Event endEvent)
> throws SAXException {
> return getNext();
> }
>
> You can see that method's signature is already quite fat - there are
> three different contexts. What I'm going to propose is not much better
> because I want to introduce one more argument (NamespaceTable
> namespaces) and change existing ExpressionContext expressionContext to
> ObjectModel objectModel. I just want to move namespace handling out of
> general interface for data holders.
>
> Before calling Expression#evaluate() I would like to add namespace table
> to Object Model with "namespace" (or similiar) key so it's available for
> JXPath implementation.
Sounds reasonable.
> Ok, I'm not sure if such approach of slimming interface to absolute
> minimum and putting things in a Map is right but nothing better comes to
> my mind.
>
>
> Could you give your advice? I'm really afraid that I'd made a commit
> only to realize that my changes are dumb and there is better design.
You are taking things to seriously. Don't worry, just commit things and
refactor and change them later if you or anyone else get a better idea.
By not committing, you can be absolutely sure that your work will be of
no use.
/Daniel | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200707.mbox/%3C4698C729.20205@nada.kth.se%3E | CC-MAIN-2014-52 | refinedweb | 1,279 | 61.36 |
Modifying features
Now that we have a way for users to load data into the editor, we want to let them edit features. We'll use the
Modify interaction for this, configuring it to modify features on our vector source.
First, import the
Modify interaction in your
main.js:
import Modify from 'ol/interaction/Modify';
Next, create a new interaction connected to the vector source and add it to the map (at the bottom of
main.js):
map.addInteraction( new Modify({ source: source, }) );
After adding data to the map confirm that you can modify features by dragging their vertices. You can also delete vertices with
Alt+Click.
| https://openlayers.org/workshop/en/vector/modify.html | CC-MAIN-2021-43 | refinedweb | 107 | 54.52 |
This code is a skeleton for perl modules. It allows you to access object variables using methods instead of using the actual hash:
Instead of $object->{'title'} = 'code';
you could use:
$object->title('code');
and to get the title:
$object->title();
Your code is easier to read and you don't have to write custom methods for each of your variables.
Perl
package Package::Name;
use strict; ##If you don't use strict a baby kitten dies
sub new{
my $class = shift;
my $this;
## Declare variables here. Remember to put in the
## full namespace.
$this->{'Package::Name::title'} = "";
$this->{'Package::Name::author'} = "";
...
bless $this, $class;
return $this;
}
sub AUTOLOAD{
my $this = shift;
my $name = our $AUTOLOAD;
die "Not an object!" unless ref($this);
return if $name =~ /::DESTROY$/; ## Let destroy fall through
unless (exists $this->{$name}){
die "Can't access '$name' field in $this";
}
if(@_) {
return $this->{$name} = shift;
} else {
return $this->{$name};
}
my $obj = new Package::Name;
$obj->title('Demonstrating Usage');
$obj->author('joshschulz');
print $obj->title()."\n".$obj->author();
would print:
Demonstrating Usage
joshschulz
I've been using this for a while, but I have a feeling I may have borrowed the idea from someone. If I have please take your credit. | http://it.toolbox.com/wiki/index.php/Automatically%5FBuild%5Faccessor%5Fmethods%5Fusing%5FAUTOLOAD | crawl-002 | refinedweb | 204 | 57.71 |
Message-ID: <1051136240.683.1429334254999.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_682_1177108972.1429334254999" ------=_Part_682_1177108972.1429334254999 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location:
Joram?=20 effel.php=20
We'll go for dinner and this is a perfect occasion for other people to j= oin informally to meet up.=20
We meet up in Hotel Steigenberger between 19:00 = and 19:30. At 19:30 we leave for the restaurant.=20
Please put your name here or send me (t o m a t alfresco d-o-t com) a ma= il if you want to join so that we can book a restaurant.=20
We'll probably meet up around 18:30 s= omewhere in the center of Stuttgart. Later will list the exact time a= nd date. List your name if you want to join.=20
Currently there is the strategy of se= tup building jars containing configurations. There is the programmatic crea= tion of a process engine, there is the ProcessEngines registry and the serv= let for automatic initialization.=20
We should establish a common strategy= on how we deal with configuration files and initialization.=20
Following aspects should be considere= d and as much as possible unified:=20
Should the test utilities and APIs be= split off into a separate project? Would mean only unit tests in activiti-= engine (but that's the way it is now anyway).=20
Current architecture=20
Alternatives=20
Is the current architecture OK for 5.0?=20
Biggest question around BPMN is the s= uitability for developers. jPDL was much more readable. Will BPMN shortcut = suffice? Will just have to take the pain of a verbose language? Or do we ne= ed to go for usability, compactness and readability without compromises.=20
How do we make it easy for users to w= ork with all these namespaces (if we decide to put custom conveniences in n= amespaces)=20
Is there a clear scope we can target?= Simple or descriptive conformance? Maybe Bernd could prepare this topic as= he's closest to the spec. But most important is not the knowledge of the a= ctual conformance, but arguments that give us guidance on what kind of conf= ormance we target and how strict we'll be. The alternative is that we defin= e our own subset of what we think is useful.=20
Database upgrades. Automatic QA for u= pgrade.=20
The biggest question here is: How wil= l we align the roadmap of researching the cloud solution with the roadmap t= owards 5.0GA in november?=20
An important aspect of cloud is the q= uery API. We currently plan to build out the query API similar to jBPM 4. F= or example=20
taskService.createTaskQuery() .processInstanceId(processInstanceId) .activityName("task1") .orderAsc(TaskQuery.PROPERTY_NAME)=20
But that might be hard to implement on cloud persistence. Maybe there ar= e solutions. MapReduce?=20
Define PVM event (api)/history event/event (listeners) and map it to BPM= N=20 | http://docs.codehaus.org/exportword?pageId=158138429 | CC-MAIN-2015-18 | refinedweb | 516 | 58.89 |
If you’re marketing an app, you likely keep a close eye on how many daily active users, or DAUs, are taking action within your app.
Why? Well, many companies consider DAUs to be the most significant measure of product stickiness and growth – two factors imperative to measuring the success of your app.
Okay, so you have your DAUs. Any app does. What’s the issue? It’s how, over time, the retention stats don’t look great for a typical app.
According to an in-depth study by Quettra, the average app loses 77% of its DAUs within the first 3 days of installation. Within 30 days, it’s lost 90% of DAUs. That’s pretty drastic.
Now before you think “that study has to be incorrect; our own experience is different, we’re seeing lots of regular engagement,” note that a lost DAU is not completely inactive – it may be a user that’s taking action a few times a month. Losing a Daily Active User isn’t the same as losing a Monthly Active User, but they do correlate.
So how do you bolster and sustain meaningful engagement with your app, and retain existing DAUs and even convert others into using it more frequently?
Why use email to drive DAUs?
As we’ve mentioned before, email isn’t going anywhere. With a predicted 255 million users in just the US by 2020, email is a channel that retains enormous reach and effectiveness. After all, it’s all about reaching your audience, and chances are pretty high that your audience is looking at their inbox at least once a day (if not constantly). And a lot of younger or more app-savvy consumers view email as a key channel.
What’s wrong about relying mainly on push notifications? With the number of apps on individual devices soaring, consumers are growing more likely to download apps and then abandon them. Email is a channel to reach them that’s both non-intrusive and effective because of the fact its users feel they’ve got more power over it.
Push notifications, on their own, may not be enough to recover users who have forgotten about your app or may be slacking off in usage. They’ve got a short character limit and rigid structure; even with emojis, there’s only so much a marketer can do with that. Plus, once they’ve abandoned the app, users are likely to turn off notifications, if they haven’t already. Some users simply don’t want to see them.
Email offers way more leeway in grabbing the user’s attention. As a marketer, focusing on optimizing what you do within their inbox opens up a world of possibility with images, messaging and personalization options.
We aren’t saying you should overlook other channels – omnichannel marketing succeeds by integrating different ones seamlessly. Stir in your push notifications and targeted ads, but with its wide reach and range of possibilities, don’t neglect email.
Types of DAU-directed emails
Here are some of the building blocks of a campaign aimed at retaining DAUs, or turning other users into DAUs. But one reminder: Don’t forget to test. No matter what type of email program you mount, A/B testing of different message types, timing, frequency, copy, creative, and incentives is always the key to success.
A simple welcome email can bring your app to the front of mind for users and tip some of them into usage. Beyond reminding them why they downloaded your app, you can offer help with set-up, quick tips for using or navigating the app, or just thank them for their download.
Thank-you emails have an engagement rate of 62% and every marketer pulling his/her weight should be tapping into that. Everyone likes being thanked!
Onboarding
Sending users step-by-step instructions helps them become comfortable with your app, making them more likely to engage with it. Depending on your app’s functionality, you may want to have a more protracted onboarding campaign to get them really enmeshed in the orientation process over a longer time.
There may be hidden features or options and settings that are tricky to navigate, or that you can deliberately “reveal” at later stages of the campaign.
Re-engagement
Whether a user didn’t complete signing up or has simply been inactive, email can provide the perfect tool for re-engagement.
This example from eFax, for instance, doesn’t offer anything new – the free trial is always included on signup – but it serves to remind the user why they signed up in the first place. They highlight some of the major features they offer, but place emphasis on messaging that’s structured around a keen financial motive: Stop wasting your money. Hard to argue with that, isn’t it?
Plus, eFax offers an incentive (more on these below) for customers to re-engage with the app: they’ll get a free month of service.
Here’s another approach to re-engagement: Cornerstone cares enough about the user’s reasons for not engaging with the app that they want them to fill out a survey. And by the way, they’ll give you free store credit for doing so.
Incentives
As we’ve just seen, another popular method of encouraging DAUs? Offer incentives. We’re only human, after all, and putting something in our pockets, or helping us save, always draws attention.
Emails that offer users a reason to return (particularly for financial reasons) get traction with users. While many products offer sign-up incentives, using them, later on, can lure a user back to engagement. Motivating customers to come back is crucial and it doesn’t have to be costly; a discount, free upgrade, or “Exclusive! Limited availability!” feature unlock might do the trick without breaking the budget.
One good point to remember about using incentives? A DAU isn’t necessarily generating value for you unless s/he’s taking specific actions that drive revenue, like buying stuff or shelling out for upgrades. Incentives help steer them down that path.
One company that constantly sends rewards and special offers through email is Starbucks. While the rewards are easily loaded into the app, most are first sent to the inbox and require users to engage before they activate.
Community Announcements
Everyone wants to think they’re hanging out with the popular crowd, right? So as your user community grows, make sure members know they’re part of a burgeoning bunch of fellow cool kids. Or at least like-minded people.
This accomplishes a few things: It lets the user know you value him/her, and that others have ratified that user’s app choice – the sheer popularity of a product can be motivating for some users. Also, it makes you look successful and stable, implying the app will be more likely to be updated and supported in the future.
Here’s an example from Readdle that hits that mark:
Usage Updates
One personalization tactic? Celebrate user engagement! This shows a user you’re paying attention, and you’re going to recognize them for engaging with your app. Or you can go even farther, in an entertaining way. Lyft provides a great example below: their “year in review” emails are really just showing users their own usage data, yet it’s a fun way for them to feel connected to the company and the use of its app.
By providing your users with a sense of accomplishment, you give them a reason to come back to you every day. Create some usage mileposts as the basis of a DAU-targeted campaign, even if they’re arbitrary or whimsical ones, to power emails that reward users with recognition so they can celebrate with a smile or a fist-pump.
~ Jen | https://www.sparkpost.com/blog/build-email-program-increase-daus/ | CC-MAIN-2020-05 | refinedweb | 1,304 | 61.46 |
The area under the receiver operating characteristic (AUROC) is a performance metric that you can use to evaluate classification models. (ref).
- For a binary handwritten digit classification model (“1” vs. “0”), the AUROC tells you the probability that a randomly selected “1” image will have a higher predicted probability of being a “1” than a randomly selected “0” image
AUROC is thus a performance metric for “discrimination”: it tells you about the model’s ability to discriminate between cases (positive examples) and non-cases (negative examples.) An AUROC of 0.8 means that the model has good discriminatory ability: 80% of the time, the model will correctly assign a higher absolute risk to a randomly selected patient with an event than to a randomly selected patient without an event.
How to interpret AUROC (ref)
Figure: ROC Curves (modified from this cartoon)
The figure above shows some example ROC curves. The AUROC for a given curve is simply the area beneath it.
The worst AUROC is 0.5, and the best AUROC is 1.0.
- An AUROC of 0.5 (area under the red dashed line in the figure above) corresponds to a coin flip, i.e. a useless model.
- An AUROC less than 0.7 is sub-optimal performance
- An AUROC of 0.70 – 0.80 is good performance
- An AUROC greater than 0.8 is excellent performance
- An AUROC of 1.0 (area under the purple line in the figure above) corresponds to a perfect classifier
How to calculate AUROC
The AUROC is calculated as the area under the ROC curve. A ROC curve shows the trade-off between true positive rate (TPR) and false positive rate (FPR) across different decision thresholds. For a review of TPRs, FPRs, and decision thresholds, see Measuring Performance: The Confusion Matrix.
In plotted ROC curves (e.g. the figure of the previous section), the decision thresholds are implicit. The decision thresholds are not shown as an axis. The AUROC itself is also not explicitly shown; it is implied, as the area beneath the displayed ROC curve.
The x-axis of a ROC curve is the false positive rate, and the y-axis of a ROC curve is the true positive rate.
- A ROC curve always starts at the lower left-hand corner, i.e. the point (FPR = 0, TPR = 0) which corresponds to a decision threshold of 1 (where every example is classified as negative, because all predicted probabilities are less than 1.)
- A ROC curve always ends at the upper right-hand corner, i.e. the point (FPR = 1, TPR = 1) which corresponds to a decision threshold of 0 (where every example is classified as positive, because all predicted probabilities are greater than 0.)
- The points in between, which create the curve, are obtained by calculating the TPR and FPR for different decision thresholds between 1 and 0. For a rough, angular “curve”, you would use only a few decision thresholds: e.g. decision thresholds of [1, 0.75, 0.5, 0.25, 0]. For a smoother curve, you would use many decision thresholds, e.g. decision thresholds of [1, 0.98, 0.96, 0.94,…,0.08, 0.06, 0.04, 0.02, 0].
In the following figure, which shows ROC curves calculated on real data, the use of discrete decision thresholds is easier to appreciate in the jagged nature of the ROC curves:
Steps for calculating test set AUROC for a binary classification task:
- Train your machine learning model
- Use the trained model to make predictions on your test set, so that each example in your test set has a classification probability between 0 and 1.
- Using the model’s output predicted probabilities for the test set, calculate the TPR and FPR for different decision thresholds, and plot a ROC curve.
- Calculate the area under the ROC curve.
In practice, you don’t need to write code to calculate the AUROC manually. There are functions for calculating AUROC available in many programming languages. For example, in Python, you can do the following:
import sklearn.metrics
fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true = true_labels, y_score = pred_probs, pos_label = 1) #positive class is 1; negative class is 0
auroc = sklearn.metrics.auc(fpr, tpr)
First, you provide to the function sklearn.metrics.roc_curve() the ground truth test set labels as the vector y_true and your model’s predicted probabilities as the vector y_score, to obtain the outputs fpr, tpr, and thresholds. fpr is a vector with the calculated false positive rate for different thresholds; tpr is a vector with the calculated true positive rate for different thresholds; thresholds is a vector with the actual threshold values, and is just provided in case you’d like to inspect it (you don’t need the explicit thresholds vector in the next function.) The vectors fpr and tpr define the ROC curve. You then pass the fpr and tpr vectors to sklearn.metrics.auc() to obtain the AUROC final value.
When to use AUROC
The AUROC is more informative than accuracy for imbalanced data. It is a very commonly-reported performance metric, and it is easy to calculate using various software packages, so it is often a good idea to calculate AUROC for models that perform binary classification tasks.
It is also important to be aware of the limitations of AUROC. The AUROC can be “excessively optimistic” about the performance of models that are built for data sets with a much larger number of negative examples than positive examples. Many real-world data sets fit this description: for example, you would expect that in a data set drawn from the general population, there are many more healthy people (“negative for sickness”) than diseased people (“positive for sickness.”) In these cases, where true negatives dominate true positives, it may be difficult to use AUROC to distinguish the performance of two algorithms.
Why? In cases with many more negative examples than positive examples, a big improvement in the number of false positives only leads to a small change in the false positive rate. This is because false positive rate is calculated as false positives / (false positives + true negatives) and if we have a HUGE number of true negatives in the denominator, it’s going to be really hard to change the false positive rate only by changing the false positives.
Pretend Algorithm 1 has far fewer false positives than Algorithm 2 (i.e. Algorithm 1 is better). If the data has a lot of true negatives, the false positive rates of Algorithm 1 and Algorithm 2 are not going to be that different, and their AUROCs may not be that different.
Key takeaway: AUROC is a useful metric, but you should be aware that AUROC does not capture the effect of a large number of negative examples on an algorithm’s performance. An alternative performance metric that will not be “swamped” by true negatives is area under the precision-recall curve (AUPRC), which will be discussed in a future post.
Reference for this section (and a great resource for additional in-depth discussion): The Relationship Between Precision-Recall and ROC Curves
What if my model predicts more than two classes?
You can calculate the AUROC for each class separately, e.g. pretend that your task is composed of many different binary classification tasks: Class A vs. Not Class A, Class B vs. Not Class B, Class C vs. Not Class C…etc.
Nomenclature
The most common abbreviation for the area under the receiver operating characteristic is just “AUC.” This is poor terminology, as AUC just stands for “area under the curve” (and doesn’t specify what curve; the ROC curve is merely implied). Hence, in this post, I’ve preferred the abbreviation AUROC. You may also see the AUROC referred to as the c-statistic or “concordance statistic.”
The picture above shows an “auroch” , not to be confused with an “AUROC” :). The auroch is a now-extinct species of cattle that used to live in North Africa, Europe, and Asia. (Nature trivia brought to you by another member of Duke +DS who reminded me of aurochs in a discussion of the “AUROC” abbreviation.)
The end! Stay tuned for a future post about AUROC’s cousin, the AUPRC. | https://glassboxmedicine.com/2019/02/23/measuring-performance-auc-auroc/ | CC-MAIN-2021-39 | refinedweb | 1,369 | 53.61 |
Opened 3 years ago
Closed 3 years ago
#18701 closed Bug (fixed)
Class Based VIew docs about JSONResponseMixin misleading
Description
Maybe I am wrong but the docs suggest to use the JSONResponseMixin like so:
from django.views.generic import View class JSONView(JSONResponseMixin, View): pass
I feel that this doesn't make sense because View never calls any of the methods implemented in the JSONResponseMixin. It would make much more sense to inherit from TemplateView here instead of View.
The relevant part of the docs can be found here:
Change History (2)
comment:1 Changed 3 years ago by ptone
- Has patch set
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Ready for checkin
comment:2 Changed 3 years ago by aaugustin
- Resolution set to fixed
- Status changed from new to closed
Merged in [0d1653395b].
Note: See TracTickets for help on using tickets.
Yup.
I tried out githubs - edit file in browser with small change, create a pull request. Pretty easy.
I'm self marking this as RFC because it is pretty trivial | https://code.djangoproject.com/ticket/18701 | CC-MAIN-2015-32 | refinedweb | 181 | 63.12 |
Home > Products >
fresh vegetables Suppliers
Home > Products >
fresh vegetables Suppliers
> Compare Suppliers
Company List
Product List
< Back to list items
Page:1/3
Malaysia
Dear sir,
welcome on our ttnet.net home page, We are manufacturer and supplier of many type of fresh vegetables such as pure white fresh garlic...
Hungary
We are a Hong Kong Trading Company branched in East Europe.
China (mainland)
Our company, Heze Jianfeng Foodstuffs Co., Ltd. is a
manufacturer and exporter for frozen and fresh vegetables.
It lies in the south west of Sha...
Xuzhou Goodway Food Co., Ltd. is an manufacturer of
producing dehydrated vegetable and dehydrated fruits.
We also export fresh vegetable and fr...
India
Dear Sir,
We take the pleasure to introduce our company, Naushie Exports a well established International Trading company started in the year 1...
Swapna Exim Corporation is one of the budding export
company. The proprietor Dr. A. Balasubramanian, is a
veterinarian turned exporter. Our main...
We are direct distributor and exporter of fresh fruits and
vegetables from China. We would like to offer you the most
competitive price with hig...
We are an experienced company specialized in exporting
fresh mushrooms and vegetables. We keep a strict control on
quality which has earned us a...
Sukdeb Saha Export and Import is an established export
import house based at Kolkata, India. We supply regularly
the following items, cosmetics,...
Gaorong Group is one of Chinese leading agricultural
enterprises specializing in growing, processing, and
marketing fresh vegetables, mushrooms,...
Qingdao Timwel International Trading Co., Ltd. is a
joint-stock limited liability company that has own imports
and exports privilege. It locates...
Shandong Chizhong Group is one of the strongest and
integrated manufacturing companies in Shandong Province.
Shandong Province is the No. 1 agri...
Weifang Green Spring Food Co., Ltd. is one leading
Chinese manufacturer and exporter of Fresh, Frozen and
Dehydrated Vegetables & Fruits in Chin...
We are a professional processes and export of fresh,
frozen and dehydrated vegetables and fruits. Locates in
Shandong, a famous original place o...
Ningxia Winsell Trading Co., Ltd. is a professional trading
company supplying you satisfied products and services. We
process and pack various o...
Egypt
We are Exporters of high quality fresh and frozen fruits
and vegetables, Palm trees, ornamental plants , granite
stone & marble.. Since 2005 we ...
Heze Yusheng Agriculture Products Imp. & Exp. Company
Limited is a comprehensive trading company which is
specialized in exporting farm produce....
Our company is engaged in agricultural products import and
export. We are specializing in providing series products of
fresh vegetables and cann...
We proudly introduce ourselves as manufactures and
marketers of coir products. We are doing business since
1995. Our products are coir fiber, cu...
United Arab Emirates
SunImpex is a leading Supplier of agro products like Fresh Fruits-Vegetables,Fruit Juice Concentrates,Pulps,Purees,Herbs.We supply best quality...
We Inherent Food Exim Pvt. Ltd, one of the best quality
food exporters from India. We are into food business for
more then 30 years. We deal wit...
we produce quality agro products as Canned Pineapple
slices/ tid-bits/chunks etc, Canned Button/ P&S/sliced
Mushrooms etc, Wild Apple, Passion...
Jinxiang Jiahao International Trade Co., Ltd. is located in
Jining City, Shandong Province, the hometown of garlic and
also named as "the capita...
Our company is located in the central China, Henan
provinc, which is famous for its abundant agricultural
resource. We specialize in the export ...
Our company is specialized in exporting fresh fruit and
vegetables.
Our company is an agriculture IMP. & EXP. Trade company. It
mostly export many kinds of fresh fruits and vegetables.
They are garlic and some ...
SHANDONG HENGDA FOODS CO.,LTD is a enterprise integrates
planting, fresh-keeping, processing and trading of
vegetables. With the fixed assets of...
We take this opportunity to introduce ourselves as a
professional Chinese supplier which specialized in the
field of Manufacturing and Exporting...
Located in Zhangzhou City of Fujian Province, the Chinese
biggest mushroom and fruit city, occupying 80% of Chinese
edible fungus export volum...
Our factory established in 2006 guangdong province of
china. We are a professional manufacturer and specialized
in the PP thin plastic food cont...
Show:
20
30
40
Showing 1 - 30 items
Supplier Name
Year Established
Business Certification
Standard Fresh Vegetables Company
Hong Kong Bright Plan (Hungary) Ltd.
Heze Jianfeng Foodstuffs Co., Ltd.
Xuzhou Goodway Food Co., Ltd./Xuzhou Goodway Trading Co., Ltd
Naushie Exports Co., Ltd.
Swapna Exim Corporation
Shenzhen Spring Trading Co., Ltd.
Shanghai Pan-global Food Company
Sukdeb Saha Export and Import
Shanghai Gaorong Food Group
Qingdao Timwel International Trading Co., Ltd.
Shandong Chizhong Group
Weifang Green Spring Food Co., Ltd.
Jining Organ Trading Co., Ltd.
Ningxia Winsell Trading Co., Ltd.
Kemet Imp. & Exp. Co.
Heze Yusheng Agriculture Products Imp. & Exp. Co., Ltd./Chengwu Longda Cold Branch Co.
Qingdao Sino-world Trading Co., Ltd.
Dhanam International Co.
Sun Impex Co.
Inherent Food Exim Pvt., Ltd.
Himla Hills Offerings Pvt Ltd.
Shandong Jinxiang Jiahao International Tade Co., Ltd.
Henan Tianhui Trading Co., Ltd.
I & E International Co., Ltd.
Jinan Gogo International Trade Co.,Ltd.
SHANDONG HENGDA FOODS CO., LTD
Qingdao Goodluck Agriculture Co.,Ltd
Zhangzhou Xiangcheng Wanglong Trade Co., Ltd.
HANNAN PLASTIC CO.,LTD ZHONGSHAN
1
2
3 | https://www.ttnet.net/hot-search/suppliers-fresh-vegetables.html | CC-MAIN-2020-34 | refinedweb | 865 | 53.27 |
Test Organization
As mentioned at the start of the chapter, testing is a complex discipline, and different people use different terminology and organization. The Rust community thinks about tests in terms of two main categories: unit tests and integration tests. Unit tests are small and more focused, testing one module in isolation at a time, and can test private interfaces. Integration tests are entirely external to your library and use your code in the same way any other external code would, using only the public interface and potentially exercising multiple modules per test.
Writing both kinds of tests is important to ensure that the pieces of your library are doing what you expect them to, separately and together.
Unit Tests
The purpose of unit tests is to test each unit of code in isolation from the
rest of the code to quickly pinpoint where code is and isn’t working as
expected. You’ll put unit tests in the src directory in each file with the
code that they’re testing. The convention is to create a module named
tests
in each file to contain the test functions and to annotate the module with
cfg(test).
The Tests Module and
#[cfg(test)]
The
#[cfg(test)] annotation on the tests module tells Rust to compile and run
the test code only when you run
cargo test, not when you run
cargo build.
This saves compile time when you only want to build the library and saves space
in the resulting compiled artifact because the tests are not included. You’ll
see that because integration tests go in a different directory, they don’t need
the
#[cfg(test)] annotation. However, because unit tests go in the same files
as the code, you’ll use
#[cfg(test)] to specify that they shouldn’t be
included in the compiled result.
Recall that when we generated the new
adder project in the first section of
this chapter, Cargo generated this code for us:
Filename: src/lib.rs
# #![allow(unused_variables)] #fn main() { #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } #}
This code is the automatically generated test module. The attribute
cfg
stands for configuration and tells Rust that the following item should only
be included given a certain configuration option. In this case, the
configuration option is
test, which is provided by Rust for compiling and
running tests. By using the
cfg attribute, Cargo compiles our test code only
if we actively run the tests with
cargo test. This includes any helper
functions that might be within this module, in addition to the functions
annotated with
#[test].
Testing Private Functions
There’s debate within the testing community about whether or not private
functions should be tested directly, and other languages make it difficult or
impossible to test private functions. Regardless of which testing ideology you
adhere to, Rust’s privacy rules do allow you to test private functions.
Consider the code in Listing 11-12 with the private function
internal_adder.
Filename: src/lib.rs
# #![allow(unused_variables)] #fn main() { pub fn add_two(a: i32) -> i32 { internal_adder(a, 2) } fn internal_adder(a: i32, b: i32) -> i32 { a + b } #[cfg(test)] mod tests { use super::*; #[test] fn internal() { assert_eq!(4, internal_adder(2, 2)); } } #}
Listing 11-12: Testing a private function
Note that the
internal_adder function is not marked as
pub, but because
tests are just Rust code and the
tests module is just another module, you can
import and call
internal_adder in a test just fine. If you don’t think
private functions should be tested, there’s nothing in Rust that will compel
you to do so.
Integration Tests
In Rust, integration tests are entirely external to your library. They use your library in the same way any other code would, which means they can only call functions that are part of your library’s public API. Their purpose is to test whether many parts of your library work together correctly. Units of code that work correctly on their own could have problems when integrated, so test coverage of the integrated code is important as well. To create integration tests, you first need a tests directory.
The tests Directory
We create a tests directory at the top level of our project directory, next to src. Cargo knows to look for integration test files in this directory. We can then make as many test files as we want to in this directory, and Cargo will compile each of the files as an individual crate.
Let’s create an integration test. With the code in Listing 11-12 still in the src/lib.rs file, make a tests directory, create a new file named tests/integration_test.rs, and enter the code in Listing 11-13.
Filename: tests/integration_test.rs
extern crate adder; #[test] fn it_adds_two() { assert_eq!(4, adder::add_two(2)); }
Listing 11-13: An integration test of a function in the
adder crate
We’ve added
extern crate adder at the top of the code, which we didn’t need
in the unit tests. The reason is that each test in the
tests directory is a
separate crate, so we need to import our library into each of them.
We don’t need to annotate any code in tests/integration_test.rs with
#[cfg(test)]. Cargo treats the
tests directory specially and compiles files
in this directory only when we run
cargo test. Run
cargo test now:
$ cargo test Compiling adder v0.1.0 () Finished dev [unoptimized + debuginfo] target(s) in 0.31 secs Running target/debug/deps/adder-abcabcabc running 1 test test tests::internal ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Running target/debug/deps/integration_test-ce99bcc2479f4607 running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
The three sections of output include the unit tests, the integration test, and
the doc tests. The first section for the unit tests is the same as we’ve been
seeing: one line for each unit test (one named
internal that we added in
Listing 11-12) and then a summary line for the unit tests.
The integration tests section starts with the line
Running target/debug/deps/integration_test-ce99bcc2479f4607 (the hash at the end of
your output will be different). Next, there is a line for each test function in
that integration test and a summary line for the results of the integration
test just before the
Doc-tests adder section starts.
Similarly to how adding more unit test functions adds more result lines to the unit tests section, adding more test functions to the integration test file adds more result lines to this integration test file’s section. Each integration test file has its own section, so if we add more files in the tests directory, there will be more integration test sections.
We can still run a particular integration test function by specifying the test
function’s name as an argument to
cargo test. To run all the tests in a
particular integration test file, use the
--test argument of
cargo test
followed by the name of the file:
$ cargo test --test integration_test Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running target/debug/integration_test-952a27e0126bb565 running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
This command runs only the tests in the tests/integration_test.rs file.
Submodules in Integration Tests
As you add more integration tests, you might want to make more than one file in the tests directory to help organize them; for example, you can group the test functions by the functionality they’re testing. As mentioned earlier, each file in the tests directory is compiled as its own separate crate.
Treating each integration test file as its own crate is useful to create separate scopes that are more like the way end users will be using your crate. However, this means files in the tests directory don’t share the same behavior as files in src do, as you learned in Chapter 7 regarding how to separate code into modules and files.
The different behavior of files in the tests directory is most noticeable
when you have a set of helper functions that would be useful in multiple
integration test files and you try to follow the steps in the “Moving Modules
to Other Files” section of Chapter 7 to extract them into a common module. For
example, if we create tests/common.rs and place a function named
setup in
it, we can add some code to
setup that we want to call from multiple test
functions in multiple test files:
Filename: tests/common.rs
# #![allow(unused_variables)] #fn main() { pub fn setup() { // setup code specific to your library's tests would go here } #}
When we run the tests again, we’ll see a new section in the test output for the
common.rs file, even though this file doesn’t contain any test functions nor
did we call the
setup function from anywhere:
running 1 test test tests::internal ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Running target/debug/deps/common-b8b07b6f1be2db70 running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Running target/debug/deps/integration_test-d993c68b431d39df running 1 test test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out Doc-tests adder running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Having
common appear in the test results with
running 0 tests displayed for
it is not what we wanted. We just wanted to share some code with the other
integration test files.
To avoid having
common appear in the test output, instead of creating
tests/common.rs, we’ll create tests/common/mod.rs. In the “Rules of Module
Filesystems” section of Chapter 7, we used the naming convention
module_name/mod.rs for files of modules that have submodules. We don’t have
submodules for
common here, but naming the file this way tells Rust not to
treat the
common module as an integration test file. When we move the
setup
function code into tests/common/mod.rs and delete the tests/common.rs file,
the section in the test output will no longer appear. Files in subdirectories
of the tests directory don’t get compiled as separate crates or have sections
in the test output.
After we’ve created tests/common/mod.rs, we can use it from any of the
integration test files as a module. Here’s an example of calling the
setup
function from the
it_adds_two test in tests/integration_test.rs:
Filename: tests/integration_test.rs
extern crate adder; mod common; #[test] fn it_adds_two() { common::setup(); assert_eq!(4, adder::add_two(2)); }
Note that the
mod common; declaration is the same as the module declarations
we demonstrated in Listing 7-4. Then in the test function, we can call the
common::setup() function.
Integration Tests for Binary Crates
If our project is a binary crate that only contains a src/main.rs file and
doesn’t have a src/lib.rs file, we can’t create integration tests in the
tests directory and use
extern crate to import functions defined in the
src/main.rs file. Only library crates expose functions that other crates can
call and use; binary crates are meant to be run on their own.
This is one of the reasons Rust projects that provide a binary have a
straightforward src/main.rs file that calls logic that lives in the
src/lib.rs file. Using that structure, integration tests can test the
library crate by using
extern crate to exercise the important functionality.
If the important functionality works, the small amount of code in the
src/main.rs file will work as well, and that small amount of code doesn’t
need to be tested.
Summary
Rust’s testing features provide a way to specify how code should function to ensure it continues to work as you expect, even as you make changes. Unit tests exercise different parts of a library separately and can test private implementation details. Integration tests check that many parts of the library work together correctly, and they use the library’s public API to test the code in the same way external code will use it. Even though Rust’s type system and ownership rules help prevent some kinds of bugs, tests are still important to reduce logic bugs having to do with how your code is expected to behave.
Let’s combine the knowledge you learned in this chapter and in previous chapters to work on a project! | https://doc.rust-lang.org/1.30.0/book/second-edition/ch11-03-test-organization.html | CC-MAIN-2019-09 | refinedweb | 2,153 | 60.95 |
Why does world frame get TF prefix?
Hello I am working with two UR5, I made them launch using
<group ns="robot1"> and
<group ns="robot2">. I also gave a unique tf_prefix to each robot within the group namespace tag i.e.
<param name="tf_prefix" value="robot1_tf" /> and
<param name="tf_prefix" value="robot2_tf" />. After running the launch file what I notice in the
rqt_tf_tree is that the "world frame" also gets a namespace i.e.
robot1_tf/world followed by
robot1_tf/baselink and all the other joints of robot1 ............... And then
robot2_tf/world and then
robot2_tf/base_link and all the other joints of robot2.
But what I want is world frame (without having any namespaces) connecting to
robot1_tf/baselink followed by all the joints of robot1............... and also to
robot2_tf/baselink followed by all the joints of robot2.............
How do I avoid the world frame to have any namespaces???
Have you solved the problem? I am in the same predicament. Can you help me? Please tell me the solution
yes i did, basically what I did that I created two tf_broadcaster for each of the tf frame i.e for. robot1_tf/world and robot2_tf/world and then I mapped both of them to world frame. Have a look below | https://answers.ros.org/question/334644/why-does-world-frame-get-tf-prefix/?answer=334694 | CC-MAIN-2019-47 | refinedweb | 208 | 84.78 |
Send / Recieve SMS using Telstra examples?
- misterlisty last edited by
Hoping some can share how to send/receive SMS using Telstra
Anthony
I had a wild stab-in-the-dark this avo
import time, network lte=network.LTE() def _getlte(): if not lte.isattached(): print('lte attaching '); lte.attach() while 1: if lte.isattached(): print(' OK'); break print('. ', end=''); time.sleep(1) _getlte() print ('try sending an SMS') lte.send_at_cmd('At+CMGF=1') # put it into text mode? lte.send_at_cmd('AT+SQNSMSSEND=61xxxxxxxxx,This is the SMS content') # where 61xxxxxxxxx' is a mobile number
A doesn't work bench mark to start from?
- Steve Williams last edited by Steve Williams
@misterlisty I experimented with SMS with the GPY some time ago and it seemed to work OK on Telstra, but it may depend on the type of SIM (mine was a shared Voice Data) used. I never went much further with it because I found the GPY/firmwares to be a bit to flaky for what I was trying to do - both LTE and WiFi seemed to be too inconsistent - would run for several thousand cycles and then suddenly throw all sorts of weird errors despite no changes to hardware or code. As a consequence I have moved to a different product for that project - much more stable and faster so I am sticking with that, despite the inconvenience of not having built in LTE.
For the SMS stuff I did try, I used the Monarch Platform LR5.1.1.0 AT Commands Reference Manual as a starting point but had to do a lot of experimenting, trial and error to get code that actually worked in both directions. There are a couple of SMS specific chapters in the manual. But there have been new versions of firmware released for both the GPY and the SEQUANS modem since my experiments - so be patient - Pycom documentation isn't the greatest. There are now some constraints on which AT commands can be used - If I remember correctly anything with AT!= is no longer supported/recommended by Pycom..
Hope this helps..
Note: Previously on this forum as Stevo52 (had to create a new id here because of email address change.)
Stevo52 is claiming success but short on detail | https://forum.pycom.io/topic/4637/send-recieve-sms-using-telstra-examples/3?lang=en-US | CC-MAIN-2021-39 | refinedweb | 375 | 71.65 |
How to Download PDF using Python Web Scraping
How to Download PDF using Python Web Scraping
Send download link to:
Not all the data that we want to scrape is available as text on web. Sometimes we want to scrape data that is in form of files like PDF such as a book, a research paper, a report, a thesis, stories, company reports or simply any other data compiled and save as PDF file. In this tutorial we will learn about how to download PDF using Python.
Generally these data are large in size and it is not easy to download by a simple get request. This is because the HTTP response content (.content) is nothing but a string which is storing the file data. So, it won’t be possible to save all the data in a single string in case of large files. To overcome this problem, we need to incorporate few alterations to our program.
requests.get() method takes an argument called stream which if set to True will keep our session with server open. By default it is set to False. We need to use this hyper parameter to download large data files.
After doing this, Request library has a method .iter_content() which download large file in small chunks at a time. The size of the chunk is defined by user.
This method will create an itreable object from the response received by get request..
Below is the code for download PDF using Python. Do watch the video for detailed explanation.
import requests file_url = "" r = requests.get(file_url, stream = True) with open("python.pdf","wb") as pdf: for chunk in r.iter_content(chunk_size=1024): ''' writing one chunk at a time to pdf file ''' if chunk: pdf.write(chunk)
This script will send a get request to file url and then create a file named python.pdf in your working directory and write the downloaded content to it. More interested on How to Read PDF File using Python Web Scraping | https://www.worthwebscraping.com/how-to-download-pdf-using-python-web-scraping/ | CC-MAIN-2021-43 | refinedweb | 333 | 74.9 |
divya, You will have to edit the SerialParamete
View Tutorial By: Ramlak at 2008-04-27 05:54:47
2. HI, like some guys in this tutorial I get this pro
View Tutorial By: omar carpio at 2009-09-06 13:17:37
3. Hi..
How can i read .mp3 files from memory
View Tutorial By: satyanarayana at 2010-03-29 11:14:27
4. Its not working ave made a few adjustments to it t
View Tutorial By: amg at 2011-11-04 13:48:09
5. Ho,i have created read and write program on differ
View Tutorial By: niranjan at 2015-08-26 09:02:57
6. Hi,.
No Change yaar, Im still getting the s
View Tutorial By: Dinesh Rajendiran at 2012-03-23 05:19:06
7. Hi I properly placed the Comm api settings,i have
View Tutorial By: Muthumani at 2010-04-19 05:24:17
8. nice article..
View Tutorial By: yummy at 2010-01-05 21:18:35
9. Simpler example:
import java.io.*;
View Tutorial By: Joseph Harner at 2011-12-04 23:20:48
10. what ll be result for s1==s2 and s1.equals(s2) for
View Tutorial By: vijay at 2011-08-21 15:09:41 | https://java-samples.com/showcomment.php?commentid=35857 | CC-MAIN-2022-33 | refinedweb | 209 | 75.71 |
Latest
Web
M. David Green, 9 hours ago
Versioning Show, Episode 5, with Rachel Smith
In this episode, Tim and David are joined by Rachel Smith, a front-end developer at CodePen. They discuss creating art with code, learning the skills of animation, the future of...
Entrepreneur
Andrew Lau, 10 hours ago
8 Ways to Stay Productive When Starting Your First Business
Your first business is the hardest because, as a lifelong employee, you're used to other people keeping you accountable. Here's how to stay productive.
JavaScript
Peter Bengtsson, 11 hours ago
Cache Fetched AJAX Requests Locally: Wrapping the Fetch API
Peter Bengtsson walks through building a wrapper for the Fetch API, step-by-step, to cache fetched AJAX results and avoid repeated requests to the server.
1 Comment
HTML & CSS
Anselm Urban, 13 hours ago
8 Clever Tricks with CSS Functions
Anselm Urban looks at some neat tricks you can use today in CSS, from fancy CSS animations to a frosted glass effect.
7 Comments
PHP
Bruno Skvorc, 15 hours ago
Up and Running with the Fastest PHP Framework on PHP7 in 5 Mins
Phalcon is back - and in style! It can now run on PHP 7, and is written completely in Zephir. Easy extension development AND perfect performance!
2 Comments
Entrepreneur
Josh Althuser, a day ago
What Is Telemedicine & What Do You Need to Know about It?
Telemedicine is an emerging market preparing to disrupt healthcare. Josh Althuser gives entrepreneurs a primer.
3 Comments
JavaScript
Nilson Jacques, 2 days ago
File Bundling and HTTP/2: Rethinking Best Practices
File bundling is the norm for JS apps these days. With the adoption of the HTTP/2 protocol, Nilson Jacques asks whether its time to rethink this practice.
4 Comments
PHP
Reza Lavaryan, 2 days ago
Framework-Agnostic PHP Cronjobs Made Easy with Crunz!
Crunz is a framework-agnostic library for scheduling and defining cronjobs wholly in PHP. Commit them to VCS, edit without server access, and more!
Design & UX
Konrad Caban, 2 days ago
How to (Almost) Painlessly Troubleshoot Your Client Sites
FInding, tagging and removing bugs may not be glamorous but it's a product development phase. Konrad has a toolset for painless troubleshooting of bug.
Ruby
Ardian Haxha, 2 days ago
Create a Slack Bot to Interact with Your Wiki
Ardian Haxha shows you how to accept our new bot-based overlords and write your own Slack bot using Ruby and Sinatra. Assimilate!
1 Comment
Entrepreneur
Joshua Kraus, 3 days ago
To the Clients Who Stiffed Us...
One risk freelancers face is spending substantial time on a project without ever getting paid. Joshua Kraus talks to four freelancers who have been there.
2 Comments
WordPress
Agbonghama Collins, 5 days ago
Understanding Namespaces in the WordPress Hook System
Agbonghama covers how to hook methods of an instantiated class (object) to actions and filters and the caveats of using namespaces in WordPress hook system.
PHP
Bruno Skvorc, 5 days ago
Quick Tip: Solution to Paypal IPN Always Returning "Invalid"
A solution to the PayPal IPN Simulator "INVALID" problem - where the verification message always returns invalid, even if everything seems fine
1 Comment
Mobile
Valdio Veliu, 5 days ago
A Step by Step Guide to Building an Android Audio Player App
Valdio Veliu presents an in-depth and step by step guide to building your very own Android audio player app.
7 Comments
Entrepreneur
Andrew McDermott, 5 days ago
You're the Best Developer on the Team — Why It'll Cost You Your Job
Being the best developer - or the best at anything - can cost you everything, if you let it. Andrew McDermott explains why, and how to avoid that fate.
86 Comments
JavaScript
Julian Motz, 5 days ago
Basic jQuery Form Validation Example (2mins)
A step by step tutorial on how to use jQuery to setup basic form validation in just a few minutes you can implement form input field validation.
4 Comments
PHP
Wern Ancheta, 6 days ago
Sculpin Extended: Customizing Your Static Site Blog
Wern Ancheta shows us how to install, use, customize, and deploy a static site blog generated with Sculpin - a PHP static site generator!
Ruby
Christopher Vundi, 6 days ago
Tap User Interests with Curated Feeds in Rails
Christopher Vundi walks through setting up an interest feed model and application for your users in Rails.
258 Comments
Offers
SitePoint Offers, 6 days ago
Get a Free Year of SitePoint Premium Thanks to Atlassian
At SitePoint, we've built a reputation for empowering developers with the resources they need to take their skills to the next level and stay up to date in web development. Thanks...
4 Comments
Web
Ben Dickson, 6 days ago
How to Prevent Replay Attacks on Your Website
Ben Dickson explores how to prevent replay attacks on your site via a nifty one-time token pattern.
5 Comments
Entrepreneur
Paul Maplesden, 6 days ago
Which Productivity System Is Best for Me?
Paul Maplesden looks at the major productivity systems, and discusses the pros and cons of each choice.
2 Comments
WordPress
Chris Burgess, 6 days ago
What's New in WordPress 4.6
Chris Burgess covers an overview of what’s new in WordPress 4.6 and what features to look out for when you update your site.
2 Comments
HTML & CSS
Hugo Giraudel, 7 days ago
Setting up a Living Styleguide in Jekyll
Hugo Giraudel looks at how to put together a styleguide of components for your design using Jekyll and the Liquid template engine.
Web
M. David Green, Aug 16
Versioning Show, Episode 4, with Chris Coyier
In this episode, Tim and David are joined by Chris Coyier, well-known creator of CSS-Tricks and co-founder of code-sharing site CodePen and the ShopTalk podcast — to discuss... | https://www.sitepoint.com/php/e-commerce/?order=latest | CC-MAIN-2016-36 | refinedweb | 961 | 64.64 |
How to Build a Real-time Collaborative Markdown Editor with React Hooks, GraphQL & AWS AppSync:
An idea that immediately stood out to me was from NagarajanFs on Twitter:
Basically his idea was Google Docs but for markdown. I loved it, so I decided to build it! The result was writewithme.dev.
Getting Started
The first thing I did was created a new React application:
npx create-react-app write-with-me
The next thing I needed to do was to find the tool I was going to use to allow markdown in a React App. I stumbled upon react-markdown by Espen Hovlandsdal (rexxars on Twitter).
npm install react-markdown
React Markdown was super simple to use. You import
ReactMarkdown from the package & pass in the markdown you’d like to render as a prop:
const ReactMarkdown = require('react-markdown')
const input = '# This is a header\n\nAnd this is a paragraph'
<ReactMarkdown source={input} />
Building the API
Now that we have the markdown tool the next set was creating the API. I used AWS AppSync & AWS Amplify to do this. With the Amplify CLI, you can set a base type & add a decorator to build out the entire backend by taking advantage of the GraphQL Transform library.
amplify init
amplify add api
// chose GraphQL
// Choose API Key as the authentication
The schema I used was this:
type Post @model {
id: ID!
clientId: ID!
markdown: String!
title: String!
createdAt: String
}
The
@modeldecorator will tell Amplify to deploy a GraphQL backend complete with a DynamoDB data source & schema (types & operations) for all crud operations & GraphQL subscriptions. It will also create the resolvers for the created GraphQL operations.
After defining & saving the schema we deploy the AppSync API:
amplify push
When we run
amplify push, we’re also given the option to execute GraphQL codegen in either TypeScript, JavaScript, or Flow. Doing this will introspect your GraphQL schema & automatically generate the GraphQL code you’ll need on the client in order to execute queries, mutations, & subscriptions.
Installing the dependencies
Next, we install the other necessary libraries we need for the app:
npm install aws-amplify react-router-dom uuid glamor debounce
- uuid — to create unique IDs to uniquely identify the client
- react-router-dom — to add routing
- aws-amplify — to interact with the AppSync API
- glamor — for styling
- debounce — for adding a debounce when user types
Writing the code
Now that our project is set up & our API has been deployed, we can start writing some code!
The app has three main files:
- Router.js — Defines the routes
- Posts.js — Fetches & renders the posts
- Post.js — Fetches & renders a single post
Router.js
Setting up navigation was pretty basic. We needed two routes: one for listing all of the posts & one for viewing a single post. I decided to go with the following route scheme:
/post/:id/:title
When someone hits the above route, we have access to everything we need to display a title for the post as well as the ID for us to fetch the post if it is an existing post. All of this info is available directly in the route parameters.
React Hooks with GraphQL
If you’ve ever wondered how to implement hooks into a GraphQL application, I recommend also reading my post Writing Custom Hooks for GraphQL because that’s exactly what we’ll be doing.
Instead of going over all of the code for the 2 components (if you’d like to see the code, click on the links above), I’d like to focus on how we implemented the necessary functionality using GraphQL & hooks.
The main API operations we needed from this app are intended to do the following:
- Load all of the posts from the API
- Load an individual post
- Subscribe to changes within an individual post & re-render the component
Let’s take a look at each.
To load the posts I went with a
useReducer hook combined with a function call within a
useEffect hook. We first define the initial state. When the component renders for the first time we call the API & update the state using the
fetchPosts function. This reducer will also handle our subscription:
import { listPosts } from './graphql/queries'
import { API, graphqlOperation } from 'aws-amplify'
const initialState = {
error: false
}
function reducer(state, action) {
switch (action.type) {
case 'fetchPostsSuccess':
return { ...state, posts: action.posts, loading: false }
case 'addPostFromSubscription':
return { ...state, posts: [ action.post, ...state.posts ] }
case 'fetchPostsError':
return { ...state, loading: false, error: true }
default:
throw new Error();
}
}
async function fetchPosts(dispatch) {
try {
const postData = await API.graphql(graphqlOperation(listPosts))
dispatch({
type: 'fetchPostsSuccess',
posts: postData.data.listPosts.items
})
} catch (err) {
console.log('error fetching posts...: ', err)
dispatch({
type: 'fetchPostsError',
})
}
}
// in the hook
const [postsState, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
fetchPosts(dispatch)
}, [])
Subscribing to new posts being created
We already have our state ready to go from the above code, now we just need to subscribe to the changes in the hook. To do that, we use a useEffect hook & subscribe to the
onCreatePost subscription:
useEffect(() => {
const subscriber = API.graphql(graphqlOperation(onCreatePost)).subscribe({
next: data => {
const postFromSub = data.value.data.onCreatePost
dispatch({
type: 'addPostFromSubscription',
post: postFromSub
})
}
});
return () => subscriber.unsubscribe()
}, [])
In this hook, we set up a subscription that will fire when a user creates a new post. When the data comes through, we call the
dispatch function & pass in the new post data that was returned from the subscription.
Fetching a single post
When a user lands on a route, we can use the data from the route params to identify the post name & ID:
In this route, the ID would be 9999b0bb-63eb-4f5b-9805–23f6c2661478 & the name would be Write with me.
When the component loads, we extract these params & use them.
The first thing we do is attempt to create a new post. If this is successful, we are done. If this post already exists, we are given the data for this post from the API call.
This may seem strange at first, right? Why not try to fetch, & if unsuccessful the create? Well, we want to reduce the total number of API calls. If we attempt to create a new post & the post exists, the API will actually return the data from the existing post allowing us to only make a single API call. This data is available in the errors:
err.errors[0].data
We handle the state in this component using
useReducer hook.
// initial state
const post = {
id: params.id,
title: params.title,
clientId: CLIENTID,
markdown: '# Loading...'
}
function reducer(state, action) {
switch (action.type) {
case 'updateMarkdown':
return { ...state, markdown: action.markdown, clientId: CLIENTID };
case 'updateTitle':
return { ]...state, title: action.title, clientId: CLIENTID };
case 'updatePost':
return action.post
default:
throw new Error();
}
}
async function createNewPost(post, dispatch) {
try {
const postData = await API.graphql(graphqlOperation(createPost, { input: post }))
dispatch({
type: 'updatePost',
...postData.data.createPost,
clientId: CLIENTID
}
})
} catch(err) {
if (err.errors[0].errorType === "DynamoDB:ConditionalCheckFailedException") {
const existingPost = err.errors[0].data
dispatch({
type: 'updatePost',
...existingPost,
clientId: CLIENTID
}
})
}
}
}
// in the hook, initialize the state
const [postState, dispatch] = useReducer(reducer, post)
// fetch post
useEffect(() => {
const post = {
...postState,
markdown: input
}
createNewPost(post, dispatch)
}, [])
Subscribing to a post change
The last thing we need to do is subscribe to changes in a post. To do this, we do two things:
- Update the API when the user types (both title or markdown changes)
async function updatePost(post) {
try {
await API.graphql(graphqlOperation(UpdatePost, { input: post }))
console.log('post has been updated!')
} catch (err) {
console.log('error:' , err)
}
}
function updateMarkdown(e) {
dispatch({
type: 'updateMarkdown',
markdown: e.target.value,
})
const newPost = {
id: post.id,
markdown: e.target.value,
clientId: CLIENTID,
createdAt: post.createdAt,
title: postState.title
}
updatePost(newPost, dispatch)
}
function updatePostTitle (e) {
dispatch({
type: 'updateTitle',
title: e.target.value
})
const newPost = {
id: post.id,
markdown: postState.markdown,
clientId: CLIENTID,
createdAt: post.createdAt,
title: e.target.value
}
updatePost(newPost, dispatch)
}
useEffect(() => {
const subscriber = API.graphql(graphqlOperation(onUpdatePost, {
id: post.id
})).subscribe({
next: data => {
if (CLIENTID === data.value.data.onUpdatePost.clientId) return
const postFromSub = data.value.data.onUpdatePost
dispatch({
type: 'updatePost',
post: postFromSub
})
}
});
return () => subscriber.unsubscribe()
}, [])
When the user types, we update both the local state as well as the API. In the subscription, we first check to see if the subscription data coming in is from the same Client ID. If it is, we do nothing. If it is from another client, we update the state.
Deploying the app on a custom domain
Now that we’ve built the app, what about deploying it to a custom domain like I did with writewithme.dev?
I did this using GoDaddy, Route53 & the Amplify console.
In the AWS dashboard, go to Route53 & click on Hosted Zones. Choose Create Hosted Zone. From there, enter your domain name & click create.
Be sure to enter your domain name as is, without www. E.g. writewithme.dev
Now in Route53 dashboard you should be given 4 nameservers. In your hosting account, on Get Started under the Deploy section.
Connect your GitHub account & then choose the repo & branch that your project lives in.
This will walk you through deploying the app in the Amplify Console & making it live. Once complete, you should see some information about the build & some screenshots of the app:
Next,):
Next Steps
The next thing I’d like to do would be to add authentication & commenting functionality (so people can comment on each individual post). This is all doable with Amplify & AppSync. If we wanted to add authentication, we could add it with the CLI:
amplify add auth
Next, we’d have to write some logic to log people in & out or we can use the
withAuthenticator HOC. To learn more about how to do this, check out these docs.
Next, we’d probably want to update the schema to add commenting functionality. To do so, we could update the schema to something like what I created here. In this schema, we’ve added a field for the Discussion (in our case it would probably be called Comment).
In the resolver, we could probably also correlate a user’s identity to the message as well but using the
$context.identity.sub which would be available after the user is signed in.
My Name is Nader Dabit . I am a Developer Advocate at AWS working with projects like AWS AppSync and AWS Amplify.
I’m also the author of React Native in Action, & the editor of React Native Training & OpenGraphQL. | https://medium.com/open-graphql/how-to-build-a-real-time-collaborative-markdown-editor-with-react-hooks-graphql-aws-appsync-dc0c121683f4?utm_source=newsletter&utm_medium=email&utm_content=offbynone&utm_campaign=Off-by-none%3A%20Issue%20%2332 | CC-MAIN-2019-18 | refinedweb | 1,732 | 57.77 |
UR::Service::JsonRpcServer - A self-contained JSON-RPC server for UR namespaces
use lib '/path/to/your/moduletree'; use YourNamespace; my $rpc = UR::Service::JsonRpcServer->create(host => 'localhost', port => '8080', api_root => 'URapi', docroot => '/html/pages/path', ); $rpc->process();
This is a class containing an implementation of a JSON-RPC server to respond to requests involving UR-based namespaces and their objects. It uses Net::HTTPServer as the web server back-end library.
Incoming requests are divided into two major categories:
api-root/class/Namespace/Class
This is the URL for a call to a class metnod on
Namespace::Class
api-root/obj/Namespace/Class/id
This is the URL for a method call on an object of class Namespace::Class with the given id
The constructor takes the following named parameters:
The hostname to listen on. This can be an ip address, host name, or undef. The default value is '0.0.0.0'. This argument is passed along verbatim to the Net::HTTPServer constructor.
The TCP port to listen on. The default value is 8080. This argument is passed along verbatim to the Net::HTTPServer constructor.
The root path that the http server will listen for requests on. The constructor registers two paths with the Net::HTTPServer with RegisterRegex() for /
api_root/class/* and /
api_root/obj/* to respond to class and instance metod calls.
All other arguments are passed along to the Net::HTTPServer constructor.
A wrapper to the Net::HTTPServer Process() method. With no arguments, this call will block forever from the perspective of the caller, and process all http requests coming in. You can optionally pass in a timeout value in seconds, and it will respond to requests for the given number of seconds before returning.
There are (or will be) client-side code in both Perl and Javascript. The Perl code is (will be) implemented as a UR::Context layer that will return light-weight object instances containing only class info and IDs. All method calls will be serialized and sent over the wire for the server process to execute them.
The Javascript interface is defined in the file urinterface.js. An example:
var UR = new URInterface(''); // Connect to the server var FooThingy = UR.get_class('Foo::Thingy'); // Get the class object for Foo::Thingy var thingy = FooThingy.get(1234); // Retrieve an instance with ID 1234 var result = thingy.call('method_name', 1, 2, 3); // Call $thingy->method_name(1,2,3) on the server
Ney::HTTPServer, urinterface.js | http://search.cpan.org/~sakoht/UR-0.39/lib/UR/Service/JsonRpcServer.pm | CC-MAIN-2016-07 | refinedweb | 409 | 55.95 |
Measuring Frontend Performance (in modern browsers)
June 19, 2019 — 15 min read
Photo by Mathew Schwartz
Up until a few months ago, I had no idea how to think about frontend performance, what it means, or how to measure it. Previously, I’ve looked at server response times and often assumed if that was “fast” the whole user experience would be “fast.” However, there’s a lot more to the performance of an application and the overall user experience. This is an overview of what I learned after a few months of trying to understand and implement frontend performance metrics.
What is frontend performance?
My simplest definition is “the time it takes for an application to become usable.” For me, this is challenging to wrap my head around because “usable” can be interpreted in different ways by different people (or maybe the same person on different days).
You could argue, when looking at something like server response time there’s one definition for “is it usable?” The overall response time. Before the server responds, it’s 0% usable. The user hasn’t received the response and they can’t do anything without that. Once the server has responded it’s now 100% usable for the user (or at least for the client to make it usable). With that, improving the server response time will improve the time it takes the server to “become usable.”
When looking at frontend performance it becomes less straightforward. Rarely, it’s
exactly 0% or 100% usable, but rather somewhere between during an application’s
life cycle. There are a large number of variables
that can affect the usability: the actual feature code efficiency (eg:
maybe using
concat vs
push in a large loop),
network latency, server response time, server response size, JavaScript and CSS
file size, browser, available resources on the client, caching,
long running tasks, loading states, etc.
Why care about frontend performance?
In general, better performance means a better user experience.
Unfortunately, we usually can’t stop here and need to go a step further to prove that it’s a worthwhile business investment. Fortunately, a better experience will usually lead to an increase in some important business metric.
This may mean users will spend more time using your product (if you care about that) or maybe it means they actually spend less time using your product because they can achieve their task quickly. Later on they might recommend it to their friend since it was a fast and delightful experience.
It’s hard to generalize what exactly improving performance will lead to, but it will generally lead to an improvement of some important metric.
If you’re looking for something more concrete, there are several great examples curated by Google Web Fundamentals outlining specific cases of how performance directly improved important metrics.
(Google Web Fundamentals was an invaluable resource when investigating and learning about frontend performance. Much of this content was inspired from their resources)
What should be measured?
Even though frontend performance may not be an exact science, we need something precise to measure. Given the qualitative feedback that “the application feels slow” how do you know it’s slow and not a networking issue? Or, some other factor? You don’t. We need to measure something, but what?
Reframed in the context of the above definition: what measurements can be made that would determine if an application is usable? The Web Fundamentals does an excellent job outlining questions that can be related to exact numbers: Is it happening? Is it usable? Is it delightful?
Is it happening?
How does the user know if anything is happening when first navigating to your application? Something visually different appears or “paints” on the screen. There are actually three common “paint” measurements:
- First Paint (FP): the time it takes to render the first pixels on the screen, something visually different from the previous page
- First Contentful Paint (FCP): the time it takes to render the first element or piece of content
- First Meaningful Paint (FMP): the time it takes the most important content to load, often referred to as the hero content
Another metric that can be helpful to provide a full perspective is the amount of time it takes to start receiving a response from the server.
- Time to First Byte (TTFB): the time it takes from the start of the request to receiving the first byte.
From the frontend perspective, this is where you can start to control the
performance experience. Before this point is the DNS lookup, request overhead,
server time, network latency, etc. (things generally out of the control of the frontend).
It’s also straightforward to calculate using the
PerformanceNavigationTiming API.
The Time to First Byte timing is also visible in the Chrome Devtools under the Network tab.Time to First Byte (TTFB) in Chrome Devtools
Is it usable?
The user is aware it’s happening, they can see something visually on the screen. Usually there are interactions like a button or link. Presumably, they’ll want to click or interact with the page in some way. But, can they?
- Time to Interactive (TTI): the time is takes for the application to render and be ready to handle user input
This metric is more complicated and relies on a few criteria. First, the application is rendered so by definition it’s always after the First Paints. Second, it’s “ready” to handle user input.
What does “ready” mean? For Time to Interactivity, it’s measured as the first time the main thread will be inactive for 5 seconds meaning that any user input could be handled. It can be a bit tricky to understand since we have to wait 5 seconds to see if that given point was followed by 5 seconds of inactivity. Time to Interactive is not a standardized performance metric and requires using the Long Tasks API (see below for more details).Time to Interactive (TTI) in Lighthouse
Is it delightful?
I like to think about all of the previous metrics as snapshots along a timeline. First Paint has to happen before First Contentful Paint. Both have to happen before Time to Interactive. But what about the prolonged usage of the application after the initial load? There are two more measurements that can help answer this question:
- Long Running Task: a long running task is any task that takes longer than 50 milliseconds to complete
- First Input Delay: the time it takes from the user interacting (eg: clicking a button) to when the browser responds
The Long Running Tasks are also used to calculate the Time to Interactive, but they can also be measured on their own. Anytime there is a Long Running Task it could potentially impact the user’s experience. The threshold is 50 milliseconds because anything above 100 milliseconds may feel delayed to a user.Example of a Long Running Task in Chrome Devtools
The First Input Delay compliments the Time to Interactive measurement, but the difference is that the First Input Delay actually requires a user to interact with the page. Each measurement is an actual length of time that a user had to wait for the browser to handle their interaction. First Input Delay can happen at any point, not at a set point along the timeline like the earlier metrics.
How should it be measured?
In general, there are two approaches for measuring frontend performance: “lab tools” and “real world tools.”
You can think of lab tools as something run on a your computer (or on a small sample) to get a general idea of how the application is performing. The numbers are not a true representation since there can be a large amount of variability depending on the device type, network connections, etc.
To collect a true representative sample the metrics need to be collected in the real world, often referred to as Real User Monitoring (RUM). This approach uses browser APIs to collect and report these metrics to a tool like Google Analytics or maybe a custom integration with Datadog or another performance monitoring tool.
Lighthouse
Lighthouse is a tool available in Chrome Devtools (screenshots above) under the Audits tab. It’s also available as a node module to run in other environments like CI.
It provides insights into many of these performance metrics and a few more. Lighthouse also includes other useful information around accessibility, Search Engine Optimization (SEO), Progressive Web Apps (PWA) and concrete approaches to improve the performance of your application.
Again, this is an excellent tool to get a general idea of the overall performance or where the bottlenecks might be. However, if you want to quantitatively discuss the performance of your application with precise numbers you’ll need to implement Real User Monitoring.
Browser APIs & Polyfills
Real User Monitoring can be implemented using browser APIs (in “modern” browsers) and polyfills available to measure the frontend performance of an application. There are also several open source packages and paid solutions that take care of most of these implementation details. As with most decisions, you’ll have to decide if the costs and benefits are worth using one of these tools or reaching for the browser APIs. Regardless, it can be beneficial to have an idea of how these metrics are being measured under the hood.
Measuring Time to First Byte (TTFB)
Measuring Time to First Byte is the easiest of these metrics to collect.
To start, most of these metrics rely on the Performance API either directly or as part of the computation for a metric. To measure the time it takes to receive the first byte of data from the server we need to know the difference between when the response started and when the request started.
This data is part of the Navigation Timing API.
It can be retrieved by passing the
entryType of
navigation
to the
getEntriesByType
function available on the performance object. To put this into code:
// Get the performance entry for the browser navigation events const pageNav = performance.getEntriesByType("navigation")[0]; // Calculate the time it took to receive the first byte const durationMs = Math.round(pageNav.responseStart - pageNav.requestStart); // Log or track the metric console.log({ name: "time-to-first-byte", durationMs });
Math.roundis optional but can be nice to collect these metrics as whole milliseconds (rather than floats) to keep the data clean.
console.logwould be replaced with custom logic to collect and aggregate the performance data.
- If using TypeScript, it may be necessary to cast
pageNavto
PerformanceNavigationTiming.
Measuring First Paints (FP & FCP)
Fortunately, there is also a browser API for tracking First Paint and First Contentful
Paint but it’s slightly more involved. The same approach as above can be used but passing
the
entryType of
paint
to
getEntriesByType.
performance.getEntriesByType("paint");
However, if this is added in the
head (or early) in the document, it may
return
[] (an empty array) if invoked before the browser has painted so
the
first-paint or
first-contentful-paint entries will not exist.
This is where the
PerformanceObserver
can be useful. It will observe performance events and can invoke a callback when
a specific event occurs. However, this can have the opposite problem if the
observer is created after the paint events have occurred the callback will never
be invoked. This will no longer be a problem once the
PerformanceObserver
accepts the
buffered
parameter. Until then, ensure
PerformanceObserver is initialized as early as
possible, such as in the head of the document.
(() => { // Early return in browsers that don't support the paint // timing API. This assumes if the browser supports // the PerformancePaintTiming API it also supports the // PerformanceObserver API. if (!("PerformancePaintTiming" in window)) { return; } const observer = new PerformanceObserver(list => { for (const entry of list.getEntries()) { // The `PerformanceEntry` has a `startTime` and // `duration` attribute. Usually, these need to // be subtracted but `duration` is always `0` for // paint entries. const durationMs = Math.round(entry.startTime); // `entry.name` will be either `first-paint` // or `first-contentful-paint`. Log or track // `entry.name` and `durationMs`. console.log({ name: entry.name, durationMs }); } }); observer.observe({ entryTypes: ["paint"] }); })();
If looking to measure First Meaningful Paint
that will likely need to be a custom implementation since that depends on the
specific application and what is considered the most important content. Check
out the Performance
mark API
for one possible approach for the custom performance measurement.
Measuring Time to Interactive (TTI)
Unfortunately, there currently is not a browser API available for tracking Time
to Interactive. However, the
tti-polyfill
package works great for polyfilling this functionality.
First, install the package as a standard dependency (
npm install tti-polyfill
or
yarn add tti-polyfill). Second, add the snippet of code under the
Usage docs
to the head of the document.
This snippet observes long running tasks. It has to be added as early as possible
to work around the same issue mentioned above when measuring first paint. This
will no longer be a problem once the
PerformanceObserver accepts the
buffered
parameter.
Now, the
getFirstConsistentlyInteractive function can be invoked at any time
from the polyfill package. This function will return a promise that resolves to
the duration of time to reach interactive.
import { getFirstConsistentlyInteractive } from "tti-polyfill"; getFirstConsistentlyInteractive().then(durationMs => { // Guard against `null` when no TTI value can be found, // or the browser doesn't support all the APIs required // to detect TTI. if (durationMs) { // Log or track the metric console.log({ name: "time-to-interactive", durationMs: Math.round(durationMs) }); } });
If using TypeScript, the following type definitions can be used for the
tti-polyfill package:
declare module "tti-polyfill" { interface Options { minValue?: number | null; useMutationObserver?: boolean; } type GetFirstConsistentlyInteractive = ( options?: Options ) => PromiseLike<number | null>; export const getFirstConsistentlyInteractive: GetFirstConsistentlyInteractive; }
Measuring First Input Delay (FID)
First Input Delay is measured in a similar fashion to Time to Interactive.
It doesn’t currently haven an official browser API but there is also a polyfill
available:
first-input-delay.
This polyfill can be installed as a package, but the recommend approach is to inline the snippet in the head of the document to ensure the first input is always captured.
Now that the snippet is added,
perfMetrics.onFirstInputDelay is exposed on
the
window.
onFirstInputDelay is invoked by passing a callback function that
will receive the duration for the First Input Delay.
window.perfMetrics.onFirstInputDelay(durationMs => { // Log or track the metric console.log({ name: "first-input-delay", durationMs: Math.round(durationMs) }); });
If using TypeScript, the following type definitions can be used with the
first-input-delay snippet:
type OnFirstInputDelay = (callback: (duration: number) => void) => void; interface PerfMetrics { onFirstInputDelay: OnFirstInputDelay; } declare global { interface Window { perfMetrics: PerfMetrics; } }
Other considerations
There are a handful of other things that may be useful to consider when measuring these frontend performance metrics. None of these are hard requirements but questions that I had when investigating frontend performance and will likely depend on your use case.
First, when should these metrics be collected? For example, are these only on the first page load? If you have a single page app (SPA) should some of these metrics like Time to Interactive be collected on page transitions? First page load is usually the easiest but may not provide a holistic view.
Furthermore, what if the user navigates to your application but then visits another
tab? It may be worthwhile to consider ignoring metrics collected if
document.hidden was true at any point since this can impact the performance
metrics. An example snippet of code that could be used to check for this:
let hidden = document.hidden; // Track if the document was hidden at any point. document.addEventListener("visibilitychange", () => { if (document.hidden) { hidden = true; } });
Another consideration may be to introduce bounds to avoid collecting any unexpected
data. For example, all metrics must be greater than
0 and less than an
arbitrary upper bound, say
60000 (1 minute). Generally, these metrics should be
positive and hopefully significantly less than 1 minute so this shouldn’t
be necessary.
Having these metrics are great, but as an entire aggregate it may be hard to pinpoint exact problems. Therefore, it may be beneficial to also collect metadata such as the device type (eg: phone, tablet), browser, connection type (eg: 2g, 4g), the page or other metadata specific to your application to slice the metrics (see the Chrome User Experience Report for more inspiration).
Lastly, where should these metrics be collected? There are several examples of collecting performance metrics in Google Analytics. This may be a good option for smaller applications. However, when working on a larger team it may be worthwhile considering tracking these metrics in the same place as other performance metrics. For example, if all your performance monitoring is in Datadog it may be worth the effort to collect the data there to have all performance monitoring, alerting, etc. collocated for easy access.
Conclusion
This post covered some of the most common frontend performance metrics, what they are and how to measure them:
- Time to First Byte (TTFB)
- First Paint (FP)
- First Contentful Paint (FCP)
- First Meaningful Paint (FMP)
- Time to Interactive (TTI)
- First Input Delay (FID)
Remember, these APIs are not available in all browsers so make sure to verify they exist before using them to avoid issues in browsers that do not yet support these APIs.
Interested in learning more? Listen to this episode on Rubber Ducking about frontend performance, read Google Web Fundamentals, or reach out on Twitter. | https://skovy.dev/measuring-frontend-performance-in-modern-browsers/ | CC-MAIN-2019-51 | refinedweb | 2,891 | 54.42 |
current position:Home
2022-04-29 14:29:57【Tomatos_ baby】
Function interface definition :
void reOut(int (*p)[3]);
Sample referee test procedure :
#include <stdio.h> int main() { void reOut(int (*p)[3]); int i, j, a[2][3], (*p)[3]; for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) scanf("%d", &a[i][j]); p= a; reOut(p); } /* Please fill in the answer here */
sample input :
Here's a set of inputs . for example :
1 2 3 4 5 6
sample output :
1 2 3 4 5 6 1 4 2 5 3 6
void reOut(int (*p)[3]) { int i,j; for(i=0;i<2;i++) { for(j=0;j<3;j++) printf("%3d",*(*(p+i)+j)); printf("\n"); } for(i=0;i<3;i++) { for(j=0;j<2;j++) printf("%3d",*(*(p+j)+i)); printf("\n"); } }
author[Tomatos_ baby] | https://en.qdmana.com/2022/119/202204291429544922.html | CC-MAIN-2022-33 | refinedweb | 147 | 56.63 |
Namespaces are quite popular in XML usage and indeed almost ubiquitous in Web services use. They most often take the form of URLs, although they can be any form of Uniform Resource Identifier (URI). Using URLs is not bad in itself, but it can create confusion if the URLs lead to nowhere. Users might try to address their browsers to the URL corresponding to a namespace to gain more information about it; if they do access the namespace URL, it's a good idea to be sure they reach some useful information, rather than a 404 "Not Found" error.
The question then is what sort of document to place at the location of a namespace URL. Some early discussion considered using a form of schema. Since namespace URLs are mostly accessed by people looking for information, many in the XML community decided that readable documentation would be friendlier. Ideally, the document could be augmented by machine-readable metadata so that automated systems could still use the namespace URL to locate such technical material for processing XML text in the namespace, including schemata.
The result of this community discussion is Resource Directory Description Language (RDDL), a standard for packaging information on a namespace. A RDDL document is an XHTML document that contains prose descriptions of the namespace. Using XHTML makes it as compatible with current browsers as possible, and takes advantage of a popular and well-known format for rich documentation. The pointers to technical resources for the namespace are expressed using embedded XLinks. I like to call RDDL documents resource glosses, a name I recommended during the community discussions from which RDDL emerged.
In this article I show how you might use a RDDL document to support namespaces in XML and Web services formats. The example uses popular conventions in SOAP, although the same lessons can be applied to other XML formats. I'll be sticking to RDDL 1.0. Some in the community have started working on RDDL 2.0, but early proposals are very controversial, so I suggest that you concentrate on RDDL 1.0 until the later versions are more settled..
RDDL is very easy and inexpensive to use with namespaces, and indeed some users have even used RDDL as a format for expressing general resource repositories. If you already make an effort to place, say, a schema at the end of the namespace, then you just need to add one level of indirection in the form of the resource gloss..
Even though I recommend sticking to RDDL 1.0 for now, the W3C's Technical Architecture Group (TAG) is working to evolve RDDL into a more formal standard for the Web. This is part of the mix of activity that has led to confusion about the development of RDDL 2.0. Proposals now in play range from expressing RDDL in RDF to suppressing the XLink trappings (relying more on re-purposed attributes from standard XHTML). The intended result is a document format that, as Tim Bray said in one of the relevant discussions on the TAG mailing list, "SHOULD be used for the representations of resources which happen to be namespaces."
-.
-. | http://www.ibm.com/developerworks/xml/library/x-rddlns.html | CC-MAIN-2015-06 | refinedweb | 525 | 51.38 |
over two months
ago.
Appendix 1 of CITES lists nearly 900 plant and animal species
and includes all the 'great' whales like humpback, fin and minke
whales.
Japan has filed what is known as a 'reservation' to the listing
of many whale species on Appendix 1, which allows it to ignore some
restrictions on trade in minke whales. But, because Panama has
ratified the treaty without reservations, it cannot commercially
import or export minke whale.
Transfering the whale meat from the Japanese registered Niss, "it is riddled with illegalities and instances where
international law has been bent, broken, and bypassed; it continues
to strain relations with our allies around the world and tarnish
Japan's reputation. It's time for Japan to stop whaling in the
Southern Ocean forever."
The Convention on International Trade in Endangered Species of
Wild Fauna and Flora (CITES) was set up in 1973 to protect animals
and plants against over-exploitation through international
trade.
Get your FREE Greenpeace newsletter delivered straight to your inbox with all the latest whale news and ways you can help end whaling in the Southern Ocean Whale Sanctuary.
Help end whaling in the Southern Ocean Whale Sanctuary for good by making a donation today. | http://www.greenpeace.org/international/en/news/features/international-law-broken-290308/ | CC-MAIN-2015-35 | refinedweb | 204 | 57.3 |
The.
Lastly, we announced our plans to release Spring Open API to the public with the IntelliJ IDEA 13.1 release (as a part of IntelliJ Platform SDK). This will enable third-party plugin developers to reuse existing Spring support in their own IntelliJ IDEA plugins (e.g. providing tight integration for frameworks) as well as extending it (e.g. fully support custom namespaces).
If you haven’t tried IntelliJ IDEA 13 yet, we would like to remind you that the new release brings many improvements for Spring support:
- The IDE now automatically detects unmapped contexts defined with @Configuration or XML files and suggests adding them to the project settings;
- The new dedicated tool window helps navigate through the beans, showing additional information such as dependencies, quick documentation, diagram as well as the corresponding HTTP information for the controller methods, defined in the project (including mapped URL, method and path variables);
- Performance improvement for large projects;
- And many other minor enhancements.
We encourage you to share your feedback on our discussion forum and we ask that you report any bugs in our issue tracker.
Be sure to check out, the new home of Spring, where among many other things you’ll be able to find easy-to-follow guides on how get started with Spring.
Keep up with the latest news on IntelliJ IDEA Blog and on Twitter @IntelliJIDEA.
Are frameworks a reliable? | https://blog.jetbrains.com/blog/2013/12/11/webinar-recording-spring-4-0-and-intellij-idea-13/ | CC-MAIN-2017-26 | refinedweb | 233 | 57.1 |
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
AST Optimizer parameters cannot be done for examples. Only optimizations on immutable types (constants) are done.
Website:
Source code hosted at:
Optimizations
- Call builtin functions if arguments are constants (need "builtin_funcs" feature).
- if a: if b: print("true") => if a and b: print("true")
- Optimize loops (range => xrange needs "builtin_funcs" features). Examples:
- while True: pass => while 1: pass
- for x in range(3): print(x) => x = 0; print(x); x = 1; print(x); x = 2; print(x)
- for x in range(1000): print(x) => for x in xrange(1000): print(x) (Python 2)
- Optimize iterators, list, set and dict comprehension, and generators (need "builtin_funcs" feature). Examples:
- iter(set()) => iter(())
- frozenset("") => frozenset()
- (x for x in "abc" if False) => (None for x in ())
- [x*10 for x in range(1, 4)] => [10, 20, 30]
- (x*2 for x in "abc" if True) => (x*2 for x in ("a", "b", "c"))
- list(x for x in iterable) => list(iterable)
- tuple(x for x in "abc") => ("a", "b", "c")
- list(x for x in range(3)) => [0, 1, 2]
- [x for x in ""] => []
- [x for x in iterable] => list(iterable)
- set([x for x in "abc"]) => {"a", "b", "c"} (Python 2.7+) or set(("a", "b", "c"))
- Replace list with tuple (need "builtin_funcs" feature). Examples:
- for x in [a, b, c]: print(x) => for x in (a, b, c): print(x)
- x in [1, 2, 3] => x in (1, 2, 3)
- list([x, y, z]) => [x, y, z]
- set([1, 2, 3]) => {1, 2, 3} (Python 2
- x in [1, 2, 3] => x in {1, 2, 3} (Python 3) or x in (1, 2, 3) (Python 2)
- def f(): return 2 if 4 < 5 else 3 => def f(): return 2
- Remove empty loop. Example:
- for i in (1, 2, 3): pass => i = 3
- Remove dead code. Examples:
- def f(): return 1; return 2 => def f(): return 1
- def f(a, b): s = a+b; 3; return s => def f(a, b): s = a+b; return s
- if DEBUG: print("debug") => pass with DEBUG declared as False
- while 0: print("never executed") => pass
Use astoptimizer in your project
To enable astoptimizer globally on your project, add the following lines at the very begining of your application:
import astoptimizer config = astoptimizer.Config('builtin_funcs', 'pythonbin') # customize the config here astoptimizer.patch_compile(config)
On Python 3.3, imports will then use the patched compile() function and so all modules will be optimized. With older versions, the compileall module (ex: compileall.compile_dir()) can be used to compile an application with optimizations enabled.
See also the issue #17515: Add sys.setasthook() to allow to use a custom AST optimizer."
- "struct": struct module, calcsize(), pack() and unpack() functions.
- "cpython_tests": disable some optimizations to workaround issues with the CPython test suite. Only use it for tests.
Use Config("builtin_funcs", "pythonbin") to enable most optimizations. You may also enable "pythonenv" to enable more optimizations, but then the optimized code will depends on environment variables and Python command line options.
Use config.enable_all_optimizations() to enable all optimizations, which may generate invalid code..6 (2014-03-05)
- Remove empty loop. Example: for i in (1, 2, 3): pass => i = 3.
- Log removal of code
- Fix support of Python 3.4: socket constants are now enum
Version 0.5 (2013-03-26)
- Unroll loops (no support for break/continue yet) and list comprehension. Example: [x*10 for x in range(1, 4)] => [10, 20, 30].
- Add Config.enable_all_optimizations() method
- Add a more aggressive option to remove dead code (config.remove_almost_dead_code), disabled by default
- Remove useless instructions. Example: "x=1; 'abc'; print(x)" => "x=1; print(x)"
- Remove empty try/except. Example: "try: pass except: pass" => "pass"
Version 0.4 (2012-12-10)
Bugfixes:
- Don't replace range() with xrange() if arguments cannot be converted to C long
- Disable float.fromhex() optimization by default: float may be shadowed. Use "builtin_funcs" to enable this optimization.
Changes:
- Add the "struct" configuration feature: functions of the struct module
- Optimize print() on Python 2 with "from __future__ import print_function"
- Optimize iterators, list, set and dict comprehension, and generators
- Replace list with tuple
- Optimize if a: if b: print("true"): if a and b: print("true")
Version 0.3.1 (2012-09-12)
Bugfixes:
- Disable optimizations on functions and constants if a variable with the same name is set. Example: "len=ord; print(len('A'))", "sys.version = 'abc'; print(sys.version)".
- Don't optimize print() function, frozenset() nor range() functions if "builtin_funcs" feature is disabled
- Don't remove code if it contains global or nonlocal. Example: "def f(): if 0: global x; x = 2".
Faster Python implementations
- PyPy
- AST optimizer of PyPy: astcompiler/optimize.py
- Hotpy and Hotpy 2, based on GVMT (Glasgow Virtual Machine Toolkit)
- numba
- pymothoa uses LLVM ("don't support classes nor exceptions")
- WPython: 16-bit word-codes instead of byte-codes
- Cython:
CPython issues
-
Old projects
- Unladen Swallow, fork of CPython 2.6, use LLVM. No more maintained
- psyco: JIT. The author of pysco, Armin Rigo, co-created the PyPy project.
AST
Bytecode
Other
- ASP: ASP is a SEJITS (specialized embedded just-in-time compiler) toolkit for Python.
- PerformanceTips | https://bitbucket.org/haypo/astoptimizer/overview | CC-MAIN-2017-34 | refinedweb | 875 | 64 |
So far I have seen an article on performance and scalability mainly focusing on how long it takes to add new links. But is there any information about limitations regarding number of files, number of folders, total size, etc?
Right now I have a single file server with millions of JPGs (approx 45 TB worth) that are shared on the network through several standard file shares. I plan to create a DFS namespace and replicate all these images to another server for high availability purposes. Will I encounter extra problems with DFS that I'm otherwise not experiencing with plain-jane file shares? Is there a more recommended way to replicate these millions of files and make them available on the network?
EDIT 2:
All files are usually written to disk once and never modified after that. The only time they are modified is when they are eventually deleted, possibly years later. So everything is pretty static.
EDIT:
I would experiment on my own and write a blog post about it, but I don't have the hardware for the second server yet. I'd like to collect information before buying 45 TB of hard drive space...
We are currently using 2008 R2 DFSR with 57 TB of replicated files ( 1.6 Million ) and have an overall volume size in excess of 90 TB, without any issues .
So MS tested limits are a bit naive in this respect, and IMHO they should buy some more disk space and do some more testing.
If you're not time critical on the initial sync DFSR can do that too.
What it doesn't like especially is the same file being modified on multiple hosts as it has to do the arbitration on which to keep.
With 45TB of data, you are above the tested limitations of DFS-R on Server 2008, as per:
DFS-R: FAQ
Size of all replicated files on a server: 10 terabytes.
Number of replicated files on a volume: 8 million.
Maximum file size: 64 gigabytes.
Edit:
If your files will likely never change, you could utilize the namespace portion of DFS to create a virtualized path for your share. You could then run robocopy in a scheduled task to sync your servers. You would need to use something like robocopy for your initial sync, even if you were going to use DFS-R.
"Is there a more recommended way to replicate these millions of files and make them available on the network?"
Yup - either a SAN or NAS device to centralize them, or distributed storage like Isilon, Gluster, etc. DFS is nice, but it means that every server has a complete copy of everything, so that's not a good architecture if you need to scale a lot bigger.
Also, your architecture might have difficulty scaling anyway. I've seen some large image systems that don't store as files - they have a database that stores the metadata and the byte offsets of the images, and rolls them up into big binary files that are distributed in a way that's easy on the disk and filesystem. Need an image, and it will look up the blob file and pull the image out of it with the start and ending byte.
By posting your answer, you agree to the privacy policy and terms of service.
asked
2 years ago
viewed
4308 times
active | http://serverfault.com/questions/440017/windows-dfs-limitations?answertab=oldest | CC-MAIN-2015-14 | refinedweb | 566 | 69.72 |
From: Jurko GospodnetiÄ (jurko.gospodnetic_at_[hidden])
Date: 2008-05-19 12:38:31
Hi again.
>> I renamed the local CRITICAL_SECTION to critical_section to avoid this
>> ambiguity. See revision 45545.
>
> Could you also add the comment from the original patch to explain why
> this has been done? Since there are no tests prepared that would catch
> this if it ever regressed...
Also... the renamed class name as used in the original patch seemed
clearer since Visual C++ still has a bug with exposing this identified
in the global namespace... and 'critical_section' seems much more likely
to cause problems than
critical_section__whatever_we_write_here_as_an_explanation.
Best regards,
Jurko GospodnetiÄ
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2008/05/137578.php | CC-MAIN-2021-17 | refinedweb | 125 | 61.93 |
Introduction to Tensorflow for Java
Last modified: October 22, 2019
1. Overview
TensorFlow is an open source library for dataflow programming. This was originally developed by Google and is available for a wide array of platforms. Although TensorFlow can work on a single core, it can as easily benefit from multiple CPU, GPU or TPU available.
In this tutorial, we'll go through the basics of TensorFlow and how to use it in Java. Please note that the TensorFlow Java API is an experimental API and hence not covered under any stability guarantee. We'll cover later in the tutorial possible use cases for using the TensorFlow Java API.
2. Basics
TensorFlow computation basically revolves around two fundamental concepts: Graph and Session. Let's go through them quickly to gain the background needed to go through the rest of the tutorial.
2.1. TensorFlow Graph
To begin with, let's understand the fundamental building blocks of TensorFlow programs. Computations are represented as graphs in TensorFlow. A graph is typically a directed acyclic graph of operations and data, for example:
The above picture represents the computational graph for the following equation:
f(x, y) = z = a*x + b*y
A TensorFlow computational graph consists of two elements:
- Tensor: These are the core unit of data in TensorFlow. They are represented as the edges in a computational graph, depicting the flow of data through the graph. A tensor can have a shape with any number of dimensions. The number of dimensions in a tensor is usually referred to as its rank. So a scalar is a rank 0 tensor, a vector is a rank 1 tensor, a matrix is a rank 2 tensor, and so on and so forth.
- Operation: These are the nodes in a computational graph. They refer to a wide variety of computation that can happen on the tensors feeding into the operation. They often result in tensors as well which emanate from the operation in a computational graph.
2.2. TensorFlow Session
Now, a TensorFlow graph is a mere schematic of the computation which actually holds no values. Such a graph must be run inside what is called a TensorFlow session for the tensors in the graph to be evaluated. The session can take a bunch of tensors to evaluate from a graph as input parameters. Then it runs backward in the graph and runs all the nodes necessary to evaluate those tensors.
With this knowledge, we are now ready to take this and apply it to the Java API!
3. Maven Setup
We'll set-up a quick Maven project to create and run a TensorFlow graph in Java. We just need the tensorflow dependency:
<dependency> <groupId>org.tensorflow</groupId> <artifactId>tensorflow</artifactId> <version>1.12.0</version> </dependency>
4. Creating the Graph
Let's now try to build the graph we discussed in the previous section using the TensorFlow Java API. More precisely, for this tutorial we'll be using TensorFlow Java API to solve the function represented by the following equation:
z = 3*x + 2*y
The first step is to declare and initialize a graph:
Graph graph = new Graph()
Now, we have to define all the operations required. Remember, that operations in TensorFlow consume and produce zero or more tensors. Moreover, every node in the graph is an operation including constants and placeholders. This may seem counter-intuitive, but bear with it for a moment!
The class Graph has a generic function called opBuilder() to build any kind of operation on TensorFlow.
4.1. Defining Constants
To begin with, let's define constant operations in our graph above. Note that a constant operation will need a tensor for its value:
Operation a = graph.opBuilder("Const", "a") .setAttr("dtype", DataType.fromClass(Double.class)) .setAttr("value", Tensor.<Double>create(3.0, Double.class)) .build(); Operation b = graph.opBuilder("Const", "b") .setAttr("dtype", DataType.fromClass(Double.class)) .setAttr("value", Tensor.<Double>create(2.0, Double.class)) .build();
Here, we have defined an Operation of constant type, feeding in the Tensor with Double values 2.0 and 3.0. It may seem little overwhelming to begin with but that's just how it is in the Java API for now. These constructs are much more concise in languages like Python.
4.2. Defining Placeholders
While we need to provide values to our constants, placeholders don't need a value at definition-time. The values to placeholders need to be supplied when the graph is run inside a session. We'll go through that part later in the tutorial.
For now, let's see how can we define our placeholders:
Operation x = graph.opBuilder("Placeholder", "x") .setAttr("dtype", DataType.fromClass(Double.class)) .build(); Operation y = graph.opBuilder("Placeholder", "y") .setAttr("dtype", DataType.fromClass(Double.class)) .build();
Note that we did not have to provide any value for our placeholders. These values will be fed as Tensors when run.
4.3. Defining Functions
Finally, we need to define the mathematical operations of our equation, namely multiplication and addition to get the result.
These are again nothing but Operations in TensorFlow and Graph.opBuilder() is handy once again:
Operation ax = graph.opBuilder("Mul", "ax") .addInput(a.output(0)) .addInput(x.output(0)) .build(); Operation by = graph.opBuilder("Mul", "by") .addInput(b.output(0)) .addInput(y.output(0)) .build(); Operation z = graph.opBuilder("Add", "z") .addInput(ax.output(0)) .addInput(by.output(0)) .build();
Here, we have defined there Operation, two for multiplying our inputs and the final one for summing up the intermediate results. Note that operations here receive tensors which are nothing but the output of our earlier operations.
Please note that we are getting the output Tensor from the Operation using index ‘0'. As we discussed earlier, an Operation can result in one or more Tensor and hence while retrieving a handle for it, we need to mention the index. Since we know that our operations are only returning one Tensor, ‘0' works just fine!
5. Visualizing the Graph
It is difficult to keep a tab on the graph as it grows in size. This makes it important to visualize it in some way. We can always create a hand drawing like the small graph we created previously but it is not practical for larger graphs. TensorFlow provides a utility called TensorBoard to facilitate this.
Unfortunately, Java API doesn't have the capability to generate an event file which is consumed by TensorBoard. But using APIs in Python we can generate an event file like:
writer = tf.summary.FileWriter('.') ...... writer.add_graph(tf.get_default_graph()) writer.flush()
Please do not bother if this does not make sense in the context of Java, this has been added here just for the sake of completeness and not necessary to continue rest of the tutorial.
We can now load and visualize the event file in TensorBoard like:
tensorboard --logdir .
TensorBoard comes as part of TensorFlow installation.
Note the similarity between this and the manually drawn graph earlier!
6. Working with Session
We have now created a computational graph for our simple equation in TensorFlow Java API. But how do we run it? Before addressing that, let's see what is the state of Graph we have just created at this point. If we try to print the output of our final Operation “z”:
System.out.println(z.output(0));
This will result in something like:
<Add 'z:0' shape=<unknown> dtype=DOUBLE>
This isn't what we expected! But if we recall what we discussed earlier, this actually makes sense. The Graph we have just defined has not been run yet, so the tensors therein do not actually hold any actual value. The output above just says that this will be a Tensor of type Double.
Let's now define a Session to run our Graph:
Session sess = new Session(graph)
Finally, we are now ready to run our Graph and get the output we have been expecting:
Tensor<Double> tensor = sess.runner().fetch("z") .feed("x", Tensor.<Double>create(3.0, Double.class)) .feed("y", Tensor.<Double>create(6.0, Double.class)) .run().get(0).expect(Double.class); System.out.println(tensor.doubleValue());
So what are we doing here? It should be fairly intuitive:
- Get a Runner from the Session
- Define the Operation to fetch by its name “z”
- Feed in tensors for our placeholders “x” and “y”
- Run the Graph in the Session
And now we see the scalar output:
21.0
This is what we expected, isn't it!
7. The Use Case for Java API
At this point, TensorFlow may sound like overkill for performing basic operations. But, of course, TensorFlow is meant to run graphs much much larger than this.
Additionally, the tensors it deals with in real-world models are much larger in size and rank. These are the actual machine learning models where TensorFlow finds its real use.
It's not difficult to see that working with the core API in TensorFlow can become very cumbersome as the size of the graph increases. To this end, TensorFlow provides high-level APIs like Keras to work with complex models. Unfortunately, there is little to no official support for Keras on Java just yet.
However, we can use Python to define and train complex models either directly in TensorFlow or using high-level APIs like Keras. Subsequently, we can export a trained model and use that in Java using the TensorFlow Java API.
Now, why would we want to do something like that? This is particularly useful for situations where we want to use machine learning enabled features in existing clients running on Java. For instance, recommending caption for user images on an Android device. Nevertheless, there are several instances where we are interested in the output of a machine learning model but do not necessarily want to create and train that model in Java.
This is where TensorFlow Java API finds the bulk of its use. We'll go through how this can be achieved in the next section.
8. Using Saved Models
We'll now understand how we can save a model in TensorFlow to the file system and load that back possibly in a completely different language and platform. TensorFlow provides APIs to generate model files in a language and platform neutral structure called Protocol Buffer.
8.1. Saving Models to the File System
We'll begin by defining the same graph we created earlier in Python and saving that to the file system.
Let's see we can do this in Python:
import tensorflow as tf graph = tf.Graph() builder = tf.saved_model.builder.SavedModelBuilder('./model') with graph.as_default(): a = tf.constant(2, name='a') b = tf.constant(3, name='b') x = tf.placeholder(tf.int32, name='x') y = tf.placeholder(tf.int32, name='y') z = tf.math.add(a*x, b*y, name='z') sess = tf.Session() sess.run(z, feed_dict = {x: 2, y: 3}) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING]) builder.save()
As the focus of this tutorial in Java, let's not pay much attention to the details of this code in Python, except for the fact that it generates a file called “saved_model.pb”. Do note in passing the brevity in defining a similar graph compared to Java!
8.2. Loading Models from the File System
We'll now load “saved_model.pb” into Java. Java TensorFlow API has SavedModelBundle to work with saved models:
SavedModelBundle model = SavedModelBundle.load("./model", "serve"); Tensor<Integer> tensor = model.session().runner().fetch("z") .feed("x", Tensor.<Integer>create(3, Integer.class)) .feed("y", Tensor.<Integer>create(3, Integer.class)) .run().get(0).expect(Integer.class); System.out.println(tensor.intValue());
It should by now be fairly intuitive to understand what the above code is doing. It simply loads the model graph from the protocol buffer and makes available the session therein. From there onward, we can pretty much do anything with this graph as we would have done for a locally-defined graph.
9. Conclusion
To sum up, in this tutorial we went through the basic concepts related to the TensorFlow computational graph. We saw how to use the TensorFlow Java API to create and run such a graph. Then, we talked about the use cases for the Java API with respect to TensorFlow.
In the process, we also understood how to visualize the graph using TensorBoard, and save and reload a model using Protocol Buffer.
As always, the code for the examples is available over on GitHub. | https://www.baeldung.com/tensorflow-java | CC-MAIN-2021-43 | refinedweb | 2,082 | 55.95 |
[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)
[/spoiler]
[spoiler title=”Lesson Source Code”]
#include <iostream> #include <cmath> using namespace std; int main(){ // == Double equals sign -- boolean comparison operator // boolean = type of variable that can only hold true or false // || or, && and, > Gt, <lt , >=, < =, ! not, !=, // bool -- Type //bool isTaken = false; //char c = ' '; //if ( isTaken ){ // cout << "This seat is already purchased" << endl; //} //else{ // cout << "This seat costs $12 would you like to purchase this seat? Y/N" << endl; // cin >> c; // if (c == 'Y'){ // isTaken = true; // cout < < "Thank you for your purchase"; // } // else{ // cout << "Thanks for your interest"; // } //} int i = 0; if ( 1 < 7 || 9 < 6 ){ cout << "Is True" << endl; i += 9; } else{ cout << "Is false" << endl; } cout << i; system("PAUSE"); return 0; }
[/spoiler]:
if (myNumber == 2){ myNumber +=5; }
or they can be much more complex, like this
int multiplier=3, manaCost=17, healthCost=14, intellect=27, playerCurrentHealth=5, playerCurrentMana=15, damage =0; bool isStunned=false; if(intellect >=20 && playerCurrentMana >= manaCost && playerCurrentHealth >= healthCost && !isStunned){ damage = multiplier*intellect; } else if(isStunned){ cout < < "You are stunned. " << endl; } else{ cout << "Insufficient health and / or mana to cast." << endl; }<<
if(myNumber ==5){ myNumber +=2; } cout < < "The value of myNumber is: " << myNumber;.
... if( startingCash >= 5000 ){ interestRate=5; } else{ //placeholder } ...:
if ( true ){ int myNumber = 1; //Declared in scope } //Gets destroyed here cout < < myNumber; //This command will fail since myNumber was destroyed at the end of the scope established by the if statement. | http://beginnerscpp.com/lesson-6-simple-if-structure/ | CC-MAIN-2019-13 | refinedweb | 243 | 51.21 |
What Is XML?
XML stand for Extensible Markup Language. The Extensible Markup Language (XML) is the universal language for data on the web.
Extensible Markup Language (XML) documents are universally accepted as a standard way of representing information in platform and language independent manner.
Extensible Markup Language (XML) is universal standard for information interchange.
Extensible Markup Language (XML) documents can be created in any language and can be used in any language.
What Are the Benefits of XML?
The Benefits of using XML on the web -
1. Simplicity - It is very easy to read and understand.
2. Extensibility - There is no fixed set of tags and the tags can be created as per your needed.
3. Openness - It is a W3C standard, endorsed by software industry market leaders.
4. Self-description - XML documents can be stored without such definitions, because they contain Meta data in the form of tags and attributes.
5. Contains machine-readable context information
6. Separates content from presentation
7. Supports multilingual documents and Unicode
8. Facilitates the comparison and aggregation of data
9. Can embed multiple data types
10. Can embed existing data
Is XML case sensitive?
Yes, XML is a case sensitive language.
What Is XML Schema?
XML Schema describes the structure of an XML instance document by defining what each element must or may contain.XML Schema is expressed in the form of a separate XML file.
Note –some XML data types are predefined and new ones can be created.
As an Example,
<xsd:schema xmlns:
<xsd:element
<xsd:complexType>
What Is a well-formed XML document?
If a document is syntactically correct it can be called as well-formed XML document.
The basic rules of well-formed XML document:
1. Each and every open tag must be closed.
2. XML is case-sensitive so that every open tag must exactly match the closing tags.
3. Each and every element must be embedded within a single root element.
4. All child tags must be closed before parent tags.
What Are the difference between XML and HTML?
The HTML is used to mark up text whereas XML is used to mark up data.
The HTML is used for UI displaying purpose but the XML is used for data representation.
The HTML uses a fixed, unchangeable set of tags but in XML, you make up your own tags.
What Is a valid XML document?
If a document is structurally correct (with the above well-formed XML rules) then it can called as valid XML documents.
How does the XML structure is defined?
The Extensible Markup Language (XML) document will have a structure which has to be defined before we can create the documents and work with them. The structural rules can be defined using
many available technologies, but the following are popular way of doing so,
1) Document Type Definition (DTD)
2) Schema
What Is DTD?
The DTD stands for Document Type Definition and used to define the legal building blocks of an XML document.
DTD defines rules for a specific type of document i.e.
1. Names of elements
2. Order of elements
3. Proper nesting and containment of elements
4. Element attributes
What Is XML Schema Element?
The schema element defines the root element of a schema.
As an Example,
<?xml version="1.0"?>
<xs:schema xmlns:
<xs:element
</xs:schema>
How To apply a DTD to an XML document?
Include the DTD's element definitions within the XML document itself. Also provide the DTD as a separate file, whose name you reference in the XML document.
What Are differences between DTD and Schema?
The DTD follow SGML syntax but the Schema document is an XML document.
In DTD everything is treated as text where as the Schema supports variety of dataTypes similar to programming language.
In Schema, we can inherit, create relationship among elements but not possible in DTD.
What Is a Complex Element?
A complex element is an XML element that contains other elements & attributes as well.
The Types of complex elements:
1. An empty element
2. A complex element that contain only text
3. A complex element that contain only other elements
4. A complex element that contain both text and other elements
What Is a Simple Element?
A simple element is an XML element that can contain only text.
Types of simple elements,
1. A simple element can't be empty
2. A simple element can't have attributes
3. A simple element contains text - it can be of many different types.
What Are namespaces in XML? Why are important?
XML namespaces are used for providing uniquely named elements and attributes in an XML instance and the uniquely named elements avoid name collisions on elements.
What Are the ways to use XML namespaces?
There are two ways,
1. Fist one, declare a default namespace
2. Second one, associate a prefix with a namespace, then use the prefix in the XML to refer to the namespace.
What.
What Is XmlReader class?
The XmlrReader class represents a reader that provides fast, noncached, forward-only access from XML data. We must need to import the Xml namespaces before using the XmlReader class in C#.NET - using System.Xml;
What Is an XML parser?
A XML parser is a program that "parses" XML and evaluates the XML code. Its use of XML parser is to read XML document by using library.
The XML parsers basically convert code into something that the hardware will recognize. The main objective of the parsers is to transform XML into a readable code.
The Features of XML parser are,
1. Analyze the XML schema (XSD) or a significant XML sample
2. Create an optimized relational target schema
3. Automatically processes the XML files
4. Can handle arbitrarily complex XML files and supports the whole XSD spec
5. Provides data lineage in the form of a source to target map
6. Scales for very large volumes
The Available Tools that use as parser,
1. XMLHttpRequest: XMLHttpRequest object has inbuilt parser.
2. Expat XML Parser: Specially written in C language.
3. CodeBeauty Parser: Free XML Viewer, XML Formatter and convert XML document/string into readable format.
4. Alteryx Parser Tool: The XML parse tool reads in a chunk of Extensible Markup Language (XML) and parse it into individual fields
What Is DOM?
The DOM stands for Document Object Model.
DOM is a cross-platform and language-independent standard object model for representing XML and related formats.
DOM represents an XML document as a tree model and the tree model makes the XML document hierarchal by nature. Each and every construct of the XML document is represented as a node in the tree.
DOM is a programming interface for HTML and XML documents.
What Is the difference between DOM and HTML?
DOM is an abstraction of a structured text. For web developers, this text is an HTML code, and the DOM is simply called HTML DOM. Elements of HTML become nodes in the DOM. So, while HTML is a text, the DOM is an in-memory representation of this text.
What Is SAX?
The SAX stands for Simple API for XML processing and the SAX provides a mechanism for reading data from an XML document.
SAX provides an event based processing approach unlike DOM which is tree based.
What Are the differences between DOM, SAX and StAX XML parsers?
DOM stands for Document Object Model while SAX stands for Simple API for XML parsing.
SAX provides an event based processing approach unlike DOM which is tree based.
DOM parser load full XML file in memory and creates a tree representation of XML document, while SAX is an event based XML parser and doesn't load whole XML document into memory.
StAX Much like SAX but instead of responding to events found in the stream you iterate through the xml.
The difference between SAX and StAX is that of push and pull. SAX Push Model and the StAX Pull Model.
StAX enables you to create bidirectional XML parsers that are fast. It proves a better alternative to other methods, such as DOM and SAX, both in terms of performance and usability.
What Are the interfaces of SAX in XML?
The interfaces of SAX are,
DocumentHandler- It is used for getting event notification relating to a document.
ErrorHandler- It is used for handling error related notifications.
EntityResolver- It is used for reading external entities.
DTDHandler- It is implemented to get the notifications related to declarations in DTD like entities and notations
What Is XSL in XML?
XSL stands for eXtensible Stylesheet Language.
XSL is used for displaying the contents of XML documents.
XSL consists of three parts,
1. XSLT
2. XPath
3. XSL-FO
What Is XSLT in XML?
XSLT stands for eXtensible Stylesheet Language Transformation.
XSLT is used for transformation of one XML document into XHTML documents or to other XML documents.
XSLT uses XPath only.
What Is XPath in XML?
XPath is used to retrieve elements from XML documents.
XPath expressions also can be use to retrieve elements, attributes and values from XML files.
What Is XSL-FO?
XSL-FO is a markup language and used to generate PDF, DOC files.
XSL-FO is part of XSL.
What Is CDATA in XML?
What does <![CDATA[]]> node in a XML document?
CDATA stands for Character Data.
A CDATA section starts with "<![CDATA[" and ends with "]]>": CDATA sections cannot be nested..
From Wikipedia:
[In] an XML document or external parsed entity, a CDATA section is a section of element content that is marked for the parser to interpret as only character data, not markup.
As an Example,
<script>
<![CDATA[
function checkNumber(a,b)
{
if (a > b) then
{
return 1;
}
else
{
return 0;
}
}
]]>
</script>
In the example above, everything inside the CDATA section is ignored by the parser.
Notes - The "]]>" that marks the end of the CDATA section cannot contain spaces or line breaks. Nested CDATA sections are not allowed.
What Is the difference between CDATA and PCDATA?
CDATA means un-parsed character data whereas PCDATA means parsed character data.
Is it possible to use graphics in XML?
Yes, you can do using XLink and XPointer.
The multiples graphics formats supports,
GIF,JPG, PNG, CGM, EPS, TIFF, and SVG
Which are the types of parser in XML?
List of XML parser are,
1. DOM Parser
2. SAX Parser
3. StAX Parser
4. JAXB
What Is XPOINTER in XML?
XPOINTER is a W3C recommendation.
XPOINTER is used to point data within XML document and also used to locate the particular part of the XML document. | https://www.code-sample.com/2019/11/xml-interview-questions-and-answers.html | CC-MAIN-2020-16 | refinedweb | 1,759 | 68.67 |
Advertise Jobs
Perl
module
-
Part of CPAN
distribution
Script 0.53.
Script - (Win32) system administrator`s library
- for login and application startup scripts, etc
use Script; # or use Script ':DEFAULT'
$a =FileRead('c:\\autoexec.bat');
FileDelete('-r','c:\\tmp\\*');
FileEdit('c:\\autoexec.bat',sub{s/(SET *TMP *= *)/${1}c:\\tmp/i});
use Script ':ALL'; # import from @EXPORT and @EXPORT_OK
Print('Using','all','functions','from','@EXPORT','and','@EXPORT_OK');
use Script ':ALL',':OVER'; # silently overwrite with imported
At primary this module was written for system administrator needs in
centralised administration of Win32 clients: logon and application
startup scripts, etc. Later some functions useful in Windows NT server
scripts was added. Now many functions may run on UNIX or may be
developed for it. But area of Win32 servers and clients is very specific.
This module was made for several reasons:
- for useful functions does not (yet?) implemented as core perl functions.
- for more flexible and powerful functional style programming functions, than exists.
- to load used perl modules when required, with "eval('use ...')".
- to support scripting modes: printing of commands executed, die on errors.
This module calls for it`s functions many other modules from standard
and site perl libraries and OS commands, and depends on their
implementations and limitations. GUI functions implemented with Perl Tk.
Currently this module is implemented and tested on Win32 platform.
use vars qw($Interact $GUI $Echo $ErrorDie $Error $FileLog $Print);
# example usage: $Script::Interact=0
$Interact =1; # interact with user in functions as Prompt, Die, GUIMsg
$GUI =1; # use GUI interaction instead of terminal in functions
# as Die, GUIMsg
$Echo =1; # print commands as 'set echo on' in DOS
$ErrorDie =0; # die on error if 1, 2 inside Try
$@ = $Error =''; # last error occurred
$FileLog =''; # log file name (LOG handle) for Echo, Print, errors...
$Print =''; # external print routine reference
NOTE:
Some functions have not printout, and are not controlled by $Echo. Some
functions are not controlled by $Echo due to used components.
Some (boolean) functions returns TRUE to show success, or FALSE (0, '').
Returning values functions returns on error empty value: 0 or '' or ().
Undefined and negative results are escaped as possible for better
functional programming style support.
Values '0E0' or '0 but true' (numeric 0 and logical true) are not used.
Variable $@ or $Error may be used to distinguish erroneous empty values from normal.
(see Exporter)
@EXPORT = qw(CPTranslate Die Echo FileACL FileCompare FileCopy FileCRC FileCwd FileDelete FileDigest FileEdit FileFind FileGlob FileHandle FileIni FileLnk FileMkDir FileNameMax FileNameMin FileRead FileSize FileSpace FileTrack FileWrite FTPCmd GUIMsg NetUse OrArgs Pause Platform Print Registry Run RunInf RunKbd SMTPSend StrTime UserEnvInit UserPath);
@EXPORT_OK = qw(FileLog TrAnsi2Oem TrOem2Ansi Try(@) TryHdr);
%EXPORT_TAGS = ('ALL'=>[@EXPORT,@EXPORT_OK], 'OVER'=>[]);
Try
TryHdr
FileACL
FileCompare
FileCopy
FileCRC
FileCwd
File
FileDigest
FileEdit
FileFind
FileGlob
FileHandle
FileIni
FileLnk
FileLog
FileMkDir
FileNameMax
FileNameMin
FileRead
FileSize
FileSpace
FileTrack
FileWrite
FTPCmd
Registry
OrArgs
Run
RunInf
RunKbd
NetUse
Platform
UserEnvInit
UserPath
SMTPSend
CPTranslate
TrAnsi2Oem
TrOem2Ansi
StrTime
Die
GUIMsg
Pause
Print
Echo
Sets access control list for directories and files matching fileMask and sub.
Without given access control list, prints current, this behaviour may be changed.
Uses FileFind, Win32::FileSecurity.
Options: 'r'ecurse subdirectories, '+' - add ACL entries instead of replacing them.
Sub parameters are like in FileFind.
Access: 'add' (not implemented), 'add&read', 'add&list' (not implemented), 'read', 'change', 'full',
reference to array of array references [[directory low level rights],[file low level rights]].
Copies fromFileMask to toPath. On 'MSWin32' uses xcopy with switches H, R, K, E, Q, Z.
xcopy
Options: 'r'ecurse subdirectories,
'd'irectory target hint,
'f'ile target hint,
'i'gnore errors - continue copying.
Calculates CRC of file or 0 if error. Uses Compress::Zlib.
Options: 'adler' or 'adler32' or '-a adler', 'crc32' (default).
Deletes files and directories fileMask. Uses FileGlob.
Options: 'r'ecurse subdirectories.
Edits given file with given sub using local variable $_ for text to edit.
Uses FileRead, FileWrite, File::Copy.
Options: 'i'nplace edit in memory (default),
'i ext' - use temporary file with given extension,
'm'ultiline edit instead of evaluation sub for each row of file.
Parameters of sub: $_, $_[0] - section name (determined with '[' sign in row beginning),
@_(1...) - temporary variables with lifetime of FileEdit execution.
Finds files and directories with given mask and evaluates sub, locally setting
$_ to filename. Returns number of sub agrees, or result if defined,
or 0 on errors. There may be
several subs and several filemasks for each sub, and they will be executed
within one transaction of FileFind call.
Uses FileGlob
Options: 'i'gnore stat errors, '!' - not, 'd'irectories,
'l'ow before deep scan, 'm'ountpoints,
'r'ecurse directories, 's'ymlinks.
Parameters of sub are local $_ with full current filename, $_[0] with
reference to @stat array, $_[1] with path, $_[2] with filename,
$_[3] as optional result storage (initially undefined).
Sub can return undefined value in $_ to signal stop, determine directories with
$_[0]->[2] & 0040000, prevent recursing by assigning $_[0]->[2] =0.
Options for FileFind and based on it functions as FileACL,
FileSize
should and should not be the same. FileFind defaulty recurses, other
commands traditionally not. Set of FileFind options may be extended in future,
but existing programs should be preserved, and so FileFind options should be
negative instead of traditionally positive options of other commands.
Based on FileFind functions are restricted, not using all possible FileFind
features. All functions may be called from comprehensive FileFind to get
all features.
Globs filenames with mask and returns list of them such as
standard function glob. On error returns empty list?
When $^O eq 'MSWin32' own implementation with fragments from
File::DosGlob is used, else glob is called.
glob
Standard glob is not well on Win32 platforms,
when working with filenames in foreign languages
and calling external executable dosglob.exe should be placed in path.
File::DosGlob has some problems with non-english letters
in filenames and long filenames.
Edits ini-file in Windows format with given items.
Without items returns a hash structure $hash{section}->{name}=value.
Uses FileRead, FileWrite.
Options: reserved for future use.
Format of items:
'[sectionName]', ';comment', [name => value];
['[sectionName]', op], [';comment', op], [name, value, op]
Operations: '+' - set (default), '-' -delete, 'i'nitial value, 'o'ptional value.
Returns Win32::Shortcut object or creates Win32 shortcut file.
Uses Win32::Shortcut.
Filename may be absolute or relative to 'm'enu or 'd'esktop according to this options.
Default filename extension is '.lnk'.
Names of parameters for shortcut may be given above or may be names of properties of Win32::Shortcut object.
Options: 'm'enu relative filename, 'd'esktop relative filename,
'a'll users profile use instead of current user profile,
'c'reate shortcut file instead of update.
Reads given file into memory as array or list ('-a'), text scalar ('-s'),
binary scalar ('-b'). Default, '-a' or '-b', is determined with wantarray.
If sub is defined, it is evaluated for each row read into local $_,
and with '-a' option results of each evaluation are returned as a list,
true is returned otherwise.
On error returns empty list or scalar, according to option '-a','-s','-b'.
Tracks changed files matched 'sub' in 'sourceDir' into 'destDir'.
Returns path to new archive directory inside 'destDir' or empty string if none archived.
'Sub' gets current filename in $_ and returns 'true' if match.
Code and interface are like FileFind.
Uses FileCopy, FileCRC, FileGlob.
Options: 'i'gnore errors, 't'est and track CRC,
'!' - not, 'c'opy changed files,
'd'irectories, 'r'ecurse directories,
't'ime check.
Works with values in Windows registry: returns value for given key and name,
sets given value, deletes if undefined value given.
Uses Win32::TieRegistry, error processing is unsupported.
Option defines delimiter for key parts: '\\' (default), '|' or '/'.
Value name may be delimited with double delimiter ('key\\\\name') as
recommended Win32::TieRegistry, or single delimiter ('key\\name') as
also supported.
Last parts of key not present in registry are automatically created,
that improves behaviour of Win32::TieRegistry.
Type may be 'REG_SZ' (default), 'REG_EXPAND_SZ', 'REG_BINARY', 'REG_MULTI_SZ', 'REG_DWORD'.
Initiates user`s environment on Win32.
Uses Win32::TieRegistry, cacls, reskit utilities winset, setx.
cacls
winset
setx
Default options are '-nhy', option '-y' redefines environment variables when they defined, options may be '-n', '-ny', '-h'.
Option 'n' sets on Win95 environment variables used on WinNT: 'OS', 'COMPUTERNAME', 'USERNAME'.
Option 'h' works if 'c:/Home' directory exists. It creates directory
'c:/Home/Username' if it not exists (WinNT ACL setting applied),
sets value for $$Registry{'CUser\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\\\Personal'}
to 'c:/Home/Username' or 'c:/Home/Work' (for systems with single user profile),
sets 'My Pictures' based on 'Personal',
sets 'HOME' environment variable to $ENV{USERPROFILE}
NetUse on Windows NT some optimization.
Platform('host') corrected to return full host name with domain.
If Sys::Hostname returns string without dot signs,
Net::Domain is catenated.
FileDigest
OrArgs
Module size reduced as sub delimiters
FileACL - blank names are now quoted in 'cacls' run
UserEnvInit - $ENV{HOME} changed to ENV{USERPROFILE}, 'My Pictures' set,
alternative documents dirs may be specified as parameters
UserPath - all arguments are optional
FileACL - echo format changed.
FileDelete - '-i'gnore option added.
NetUse - WinNT specific code added.
StrTime - 'mm' is month placeholder, 'MM' or second 'mm' is minutes placeholder.
Echo, Print - are exported by default (moved from @EXPORT_OK to @EXPORT).
FileACL - processed files are printed, not echoed; uses 'cacls.exe' when possible.
FileCopy - '-d' removed from 'cp'.
FileCopy - uses Run(...sub{}).
FileGlob - support for filenames with '()'.
FileLog - $SIG{__DIE__} dies if !defined($^S) too.
FileSpace - digit grouping symbol may be ','.
FileTrack - internal filehandle renamed from 'LOG' to 'TRACK'.
NetUse - invokes 'net use ... /Yes' on Win95.
Registry - supports unnamed registry values.
Run - last argument may be sub to print to program called.
UserPath - excludes blanks at the end of path as may be on WinNT.
FileCwd
FileLnk
RunInf
RunKbd
UserPath
$ErrorDie - value 2 introduced and used inside Try because of $^S may be incorrect inside eval('string') or do(script).
$ErrorDie
$^S
eval
do
FileCopy - used pipe to answer to xcopy before system call
because of codepage translation problem in open(commandline) on Win32
and incorrect $? of wait of IPC::Open3 on Win95.
pipe
system
open
wait
FileEdit - restored sub's parameter $_[0] with with section name, removed 28/02/2000.
FileFind, FileTrack - filenames with '?' are ignored only when $^O eq 'MSWin32'.
FileFind - options added: !'l'ow before deep scan, 'm'ountpoints, 's'ymlinks.
FileGlob - created own implementation for 'MSWin32'
supporting non-english letters and long filenames
instead of File::DosGlob.
FileHandle - uses caller's namespace for HANDLE.
FileTrack - added '!t' option to disable mtime checking.
FTPCmd - first parameter may be hash ref with host, username and password.
Pause - returns string entered as documented, instead of chomp result.
chomp
Platform - new parameter 'windir'.
Module Carp used, croak should be called instead of TryErr or die.
Carp
croak
TryErr
die
TryEnd
Error processing made with eval{} and $@, see Try.
Variable $Error is syncronised with $@ and becomes optional.
$^O (osname) introduced into some functions.
getlogin
PrintErr
warn
stat
FileFind - review options and arguments.
It should accept violating needs when deleting and creating.
When creating, sub should see directories first, when deleting - contents first.
FTPCmd, Platform, SMTPSend, - approve and test.
p - 5 - platform (windows specific) realisation only, 2 - unix+win
w - 3 - windows specific
e - - no error handling
31 - total number of functions
pwe
CPTranslate e
Die e
Echo e
FileACL p
FileCompare
FileCopy 2
FileCRC
File
FileEdit
FileFind
FileGlob e
FileHandle
FileIni
FileMkDir
FileNameMax
FileNameMin
FileRead
FileSize
FileSpace p
FileWrite
FTPCmd
GUIMsg
NetUse pw
Pause
Platform ?
Print e
Registry pw
Run
SMTPSend
StrTime e
UserEnvInit pw
RetCodes - '0E0' for successful empty?
FileACL - debug and develop.
FileFind - corrected stat bug for filenames with sign '?'.
FileFind - review options and arguments.
FileFind - should accept violating needs when deleting and creating. When
creating, sub should see directories first, when deleting - contents first.
FTPCmd - approve and test.
Platform - approve and test.
Print and PrintErr - should this functions be exported by default?
UserEnvInit - approve and test, especially for russian WinNT.
Corrections and developments was made
02/07/99, 28/06/99, 23/06/99, 15/06/99, 01/04/99, 25/03/99, 23/03/99, 20/03/99, 19/03/99, 17/03/99, 15/03/99, 13/03/99, 12/03/99, 09/03/99, 06/03/99, 03/03/99, 02/03/99, 01/03/99, 27/02/99, 24/02/99
A small module with a few functions was created and turned onto
exploitation.
Andrew V Makarow <makarow@mail.com>, Denis E Medvedyuk <demed@mail.com> | http://aspn.activestate.com/ASPN/CodeDoc/Script/Script.html | crawl-002 | refinedweb | 2,083 | 58.48 |
Walkthrough: Creating a Basic Control Designer for a Web Server Control
This.
In this section, you create three basic Web server controls and an associated custom control designer for each of them.
To create a file for the code.
To create a composite control and an associated designer
Within the namespace you declared in the SimpleControlDesigners file, create a public declaration for a composite control class that inherits from CompositeControl, as shown in the following code..
To create a Web server control and a container designer with an editable region
Within the namespace you declared in the SimpleControlDesigners file, create a public declaration for a new Web server control class, as shown in the following code example...
Container control with child controls
Save the page.
To view the page at run time
Load the page in a browser.
The controls should appear as you customized them in Design view. Your page should look similar to the following screen shot.
Completed control designers Web page. | https://msdn.microsoft.com/en-us/library/12yydcke(v=vs.80)?cs-save-lang=1&cs-lang=vb | CC-MAIN-2015-27 | refinedweb | 164 | 54.83 |
Getting error when trying to access 2D QVector's elements.
Hello, I would like to create a matrix by using QVector. Could you tell me where I make mistake? Here is the code:
#include <QCoreApplication> #include <QVector> #include <QDebug> int main(int argc, char* argv[]) { QCoreApplication a(argc, argv); QVector< QVector<double> > list(3); QVector<double> first(5, 1.0); QVector<double> second(5, 2.0); QVector<double> third(5, 3.0); list.append(first); list.append(second); list.append(third); qDebug() << list.at(0).at(0); return a.exec(); }
It is compiled successfully, but when I run it, it prompts a console output which says:
ASSERT failure in QVector<T>::at: "index out of range", file ../../Qt/5.4/gcc_64/include/QtCore/qvector.h, line 388
How can I solve this? If I use standard library vector class, would it solve?
- SGaist Lifetime Qt Champion
Hi,
You create list with three empty elements and then you append your three other vectors. So you have in fact list size that is 6 and the first three are empty hence the assert failure. | https://forum.qt.io/topic/54913/getting-error-when-trying-to-access-2d-qvector-s-elements | CC-MAIN-2018-51 | refinedweb | 182 | 59.9 |
Framework Versions
You can create different versions of a framework based on the type of changes made to its dynamic shared library. There are two types of versions: major (or incompatible) and minor (or compatible) versions. Both have an impact on the programs linked to the framework, albeit in different ways.
Major Versions
A major version of a framework is also known as an incompatible version because it breaks compatibility with programs linked to a previous version of the framework’s dynamic shared library. Any such program running under the newer version of the framework is likely to experience runtime errors because of the changes made to the framework.
The following sections describe how you designate major version information in your framework and how the system uses that information to ensure applications can run.
Major Version Numbering Scheme
Because all major versions of a framework are kept within the framework bundle, a program that is incompatible with the current version can still run against an older version if needed. The path of each major version encodes the version (see Framework Bundle Structure). For example, the letter “A” in the path below indicates the major version of a hypothetical framework:
When a program is built, the linker records this path in the program executable file. The dynamic link editor uses the path at runtime to find the compatible version of the framework’s library. Thus the major versioning scheme enables backward compatibility of a framework by including all major versions and recording the major version for each executable to run against.
When to Use Major Versions
You should make a new major version of a framework or dynamic shared library whenever you make changes that might break programs linked to it. The following changes might cause programs to break:
Removing public interfaces, such as a class, function, method, or structure
Renaming any public interfaces
Changing the data layout of a structure
Adding, changing, or reordering the instance variables of a class
Adding virtual methods to a C++ class
Reordering the virtual methods of a C++ class
Changing C++ compilers or compiler versions
Changing the signature of a public function or method
Changes to the signature of a function include changing the order, type, or number of parameters. The signature can also change by the addition or removal of
const labels from the function or its parameters.
When you change the major version of a framework, you typically make the new version the “current” version. Xcode automatically generates a network of symbolic links to point to the current major version of a framework. See Framework Bundle Structure for details.
Avoiding Major Version Changes
Creating a major version of a framework is something that you should avoid whenever possible. Each new major version of a framework requires more storage space than a comparable minor version change. Adding new major versions is unnecessary in many cases.
Before you find yourself needing to create a new major version of your framework, consider the implementation of your framework carefully. The following list shows ways to incorporate features without requiring a new major version:
Pad classes and structures with reserved fields. Whenever you add an instance variable to a public class, you must change the major version number because subclasses depend on the size of the superclass. However, you can pad a class and a structure by defining unused (“reserved”) instance variables and fields. Then, if you need to add instance variables to the class, you can instead define a whole new class containing the storage you need and have your reserved instance variable point to it.
Keep in mind that padding the instance variables of frequently instantiated classes or the fields of frequently allocated structures has a cost in memory.
Don’t publish class, function, or method names unless you want your clients to use them. You can freely change private interfaces because you can be sure no programs are using them. Declare any interfaces that may change in a private header.
Don’t delete interfaces. If a method or function no longer has any useful work to perform, leave it in for compatibility purposes. Make sure it returns some reasonable value. Even if you add additional arguments to a method or function, leave the old form around if at all possible.
Remember that if you add interfaces rather than change or delete them, you don't have to change the major version number because the old interfaces still exist. The exception to this rule is instance variables.
While many of the preceding changes do not require the creation of a major version of your framework, most require changing the minor version information. See Versioning Guidelines for more information.
Creating a Major Version of a Framework
When you create a major version of a framework, Xcode takes care of most of the implementation details for you. All you need to do is specify the major-version designator. A popular convention for this designator is the letters of the alphabet, with each new version designator “incremented” from the previous one. However, you can use whatever convention is suitable for your needs, for example “2.0” or “Two”.
To set the major version information for a framework in Xcode, do the following:
Open your project in Xcode 2.4.
In the Groups & Files pane, select the target for your framework and open an inspector window.
Select the Build tab of the inspector window.
In the Packaging settings, set the value of the “Framework Version” setting to the designator for the new major version of your framework, for example,
B..
You can also make major versions of standalone dynamic shared libraries (that is, libraries not contained within a framework bundle). The major version for a standalone library is encoded in the filename itself, as shown in the following example:
To make it easier to change the major version, you can create a symbolic link with the name
libMyLib.dylib to point to the new major version of your library. Programs that use the library can refer to the symbolic link. When you need to change the major version, you can then update the link to point to a new library.
Minor Versions
Within a major version of a framework, you can also designate the current minor version. Minor versions are also referred to as “compatible versions” because they retain compatibility with the applications linked to the framework. Minor versions don’t change the existing public interfaces of the framework. Instead, they add new interfaces or modify the implementation of the framework in ways that provide new behavior without changing the old behavior.
Within any major version of the framework, only one minor version at a time exists. Subsequent minor versions simply overwrite the previous one. This differs from the major version scheme, in which multiple major versions coexist in the framework bundle.
The following sections describe how you designate minor version information in your framework and how the system uses that information to ensure applications can run.
Minor Version Numbering Scheme
Frameworks employ two separate numbers to track minor version information. The current version number tracks individual builds of your framework and is mostly for internal use by your team. You can use this number to track a group of changes to your framework and you can increment it as often as seems appropriate. A typical example would be to increment this number each time you build and distribute your framework to your internal development and testing teams.
The compatibility version number of your framework is more important because it marks changes to your framework’s public interfaces. When you make certain kinds of changes to public interfaces, you should set the compatibility version to match the current version of your framework. Thus, the compatibility version typically lags behind the current version. Only when your framework’s public interfaces change do the two numbers match up.
Remember that not all changes to your framework’s public interfaces can be matched by incrementing the compatibility version. Some changes may require that you release a new major version of your framework. See Versioning Guidelines for a summary of the changes you can make for each version.
When to Use Minor Versions
You should update the version information of your framework when you make any of the following changes:
Add a class
Add methods to an Objective-C class
Add non-virtual methods to a C++ class
Add public structures
Add public functions
Fix bugs that do not change your public interfaces
Make enhancements that do not change your public interfaces
Any time you change the public interfaces of your framework, you must update its compatibility version number. If your changes are restricted to bug fixes or enhancements that do not affect the framework’s public interfaces, you do not need to update the compatibility version number.
Compatibility Version Numbers at Runtime
When a program is linked with a framework during development, the linker records the compatibility version of the development framework in the program’s executable file. At runtime, the dynamic link editor compares that version against the compatibility version of the framework installed on the user’s system. If the value recorded in the program file is greater than the value in the user’s framework, the user’s framework is too old and cannot be used.
Cases where a framework is too old are uncommon, but not impossible. For example, it can happen when the user is running a version of OS X older than the version required by the software. When such an incompatibility occurs, the dynamic link editor stops launching the application and reports an error to the console.
To run an application on earlier versions of a framework, you must link the application against the earliest version of the framework it supports. Xcode provides support for linking against earlier versions of the OS X frameworks. This feature lets you link against specific versions of OS X version 10.1 and later. For more information, see SDK Compatibility Guide.
Creating a Minor Version of a Framework
If you are developing a framework, you need to increment your current version and compatibility version numbers at appropriate times. You set both of these numbers from within Xcode. The linking options for Xcode framework projects include options to specify the current and compatibility version of your framework. To set these numbers for a specific target, do the following:
Open your project in Xcode 2.4.
In the Groups & Files pane, select the target for your framework and open an inspector window.
Select the Build tab of the inspector window.
In the Linking settings, set the value of the “Current Library Version” setting to the current version of your framework.
Update the “Compatibility version” option as needed to reflect significant changes to your framework. (See Compatibility Version Numbers at Runtime for more information.)
Versioning Guidelines
Whenever you change the code in your framework, you should also modify the configuration information in your framework project to reflect the changes. For simple changes, such as bug fixes and most new interfaces, you may need to increment only the minor version numbers associated with your framework. For more extensive changes, you must create a new major version of your framework.
Table 1 lists the types of changes you can make to your framework code and the corresponding configuration changes you must make to your project file. Most changes that require a major or minor version update occur because the changes affect public interfaces.
If you don’t change the framework’s major version number when you need to, programs linked to it may fail in unpredictable ways. Conversely, if you change the major version number when you didn’t need to, you clutter up the system with unnecessary framework versions.
Because major versions can be very disruptive to development, it is best to avoid them if possible. Avoiding Major Version Changes describes techniques you can use to make major changes without releasing a new major version of your framework.
Copyright © 2003, 2013 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2013-09-17 | https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPFrameworks/Concepts/VersionInformation.html | CC-MAIN-2015-11 | refinedweb | 2,022 | 51.99 |
<<
FHATUWANI Dondry MUVHANGO17,796 Points
having trouble with strings and dictionaries
when i run this, it keeps saying 'dicts' is a list and not a map. what is it that i should do to solve this problem?
dicts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, {'name': 'Walter', 'food': 'pancakes'}, {'name': 'Galactus', 'food': 'worlds'} ] string = "Hi, I'm {name} and I love to eat {food}!" def string_factory(dicts, string): return string.format(**dicts) string_factory(dicts, string)
4 Answers
FHATUWANI Dondry MUVHANGO17,796 Points
hi Ryan, i managed to tweek my code a bit. but it still giving me an error, now it say "what happened to 'string_factory'"
icts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, {'name': 'Walter', 'food': 'pancakes'}, {'name': 'Galactus', 'food': 'worlds'} ]
string = "Hi, I'm {name} and I love to eat {food}!"
string_list = [] def string_fatory(dicts, string): for item in dicts: string_list.append(item) string.format(**string_list) return string_factory
Ryan S27,275 Points
Hi Fhatuwani,
It's hard to tell from the format of your code but I think you are pretty close. You have the right idea but there are just a couple things to fix. First, you will need to define string_list inside the function, but before the for loop. And second, you will need to format the string in the append() function, but you will be unpacking the item, not the string_list. Remember that the item, in this case, is a dictionary that is contained within a list.
Try the following:
def string_factory(dicts, string): string_list = [] for item in dicts: string_list.append(string.format(**item)) return string_list
Ryan S27,275 Points
Hi Fhatuwani,
The variable
dicts is a list that contains a bunch of dictionaries, so in your return statement you are trying to unpack a list, not a dictionary. Another thing is that the challenge is asking you to return a list of formatted strings, not a single formatted string. So you will need to define an empty list,
string_list = [], for example, and append that list in a
for loop. You'd then return
string_list when the looping is done.
Remember that in the
for loop you will be looping through an individual
dictionary in the
dicts list, and will need to unpack each dictionary.
Also, you don't need to call the function at the end. The code challenge will do that for you when you submit.
Hope this helps, | https://teamtreehouse.com/community/having-trouble-with-strings-and-dictionaries | CC-MAIN-2022-40 | refinedweb | 398 | 78.69 |
while True:
bigScreenReg = Region(
bigScreenRe
r = bigScreenReg
r.onChange(100, changed)
Settings.
r.observe(5) # observing for 5 seconds (script pauses here)
if Settings.isChanged: # check wether the handler was called (because there where changes)
else:
print "there haven't been any changes"
continue
It seems to be highlighting when there are changes in the region, but the popup never get's activated, the log just forever is filled with "there haven't been any changes" even though there were definitely changes in the region that I observed.
Basically I just want it to throw a popup when there are changes in the region.
Question information
- Language:
- English Edit question
- Status:
- Solved
- For:
- Sikuli Edit question
- Assignee:
- No assignee Edit question
- Solved:
- 2017-11-18
- Last query:
- 2017-11-18
- Last reply:
- 2017-11-17
not my variable, I found it on a google search and tried to get it to work, but found this one way easier.
def changeHandler(
while True:
nav = Region(
if nav.somethingCh
print "changed within observation time"
if not nav.somethingCh
print "did not change within observation time"
continue
"Settings.
isChanged" is your own variable?
Now, Settings.isChanged is set False in your codes and Settings.isChanged is not modified anywhere.
You have to add code in function "changed" to modify the value of Settings.isChanged to True. | https://answers.launchpad.net/sikuli/+question/660875 | CC-MAIN-2017-51 | refinedweb | 223 | 65.12 |
Appendix C Proxy Configuration Files
This appendix describes the directives and functions in the configuration files that iPlanet Web Proxy Server uses. You can configure iPlanet Web Proxy Server manually by editing the files directly.
The files that you use to configure the proxy are in a directory called proxy-id/config in your server root directory. Here's a brief description of each file described in this appendix:
-.
- socks5.conf is a file that contains the SOCKS server configuration. The SOCKS daemon is a generic firewall daemon that controls point-to-point access through the firewall.
-.
Other files that affect the proxy are explained elsewhere in this book:
- mime.types is the file the server uses to convert filename extensions such as .GIF into a MIME type like image/gif. This file is described in Chapter 16 "Configuring the Proxy Manually."
- admpw is the administrative password file. Its format is user:password. The password is DES-encrypted just like /etc/passwd. This file is described in Chapter 16 "Configuring the Proxy Manually." The admpw file is located in the admin-serv directory.
- autoconfig is a file in Netscape Navigator 2.0 JavaScript software that enables you to specify when to use the proxy. This file is described in Chapter 11 "Using the Client Autoconfiguration File."
-
For each directive, this section provides the directive's characteristics, including the directive name, description, format for the value string, default value if the directive is omitted, and how many times the directive can be in the file. The directives are:
- Certfile specifies the location of the certificate file.
- Ciphers specifies which ciphers are enabled for your server.
- DNS specifies if the server does DNS lookups on clients who access the server.
- ErrorLog specifies the directory where the server logs its errors.
- Keyfile specifies the location of the key file.
- LDAPConnPool specifies the number of persistent connections to the LDAP directory.
- LoadObjects specifies a startup object configuration file.
- MaxProcs sets the maximum number of active processes.
- PidLog specifies a file to record the proxy's main process ID (pid).
- Port defines the TCP port to which the server listens.
- ProcessLife specifies the number of requests each child process serves during its lifetime.
- RootObject defines the default server object.
- Security specifies whether SSL is enabled or disabled.
- ServerName defines the proxy host name.
- SSLClientAuth requires that client authentication be done for every request.
- SSL2 specifies whether SSL 2.0 is enabled or disabled.
- SSL3 specifies whether SSL 3.0 is enabled or disabled.
- SSL3Ciphers specifies which encryption schemes are enabled.
- User specifies the proxy's Unix user account.
Certfile
The Certfile directive specifies where the certificate file is located.
Syntax
certfile [filename]
certfile is the server's certificate file, specified as a relative path from the server root or as an absolute path.
Ciphers
The Ciphers directive specifies the ciphers enabled for your server. For a discussion of the pros and cons of these ciphers, see Chapter 14 "Understanding Encryption and SSL."
Syntax
Ciphers +rc4 +rc4export -rc2 -rc2export +idea +des +desede3
A + means the cipher is active, and a - means the cipher is inactive.
Valid ciphers are rc4, rc4export, rc2, rc2export, idea, des, desede3. Any cipher with export as port of its name is not stronger than 40 bits.
DNS
The DNS directive specifies whether the server performs DNS lookups on clients accessing, error reporting, and access logging.
If your server responds to many requests per day, you might want (or need) to stop host name resolution; doing so can reduce the load on the DNS or NIS server.
Syntax
DNS [on|off]
Default
DNS host name resolution is on as a default.
ErrorLog
The ErrorLog directive specifies the directory where the server logs its errors. You can also use the syslog facility. If errors are reported to a file (instead of syslog), then the file and directory in which the log is kept must be writable by whatever user account the server runs as.
Syntax
ErrorLog logfile
logfile can be a full path and filename or the keyword SYSLOG (which must be in all capital letters).
Keyfile
The Keyfile directive tells the server where the key file is located.
Syntax
keyfile [filename]
keyfile is the server's key file, specified as a relative path from the server root or as an absolute path.
LDAPConnPool
The LDAPConnPool Directive specifies the number of persistent connections to maintain to the LDAP directory server. Creating these connections and binding to the directory on each one is an expensive operation. This setting establishes a reasonably sized pool of connections that will be shared among the proxy's request handler threads. Increase this value to allow more connections and to improve proxy performance if your directory server is not overloaded. Decrease the value if your directory server is very busy.
The default value for LDAPConnPool is 5.
LoadObjects
The LoadObjects directive specifies one or more object configuration files to use on startup; these files tell the server the kinds of URLs to proxy and cache. If any User directive is in the magnus.conf file, it must appear before the LoadObjects directive.
Although you can have more than one object configuration file, the proxy's administration forms work with only one file and assume that it is in the server root in proxy-id/config/obj.conf. If you use the online forms (or plan to), don't put the obj.conf file in any other directory and don't rename it.
Syntax
LoadObjects filename
filename is either the full pathname or a relative pathname. Relative pathnames are resolved from the directory specified with the -d command line flag. If no -d flag is given, the server looks in the current directory.
MaxProcs
The MaxProcs directive sets the maximum number of processes the server can have active. The MaxProcs number is the number of processes that the proxy is to constantly keep active.
When you change MaxProcs, you must do a hard restart for the change to take effect.
Choose a number that is appropriate for the volume of access you expect for the proxy server. If this number is too small, clients will experience delays. If the number is too large, you might waste resources that other programs could use.
Syntax
MaxProcs number
number is a whole number between 1 and the size of your system's process table.
Default
MaxProcs 50
PidLog
The PidLog directive specifies a file in which to record the process ID (pid) of the base proxy server process. Some of the server support programs (including the forms-based iPlanet Web Proxy Server Manager) assume that the pid log file isn't writable by the user account that the server uses, the server does not log its process ID anywhere.
Syntax
PidLog file
file is the full pathname and filename where the process ID is stored.
Port
The Port directive controls to which TCP port the server listens. If you choose a port number less than 1024, the server must be started as root or superuser. The port you choose also affects how the proxy users configure their browsers (they must specify the port number when accessing the proxy server). There should be only one Port directive in magnus.conf.
There are no official port numbers for proxy servers, but two commonly used numbers are 8080 and 8000. If you use iPlanet Web Proxy Server's SOCKS daemon feature, the proxy should use the standard SOCKS port (1080).
Syntax
Port number
number is a whole number between 0 and 65535.
Default
Port 8080
ProcessLife
The ProcessLife directive specifies the number of requests that each of the proxy's child processes serves before the processes exit and get respawned. When the processes are stopped and restarted, the memory they use is freed and then reused.
Syntax
ProcessLife number
number is how many requests each child process serves before the processes exit and get respawned.
Default
ProcessLife 1024
By stopping and restarting a process, the proxy ensures that memory isn't wasted by "lost" processes. For example, on rare occasions, when a connection is terminated by the client or the remote server while the proxy is processing the request, the request fails and some part of allocated memory isn't freed. ProcessLife ensures that the memory is eventually freed.
RootObject
The RootObject directive tells the server which object loaded from an object file is the server default. The default object is expected to have all of the name translation directives for the server; any server behavior that is configured in the default object affects the entire server.
If you specify an object that doesn't exist, the server doesn't report an error until a client tries to retrieve a document.
Syntax
RootObject name
name is the name of an object defined in one of the object files loaded with a LoadObjects directive.
Default
There is no default if you do not specify a root object name; even if it is the "default" named object, you must specify "default." The administration forms assume you will use the default named object. Don't deviate from this convention if you plan to use the online forms.
Security
The Security directive tells the server whether encryption (Secure Sockets Layer version 2 or version 3 or both) is enabled or disabled.
If Security is set to on, and both SSL2 and SSL3 are enabled, then the server tries SSL3 encryption first. If that fails, the server tries SSL2 encryption.
Syntax
Security on|off
Default
By default, security is off.
ServerName
The ServerName directive tells the server what to put in the host name section of any URLs it sends back to the client. This affects redirections that you have set up using the online forms. Combined with the port number, this name is what all clients use to access the server.
You can have only one ServerName directive in magnus.conf.
Syntax
ServerName host
host is a fully qualified domain name such as myhost.netscape.com.
Default
If ServerName isn't in magnus.conf, the proxy server attempts to derive a host name through system calls. If they don't return a qualified domain name (for example, they get myhost instead of myhost.netscape.com), the proxy server won't start, and you'll get a message telling you to set this value manually, meaning put a ServerName directive in your magnus.conf file.
SSLClientAuth
The SSLClientAuth directive causes SSL3 client authentication on all requests.
Syntax
SSL3ClientAuth on|off
on directs that SSL3 client authentication be performed on every request, independent of ACL-based access control.
SSL2
The SSL2 directive tells the server whether Secure Sockets Layer, version 2 encryption is enabled or disabled. The Security directive dominates the SSL2 directive; if SSL2 encryption is enabled but the Security directive is set to off, then it is as though SSL2 were disabled.
Syntax
SSL2 on|off
Default
By default, security is off.
SSL3
The SSL3 directive tells the server whether Secure Sockets Layer, version 3 security is enabled or disabled. The Security directive dominates the SSL3 directive; if SSL3 security is enabled but the Security directive is set to off, then it is as though SSL3 were disabled.
Syntax
SSL3 on|off
Default
By default, security is off.
SSL3Ciphers
The SSL3Ciphers directive specifies the SSL3 ciphers enabled for your server.
Syntax
SSL3Ciphers +rc4 +rc4export -rc2 -rc2export +idea +des +desede3
A + means the cipher is active, and a - means the cipher is inactive.
Valid ciphers are rsa_rc4_128_md5, rsa3des_sha, rsa_des_sha, rsa_rc4_40_md5, rsa_rc2_40_md5, and rsa_null_md5. Any cipher with 40 as part of its name is 40 bits.
User
The User directive specifies the Unix user account for the proxy server. If the proxy is started by the superuser or root user, the server binds to the port you specify and then switches its user ID to the user account specified with the User directive. This directive is ignored if the server isn't started as the superuser. The User directive must occur before any LoadObjects directive.
The user account you specify should have write permission to the proxy server's root and cache directories. The user account doesn't need any special privileges. Although you can use the nobody user for Unix proxy servers, it isn't recommended, and it will not work on some systems, such as HP-UX.
Syntax
User login
login is the eight-character (or fewer) login name for the user account.
Default
If there is no User directive, the server runs with the user account with which it was started. If the server was started as root or superuser, you'll see a warning message after startup.
The obj.conf File
This section defines the obj.conf directives and describes their characteristics, including the directive name and description, format for the function string, default value if the directive is omitted, and how many instances of the directive can be in the file. The directives are:
- AddLog adds log entries to any log files.
- AuthTrans protects server resources from specific users.
- Connect provides a hook for you to call a custom connection function.
- DNS calls a custom DNS function you specify.
- Error sends customized error messages to clients.
- Filter provides content-filtering hooks for functions such as virus detection.
- Init (a special directive) initializes server subsystems.
- NameTrans maps URLs to mirror sites and the local file system.
- ObjectType tags additional information to requests.
- PathCheck checks URLs after NameTrans.
- Service sends data and completes the requests.
AddLog
After the request is finished and the proxy server has stopped sending to and receiving from the client, the proxy server logs the transaction. The proxy server records information about every time a client tries to gain access to the content server through the proxy, and it records information about the client making the request.
If an object has more than one AddLog directive, all are used.
The AddLog directive works with the log file function init-clf in the Init directive. For example, you could create three separate log files using the init-clf function::
AddLog fn=proxy-log name=log1
In some other <Object> you could have this command to record those accesses in another log file:
AddLog fn=proxy-log name=log2
To log only the IP address of the client, and not the DNS name, the AddLog
fn-flex-log function takes one more optional parameter: iponly=1. This optional parameter saves CPU cycles because the DNS name of the client host doesn't have to be resolved by contacting the DNS server:
AddLog fn=flex-log name=log3 iponly=1
If the name parameter is left out, it defaults to global. The following are equivalent:
AddLog fn=flex-log
AddLog fn=flex-log name=global
This function initializes the URL database; it specifies whether to cache URLs and, if so, the directory where they will be contained.
To log URLs, the AddLog fn=urldb-record function has to be called for each object ("<Object>") for which URL recording is desired. Also, the init-urldb function of the Init directive status has to be on. If the init-urldb status is off, URLs will not be recorded even if the AddLog fn=urldb-record function is called. URLs for documents that don't get cached will not be recorded in the URL database.
flex-log (starting proxy logging)
The flex-log function is an AddLog function that records request-specific data in the flexible, common, extended (used by most HTTP servers), or extended-2 log format. There are a number of free statistics generators for the common format, but the extended format gives more detailed information about the bytes transferred and the time elapsed. The extended-2 format provides as much information as the extended format, with additional kinds of information: the route through which the document was received as well as the finish status for the remote connection, the client connection, and the cache.
The log format is specified by the init-proxy function call, described in "init-proxy (starting the network software for proxy)".
Syntax
AddLog fn=proxyflex-log
name=name iponly
Parameters
name (optional) gives the name of a log file, which must have been given as a parameter to the init-clf function of the Init directive. If no name is given, global is the default.
iponly (optional) instructs the server not to look up the host name of the remote client but to record the IP address instead. The value of iponly can be anything, as long as it exists; the online forms set iponly="1".
Example
# Log all accesses to the central log file
AddLog fn=flex-log
# Log non-local accesses to another log file
<Client ip=*~198.93.9[2345].*>
AddLog fn=flex-log name=nonlocal
</Client>
AuthTrans
AuthTrans is the Authorization Translation directive. Server resources can be protected so that accessing them requires the client to provide certain information about the person using the client program. This authorization information is "encoded" to prevent clients from authorizing themselves as different users.
The server analyzes the authorization of client users in two steps. First, it translates authorization information sent by the client, and then it requires that such authorization information be present. This is done in the hope that multiple translation schemes can be easily incorporated, as well as providing the flexibility to have resources that record authorization information but do not require it.
If there is more than one AuthTrans directive in an object, all functions will be applied. The AuthTrans directive has a function called proxy-auth.
proxy-auth (translating proxy authorization)
The proxy-auth function of the AuthTrans directive translates authorization information provided through the basic proxy authorization scheme. This scheme is similar to the HTTP authorization scheme but doesn't interfere with it, so using proxy authorization doesn't block the ability to authenticate to the remote server.
This function is usually used with the PathCheck fn=require-proxy-auth function.
Syntax
AuthTrans fn=proxy-auth auth-type=basic
dbm=full path name
AuthTrans fn=proxy-auth auth-type=basic
userfile=full path name
grpfile=full path name
Parameters
auth-type specifies the type of authorization to be used. The type should be "basic" unless you are running a Unix proxy and are going to use your own function to perform authentication.
dbm specifies the full path and base filename of the user database in the server's native format. The native format is a system DBM file, which is a hashed file format allowing instantaneous access to billions of users. If you use this parameter, don't use the userfile parameter.
userfile specifies the full pathname of the user database in the NCSA-style httpd user file format. This format consists of name:password lines.
Example
A Unix example:
AuthTrans fn=proxy-auth auth-type=basic
dbm=/usr/ns-home/proxy-EXAMPLE/userdb/rs
A Windows NT example:
AuthTrans fn=proxy-auth auth-type=basic
userfile=\netscape\server\proxy-EXAMPLE\.htpasswd
grpfile=\netscape\server\proxy-EXAMPLE\.grpfile
It is possible to have authentication be performed by a user-provided function by passing the user-fn parameter to the proxy-auth function.
Syntax
AuthTrans fn=proxy-auth auth-type=basic
user-fn=your function
userdb=full path name
Parameters
user-fn specifies the name of the user-provided function that will be used to perform authentication in place of the built-in authentication. If authentication succeeds, the function should return REQ-PROCEED and if authentication fails, it should return REQ-NOACTION.
userdb specifies the full path and base filename of the user database in the server's native format. The native format is a system DBM file, which is a hashed file format allowing instantaneous access to billions of users.
Connect
The Connect directive calls the connect function you specify.
Syntax
Connect fn=your-connect-function
Only the first applicable Connect function is called, starting from the most restrictive object. Occasionally it is desirable to call multiple functions (until a connection is established). The function returns REQ_NOACTION if the next function should be called. If it fails to connect, the return value is REQ_ABORT. If it connects successfully, the connected socket descriptor will be returned.
The Connect function must have this prototype:
int your_connect_function(pblock *pb, Session *sn, Request *rq);
Connect gets its destination host name and port number from:
rq->host (char *)
rq->port (int)
The host can be in a numeric IP address format.
To use the NSAPI custom DNS class functions to resolve the host name, make a call to this function:
struct hostent *servact_gethostbyname(char *host name, Session *sn, Request *rq);
Example
This example uses the native connect mechanism to establish the connection:
#include "base/session.h"
#include "frame/req.h"
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int my_connect_func(pblock *pb, Session *sn, Request *rq)
{
struct sockaddr_in sa;
int sd;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(rq->port);
/* host name resolution */
if (isdigit(*rq->host))
sa.sin_addr.s_addr = inet_addr(rq->host);
else
{
struct hostent *hp = servact_gethostbyname(rq->host, sn, rq);
if (!hp)
return REQ_ABORTED; /* can't resolv */
memcpy(&sa.sin_addr, hp->h_addr, hp->h_lenght);
}
/* create the socket and connect */
sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sd == -1)
return REQ_ABORTED; /* can't create socket */
if (connect(sd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
close(sd);
return REQ_ABORTED; /* can't connect */
}
return sd; /* ok */
}
DNS
The DNS directive calls either the dns-config built-in function or a DNS function that you specify.
dns-config (suggest treating certain host names as remote)
Syntax
DNS fn=dns-config local-domain-levels=<n>
local-domain-levels specifies the number of levels of subdomains that the local network has. The default is 1.
iPlanet Web Proxy Server optimizes DNS lookups by reducing the times of trying to resolve hosts that are apparently fully qualified domain names but which DNS would otherwise by default still try to resolve relative to the local domain.
For example, suppose you're in the netscape.com domain, and you try to access the host. At first, DNS will try to resolve:
and only after that the real fully-qualified domain name:
If the local domain has subdomains, such as corp.netscape.com, it would do the two additional lookups:
To avoid these extra DNS lookups, you can suggest to the proxy that it treat host names that are apparently not local as remote, and it should tell DNS immediately not to try to resolve the name relative to the current domain.
If the local network has no subdomains, you set the value to 0. This means that only if the host name has no domain part at all (no dots in the host name) will it be resolved relative to the local domain. Otherwise, DNS should always resolve it as an absolute, fully qualified domain name.
If the local network has one level of subdomains, you set the value to 1. This means that host names that include two or more dots will be treated as fully qualified domain names, and so on.
An example of one level of subdomains would be the netscape.com domain, with subdomains:
corp.netscape.com
engr.netscape.com
mktg.netscape.com
This means that hosts without a dot, such as step would be resolved with respect to the current domain, such as engr.netscape.com, and so the dns-config function would try this:
step.engr.netscape.com
If you are on corp.netscape.com but the destination host step is on the engr subdomain, you could say just:
step.engr
instead of having to specify the fully qualified domain name:
step.engr.netscape.com
your-dns-function (a plug-in dns function you create)
This is a DNS-class function that you define.
Syntax
DNS fn=your-dns-function
Only the first applicable DNS function is called, starting from the most restrictive object. In the rare case that it is desirable to call multiple DNS functions, the function can return REQ_NOACTION.
The DNS function must have this prototype:
int your_dns_function(pblock *pb, Session *sn, Request *rq);
The DNS function looks for its parameter host name from:
rq->host (char *)
and it should place the resolved result into:
rq->hp (struct hostent *)
The struct hostent * will not be freed by the caller but will be treated as a pointer to a static area, as with the gethostbyname call. It is a good idea to keep a pointer in a static variable in the custom DNS function and on the next call either use the same struct hostent or free it before allocating a new one.
The DNS function returns REQ_PROCEED if it is successful, and REQ_NOACTION if the next DNS function (or gethostbyname, if no other applicable DNS class functions exist) should be called instead. Any other return value is treated as failure to resolve the host name.
Example
This example uses the normal gethostbyname call to resolve the host name:
#include "base/session.h"
#include "frame/req.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int my_dns_func(pblock *pb, Session *sn, Request *rq)
{
rq->hp = gethostbyname(rq->host);
if (rq->hp)
return REQ_PROCEED;
else
return REQ_ABORTED;
}
Error
At any time during a request, conditions can occur that cause the server to stop fulfilling a request and to return an error to the client. When this happens, the server can send a short HTML page to the client, very generically describing the error.
To help you make error handling more user friendly, the proxy server lets you intercept certain errors and send a file with your customized error message in place of the server's default error message. You can create an HTML file containing the error message you want to send and associate that message with an error.
Syntax
Error fn=send-error code=code path=path
code is the error code for the default error message, as listed below.
path is the full path to the HTML file containing the message you want to send.
The following are errors returned by the server. Each error has a three-digit HTTP code that designates it, followed by a short description of the error. The description might help you write your custom error message, in some of cases below:
- 401 Unauthorized (for administration forms only). The server requires HTTP user authorization to allow access to the administration forms, and either the client provided none or its HTTP authorization was insufficient. You can customize this error message only when you use Sun ONE Web Proxy Server as a reverse proxy.
- 403 Forbidden. The server tried to access a file or directory and found that the user it was running as didn't have sufficient permission to access the file. You can customize this error message.
- 404 Not Found. The client asked for a file system path that doesn't exist or the server was configured to tell the client that it doesn't exist. Since this message is not generated by proxy server, it cannot be customized.
- 407 Proxy Authorization Required. The proxy requires proxy authorization, and either the client didn't provide any or it was insufficient. Also, the client software might not support proxy authorization. Netscape Navigator version 1.1 or newer supports this authorization. This error message can be customized.
- 500 Server Error. Server errors mean that an error has occurred in the server that prevents it from finishing the request. Server errors mainly happen because of misconfiguration or machine resources such as swap space being exhausted. Since this message is not generated by proxy server, it cannot be customized.
Example
Error fn=send-error Code=403
path=/usr/ns-home/proxy-EXAMPLE/errors/403.html
Filter
The Filter directive runs an external command and then pipes the data through the external command before processing that data in the proxy. This is accomplished using the pre-filter function. The format of the Filter directive is as follows:
Syntax
Filter fn="pre-filter" path="/your/filter/prog"
The Filter directive performs these tasks:
- It runs the program /your/filter/prog as a separate process.
- It establishes pipes between the proxy and the external program.
- It writes the response data from the remote server to the stdin of the external program.
- It reads the stdout of the program as if it were the response generated by the server.
This is equivalent to this command:
Filter fn="pre-filter"
path="/your/filter/prog"
headers="stdin"
Init
Init is a special directive that initializes certain proxy subsystems such as the networking library, caching module, and access logging. The functions referenced with the Init directive load data for specific subsystems once on server startup and keep that data internally until the server is shut down.
Init lines can contain spaces at the beginning of the line and between the directive and value, but you shouldn't have spaces after the value because they might confuse the server. Long lines (although probably not necessary) can be continued with a backslash (\) continuation character before the line feed.
Syntax
Init fn=function-name [parm1=value1]...[parmN=valueN]
function-name identifies the server initialization function to call. These functions shouldn't be called more than once.
parm=value pairs are values for function-specific parameters. The number of parameters depends on the function you use. The order of the parameters doesn't matter. The functions of the Init directive listed here are described in detail in the following sections.
- flex-init initializes the flex-log flexible access logging feature
- icp-init initializes the ICP feature.
- init-batch-update initializes the batch update feature.
- init-cache enables and initializes caching.
- init-clf initializes the Common Log File subsystem.
- init-dns-cache enables and initializes dns caching.
- init-partition initializes the partitions.
- init-proxy initializes the networking code used by the proxy.
- init-proxy-auth tells proxy how to authenticate itself.
- init-proxy-certs loads a default certificate database on startup.
- init-sockd enables and initializes the SOCKD feature.
- init-urldb initializes the URL database that you specify.
- load-modules tells the server to load functions from a shared object file.
- load-types maps file extensions to MIME types.
Init function order in obj.conf
The Init functions are a series of steps that the server has to follow in order for the proxy to run. Each function depends on the results of the one before it:
- Start the proxy.
- Start the proxy's cache.
- Initialize the partitions inside the cache.
- Initialize the batch update process (which might be updating what's inside the partitions).
Calling Init functions
Some functions of the Init directive are crucial to proxy functioning and must be called once and only once. Others are optional but must be called no more than once, and some are optional and can be called many times. They are shown in Table C-1.
flex-init (starting the flex-log access logs)
The flex-init function initializes the flexible logging system. It opens the log file whose name is passed as a parameter and establishes a record format that is passed as another parameter. The log file stays open until the server is shut down, or for Unix proxies, until the base server process is sent the -HUP signal (at which time all logs are closed and reopened).
You use flex-init to specify a log filename (such as
loghttp=/var/ns-server/loghttp); then you use that name with the flex-log function in the obj.conf file to add a log entry to the file (such as AddLog fn=flex-log name=loghttp).
If you move, remove, or change the log file without shutting down or restarting the server, client accesses might not be recorded. To save or back up a log file on a Unix proxy, you need to rename the file and then send the -HUP signal to restart the server. The server uses the inode number, but when you do a soft restart, the server first looks for the filename, and if it doesn't find the log file, it creates a new one (the renamed original log file is left for you to use).
Parameters
The flex-init function recognizes two possible parameters: one that names the log file and one that specifies the components of a record in that file.
The flex-init function recognizes anything contained between percent signs (%) as the name portion of a name-value pair stored in a parameter block in your program. (The one exception to this rule is the %SYSDATE% component, which delivers the current system date.)
Any additional text is treated as literal text, so you can add to the line to make it more readable. Typical components of the formatting parameter are listed in Table C-1. Certain components might contain spaces, so they should be bounded by escaped quotes (/").
Example
This example for a Unix proxy server initializes flexible logging in to the file /usr/ns-home/proxy-NOTES/logs/access:
Init fn=flex-init access="/usr/ns-home/https-NOTES/logs/access" format.access=
"%Ses->client.ip% - %Req->vars.auth-user% [%SYSDATE%] /"%Req->reqpb.proxy-request%/"
%Req->srvhdrs.clf-status% %Req->vars.p2c-c1%"
This example for a Windows NT proxy server initializes flexible logging in to the file netscape\server\proxy-NOTES\logs\access:
Init fn=flex-init access="\" format.access=
"%Ses->client.ip% - %Req->vars.auth-user% [%SYSDATE%] /"%Req->reqpb.proxy-request%/"
%Req->srvhdrs.clf-status% %Req->vars-p2c-c1%"
This will log the following items:
- IP or host name, followed by the three characters " - "
- the user name, followed by the two characters " ["
- the system date, followed by the two characters "] "
- the full request, followed by a single space
- the full status, followed by a single space
- the content length
This is the default format, which corresponds to the Common Log Format (CLF).
The first six elements of any log should always be in exactly this format, because a number of log analyzers expect that as output.
icp-init (initializes ICP)
The icp-init function enables and initializes ICP. ICP (Internet Cache Protocol) is an object location protocol that enables caches to communicate with one another. Caches can use ICP to send queries and replies about the existence of cached URLs and about the best locations from which to retrieve those URLs.
Syntax
Init fn="icp.init"
config_file="file name"
status="on|off"
Parameters
config_file is the name of the ICP configuration file.
status specifies whether ICP is enabled or disabled. Possible values are:
- on means that ICP is enabled.
- off means that ICP is disabled.
Example
Init fn="icp.init"
config_file="icp.conf"
status="on"
init-batch-update (starting batch updates)
The init-batch-update function starts and specifies a configuration file for batch updating. Batch updating (or similarly, autoloading) is the process of loading frequently requested objects into the proxy cache in anticipation of those requests.
Batch updating is useful for a number of tasks. A proxy administrator might want to perform up-to-date checks during low-usage hours on all the cached objects to avoid doing these checks when usage is heavier. If a site has heavy daytime usage but little in the evening, the batch update could run in the evening. The process can converse with remote servers and update any objects that have been modified.
At larger sites with a network of servers and proxies, you, as the administrator, might want to use autoloading to "inhale" (pre-load into the cache) a given area of the web. You provide an initial URL, and the batch process does a recursive ("worm") descent across links in the document. Because this function can be a burden on remote servers, be careful when using it. Measures are taken to keep the process from performing recursion indefinitely, and the parameters in bu.conf give you some control of this process. You could also use this functionality to update proxies to compensate for any unexpected changes in a company-wide directory index.
Syntax
Init fn=init-batch-update
status=on|off
conf-file="absolute filename"
Parameters
status enables or disables batch updating.
- on means batch updating will be started, and the update function expects to find a configuration file (otherwise it will abort).
- off means no batch updating or autoloading activity will occur.
conf-file is the pathname to the batch update (autoload) configuration file.
Example
A Unix example:
Init fn=init-batch-update
status=on
conf-file="/usr/ns-home/java-proxy/config/bu.conf"
A Windows NT example:
Init fn=init-batch-update
status=on
conf-file=""
init-cache (starting the caching system)
The init-cache function enables and initializes the cache and starts the caching system. Calling this function is crucial if you want to use caching; otherwise it is optional and must be called only once.
Syntax
For Unix version:
Init fn=init-cache
status=on|off
dir=directory
ndirs=n
cmon=on|off
Parameters
status enables or disables caching.
- on enables caching
- off turns caching off
dir specifies a working directory for the proxy's caching module. This is not necessarily the cache directory. To specify directories where cached data is actually stored, use the init-partition function.
cmon enables or disables monitoring of the cache size.
- on enables monitoring and is the default
- off disables monitoring
Setting cmon to off disables the internal Cache Monitor and Cache Manager processes that the ns-proxy process automatically initiates when caching is enabled. The Cache Monitor process monitors the cache size and when necessary sends a message to the Cache Manager process to trigger garbage collection (cleaning up the cache to allow more space for new cache files). Disabling these internal cache management processes lets you use an external custom program to perform cache management tasks.
Further, setting cmon to off makes it possible for two separate proxy pools to share the same cache. In this situation, only one of the proxies can have cache management enabled, and the other must have it disabled.
ndirs specifies cache capacity as the number of cache sections you want set up for the proxy. The number you specify must be a power of 2, from 1 to 256. This number is related to cache capacity as shown in Table C-3. To determine the number to use, see the capacity entry in Table C-3 for the optimum designed capacity of your machine.
Table C-3 shows the optimum designed capacity, the minimum suggested capacity, and the maximum suggested capacity for each valid number of sections. The optimum capacity for a specific ndir matches the minimum capacity for the next larger ndir and also matches the maximum capacity for the next smaller ndir.
For a small cache size you can set a small cache capacity, although an oversized cache structure is not a problem. If the cache is actually larger than the maximum capacity for the number of sections you specify, its performance could be diminished because of an undersized cache structure, that is, there may not be enough sections.
Example
Init fn=init-cache
status=on
dir=/usr/ns-home/cache
ndirs=8
init-dns-cache (starting dns caching)
The init-dns-cache function specifies (when DNS lookups are enabled through a Server Manager setting) that you want to cache the DNS entries. If you cache DNS entries, then when the server gets a client's host name information, it can store the data it receives. Then, if the server needs information about the client in the future, the information is available to the server without querying for the information again.
You can specify the size of the DNS cache and the time it takes before a cache entry becomes invalid. The DNS cache can contain 32 to 32768 entries; the default value is 1024 entries. Values for the time it takes for a cache entry to expire can range from 1 second to 1 year (specified in seconds); the default value is 1200 seconds (20 minutes).
Syntax
Init fn=init-dns-cache
cache-size=entries
expire=seconds
visible=yes|no
Parameters
The init-dns-cache function takes two arguments, cache-size and expire.
cache-size specifies how many entries are contained in the cache. Acceptable values for cache-size are 32 to 32768; the default value is 1024.
expire specifies how long it takes for a cache entry to expire. Acceptable values (specified in seconds) for expire are 1 second to 1 year; the default is 1200 seconds (20 minutes).
visible specifies whether the DNS cache file is visible. Possible values include:
- yes means the DNS cache file is visible.
- no means the DNS cache file is invisible. This is the default.
Example
Init fn="init-dns-cache"
cache-size="2140"
expire="600"
visible=yes
init-clf (starting the Common Log File subsystem)
The init-clf function initializes the Common Log File subsystem. Use this function to specify which log files the proxy uses to record transactions. Then, use the AddLog directive to specify the log file where the proxy stores the transaction record. For more information on the AddLog directive, see page 413.
The init-clf function opens the log files that you specify. The log files stay open until the server is shut down or, for a Unix proxy server, until the base server process is sent the -HUP signal (at which time the logs are closed and re-opened). Initializing this function is required if you are using the log features.
Syntax
Init fn=init-clf
global=main log filename
Parameters
global tells the proxy to use this log file by default. This function doesn't have any predefined parameters, just name and pathname pairs in the format <name>=<pathname> where:
- name is a symbolic name that you give to a log file pathname.
- pathname is the directory and filename for the log file.
Example
Init fn=init-clf
global=\netscape\server\proxy-TEST\logs\access
To open three separate log files, you could use name and pathname pairs like this:. For details, see AddLog.
init-partition (specifying cache partitions)
The init-partition function specifies the status, location, and size of cache partitions.
Syntax
Init fn=init-partition
status=on|off
dir=directory
max-size=megabytes
min-avail=megabytes
Parameters
status enables or disables the cache partition.
- on means that the cache partition is active (in normal use, data is written to and read from that partition).
- off means that the cache partition is not in use (cache data mapping to that partition will not be written to or looked up from that partition).
dir is the directory to use as the cache. The cache structure (that is, sections) must exist under that directory (which can be created and maintained through the online forms).
max-size is the optional number for the maximum size, in megabytes, to allow for the cache partition to grow. You can choose not to set size limits by leaving this parameter out.
min-avail is the minimum amount of available space, in megabytes, on the physical partition. This is the actual disk on which the cache partition (defined by the dir parameter) resides. If less space is ever available, the proxy stops caching to that cache partition, even if it hasn't reached the maximum size (max-size). It continues to write to other partitions that are not full. It also notifies the Cache Monitor that the partition is filling up, and the Cache Manager consequently starts to clean up the cache. You can choose not to set the minimum by leaving this parameter out.
Example
Init fn=init-partition
status=on
dir=/usr/ns-home/cache
max-size=2000
min-avail=5
init-proxy (starting the network software for proxy)
The init-proxy function initializes the networking software used by the proxy. Calling this function in obj.conf is crucial (even though it is called automatically, you should call it manually as a safety measure).
Syntax
For Unix version:
Init fn=init-proxy
timeout=<seconds>
timeout-2=seconds
read-timeout=seconds
keep-alive-timeout=seconds
stall-timeout-override=seconds
netlib-timeout=seconds
sig="Some readable name"
anon-pw="e-mail address"
socks-ns="IP address"
Parameters
timeout is the number of seconds of delay allowed between consecutive network packets received from the remote server. If the delay exceeds the timeout, the connection is dropped. The default is 120 seconds (2 minutes). This is not the maximum time allowed for an entire transaction, but the delay between the packets. For example, the entire transaction can last 15 minutes, as long as at least one packet of data is received before each timeout period.
timeout-2 tells the proxy how much time it has to continue writing a cache file after a client has aborted the transaction. In other words, if the proxy server has almost finished caching a document and the client aborts the connection, the proxy can continue caching the document until it reaches the timeout after interrupt value.
To determine the best timeout-2 (timeout after interrupt) value for your proxy server, use sitemon. If sitemon reports that the proxy server is using too much of its process pool, you should reduce your timeout after interrupt accordingly. The highest recommended timeout after interrupt value is 5 minutes.
read-timeout is the number of seconds the proxy server will wait for an incoming request. The default value for this timeout is 60 seconds. Setting the timeout a few seconds shorter will allow proxy resources to be released faster if the connection stays idle (e.g., if you telnet to the proxy port and let it just sit there).
keep-alive-timeout is the number of seconds the proxy server will wait for the next request from a keep-alive connection. The default value for this timeout is 5 seconds. Shorter timeouts let the proxy release resources that are tied up by idle keep-alive connections. Longer timeouts will make keep-alive more effective, but can tie up valuable proxy resources, and thus, bog down the server. You should not use the keep-alive feature because it can easily cause problems when the entire process pool is tied up by idle keep-alive connections. This problem can occur quickly - especially with clients that open multiple simultaneous connections, such as Navigator, which by default, opens 4 connections.
stall-timeout-override should not be changed.
netlib-timeout is the absolute maximum number of seconds that the proxy will wait for any HTTP, FTP, Gopher or HTTPS retrieval. The default value for this timeout is 10800 seconds (3 hours).
sig is the signature (trailer) that the proxy appends to its error messages. By default, it contains the proxy host name and the port number. If your site does not want to send that information out or perhaps gives more descriptive names to proxies, you can use sig to do that.
anon-pw is the email address to send to anonymous FTP servers as the password. This information can be used by FTP sites to later send notifications to people who downloaded files from their FTP site. Using this option overrides the default that the proxy will derive from its current execution environment (which could be, for example, "nobody@your.site").
socks-ns is equivalent to using the SOCKS_NS environment variable in the proxy's execution environment. This tells the proxy the DNS server IP address instead of having the proxy try to derive the default from its environment. This option is useful when the internal DNS server is not capable of resolving external DNS names. It is often necessary when routing the proxy through a SOCKS server.
Example
Init fn=init-proxy
log-format=extended-2
timeout=120
sig="Main proxy gateway"
anon-pw="webmaster@your.site"
socks-ns="123.1.2.3"
init-proxy-auth (specifying the authentication strategy)
The init-proxy-auth function tells the proxy server whether it should require authentication from clients as a proxy, or reverse proxy (web server). If the obj.conf file does not call this function, the server will automatically act as a proxy requiring authentication.
Syntax
Init fn=init-proxy-auth
pac-auth=on|off
Parameters
pac-auth specifies whether local files ( PAC files, local icons, etc.) are password-protected.
- on means that local files are password-protected and require authentication. This setting has no effect if access control is not enabled for your proxy server. If you set pac-auth to yes, and proxy authentication is enabled, users will be prompted for their password twice.
- off means that local files do not require authentication.
Example
Init fn=init-proxy-auth
pac-auth=yes
init-proxy-certs (loading the default certificate
database)
The init-proxy-certs function points the proxy to the default certificate database and loads that file at startup.
Syntax
When you make changes to the certificate database and Initialize Certificates Only is disabled, this line is automatically inserted into the obj.conf file upon restart:
Init fn=init-proxy-certs
certfile=absolute filename
If the proxy is set up to authenticate itself to remote servers by using its certificate, and Initialize Certificates Only is enabled, this line is automatically inserted into the obj.conf file upon restart:
Init fn=init-proxy-certs
security=on|off
keyfile=absolute filename
Parameters
certfile is the absolute filename of the default certificate database.
security enables or disables encryption for the proxy.
- on means that encryption is enabled.
- off means that encryption is disabled.
keyfile is the absolute filename of the private keyfile for the proxy.
Example
Init fn=init-proxy-certs
certfile="/usr/ns-home/proxy-java-proxy/config/ServerCert"
Init fn=init-proxy-certs
security=on
keyfile="/usr/ns-home/proxy-java-proxy/config/ ServerKey.db"
init-sockd (starting the SOCKD feature)
The init-sockd function enables and initializes iPlanet Web Proxy Server's SOCKD feature. It makes the proxy behave like a SOCKS daemon in addition to its normal tasks.
The SOCKD configuration is done through the normal SOCKD configuration file, /etc/socks5.conf. The same care must be taken as when configuring any other SOCKS daemon.
Syntax
Init fn=init-sockd
status=on|off
sockd-conf=absolute filename
ident-check=none|loose|strict
log-type=common-separate|syslog|syslogseparate
log-name=absolute filename
Parameters
status enables or disables the sockd function.
- on means the SOCKD feature is enabled; that is, the proxy will act as a SOCKS server.
- off means the SOCKD feature is disabled; same as if the function is left out. SOCKS requests will not be answered by the proxy (an error will be returned to the client).
sockd-conf (optional) specifies the absolute pathname for the SOCKD configuration file to use. The default is /etc/sockd.conf. The format follows the standard SOCKD configuration file format.
ident-check (optional) specifies the type of remote identity checking. The possible values are:
- strict means an identity check is required, and if the remote host is not running identd, ("Identity Daemon") the request is denied. The strict identity check is like the "loose" identity check, except that if the remote identity query fails, access will be denied.
- loose means an identity check is required, but if the remote host is not running identd, access is granted anyway. Remote identity will be queried from the remote identd, and the given user name will be verified against the one returned by the remote identd. If there's a mismatch, access will be denied. If the remote identity query fails (the remote server's not running identd), access will be granted.
- none means no remote identity check is performed. The remote user name will not be queried from the remote identd. The user name given in the SOCKS request will not be verified.
log-type (optional) specifies where the proxy SOCKD module stores the access information. The directive can be one of the following:
- common-separate uses the common log format, but puts the entries in a separate log file (the log filename is given in the log-name parameter).
- syslog uses the traditional SOCKD format and reports to the syslog facility.
- syslog-separate uses the SOCKD syslog format, but instead of syslog, it uses a separate log file as specified by the log-name parameter.
log-name specifies the absolute pathname for a separate log file used for logging SOCKS accesses. This name is required when the log-type is either common-separate or syslog-separate.
Example
Init fn=init-sockd
status=on
sockd-conf=/etc/sockd.conf
ident-check=strict
log-type=syslog
log-name=/d/proxy/logs/sockd.log
init-urldb (setting up the URL database)
The init-urldb function initializes the URL database and it specifies whether to cache URLs. It also identifies the directory where URLs will be contained if they are cached.
Syntax
Init fn=init-urldb
status=on|off
dir=absolute filename
Parameters
status is whether the URL database is enabled or disabled.
- on means that URL recording to the URL database is enabled. This database is the one that can be browsed from the administration interface to find out what's actually cached.
-
To log the URLs, the AddLog fn=urldb-record function has to be called for each object ("<Object>") for which URL recording is desired. URLs for documents that don't get cached will never be recorded in this database.
- off means that URL recording is disabled. URLs will not be recorded even if the AddLog fn=urldb-record function is called.
dir is the name of the directory containing the URL database. Don't use /tmp because it is cleared at boot time.
Example
Init fn=init-urldb
status=on
dir=/usr/ns-home/cache/urldb
load-modules (loading shared object modules)
You can use the load-modules function to tell the server to load the functions you need from the shared object. Calling the load-modules function is crucial to proxy function.
Unix allows shared libraries, which are archives of multiple functions packed into a single file (with a .so suffix). If you want to link in functions from shared libraries you have created, use this function to pass required information to the server. To do this, you have to tell the main executable where the shared library file resides and the names of the functions to be loaded (which are indexed by name in the .so file).
Binaries referring to functions in the shared libraries you specify dynamically load the individual functions at runtime (without loading the entire library).
To register SAF classes with the server you could use this:
Init fn=load-modules shlib=/your/lib.so funcs=alpha,beta,alpha-beta
where alpha, beta, and alpha-beta represent the functions alpha(), beta(), and alpha_beta() from the shared library /your/lib.so. Note the correlation between hyphens and underscores (where the configuration files use hyphens, C code uses underscores).
You can call those functions as you normally would; for example, to call the C function alpha_beta() you would use:
Connect fn=alpha-beta
Syntax
Init fn=load-modules
shlib=[path]filename.so
funcs="function1, function2, ..., functionN"
Parameters
shlib is the full path and filename of the shared object library containing the functions of interest.
funcs is a list of functions in the shared library to be dynamically loaded.
Example
A Unix example:
Init fn=load-modules
shlib=/u/myfolder/func.so
funcs="func1, func2"
A Windows NT example:
Init fn=load-modules
shlib= funcs="func1, func2"
load-types (loading MIME-type mappings)
The load-types function scans a file that tells it how to map filename extensions to MIME types. MIME types are essential for network navigation software like Netscape Navigator to tell the difference between file types. For example, they are used to tell an HTML file from a GIF file. See "The mime.types File" for more information.
Calling this function is crucial if you use iPlanet Web Proxy Server Manager online forms or the FTP proxying capability.
Syntax
Init fn=load-types
mime-types="mime.types"
This function loads the MIME type file mime.types from the configuration directory (the same directory as magnus.conf and obj.conf). This function call is mandatory and in practice is always as shown in the syntax.
Parameters
mime-types specifies either the full path to the global MIME types file or a filename relative to the server configuration directory. The proxy server comes with a default file called mime.types.
local-types is an optional parameter to a file with the same format as the global MIME types file, but it is used to maintain types that are applicable only to your server.
Example
Init fn=load-types mime-types=mime.types
Init fn=load-types mime-types=/tp/mime.types \
local-types=local.types
pa-init-parent-array (initializing a parent array member)
The pa-init-parent-array function initializes a parent array member and specifies information about the PAT file for the parent array of which it is a member.
Syntax
Init fn=pa-init-parent-parent-array
poll="no"
file="c:/netscape/server/bin/proxy/pa1.pat"
The following example specifies that the member should poll for a PAT file. This member is not the master proxy.
Init fn=pa-init-parent-array
poll="yes"
file="c:/netscape/server/bin/proxy/pa2.pat"
pollhost="proxy1"
pollport="8080"
pollhdrs="c:/netscape/server/proxy-name/parray/pa2.hdr"
status="on"
set-status-fn=set-member-status
pollurl="/pat"
pa-init-proxy-array (initializing a proxy array member)
The pa-init-proxy-array function initializes a proxy array member and specifies information about the PAT file for the array of which it is a member.
Syntax
Init fn=pa-init-proxy-proxy-array
poll="no"
file="c:/netscape/server/bin/proxy/pa1.pat"
The following example specifies that the member should poll for a PAT file. This member is not the master proxy.
Init fn=pa-init-proxy-array
poll="yes"
file="c:/netscape/server/bin/proxy/pa2.pat"
pollhost="proxy1"
pollport="8080"
pollhdrs="c:/netscape/server/proxy-name/parray/pa2.hdr"
status="on"
set-status-fn=set-member-status
pollurl="/pat"
tune-proxy (tuning server performance)
The tune-proxy function allows you to tune the performance of your proxy server.You should not change the default settings unless directed to do so by iPlanet Technical Support.
Syntax
Init fn=tune-proxy
byte-ranges=on|off
single-accept= (do not change)
ftp-listing-width=number
Parameters
byte-ranges determines whether or not the proxy is allowed to generate byte-range responses from the cache. By default, this feature is disabled. This version of the proxy server supports single byte-ranges only.
single-accept should not be changed.
ftp-listing-width is the maximum number of characters allowed for filenames in the FTP listing. The default is 80.
Example
Init fn=tune-proxy
byte-ranges=off
single-accept=(do not change)
ftp-listing-width=80
tune-cache (tuning cache performance)
The tune-cache function allows you to tune the performance of your proxy server's cache. You should not change the default settings unless directed to do so by iPlanet Technical Support.
Syntax
Init fn=tune-cache
cch-status=DO-NOT-CACHE|NON-CACHEABLE|NOT-IN-CACHE
mmap-wr=on|off
mmap-rdwr=on|off
shmem-io=on|off
notify-num-changes=number
notify-blk-limit=number
cmon-tick-interval=(do not change)
mmap-max=kilobytes
min-sync-interval=seconds
notify-block-chunk-per-proc=blocks
cache-fs-full-retry-after=number
update-after-percent=percentage
sync-dump-ticks=(do not change)
cch-status determines whether to use additional cache status values in the access log. Possible values are:
- DO-NOT-CACHE - pre-determined non-cacheable (by configuration)
- NON-CACHEABLE - post-determined non-cacheable (by response fields)
- NOT-IN-CACHE - with disconnected operation, cache miss
mmap-wr determines whether to use mmap or lseek+write to create the initial CIF header. By default, this value is off. You should not change this value. Possible values are:
- on means that mmap and lseek+ will create the initial CIF header.
- off means that mmap and lseek+ will not create the initial CIF header.
mmap-rdwr determines whether to use memory mapped I/O when sending data from the cache and updating cache files. By default, this value is on.
- on means that memory mapped I/O will be used to send data from the cache or to update cache files.
- off means that memory mapped I/O will not be used to send data from the cache or to update cache files.
shmem-io determines whether shared memory is enabled. The child processes communicate with the cache monitor and cache manager via either an interprocess pipe/socket, or shared memory. The shared memory based I/O is faster. By default, shared memory I/O is enabled.
- on means that shared memory is enabled.
- off means that shared memory is disabled.
notify-num-changes is used only when shared memory I/O is enabled. This parameter determines the number of changes after which the cache monitor is notified about changes made by that child process. More frequent notifications keep the cache monitor up-to-date on the status and size of the cache, but create more work for the cache monitor. The valid range for notify num changes is 1 to 500, and the default value is 10.
notify-blk-limit is used only when shared memory I/O is enabled. This parameter determines the number of blocks cache size usage has changed by a single child process until the cache monitor is notified. Smaller notification limits keep the cache monitor up-to-date on the status and size of the cache, but create more work for the cache monitor. The valid range for notify num changes is 1 to 10000 (0.5K to 5MB), and the default value is 100 (50K).
cmon-tick-interval should not be changed.
mmap-max is the maximum number of kilobytes memory-mapped at once by a single process. Files larger than the max mmap size will be memory-mapped in portions of this size. By default, the max mmap size is 256K.
The max mmap size must be at least 16, and it must be a multiple of page size, which is often four.
min-sync-interval specifies the amount of time the cache manager waits before traversing the entire cache to find out the actual cache size. The cache monitor attempts to maintain current information about the size of each cache section. However, the information may get skewed by unexpected software shutdowns, system crashes, power failures, etc. Another reason for skew is that a server shutdown will lose unnotified changes to the cache in child processes. Because of these skews, the cache manager periodically traverses the entire cache to determine the actual cache size.
The valid range for min-sync-interval is 1800 seconds(1/2 hour) to 604800 seconds (1 week), and the default is 86400 seconds (24 hours).
notify-block-chunk-per-proc controls the threshold which triggers each child process to report their cache usage to the cache monitor. Each server child process notifies the cache monitor about how much new cache space it has taken up (or released) by creating new cache files or updating old ones. To avoid message overflow, these notifications are not sent for every cache operation, but rather each process waits until it has reached a certain threshold before notifying the cache monitor about its activities. The notify-blk-chunk-per-proc parameter controls this threshold. The units are in "blocks". A block is always 512 bytes (0.5 KB), regardless of the operating system filesystem block size.
The notify-block-chunk-per-proc value is multiplied by the value of the MaxProcs directive. Therefore, the effect of having a higher MaxProcs setting is that child processes will buffer more cache change messages before they notify the cache monitor about them. This effect avoids message overflow on systems with a high load (large MaxProcs), and allows small caches to maintain more accurate size information (small MaxProcs).
cache-fs-full-retry-after controls how many cache write requests should be skipped before the proxy attempts a write operation. When a server child process fails to write to disk and the error code is ENOSPC (No space left on device), the process stops writing data to that cache partition, allowing time for the garbage collector to correct the situation. The fs full retry after variable controls the number of cache write requests that are skipped before the proxy attempts a write operation again.
The valid range for fs full retry after is 1 (retry immediately) to 1024 (practically don't retry), and the default value is 50.
update-after-percent controls the percentage of used cache space that triggers a partition table update. The cache monitor continuously receives messages from server child processes about how much new cache space they have used (see the parameter, notify-block-chunk-per-proc). To conserve CPU time, the cache monitor does not update its partition table or evaluate garbage collection needs after every such message. Instead, it waits until there is big enough percentage change in size. The update after percent value controls that percentage.
The valid range for update after percent is 0 (every time) to 100 (after size doubles), and the default value is 1.
sync-dump-ticks should not be changed.
Example
Init fn=tune-cache
cch-status=DO-NOT-CACHE
mmap-wr=off
mmap-rdwr=on
shmem-io=off
notify-num-changes=10
notify-blk-limit=100
cmon-tick-interval=(do not change)
mmap-max=256
min-sync-interval=86400
notify-block-chunk-per-proc=67
cache-fs-full-retry-after=50
update-after-percent=1
sync-dump-ticks=(do not change)
tune-gc (tuning garbage collector performance)
The tune-gc function allows you to tune the performance of your proxy server's garbage collector.You should not change the default settings unless directed to do so by iPlanet Technical Support.
Syntax
Init fn=tune-gc
gc-urldb-interval=seconds
gc-nap-length=seconds
hard-gc-nap-count=number
soft-gc-nap-count=number
hard-gc-chunk-entries=number
gc-dir-chunk=number
gc-hi-margin-percent=percent
gc-lo-margin-percent=percent
gc-extra-margin-percent=percent
gc-leave-fs-full-percent=percent
Parameters
gc-urldb-interval controls how often the URL database is cleaned of old URLs and how often it is checked for consistency.
The valid range for the gc URL db interval is 1800 sec (30 minutes) to 604800 (1 week), and the default value is 79200 seconds (22 hours).
gc-nap-length is the amount of time that the garbage collector sleeps during one "nap." The garbage collector takes "naps" every so often so that it does not hog all the CPU from other processes. The frequency of these naps is controlled by two variables: hard gc nap count and soft gc nap count.
The valid range for gc nap length is 0 (no naps) to 120 (2 minutes), and the default is 1 second
hard-gc-nap-count specifies how many naps hard garbage collector takes during the garbage collection cycle of a single cache section. There are two types of garbage collection: hard and soft. The hard garbage collector traverses the entire cache section and finds all the files individually, picking the ones to delete, and then generates lists of files in the cache ordered by their relative value. These lists are then used by the soft garbage collector to delete files without traversing the entire cache structure.
Hard garbage collection is more resource intensive than soft garbage collection, but it is required every time soft garbage collection runs out of the lists generated by hard garbage collection.
There are 64 subdirectories on each cache section, and naps can be taken between directories only. This means that there can be at most 64 naps. The number of naps should be a power of two.
The valid values for hard gc nap count are: 0 (no sleeps), 1, 2, 4, 8, 16, 32, and 64 (max). The default value is 16 (sleep after every 4 directories).
soft-gc-nap-count specifies how many naps the soft garbage collector takes during the garbage collection cycle. The soft garbage collector simply reads a list of cache files from a set of files produced by the hard garbage collector. It still looks up the file using the stat() system call, to find out if there have been subsequent accesses to the cache file during the last garbage collection, which suggests that the cache file is being (or may be) actively used, and should not be removed.
The valid range for soft gc nap count is 0 (no naps) to 1000 naps, and the default value is 20 naps.
hard-gc-chunk-entries identifies the number of cache entry slots allocated during one pass for garbage collection. One "pass" in garbage collection is defined by the variable gc dir chunk, which is the number of subdirectories within a cache section that will be processed in one pass.
This number should be of the same order as the number of files in a typical chunk of directories. As an example, a typical subdirectory in a cache section has 100-200 files. If the gc dir chunk variable is set to 8, then the "hard gc max entries" value should be set to around 800-1600.
A single cache entry is about 32 bytes, so every 1000 entries in this variable means 32KB pool allocation. A valid range for hard gc max entries is 100(3K) to 5000 (160K), and the default value is 500 (16K).
gc-dir-chunk controls the sample size for the LRU algorithm. Basically, this means it controls how many subdirectories under each cache section are processed by the garbage collector in one pass. Because a larger gc dir chunk value causes the proxy to process more files simultaneously, more memory is required. Larger gc dir chunk values also cause the garbage collector to be slower and more CPU intensive. The smaller the gc dir chunk value is, the lighter-weight garbage collection becomes. However, the sample size for the LRU algorithm becomes smaller.
The gc dir chunk value must be a power of two.
Valid values for gc dir chunk are: 1 (single directory), 2, 4, 8, 16, 32, and 64 (all directories at once). The default value is 8 directories.
gc-hi-margin-percent controls the percentage of the maximum cache size that, when reached, triggers garbage collection. This value must be higher than the value for gc lo margin percent.
The valid range for gc hi margin percent is 10 to 100 percent (trigger garbage collection when full). The default value is 80 percent (trigger gc when 80% full).
gc-lo-margin-percent% full cache after gc).
gc-extra-margin-percent specifies the fraction of the cache the garbage collector will remove. If the garbage collection is triggered by a reason other than the partition's size getting close to the maximum allowed size (see gc-hi-margin-percent), the garbage collector will use the percentage set by the gc extra margin percent variable to determine the fraction of the cache to remove.
The valid range for gc extra margin percent is 0 to 100 percent, and the default value is 30 percent (remove 30% of existing cache files).
gc-leave-fs-full-percent determines the percentage of the cache partition size below which garbage collection will not go. This value prevents the garbage collector from removing all files from the cache if some other application is hogging the disk space.
The valid range for gc leave fs full percent is 0 (allow total removal) to 100 percent (remove nothing). The default value is 60 percent (allow the cache size to shrink to 60% of current).
Example
Init fn=tune-gc
gc-urldb-interval=79200
gc-nap-length=1
hard-gc-nap-count=16
soft-gc-nap-count=20
hard-gc-chunk-entries=500
gc-dir-chunk=8
gc-hi-margin-percent=80
gc-lo-margin-percent=70
gc-extra-margin-percent=30
gc-leave-fs-full-percent=60
NameTrans
NameTrans is the name translation directive, which maps URLs to mirror sites and to the local file system (for the online forms). NameTrans directives should appear in the root object (the "default" object), although you can put them elsewhere. If an object has more than one NameTrans directive, the server applies each name translation function until one succeeds and then modifies the URL to either a mirror site URL or to a full file system path.
assign name (associating templates with path)
The assign-name function associates the name of a configuration object with a path specified by a regular expression. It always returns REQ_NOACTION.
Syntax
NameTrans fn=assign-name
from=regular expression
name=named object
Parameters
from specifies a pattern, presented as a regular expression,. that specifies a path to be affected.
name is the name of the configuration object to associate with the path.
Example
NameTrans fn=assign-name
name=personnel from=/httpd/docs/pers*
map (mapping URLs to mirror sites)
The map function of the NameTrans directive looks for a certain URL prefix in the URL that the client is requesting. If map finds the prefix, it replaces the prefix with the mirror site prefix. When you specify the URL, don't use trailing slashesthey cause "Not Found" errors.
Syntax
NameTrans fn=map
from="site prefix"
to="site prefix"
name="named object"
Parameters
from is the prefix to be mapped to the mirror site.
to is the mirror site prefix.
name (optional) gives a named object from which to derive the configuration for this mirror site.
Example
# Map site to mirror site
NameTrans fn=map from=""
to=""
pac-map (mapping URLs to a local file)
The pac-map function maps proxy-relative URLs to local files that are delivered to clients who request configuration.
Syntax
NameTrans fn=pac-map
from=URL
to=prefix
name=named object
Parameters
from is the proxy URL to be mapped.
to is the local file to be mapped to.
name (optional) gives a named object (template) from which to derive configuration.
Example
NameTrans fn=pac-map
from=
to=index.html
name=file
pat-map (mapping URLs to a local file)
The pat-map function maps proxy-relative URLs to local files that are delivered to proxies who request configuration.
Syntax
NameTrans fn=pat-map
from=URL
to=prefix
name=named object
Parameters
from is the proxy URL to be mapped.
to is the local file to be mapped to.
name (optional) gives a named object (template) from which to derive configuration.
Example
NameTrans fn=pat-map
from=
to=index.html
name=file
pfx2dir (replacing path prefixes with directory names)
The pfx2dir function looks for a directory prefix in the path and replaces the prefix with a real directory name. Don't use trailing slashes in either the prefix or the directory.
Syntax
NameTrans fn=pfx2dir
from=prefix
dir=directory
name=named object
Parameters
from is the prefix to be mapped.
dir is the directory that the prefix is mapped to.
name (optional) gives a named object (template) from which to derive configuration for this mirror site.
Example
NameTrans fn=pfx2dir
from=/icons
dir=c:/netscape/suitespot/ns-icons
ObjectType
The ObjectType directives tag additional information to the requests, such as caching information and whether another proxy should be used.
If there is more than one ObjectType directive in an object, the directives are applied in the order they appear. If a directive sets an attribute and a later directive tries to set that attribute to something else, the first setting is used and the subsequent one is ignored.
cache-enable (enabling caching)
The cache_enable function tells the proxy that an object is cacheable, based on specific criteria. As an example, if it appears in the object
<Object ppath="http://.*">, then all the HTTP documents are considered cacheable, as long as other conditions for an object to be cacheable are met.
Syntax
ObjectType fn=cache-enable
cache-auth=0|1
query-maxlen=number
min-size=number
max-size=number
log-report=feature
cache-local=0|1
Parameters
cache-enable tells the proxy that an object is cacheable. As an example, if it appears in the object <Object ppath="http://.*">, then all HTTP documents are considered cacheable (as long as other conditions for an object to be cacheable are met).
cache-auth specifies whether to cache items that require authentication. If set to 1, pages that require authentication can be cached also. If not specified, defaults to 0.
query-maxlen specifies the number of characters in the query string (the "?string" part at the end of the URL) that are still cacheable. The same queries are rarely repeated exactly in the same form by more than one user, and so caching them is often not desirable. That's why the default is 0.
min-size is the minimum size, in kilobytes, of any document to be cached. The benefits of caching are greatest with the largest documents. For this reason, some people prefer to cache only larger documents.
max-size represents the maximum size in kilobytes of any document to be cached. This allows users to limit the maximum size of cached documents, so no single document can take up too much space.
log-report is used to control the feature that reports local cache accesses back to the origin server so that content providers get their true access logs.
cache-local is used to enable local host caching, that is, URLs without fully qualified domain names, in the proxy. If set to 1, local hosts are cached. If not specified, it defaults to 0, and local hosts are not cached.
Example
The following example of cache-enable allows you to enable caching of objects matching the current resource. This applies to normal, non-query, non-authenticated documents of any size. The proxy requires that the document carries either last-modified or expires headers or both, and that the content-type reported by the origin server (if present) is accurate.
ObjectType fn=cache-enable
The example below is like the first example, but it also caches documents that require user authentication, and it caches queries up to five characters long. The cache-auth=1 indicates that an up-to-date check is always required for documents that need user authentication (this forces authentication again).
ObjectType fn=cache-enable
cache-auth=1
query-maxlen=5
The example below is also like the first example, except that it limits the size of cache files to a range of 2 KB to 1 MB.
ObjectType fn=cache-enable
min-size=2
max-size=1000
cache-setting (specifying caching parameters)
cache-setting is an ObjectType function that sets parameters used for cache control. Defaults for these settings are provided through the init-cache function, described on page 430.
This function is used to explicitly cache (or not cache) a resource, create an object for that resource, and set the caching parameters for the object.
Syntax
ObjectType fn=cache-setting
max-uncheck=seconds
lm-factor=factor
connect-mode=always|fast-demo|never
cover-errors=number
Parameters
max-uncheck (optional) is the maximum time in seconds, allowed between consecutive up-to-date checks. If set to 0 (default), a check is made every time the document is accessed, and the lm-factor has no effect.
lm-factor (optional) is a floating point number representing the factor used in estimating expiration time (how long a document might be up to date based on the time it was last modified). The time elapsed since the last modification is multiplied by this factor, and the result gives the estimated time the document is likely to remain unchanged. Specifying a value of 0 turns off this function, and then the caching system uses only explicit expiration information (rarely available). Only explicit Expires HTTP headers are used. This value has no effect if max-uncheck is set to 0.
connect-mode specifies network connectivity and can be set to these values:
- always (default) connects to remote servers when necessary.
- fast-demo connects only if the item isn't found in the cache.
- never no connection to a remote server is ever made; returns an error if the document is not found in the cache.
cover-errors, if present and greater than 0, returns a document from the cache if the remote server is down and an up-to-date check cannot be made. The value specified is the maximum number of seconds since the last up-to-date check; if more time has elapsed, an error is returned. Using this feature involves the risk of getting stale data from the cache while the remote server is down. Setting this value to 0, or not specifying it (default) causes an error to be returned if the remote server is unavailable.
term-percent means to keep retrieving if more than the specified percentage of the document has already been retrieved.
Example
<Object ppath="http://.*">
ObjectType fn=cache-enable
ObjectType fn=cache-setting max-uncheck="7200"
ObjectType fn=cache-setting lm-factor="0.020"
ObjectType fn=cache-setting connect-mode="fast-demo"
ObjectType fn=cache-setting cover-errors="3600"
Service fn=proxy-retrieve
</Object>
# Force check every time
ObjectType fn=cache-setting max-uncheck=0
# Check every 30 minutes, or sooner if changed less than
# 6 hours ago (factor 0.1; last change 1 hour ago would
# give 6-minute maximum check interval).
ObjectType fn=cache-setting max-uncheck=1800 lm-factor=0.1
# Disable caching of the current resource
ObjectType fn=cache-setting cache-mode=nothing
force-type (assigning MIME types to objects)
The force-type function assigns a type to objects that do not already have a MIME type. This is used to specify a default object type.
Syntax
ObjectType fn=force-type
type=text/plain
enc=encoding
lang=language
Parameters
type is the type to assign to matching files.
enc (optional) is the encoding given to matching files.
lang (optional) is the language assigned to matching paths.
Example
ObjectType fn=force-type
type=text/plain
ObjectType fn=force-type
lang=en_US
http-config (using keep-alive feature)
http-config is an ObjectType function that lets the proxy use the HTTP keep-alive feature between the client and the proxy server, and between the proxy server and the remote server.
Syntax
ObjectType fn=http-config a
keep-alive=on|off
Parameters
on enables this keep-alive feature.
off disables the keep-alive feature, and is the default.
The keep-alive feature lets several requests be sent through the same connection.
Using this feature could actually degrade performance if the proxy is heavily loaded and it receives a lot of new requests every second and the network can establish connections fairly quickly. The reason for this degradation is that every connection is kept by the server for several seconds after the request processing has finished, even if the client doesn't happen to send a new request.
If connections to the proxy server take a long time to establish, or if the connection simply hangs, this feature should be disabled to reduce the total number of active connections.
Example
ObjectType fn=http-config keep-alive=on
java-ip-check (checking IP addresses)
The java-ip-check function allows clients to query the proxy server for the IP address used to rerouted a resource. Because DNS spoofing often occurs with Java Applets, this feature enables clients to see the true IP address of the origin server. When this features is enabled, the proxy server attaches a header containing the IP address that was used for connecting to the destination origin server.
Syntax
ObjectType fn=java-ip-check
status=on|off
Parameters
status specifies whether Java IP address checking is enabled or not. Possible values are:
- on means that Java IP address checking is enabled and that IP addresses will be forwarded to the client in the form of a document header. On is the default setting.
- off means that Java IP address checking is disabled.
type-by-extension (determining file information)
The type-by-extension function uses file extensions to determine information about files. (Extensions are strings after the last period in a file name.) This matches an incoming request to extensions in the mime.types file. The MIME type is added to the "content-type" header sent back to the client. The type can be set to internal server types that have special results when combined with function you write using the server plug-in API.
Syntax
ObjectType fn=type-by-extension
Parameters
None.
Example
ObjectType fn=type-by-extension
PathCheck
The PathCheck directives check the URL that is returned after all of the NameTrans directives finish running. Local file paths (with the administration forms) are checked for elements such as ../ and //, and then any access restriction is applied.
If an object has more than one PathCheck directive, all of the directives will be applied in the order they appear.
check-acl (attaching an ACL to an object)
The check-acl function attaches an Access Control List to the object in which the directive appears. Regardless of the order of PathCheck directives in the object, check-acl functions are executed first, and will cause user authentication to be performed if required by the specified ACL, and will also update the access control state.
Syntax
PathCheck fn=check-acl
acl="ACL name"
bong-file=path name
Parameters
acl is the name of an Access Control List.
bong-file (optional) is the path name for a file that will be sent if this ACL is responsible for denying access.
Example
PathCheck fn=check-acl
acl="HRonly"
deny-service (denying client access)
The deny-service function is a PathCheck function that sends a "Proxy Denies Access" error when a client tries to access a specific path. If this directive appears in a client region, it performs access control on the specified clients.
The proxy specifically denies clients instead of specifically allowing them access to documents (for example, you don't configure the proxy to allow a list of clients). The "default" object is used when a client doesn't match any client region in objects, and because the "default" object uses the deny-service function, no one is allowed access by default.
Syntax
PathCheck fn=deny-service path=.*someexpression.*
Parameters
path is a regular expression representing the path to check. Not specifying this parameter is equivalent to specifying *. URLs matching the expression are denied access to the proxy server.
Example
<Object ppath=".*">
# Deny servicing proxy requests for fun GIFs
PathCheck fn=deny-service path=.*fun.*.gif
# Make sure nobody except Netscape employees can use the object
# inside which this is placed.
<Client dns=*~.*.netscape.com>
PathCheck fn=deny-service
</Client>
</Object>
require-proxy-auth (requiring proxy authentication)
The require-proxy-auth function is a PathCheck function that makes sure that users are authenticated and triggers a password pop-up window.
Syntax
PathCheck fn=require-proxy-auth
auth-type=basic
realm=name
auth-group=group
auth-users=name
Parameters
auth-type specifies the type of authorization to be used. The type should be "basic" unless you are running a Unix proxy and are going to use your own function to perform authentication.
realm is a string (enclosed in double-quotation marks) sent to the client application so users can see what object they need authorization for.
auth-user (optional) specifies a list of users who get access. The list should be enclosed in parentheses with each user name separated by the pipe | symbol.
auth-group (optional) specifies a list of groups that get access. Groups are listed in the password-type file.
Example
PathCheck fn=require-auth
auth-type=basic
realm="Marketing Plans"
auth-group=mktg
auth-users=(jdoe|johnd|janed)
url-check (checking URL syntax)
The url-check function checks the validity of URL syntax.
Route
The Route directive specifies information about where the proxy server should route requests.
icp-route (routing with ICP)
The icp-route function tells the proxy server to use ICP to determine the best source for a requested object whenever the local proxy does not have the object.
Syntax
Route fn=icp-route
redirect=yes|no
Parameters
redirect specifies whether the proxy server will send a redirect message back to the client telling it where to get the object.
- yes means the proxy will send a redirect message back to the client to tell it where to retrieve the requested object.
- no means the proxy will not send a redirect message to the client. Instead it will use the information from ICP to get the object.
pa-enforce-internal-routing (enforcing internal distributed routing)
The pa-enforce-internal-routing function enables internal routing through a proxy array. Internal routing occurs when a non PAC-enabled client routes requests through a proxy array.
Syntax
Route fn="pa_enforce_internal_routing"
redirect="yes|no"
Parameters
redirect specifies whether or not client's requests will be redirected. Redirecting means that if a member of a proxy array receives a request that it should not service, it tells the client which proxy to contact for that request.
pa-set-parent-route (setting a hierarchical route)
The pa-set-parent-route function sets a route to a parent array.
Syntax
Route fn="pa_set_parent_route"
set-proxy-server (using another proxy to retrieve a resource)
The set-proxy-server function directs the proxy server to connect to another proxy for retrieving the current resource. It also sets the address and port number of the proxy server to be used.
Syntax
Route fn=set-proxy-server
host name=otherhost name
port=number
Parameters
host name is the name of the host on which the other proxy is running.
port is the port number of the remote proxy.
Example
Route fn=set-proxy-server
host name=proxy.netscape.com
port=8080
set-socks-server (using a SOCKS server to retrieve a resource)
The set-socks-server directs the proxy server to connect to a SOCKS server for retrieving the current resource. It also sets the address and port number of the SOCKS server to be used.
Syntax
Route fn=set-socks-server
host name=sockshost name
port=number
Parameters
host name is the name of the host on which the SOCKS server runs.
port is the port on which the SOCKS server listens.
Example
ObjectType fn=set-socks-server
host name=socks.netscape.com
port=1080
unset-proxy-server (unsetting a proxy route)
The unset-proxy-server function tells the proxy server not to connect to another proxy server to retrieve the current resource. This function nullifies the settings of any less specific set-proxy-server functions.
Syntax
Route fn=unset-proxy-server
unset-socks-server (unsetting a SOCKS route)
The unset-socks-server function tells the proxy server not to connect to a SOCKS server to retrieve the current resource. This function nullifies the settings of any less specific set-socks-server functions.
Syntax
Route fn=unset-socks-server
Service
Once the other directives have done all the necessary checks and translations, the functions of the Service directive send the data (first receiving it from a remote server when necessary) and complete the request. Most of the time, the Service directive connects to a remote server, making the request for the client and then passing the results back to the client.
Parameters
Service directives support these optional parameters to help determine if the directive is used:
method specifies a regular expression that indicates which HTTP methods the client must be using to have the directive applied. Valid HTTP methods include GET, HEAD, POST, and INDEX (CONNECT through SSL tunneling is also available). Multiple values are enclosed in parentheses and separated by the pipe (|) symbol.
type (not with proxy-retrieve) specifies a regular expression that indicates the MIME types to which to apply the directive. The proxy server defines several MIME types internally that are used only to select a Service function that translates the internal type into a form presentable to the client.
If an object has more than one Service directive, the first applicable directive is used and the rest are ignored.
proxy-retrieve (retrieving documents with the proxy)
The proxy-retrieve function retrieves a document from a remote server and returns it to the client. It also manages caching if it is enabled.
Syntax
Service fn=proxy-retrieve
method=GET|HEAD|POST|INDEX|CONNECT...
Parameters
method lets you specify a retrieval method. By default, all methods are allowed unless the method parameter is given.
Example
# Normal proxy retrieve
Service fn=proxy-retrieve
# Proxy retrieve with POST method disabled
Service fn=proxy-retrieve
method=(POST)
send-file (sending text file contents to client)
The send-file function sends the contents of a plain text file to the client. If this function finds any extra path information, it doesn't send the text file to the client.
Syntax
Service fn=send-file
method=GET|HEAD|POST|INDEX|CONNECT...
type=MIME type
Parameters
method lets you specify a retrieval method. By default, all methods are allowed unless the method parameter is given.
type specifies a regular expression that indicates the MIME types to which to apply the directive.
Example
Service fn=send-file
method=(GET|HEAD)
type=*~magnus-internal/*
deny-service (denying access to a resource)
The deny-service function is the only function that belongs to two classes: PathCheck and Service. It prevents access to the requested resource.
The socks5.conf File
The proxy uses the file /etc/socks5.conf to control access to the SOCKS proxy server SOCKD and its services. Each line defines what the proxy does when it gets a request that matches the line.
When SOCKD receives a request, it checks the request against the lines in
/etc/socks5.conf..
There are five sections in the socks5.conf file. These sections do not have to appear in the following order. However, because the daemon uses only the first line that matches a request, the order of the lines within each section is extremely important. The five sections of the socks5.conf file are:
- ban host/authentication - identifies the hosts from which the SOCKS deamon should not accept connections and which types of authentication the SOCKS daemon should use to authenticate these hosts
- routing - identifies which interface the SOCKS deamon should use for particular IP addresses
- variables and flags - identifies which logging and informational messages the SOCKS daemon should use
- proxies - identifies the IP addresses that are accessible through another SOCKS server and whether that SOCKS server connects directly to the host
- access control - specifies whether the SOCKS daemon should permit or deny a request
When the SOCKS daemon receives a request, it sequentially reads the lines in each of these five sections to check for a match to the request. When it finds a line that matches the request, it reads the line to determine whether to permit or deny the request. If there are no matching lines, the request is denied.
Each line in this file can be up to 1023 characters long and in order for a line to match a request, each entry in the line must match.
Authentication/Ban Host Entries
There are two lines in authentication/ban host entries. The first is the authentication line.
Syntax
auth source-hostmask source-portrange auth-methods
Parameters
source-hostmask identifies which hosts the SOCKS server will authenticate.
source-portrange identifies which ports the SOCKS server will authenticate.
auth-methods are the methods to be used for authentication. You can list multiple authentication methods in order of your preference. In other words, if the client does not support the first authentication method listed, the second method will be used instead. If the client does not support any of the authentication methods listed, the SOCKS server will disconnect without accepting a request. If you have more than one authentication method listed, they should be separated by commas with no spaces in between. Possible authentication methods are:
- n (no authentication required)
- u (user name and password required)
- - (any type of authentication)
The second line in the authentication/ban host entry is the ban host line.
Syntax
ban source-hostmask source-portrange
Parameters
source-hostmask identifies which hosts are banned from the SOCKS server.
source-portrange identifies from which ports the SOCKS server will not accept requests.
Example
auth 127.27.27.127 1024 u,-
ban 127.27.27.127 1024
Routing Entries
Syntax
route dest-hostmask dest-portrange interface/address
Parameters
dest-hostmask indicates the hosts for which incoming and outgoing connections must go through the specified interface.
dest-portrange indicates the ports for which incoming and outgoing connections must go through the specified interface.
interface/address indicates the IP address or name of the interface through which incoming and outgoing connections must pass. IP addresses are preferred.
Example
route 127.27.27.127 1024 le0
Variables and Flags
Syntax
set variable value
Parameters
variable indicates the name of the variable to be initialized.
value is the value to set the variable to.
Example
set SOCKS5_BINDPORT 1080
Available Settings
The following settings are those that can be inserted into the variables and flags section of the SOCKS5.conf file. These settings will be taken from the administration forms, but they can be added, changed, or removed manually as well.
SOCKS5_BINDPORT
The SOCKS5_BINDPORT setting sets the port at which the SOCKS server will listen. This setting cannot be changed during rehash.
Syntax
set SOCKS5_BINDPORT port number
Parameters
port number is the port at which the SOCKS server will listen.
Example
set SOCKS5_BINDPORT 1080
SOCKS5_PWDFILE
The SOCKS5_PWDFILE setting is used to look up user name/password pairs for user name/password authentication. This setting only applies to situations in which ns-sockd is running separately from the administration server.
Syntax
set SOCKS5_PWDFILE full pathname
Parameters
full pathname is the location and name of the user name/password file.
Example
set SOCKS5_PWDFILE /etc/socks5.passwd
SOCKS5_CONFFILE
The SOCKS5_CONFFILE setting is used to determine the location of the SOCKS5 configuration file.
Syntax
set SOCKS5_CONFFILE full pathname
Parameters
full pathname is the location and name of the SOCKS configuration file.
Example
set SOCKS5_CONFFILE /etc/socks5.conf
SOCKS5_LOGFILE
The SOCKS5_LOGFILE setting is used to determine where to write log entries.
Syntax
set SOCKS5_LOGFILE full pathname
Parameters
full pathname is the location and name of the SOCKS logfile.
Example
set SOCKS-5_LOGFILE /var/log/socks5.log
SOCKS5_NOIDENT
THe SOCKS5_NOIDENT setting disables Ident so that SOCKS does not try to determine the user name of clients. Most servers should use this setting unless they will be acting mostly as a SOCKS4 server. (SOCKS4 used ident as authentication.)
Syntax
set SOCKS5_NOIDENT
Parameters
None.
SOCSK5_DEMAND_IDENT
The SOCKS5_DEMAND_IDENT setting sets the Ident level to "require an ident response for every request". Using Ident in this way will dramatically slow down your SOCKS server. If neither SOCKS5_NOIDENT or SOCKS5_DEMAND_IDENT is set, then the SOCKS server will make an Ident check for each request, but it will fulfill requests regardless of whether an Ident response is received.
Syntax
set SOCSK5_DEMAND_IDENT
Parameters
None.
SOCKS5_DEBUG
The SOCKS5_DEBUG setting causes the SOCKS server to log debug messages. You can specify the type of logging your SOCKS server will use.
If it's not a debug build of the SOCKS server, only number 1 will work.
Syntax
set SOCSK5_DEBUG number
Parameters
number determines the number of the type of logging your server will use. Possible values are:
- 1 - log normal debugging messages. This is the default.
- 2 - log extensive debugging (especially related to configuration file settings).
- 3 - log all network traffic.
Example
set SOCKS5_DEBUG 2
SOCKS5_USER
The SOCKS5_USER setting sets the user name to use when authenticating to another SOCKS server.
Syntax
set SOCKS5_USER user name
Parameters
user name is the user name the SOCKS server will use when authenticating to another SOCKS server.
Example
set SOCKS5_USER mozilla
SOCKS5_PASSWD
The SOCKS5_PASSWD setting sets the password to use when authenticating to another SOCKS server. It is possible for a SOCKS server to go through another SOCKS server on its way to the Internet. In this case, if you define SOCKS5_USER, ns-sockd will advertise to other SOCKS servers that it can authenticate itself with a user name and password.
Syntax
set SOCKS5_PASSWD password
Parameters
password is the password the SOCKS server will use when authenticating to another SOCKS server.
Example
set SOCKS5_PASSWD m!2@
SOCKS5_NOREVERSEMAP
The SOCKS5_NOREVERSEMAP setting tells ns-sockd not to use reverse DNS. Reverse DNS translates IP addresses into host names. Using this setting can increase the speed of the SOCKS server.
If you use domain masks in the configuration file, the SOCKS server will have to use reverse DNS, so this setting will have no effect.
Syntax
set SOCKS5_NOREVERSEMAP
Parameters
None.
SOCKS5_HONORBINDPORT
The SOCKS5_HONORBINDPORT setting allows the client to specify the port in a BIND request. If this setting is not specified, the SOCKS server ignores the client's requested port and assigns a random port.
Syntax
set SOCKS5_HONORBINDPORT
Parameters
None.
SOCKS5_ALLOWBLANKETBIND
The SOCKS5_ALLOWBLANKETBIND setting allows the client to specify an IP address of all zeros (0.0.0.0) in a BIND request. If this setting is not specified, the client must specify the IP address that will be connecting to the bind port, and an IP of all zeros is interpreted to mean that any IP address can connect.
Syntax
set SOCKS5_ALLOWBLANKETBIND
Parameters
None.
SOCKS5_STATSFILE
The SOCKS5_STATSFILE setting identifies a different file for storing running statistics about the SOCKS server.
Syntax
set SOCKS5_STATSFILE full pathname
Parameters
full pathname is the location and name of the statistics file.
Example
set SOCKS5_STATSFILE /tmp/socksstat.any.1080
SOCSK5_QUENCH_UPDATES
The SOCKS5_QUENCH_UPDATES setting tells the SOCKS server not to write a line to the logfile every hour. This line, if written, provides a brief summary of statistics. The following is a sample line:
[04/aug/1997:21:00:00] 000 info: 78 requests,
78 successful: connect 77, bind 1, udp 0
Syntax
set SOCKS5_QUENCH_UPDATES
Parameters
None.
SOCKS5_WORKERS
The SOCKS5_WORKERS setting tunes the performance of the SOCKS server by adjusting the number of worker threads. Worker threads perform authentication and access control for new SOCKS connections. If the SOCKS server is too slow, you should increase the number of worker threads. If it is unstable, decrease the number of worker threads.
The default number of worker threads is 40, and the typical number of worker threads falls between 10 and 150.
Syntax
set SOCKS5_WORKERS number
Parameters
number is the number of worker threads the SOCKS server will use.
Example
set SOCKS5_WORKERS 40
SOCKS5_ACCEPTS
The SOCKS5_ACCEPTS setting tunes the performance of the SOCKS server by adjusting the number of accept threads. Accept threads sit on the SOCKS port listening for new SOCKS requests. If the SOCKS server is dropping connections, you should increase the number of accept threads. If it is unstable, decrease the number of accept threads.
The default number of accept threads is 1, and the typical number of accept threads falls between 1 and 10.
Syntax
set SOCKS5_ACCEPTS number
Parameters
number is the number of accepts threads the SOCKS server will use.
Example
set SOCKS5_ACCEPTS 1
LDAP_URL
The LDAP-URL setting sets the URL for the LDAP server.
Syntax
set LDAP-URL URL
Parameters
URL is the URL for the LDAP server used by SOCKS.
Example
set LDAP-URL ldap://name:8180/0=Netscape,c=US
LDAP_USER
The LDAP-USER setting sets the user name that the SOCKS server will use when accessing the LDAP server.
Syntax
set LDAP-USER user name
Parameters
user name is the user name SOCKS will use when accessing the LDAP server.
Example
set LDAP-USER admin
LDAP_PASSWD
The LDAP-PASSWD setting sets the password that the SOCKS server will use when accessing the LDAP server.
Syntax
set LDAP-PASSWD password
Parameters
password is the password SOCKS will use when accessing the LDAP server.
Example
set LDAP-PASSWD T$09
SOCKS5_TIMEOUT
The SOCKS5-TIMEOUT setting specifies the idle period that the SOCKS server will keep a connection alive between a client and a remote server before dropping the connection.
Syntax
set SOCKS5_TIMEOUT time
Parameters
time is the time, in minutes, SOCKS will wait before timing out. The default value is 10. The value can range from 10 to 60, including both these values.
Example
set SOCKS5_TIMEOUT 30
Proxy Entries
Syntax
proxy-type dest-hostmask dest-portrange proxy-list
Parameters
proxy-type indicates the type of proxy server. This value can be:
- socks5 - SOCKS version 5
- socks4 - SOCKS version 4
- noproxy - a direct connection
dest-hostmask indicates the hosts for which the proxy entry applies.
dest-portrange indicates the ports for which the proxy entry applies.
proxy-list contains the names of the proxy servers to use.
Example
socks5 127.27.27.127 1080 proxy1
Access Control Entries
Syntax
permit|deny auth-type connection-type source-hostmask dest-hostmask source-portrange dest-portrange [LDAP-group]
Parameters
auth-type indicates the authentication method for which this access control line applies.
connection-type indicates the type of command the line matches. Possible command types are:
- c (connect)
- b (bind; open a listen socket)
- u (UDP relay)
- - (any command)
source-hostmask - indicates the hosts for which the access control entry applies.
dest-hostmask indicates the hosts for which the access control entry applies.
source-portrange indicates the ports for which the access control entry applies.
dest-portrange is the port number of the destination.
LDAP-group is the group to deny or permit access to. This value is optional. If no LDAP group is identified, the access control entry applies to everyone.
Example
permit u c - - - [0-1023] group1
Specifying Ports
You will need to specify ports for many entries in your socks5.conf file. Ports can be identified by a name, number, or range. Ranges that are inclusive should be surrounded by brackets (i.e. [ ]). Ranges that are not inclusive should be in parentheses.
The bu.conf File
The optional bu.conf file contains batch update directives. You can use these directives to update many documents at once. You can time these updates to occur during off-peak hours to minimize the effect on the efficiency of the server. The format of this file is described in this section.
Accept
A valid URL Accept filter consists of any POSIX regular expression. It is used as a filter to test URLs for retrieval in the case of internal updates, and determines whether branching occurs for external updates.
This directive may occur any number of times, as separate Accept lines or as comma or white space delimited entries on a single Accept line and is applied sequentially. Default behavior is .*, letting all URLs pass.
Syntax
Accept regular expression
Connections
For the Connections directive, n is the number of simultaneous connections to be used while retrieving. This is a general method for limiting the load on your machine and, more importantly, the remote servers being contacted.
This directive can occur multiple times in a valid configuration, but only the smallest value is used.
Syntax
Connections n
Count
The argument n of the Count directive specifies the total maximum number of URLs to be updated via this process. This is a simple safeguard for limiting the process and defaults to a value of 300. This directive can occur multiple times in a valid configuration, but only the smallest value is used.
Syntax
Count n
Days
The Days directive specifies on which days you want to allow the starting of batch updates. You can specify this by naming the days of the week (Sunday,..., Saturday), and you can use three-letter abbreviations (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
This directive can occur multiple times in a valid configuration, but only the first value is used. The default is seven-day operation.
Syntax
Days day1 day2...
Depth
The Depth directive lets you ensure that, while enumerating, all collected objects are no more than a specified number of links away from the initial URL. The default is 1.
Syntax
Depth depth
Object boundaries
The Object wrapper signifies the boundaries between individual configurations in the bupdate.conf file. It can occur any number of times, though each occurrence requires a unique name.
All other directives are only valid when inside Object boundaries.
Syntax
<Object name=name>
...
</Object>
Reject
A valid URL Reject filter consists of any POSIX regular expression. It is used as a filter to test URLs for retrieval in the case of internal updates, and determines whether branching occurs for external updates.
This directive may occur any number of times, as separate Reject lines or as comma or white space delimited entries on a single Reject line, and is applied sequentially. Default behavior is no reject for internal updates and .* (no branching, get single URL) for recursive updates.
Syntax
Reject regular expression
Source
In the Source directive, if the argument is the keyword internal, it specifies batch updates are to be done only on objects currently in the cache (and a directive of Depth 1 is assumed); otherwise, you specify the name of a URL for recursive enumeration.
This directive can occur only once in a valid configuration.
Syntax
Source internal
Source URL
Time
The Time directive specifies the time to start and stop updates. Valid values range from 00:00 to 24:00 (24-hour "military" time).
This directive can occur multiple times in a valid configuration, but only the first value will be used.
Syntax
Time start - end
Type
This function lets you control the updating of mime types that the proxy caches. This directive can occur any number of times, in any order.
Syntax
Type ignore
Type inline
Type mime_type
Parameters
ignore means that updates will act on all MIME types that the proxy currently caches. This is the default behavior and supersedes all other Type directives if specified.
inline means that in-lined data is updated as a special type, regardless of any later MIME type exclusions, and are meaningful only when doing recursive updates.
mime-type is assumed to be a valid entry from the system mime-types file, and is included in the list of MIME types to be updated. If the proxy doesn't currently cache the given MIME type, the object may be retrieved but is not cached..
add_parent (adding parent servers to an ICP neighborhood)
The add_parent function identifies and configures a parent server in an ICP neighborhood.
Syntax
add_parent name=name icp_port=port number
proxy_port=port number mcast_address=IP address ttl=number round=1|2
Parameters
name specifies the name of the parent server. It can be a dns name or an IP address.
icp_port specifies the port on which the parent listens for ICP messages.
proxy_port specifies the port for the proxy on the parent.
mcast_address specifies the multicast address the parent parent will be queried. A polling round is an ICP query cycle. Possible values are:
- 1 means that the parent will be queried in the first query cycle with all other round one neighbors.
- 2 means that the parent will only be queried if none of the neighbors in polling round one return a "HIT."
Example
add_parent name=proxy1 icp_port=5151 proxy_port=3333 mcast_address=189.98.3.33 ttl=3 round=2
add_sibling (adding sibling servers to an ICP neighborhood)
The add_sibling function identifies and configures a sibling server in an ICP neighborhood.
Syntax
add_sibling name=name icp_port=port number proxy_port=port number mcast_address=IP address ttl=number round=1|2
Parameters
name specifies the name of the sibling server. It can be a dns name or an IP address.
icp_port specifies the port on which the sibling listens for ICP messages.
proxy_port specifies the port for the proxy on the sibling.
mcast_address specifies the multicast address the sibling sibling will be queried. A polling round is an ICP query cycle. Possible values are:
- 1 means that the sibling will be queried in the first query cycle with all other round one neighbors. This is the default polling round value.
- 2 means that the sibling will only be queried if none of the neighbors in polling round one return a "HIT."
Example
add_sibling name=proxy2 icp_port=5151 proxy_port=3333 mcast_address=190.99.2.11 ttl=2 round=1
server (configuring the local proxy in an ICP neighborhood)
The server function identifies and configures the local proxy in an ICP neighborhood.
Syntax
server bind_address=IP address mcast=IP address num_servers=number icp_port=port number default_route=name default_route_port=port number no_hit_behavior=fastest_parent|default timeout=seconds
Parameters
bind_address specifies the IP address to which the server will bind. For machines with more than one IP address, this parameter can be used to determine which address the ICP server will bind to.
mcast the multicast address to which the neighbor listens. A multicast address is an IP address to which multiple servers can listen. Using a multicast address allows a proxy to send one query to the network that all neighbors who are listening to that multicast address can see, therefore eliminating the need to send a query to each neighbor separately.
If both a multicast address and bind address are specified for the neighbor, the neighbor uses the bind address to communicate with other neighbors. If neither a bind address nor a multicast address is specified, the communication subsystem will decide which address to use to send the data.
num_servers specifies the number of processes that will service ICP requests.
icp_port specifies the port number to which the server will listen.
default_route tells the proxy server where to route a request when none of the neighboring caches respond. If default_route and default_route_port are set to "origin," the proxy server will route defaulted requests to the origin server. The meaning of default_route is different depending on the value of no_hit_behavior. If no_hit_behavior is set to default, the default_route is used when none of the proxy array members return a hit. If no_hit behavior is set to fastest_parent, the default_route value is used only if no parent responds.
default_route_port specifies the port number of the machine specified as the default_route. If default_route and default_route_port are set to "origin," the proxy server will route defaulted requests to the origin server.
no_hit_behavior specifies the proxy's behavior whenever none of the neighbors returns a "HIT" for the requested document. Possible values are:
- fastest_parent means the request is routed through the first parent that returned a "MISS."
- default means the request is routed to the machine specified as the default route.
timeout specifies the maximum number of milliseconds the proxy will wait for an ICP response.
Example
server bind_address=198.4.66.78 mcast=no num_servers=5 icp_port=5151 default_route=proxy1 default_route_port=8080 no_hit_behavior=fastest_parent timeout=2000 | http://docs.oracle.com/cd/E19392-01/817-0535-10/manulcfg.html | CC-MAIN-2015-40 | refinedweb | 19,154 | 55.03 |
I’d been wanting to make my Ruby on Rails based San Francisco Sailing Weather site available for mobile / cell phones. Now that I’m on vacation in Germany I had a stretch on a train ride where I was able to crank out a simple working version. Here are the steps I took:
1. Set the WAP WML content type. You can do this on each controller method, or by using a controller specific before_filter, or an application wide before_filter as I did that applies to all actions with the name wap in app/controllers/application.rb:
before_filter :set_wap_content_type, <span>:</span>only => :wap
</small>
def set_wap_content_type
@headers["Content-Type"] = "text/vnd.wap.wml; charset=iso-8859-1"
end
</small>
2. Next I created an app/views/layouts/wap.rhtml decorator to wrap all of my WML documents with:
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "">
<wml>
<card title="<%= @title %>">
<p align="center">
<%= @content_for_layout %>
</p>
</card>
</wml>
</small>
3. Then I added a wap method to my index controller so that users can access the mobile version of the site via
def wap
@title = "San Francisco Sailing Weather"
render(:layout => "wml")
end
</small>
4. Finally I created a app/views/index/wap.rhtml to provide the content for the home page:
<%= link_to 'NOAA Marine Forecast', { :controller => '/marine/forecast', :action => 'wap' } %><br/>
<%= link_to 'Wind Readings', { :controller => '/marine/wind', :action => 'wap' } %><br/>
<%= link_to 'Current Predictions', { :controller => '/marine/tide', :action => 'wap' } %>
</small>
Here is a demo of the result. You could probably also use your regular actions and adjust the content-type and view you serve based on the accepts header which you can access via the respond_to method. WAP/WML enabling the sub pages turned out to be a snap as I’d already broken out the content into partials from when I added RSS support so I was able to re-use those partials without any additional changes.
Some helpful web tools and references that I used were:
W3schools WAP tutorial
W3schools WML reference
Web based WAP Emulator
Thanks for the helpful write-up Todd. I’m thinking of WAP-enabling my wifi cafes site (), so this is useful.
I would also encourage you to look up the deck WML tag. I’ve found that it is cumbersome to browse WML pages when scrolling is involved. Decks and cards work really well to take that pain out of the process, however you’d have to do a bit more work and alter those partials a bit.
Pingback: Labnotes » Rounded Corners
May I suggest you look into the WURFL SDN Java project and this link
-E
Hi,
I am a surfer and have been doing some Rails stuff. I just started a rails site that has buoy reports for various places. I have an admin backend so I can add any regions that people would like. I just started out with some east/west coast areas for now. Thanks for the info, I figured out how to set the header info from your site, and was partly inspired from looking at what you did as well, so I knew it was doable. Sorry that my front page looks kind of primitive, html,css and content isn’t my thing, but I may try to get a picture up for the web part of it:
Pingback: 使用Rails开发支持WAP/WML的应用 - IceskYsl@1sters | http://gabrito.com/post/making-your-rails-app-mobile-with-wap-and-wml | CC-MAIN-2017-17 | refinedweb | 563 | 69.01 |
JavaFX and Near Field Communication on the Raspberry Pi
Learn how to use Java SE 8 to communicate with a near field communication (NFC) card reader, show a status message on a screen, or send information to a back-end system.
Use your Java skills to create end-to-end applications that span card readers on embedded devices to back-end systems.
JavaFX has already proven to be an excellent platform running on the Raspberry Pi. If you are working on client-side Java development on embedded devices, you probably know that JavaFX and the Raspberry Pi make for a great combination. In a number of cases, embedded devices are used in kiosk environments. A card reader is connected to an embedded device, and users have to scan a card to initiate an action—for example, to be allowed to enter a room, pay for something, or gain some credits.
There are different types of card readers, different types of cards, and different protocols. In this article, we look at how Java SE 8, which is available for the Raspberry Pi, can be used to communicate with a near field communication (NFC) card reader, show a status message on a screen, or send information to a back-end system.
Note: The source code for the examples shown in this article is available at .org/johanvos/javafx-pi-nfc.
Components of Our System
The NFC specification defines a number of standards for the near field communication between devices, including radio communication between devices that are close to each other. Various cards are equipped with a chipset. In this article, we will use a MIFARE DESFire card.
You can use your existing Java skills to create end-to-end applications that span different environments.
A card reader needs to be chosen that works out of the box on the Raspberry Pi. The USB-based ACR122U card reader from Advanced Card Systems Ltd. is a widely used device that can easily be connected to the Raspberry Pi and allows it to read MIFARE cards.
Note: It is recommended that a powered USB hub be used for connecting the card reader to the Raspberry Pi, because card readers consume a lot of power.
In order to have visual feedback, we need to attach a screen to the Raspberry Pi. A variety of screens are available, including a regular HDMI monitor and smaller screens suited for cars, kiosks, and copiers. Although this is the setup we will use in this article, different setups are possible.
Set Up the Raspberry Pi
In order to run the code provided for this project, you need a working setup. We will use an image for the Raspberry Pi that is available for download here.
In order to have the ACR122U card reader work with this image, you have to install two additional packages. Run the following commands to do this:
sudo apt-get update sudo apt-get install libpcsclite1 pcscd
Install Java
Download Java SE 8 and install on the Raspberry Pi.
Java SE comes with a
package,
javax.smartcardio, that allows
developers to communicate with smart card readers. By default, this
package will look for a personal computer/smart card (PC/SC)
implementation on the system.
Now that you have installed the required Linux packages on your
Raspberry Pi, the only remaining task is that we have to point the
Java Virtual Machine to the location of
the
pcsclite library.
This is done by setting the system
property
sun.security.smartcardio.library to
the location of the
pcsclite library as
follows:
java -Dsun.security.smartcardio .library=/path/to/libpcsclite.so
The JavaFX Application
Making a connection with a card reader and reading cards are operations that can take some time. Hence, it is not a good idea to execute those tasks at the JavaFX application thread level. Instead, we will create a dedicated thread that will deal with the card reader and uses the standard JavaFX way to update the user interface.
In a kiosk, a card reader is connected to an embedded device, and users scan a card to initiate an action.
Creating the user interface. We will
create a very simple user interface that shows the identifier of
the latest successfully scanned card. This identifier is stored
in
StringProperty latestId, as follows:
private StringProperty latestId = new SimpleStringProperty(" --- ")
Our simple user interface contains only
an
HBox with a label containing some static
information followed by a label containing the identifier of the
latest scanned card. It is constructed as shown in Listing 1.
HBox hbox = new HBox(3); Label info = new Label("Last checkin by: "); Label latestCheckinLabel = new Label(); latestCheckinLabel.textProperty().bind(latestId); hbox.getChildren().addAll(info, latestCheckinLabel); Scene scene = new Scene(hbox, 400, 250); primaryStage.setScene(scene); primaryStage.show();
Listing 1
Communicating with the card reader. The
thread responsible for the communication with the card reader is
created in a function called
doCardReaderCommunication,
which is called in the
start() method of the
JavaFX application. A JavaFX
Task is
created, assigned to a new thread, and started, as follows:
Task task = new Task() { … }; Thread thread = new Thread(task); thread.start();
This
Task performs the following
work:
- It detects a card reader.
- It detects a card being recognized by the card reader.
- It reads the identifier from the card.
- It updates the value of
latestId.
- It waits for the card to be removed.
- It goes back to Step 2.
Detecting a card reader. Before we can
access a card reader we need a
TerminalFactory.
The
javax.microcard package provides a
static method for getting a
default
TerminalFactory, and it allows us to
create
more-specific
TerminalFactory instances for
different types of card readers. The
default
TerminalFactory will use the PC/SC
stack that we installed on the Raspberry Pi, and it is obtained by
calling the code shown in Listing 2. Using
the code shown in Listing 3, we can
query
terminalFactory to detect the card
readers that are installed.
TerminalFactory terminalFactory = TerminalFactory.getDefault();
Listing 2
List<CardTerminal> cardTerminalList = terminalFactory.terminals().list();
Listing 3
In this case, our setup was successful,
and
cardTerminal List contains one element.
This
CardTerminal is obtained by running the
code shown in Listing 4.
CardTerminal cardTerminal = cardTerminalList.get(0);
Listing 4
Detecting cards. Once we have a reference to the card reader, we can start reading cards. We will do this using the infinite loop shown in Listing 5. In real-world cases, a dummy card could be used to stop reading.
while (true) { cardTerminal.waitForCardPresent(0); handleCard(cardTerminal); cardTerminal.waitForCardAbsent(0); }
Listing 5
The thread will block until the reader detects a card. Once a card is detected, we will handle it as discussed in the next section. Then, the thread will block again until the card is removed.
Handling
cards. The
handleCard method
is called when we know that a card is presented to the card reader.
Note that a card can be removed during the process of reading, and
proper exception handling is required.
A connection to the card is obtained by calling the code shown in Listing 6.
Card card = cardTerminal.connect("*");
Listing 6
Before we can read the identifier on the card, we need to know what type of card we are reading. Different card types use different addresses to store the identifier. In our simple demo, we will limit ourselves to MIFARE DESFire cards, but the example can easily be extended to other card types.
Information on the type of card we are reading can be obtained by inspecting the ATR (answer-to-reset) bytes of the card as follows:
ATR atr = card.getATR();
We compare the bytes in this
atr object
with the bytes we expect on a DESFire card, as follows:
Arrays.equals( desfire, atr.getBytes());
As shown in Listing
7,
desfire is a static byte array
containing the information we expect.
static byte[] desfire = new byte[]{0x3b, (byte) 0x81, (byte) 0x80, 0x01, (byte) 0x80, (byte) 0x80};
Listing 7
If we have a supported card type (that is, a DESFire card), we
can query the identifier. In order to do so, we need to transmit an
application protocol data unit (APDU) command over the basic logic
channel of the card, and then read the response. Using
the
javax .microcard package, this is done
as shown in Listing 8.
CardChannel channel = card.getBasicChannel(); CommandAPDU command = new CommandAPDU(getAddress); ResponseAPDU response = channel.transmit(command); byte[] uidBytes = response.getData(); final String uid = readable(uidBytes);
Listing 8
The
getAddress parameter we are passing
is a static byte array that defines how to read the identifier for
a DESFire card, and it is declared as shown in Listing
9. Different card types might require a different byte
array.
static byte[] getAddress = new byte[]{(byte) 0xff, (byte) 0xca, 0, 0, 0};
Listing 9
The function
readable(byte[]) translates
the byte array into a more human-readable format by converting each
byte to its
hexadecimal
String representation
(see Listing 10).
private static String readable(byte[] src) { String answer = ""; for (byte b : src) { answer = answer + String.format("%02X", b); } return answer; }
Listing 10
Now that we have a readable identifier for the card, we need to
show the identifier in the user interface. Because the identifier
is obtained on a thread different from the JavaFX application
thread (that is, from the communication thread), we need to make
sure that we don’t change the
latestId
StringProperty directly from the communication thread.
Rather, we need to put the change on the JavaFX application thread
as shown here.
Platform.runLater(new Runnable() { public void run() { latestId.setValue(uid); } });
This separation of concerns also guarantees that the communication with the card reader is not disturbed by activity in the user interface and vice versa.
Sending the data to a back end. In many cases, visual feedback is required when a reader scans a card. In other cases, the information needs to be sent to a back-end system. In the next section, we will send data to the back end using a very simple client-server module by which identifiers are sent from the Raspberry Pi to a Java EE 7 back end and then visualized on a web page. Sending data from a JavaFX application to a REST-based back-end system is easily done using DataFX.
The code shown in Listing 11 will
send the identifier
uid to a REST endpoint
at http:// 192.168.1.6:8080/webmonitor/ rest/card/checkin.
private void sendToBackend(String uid) { RestSource restSource = RestSourceBuilder.create() .host("") .path("webmonitor") .path("rest/card/checkin") .formParam("id", uid) .build(); ObjectDataProvider odp = ObjectDataProviderBuilder.create() .dataReader(restSource).build(); odp.retrieve(); }
Listing 11
Note that we will use the
POST method,
because a form parameter is specified in the REST request. This
method should be called whenever a new identifier is read. Because
DataFX deals with the threading, we have to call this method from
the JavaFX application thread. Hence, we can do this in the same
code block in which we set the value of
the
latestId property
(see Listing 12).
Platform.runLater(new Runnable() { public void run() { latestId.setValue(uid); sendToBackend(uid); } });
Listing 12
In real-world applications, the server might send additional information, such as the real name of the user of the card, back to the client. The client application can use this information to make the user interface more personal.
The Back End
We will now create a very simple back end that accepts the REST requests and shows them on a web page. Because it is not assumed that the user of the web page knows when cards are being scanned, it makes sense to dynamically update the web page whenever a card has been scanned. This can easily be done leveraging the WebSocket API in Java EE 7. It is surprising how little code is required for doing this.
It’s easy to create an embedded Java application, enrich it with a simple JavaFX user interface, connect it to a card reader, connect it to a Java EE system, and visualize the information using HTML5.
We will start with the web page, which is a simple HTML page
with a division named
checkins that will
contain the list of identifiers and a time stamp indicating when
each card scan happened.
When the HTML page is loaded, a WebSocket is created, pointing
to our simple back end. The content of
the
checkins division is populated whenever
a message arrives over the WebSocket. This is easily achieved using
the code shown in Listing 13.
function openConnection() { connection = new WebSocket('ws://localhost:8080/webmonitor/endpoint'); connection.onmessage = function(evt) { var date = new Date(); var chld = document.createElement("p"); chld.innerHTML = date + " : " + evt.data; var messages = document.getElementById("checkins"); messages.appendChild(chld); }; }
Listing 13
Note that the HTML page will open a WebSocket toward
localhost:8080/webmonitor/endpoint, while the JavaFX application
will push identifiers to
localhost:8080/webmonitor/rest/card/checkin. The glue for this is
our single-file back-end system, implemented in a class
named
CardHandler.
Because
CardHandler provides a REST
endpoint, it extends
javax
.ws.rs.core.Application, and it contains
an
@ApplicationPath annotation specifying that the
REST interface is located at the
rest value.
The handler itself is registered at a path
card, and
the particular method for receiving identifiers is associated with
the path
checkin. This method also takes a form
parameter named
id, which contains the identifier
(see Listing 14).
@ApplicationPath("rest") @Path("card") public class CardHandler extends Application { @Path("checkin") @POST public Response checkin( @FormParam("id") String id) throws IOException { System.out.println("Received card with id " + id); return Response.ok().build(); }
Listing 14
If we want to send this information to WebSocket clients, for
example, to the simple web page we created in the previous section,
we need to register a WebSocket endpoint as well. We can
leverage
CardHandler for this, because a
class can have multiple annotations. Doing so, we put all the
back-end code into a single file. This is probably not the best
idea for a more complex production system, but by doing it here, we
can see how easy it is to create an enterprise application in Java,
combining REST and WebSockets.
When the WebSocket endpoint receives a connection request, the
created session is stored in a
Set. When the
connection is closed, the session is removed from
the
Set, as shown in Listing
15.
@ServerEndpoint(value="/endpoint") public class CardHandler extends Application { private static Set<Session> sessions = new HashSet<>(); @OnOpen public void onOpen (Session s) { sessions.add(s); } @OnClose public void onClose (Session s) { sessions.remove(s); } }
Listing 15
We can now modify the
checkin method
created in Listing 14, and send the
identifier to the connected WebSocket clients, as shown
inListing 16.
@Path("checkin") @POST public Response checkin(@FormParam("id") String id) throws IOException { System.out.println("Received card with id " + id); System.out.println("sessions = "+sessions); for (Session session: sessions) { session.getBasicRemote().sendText(id); } return Response.ok().build(); }
Listing 16
Conclusion
In this article, we saw how easy it is to create an embedded Java application, enrich it with a simple JavaFX user interface, connect it to external hardware (a card reader), connect it to a Java EE system, and visualize the information using HTML5.
The underlying systems all use the same Java SE code. As a consequence, developers can use their existing Java skills to create end-to-end applications that span different environments.
Originally published in the March/April 2014 issue of Java Magazine. Subscribe today..
(1) Originally published in the March/April
2014 Edition of Java Magazine
(2) Copyright © [2014] Oracle. | http://jaxenter.com/javafx-and-near-field-communication-on-the-raspberry-pi-107714.html | CC-MAIN-2014-42 | refinedweb | 2,600 | 54.93 |
Enough general talk! Let us test-drive both tools using a simple piece of fractal-drawing code. This problem is tailor-made for C, because generating a fractal image involves performing a series of computations on every pixel, which calls for compact data structures and fast number-crunching. This exercise creates the familiar Mandelbrot set image shown in Figure 18.3.
Our Mandelbrot code is implemented in mandel.c and mandel.h. To avoid a non-portable GUI solution, we use a public domain library, gd, written by Tom Boutell [14], which allows you to treat a GIF file as a canvas and render points, lines, and circles on it. This GIF file can then be viewed by using any web browser.
mandel.c implements one function called draw_mandel, with the signature shown in Example 18.1.
extern int draw_mandel (char *filename, int width, int height, double origin_real, double origin_imag, double range, double depth);
The meaning of the parameters will be explained in the Section 18.6, "A Detour into Fractals," later in this chapter. First, we'll first concentrate on making it callable from Perl.
We start by writing a SWIG interface file, Fractal.i, as in Example 18.2.
%module Fractal %{ #include "mandel.h" %} %include mandel.h
The %module statement gives a unique namespace to all the interface declarations in that file. We call the module Fractal because we would like to have one namespace for all fractal drawing code, and the Mandelbrot set is only one of many choices.
The statements between %{ and %} are meant for "raw" C code. We include mandel.h here because the interface file is soon going to be converted to C glue code, which in turn needs this header. Now comes the portion where all data structures and exported functions (with complete signatures) are to be listed. Since the interface file format is very close to ANSI C, we can simply %include mandel.h. Unlike the first include, which began with a # because it is called later from C code, this include starts with % because it is called immediately within SWIG.
Next, we invoke SWIG on this interface file and specify perl5 as the scripting language:
% swig -perl5 Fractal.i Generating wrappers for Perl 5 % ls mandel.h mandel.c Fractal_wrap.doc Fractal.i Fractal.pm Fractal_wrap.c
SWIG creates four files from the interface file. Fractal.pm contains some code to make the C library dynamically loadable. Fractal_wrap.c contains the wrapper code; for a function foo listed in the interface file, this wrapper file contains a function called _wrap_foo that translates Perl argument values to C, calls foo, and packages the return results back into Perl data types. You don't have to understand the contents of Fractal.pm and Fractal_wrap.c. SWIG also extracts all documentation out of the interface file into Fractal_wrap.doc (ASCII), or Fractal_wrap.html (HTML), or Fractal_wrap.tex (LaTeX).
All we have left to do is to compile the two .c files and make them dynamically loadable.[3] SWIG (as well as XS) simplifies this part again by helping you create a makefile. Because a makefile is dependent on machine- and site-specific details such as operating system peculiarities, compiler, linker options, Perl installation directories, the name and location of the C compiler, and so on, these tools do not generate a makefile directly. Instead they generate a Perl script called Makefile.PL, which, when executed, produces a makefile that is customized for your system. This script is very simple, shown here after manually adding the LIBS and OBJECT lines:
use ExtUtils::MakeMaker; WriteMakefile( 'NAME' => 'Fractal', # Name of module 'LIBS' => [M # All custom libraries to be linked with 'OBJECT' => 'mandel.o Fractal_wrap.o' # All object files );
The standard ExtUtils::MakeMaker module does all the magic of finding out about the configuration of your system and creating a custom makefile.
The next three steps build and install this extension:
% perl Makefile.PL # create Makefile % make # compiles sources and creates shared library % make install # optional. installs library
(How much easier and more portable do you want it to get?)
We are now all set to create fractal images. The following call to draw_mandel() creates the beautiful image shown in Figure 18.3.
use Fractal; Fractal::draw_mandel('mandel.gif', 300, 300, # file, width, height -1.5, 1.0, # origin x, y 2.0, 20); # range, max iterations
Since the chief purpose of this chapter is to illustrate writing extensions, we'll (reluctantly) put off the discussion of draw_mandel to the end.
The XS process is also extremely straightforward. h2xs understands normal C header files, so a fractal extension is produced as follows:
% h2xs -x -n Fractal mandel.h
This creates Fractal.pm, the Perl module, Makefile.PL, the makefile-generating script, and Fractal.xs. At this point, you don't need to know what this file contains.
Since Makefile.PL is automatically generated, you will need to add or modify the OBJECT and LIB lines, as shown earlier. The build and install are identical to what we saw earlier:
% perl Makefile.PL % make % make install
The makefile generated in the first step notices Fractal.xs, and feeds it to xsubpp to create the glue code in Fractal.c. Note that the name is not Fractal_wrap.c as with SWIG, so the OBJECT line in Makefile.PL should look like this:
'OBJECT' => 'mandel.o Fractal.o' # mandel.o contains the real function # Fractal.o contains the glue code | http://doc.novsu.ac.ru/oreilly/perl/advprog/ch18_02.htm | CC-MAIN-2018-05 | refinedweb | 909 | 58.48 |
getNodeSet
Percentile
Find matching nodes in an internal XML tree/DOM
These functions provide a way to find XML nodes that match a particular
criterion. It uses the XPath syntax and allows very powerful
expressions to identify nodes of interest within a document both
clearly and efficiently. The XPath language requires some
knowledge, but tutorials are available on the Web and in books.
XPath queries can result in different types of values such as numbers,
strings, and node sets. It allows simple identification of nodes
by name, by path (i.e. hierarchies or sequences of
node-child-child...), with a particular attribute or matching
a particular attribute with a given value. It also supports
functionality for navigating nodes in the tree within a query
(e.g.
ancestor(),
child(),
self()),
and also for manipulating the content of one or more nodes
(e.g.
text).
And it allows for criteria identifying nodes by position, etc.
using some counting operations. Combining XPath with R
allows for quite flexible node identification and manipulation.
XPath offers an alternative way to find nodes of interest
than recursively or iteratively navigating the entire tree in R
and performing the navigation explicitly.
One can search an entire document or start the search from a particular node. Such node-based searches can even search up the tree as well as within the sub-tree that the node parents. Node specific XPath expressions are typically started with a "." to indicate the search is relative to that node.
The set of matching nodes corresponding to an XPath expression are returned in R as a list. One can then iterate over these elements to process the nodes in whatever way one wants. Unfortunately, this involves two loops - one in the XPath query over the entire tree, and another in R. Typically, this is fine as the number of matching nodes is reasonably small. However, if repeating this on numerous files, speed may become an issue. We can avoid the second loop (i.e. the one in R) by applying a function to each node before it is returned to R as part of the node set. The result of the function call is then returned, rather than the node itself.
One can provide an R expression rather than an R function for
fun. This is expected to be a call
and the first argument of the call will be replaced with the node.
Dealing with expressions that relate to the default namespaces in the XML document can be confusing.
xpathSApply is a version of
xpathApply
which attempts to simplify the result if it can be converted
to a vector or matrix rather than left as a list.
In this way, it has the same relationship to
xpathApply
as
sapply has to
lapply.
matchNamespaces is a separate function that is used to
facilitate
specifying the mappings from namespace prefix used in the
XPath expression and their definitions, i.e. URIs,
and connecting these with the namespace definitions in the
target XML document in which the XPath expression will be evaluated.
matchNamespaces uses rules that are very slightly awkard or
specifically involve a special case. This is because this mapping of
namespaces from XPath to XML targets is difficult, involving
prefixes in the XPath expression, definitions in the XPath evaluation
context and matches of URIs with those in the XML document.
The function aims to avoid having to specify all the prefix=uri pairs
by using "sensible" defaults and also matching the prefixes in the
XPath expression to the corresponding definitions in the XML
document.
The rules are as follows.
namespaces is a character vector. Any element that has a
non-trivial name (i.e. other than "") is left as is and the name
and value define the prefix = uri mapping.
Any elements that have a trivial name (i.e. no name at all or "")
are resolved by first matching the prefix to those of the defined
namespaces anywhere within the target document, i.e. in any node and
not just the root one.
If there is no match for the first element of the
namespaces
vector, this is treated specially and is mapped to the
default namespace of the target document. If there is no default
namespace defined, an error occurs.
It is best to give explicit the argument in the form
c(prefix = uri, prefix = uri).
However, one can use the same namespace prefixes as in the document
if one wants. And one can use an arbitrary namespace prefix
for the default namespace URI of the target document provided it is
the first element of
namespaces.
See the 'Details' section below for some more information.
Usage
getNodeSet(doc, path, namespaces = xmlNamespaceDefinitions(doc, simplify = TRUE), fun = NULL, sessionEncoding = CE_NATIVE, addFinalizer = NA, ...) xpathApply(doc, path, fun, ... , namespaces = xmlNamespaceDefinitions(doc, simplify = TRUE), resolveNamespaces = TRUE, addFinalizer = NA) xpathSApply(doc, path, fun = NULL, ... , namespaces = xmlNamespaceDefinitions(doc, simplify = TRUE), resolveNamespaces = TRUE, simplify = TRUE, addFinalizer = NA) matchNamespaces(doc, namespaces, nsDefs = xmlNamespaceDefinitions(doc, recursive = TRUE, simplify = FALSE), defaultNs = getDefaultNamespace(doc, simplify = TRUE))
Arguments
- doc
an object of class
XMLInternalDocument
- path
a string (character vector of length 1) giving the XPath expression to evaluate.
- namespaces
a named character vector giving the namespace prefix and URI pairs that are to be used in the XPath expression and matching of nodes. The prefix is just a simple string that acts as a short-hand or alias for the URI that is the unique identifier for the namespace. The URI is the element in this vector and the prefix is the corresponding element name. One only needs to specify the namespaces in the XPath expression and for the nodes of interest rather than requiring all the namespaces for the entire document. Also note that the prefix used in this vector is local only to the path. It does not have to be the same as the prefix used in the document to identify the namespace. However, the URI in this argument must be identical to the target namespace URI in the document. It is the namespace URIs that are matched (exactly) to find correspondence. The prefixes are used only to refer to that URI.
- fun
a function object, or an expression or call, which is used when the result is a node set and evaluated for each node element in the node set. If this is a call, the first argument is replaced with the current node.
- ...
any additional arguments to be passed to
funfor each node in the node set.
- resolveNamespaces
a logical value indicating whether to process the collection of namespaces and resolve those that have no name by looking in the default namespace and the namespace definitions within the target document to match by prefix.
- nsDefs
a list giving the namespace definitions in which to match any prefixes. This is typically computed directly from the target document and the default value is most appropriate.
- defaultNs
the default namespace prefix-URI mapping given as a named character vector. This is not a namespace definition object. This is used when matching a simple prefix that has no corresponding entry in
nsDefsand is the first element in the
namespacesvector.
- simplify
a logical value indicating whether the function should attempt to perform the simplification of the result into a vector rather than leaving it as a list. This is the same as
sapplydoes in comparison to
lapply.
- sessionEncoding
experimental functionality and parameter related to encoding.
- addFinalizer
a logical value or identifier for a C routine that controls whether we register finalizers on the intenal node.
Details
When a namespace is defined on a node in the XML document,
an XPath expressions must use a namespace, even if it is the default
namespace for the XML document/node.
For example, suppose we have an XML document
<help xmlns=""><topic>...</topic></help>
To find all the topic nodes, we might want to use
the XPath expression
"/help/topic".
However, we must use an explicit namespace prefix that is associated
with the URI corresponding to the one in
the XML document.
So we would use
getNodeSet(doc, "/r:help/r:topic", c(r = "")).
As described above, the functions attempt to allow the namespaces to be specified easily by the R user and matched to the namespace definitions in the target document.
This calls the libxml routine
xmlXPathEval.
Value
The results can currently be different based on the returned value from the XPath expression evaluation:
a node set
a number
a boolean
a string, i.e. a single character element.
If fun is supplied and the result of the XPath query is a node set, the result in R is a list.
Note
In order to match nodes in the default name space for
documents with a non-trivial default namespace, e.g. given as
xmlns="", you will need to use a prefix
for the default namespace in this call.
When specifying the namespaces, give a name - any name - to the
default namespace URI and then use this as the prefix in the
XPath expression, e.g.
getNodeSet(d, "//d:myNode", c(d = ""))
to match myNode in the default name space.
This default namespace of the document is now computed for us and is the default value for the namespaces argument. It can be referenced using the prefix 'd', standing for default but sufficiently short to be easily used within the XPath expression.
More of the XPath functionality provided by libxml can and may be made available to the R package. Facilities such as compiled XPath expressions, functions, ordered node information are examples.
Please send requests to the package maintainer.
References,
See Also
xmlTreeParse with
useInternalNodes as
TRUE.
Aliases
- getNodeSet
- xpathApply
- xpathSApply
- matchNamespaces
Examples
# NOT RUN { doc = xmlParse(system.file("exampleData", "tagnames.xml",.. # as these are the ones we want. if(!is.null(xmlRoot(doc))) { o = getNodeSet(doc, "//div/table[@class='yfirttbl']") } # Write a function that will extract the information out of a given table node. readHTMLTable = function(tb) { # get the header information. colNames = sapply(tb[["thead"]][["tr"]]["th"], xmlValue) vals = sapply(tb[["tbody"]]["tr"], function(x) sapply(x["td"], xmlValue)) matrix(as.numeric(vals[-1,]), nrow = ncol(vals), dimnames = list(vals[1,], colNames[-1]), byrow = TRUE ) } # Now process each of the table nodes in the o list. tables = lapply(o, readHTMLTable) names(tables) = lapply(o, function(x) xmlValue(x[["caption"]])) # } # NOT RUN { # this illustrates an approach to doing queries on a sub tree # within the document. # Note that there is a memory leak incurred here as we create a new # XMLInternalDocument in the getNodeSet(). f = system.file("exampleData", "book.xml",<r:a><b/></r:a></top>' doc = xmlInternalTreeParse(txt, asText = TRUE) # } # NOT RUN { # Will fail because it doesn't know what the namespace x is # and we have to have one eventhough it has no prefix in the document. xpathApply(doc, "//x:b") # } # NOT RUN { # So this is how we do it - just say x is to be mapped to the # default unprefixed namespace which we shall call x! xpathApply(doc, "//x:b", namespaces = "x") # Here r is mapped to the the corresponding definition in the document. xpathApply(doc, "//r:a", namespaces = "r") # Here, xpathApply figures this out for us, but will raise a warning. xpathApply(doc, "//r:a") # And here we use our own binding. xpathApply(doc, "//x:a", namespaces = c(x = "")) # Get all the nodes in the entire tree. table(unlist(sapply(doc["//*|//text()|//comment()|//processing-instruction()"], class))) # } | https://www.rdocumentation.org/packages/XML/versions/3.98-1.19/topics/getNodeSet | CC-MAIN-2021-04 | refinedweb | 1,892 | 54.73 |
Ummm... no fans, no foes, no journal.
Fixed Journal. This is my first and probably last entry in this journal.
Now to find some fans and foes. GNOME Foundation Is Running Out of Money.
Microsoft's Lost Decade
The MS or nothing is shrinking even faster than that with all the android and ios in the executives pockets demanding equal rights to company resources.
1366x768 Monitors Top 1024x768 For the First Time
Most porn has to be scrolled vertically...
World's Creepiest iPhone App Pulled After Outcry...
Firefox: In With the New, Out With the Compatibility
I use kubuntu and the continuous upgrades of firefox and thunderbird and very annoying!!!
I switched to thunderbird recently following a kmail2 upgrade failure. The thing is that firefox and especially thunderbird are useless without plugins. I have 17 extensions on thunderbird, ranging from standard enigmail and lightning to firetray because the stock tunderbird does not seem to have a system tray icon (duh!).
The latest and greatest firefox broke zotero for a some days. Zotero is the sole reason why I use mostly firefox.
What's Your Favorite Renewable Energy
Generators breed, and you can eat the surplus generators!
Making Data Centers More People-Friendly
That's boiling water temperture! I can just imagine the piles of cooked sysadmins there.
Why You Shouldn't Reboot Unix Servers
We reboot servers on our (very small) installation.
The most obvious is if I change the configuration of the server in a non trivial manner, and need to make sure the whole server is consistent.A reboot is the quickest way to find that out if the changes stick and are consistent with the rest of the server software. It is best to test then than to wait for a reboot due to an unrelated problem (hardware failure, power cut, trip on the cable, etc...) and then have to figure out why the server is not working as expected.
Some of our servers running commercial software also have to be rebooted periodically, due to bugs of the software that clog the server to a useless state if left alone. We could shutdown all offending processes, clean the server state, and restart them, but a supervised reboot will reset the state of the server in a reproducible manner.
Other than that, we only reboot if and only if there is a security patch for the kernel that we have to apply or a critical firmware update.
These are probably not best practices, but work in our environment.
America Losing Its Edge In Innovation
This happens all over the world. I also have a PhD in immunology, not from US or UK, but from a University and research institute somewhere in Europe.
I left science after my PhD to take advantage of a (risky) one time opportunity between my Thesis defence and a post-doc. This was such a rewarding and fruitful experience that I embarked in different career. I left Immunology for an IT job.
If I had stayed in academia, I would have to leave my life to pursue at least two top-tier post-doc in top labs outside my country. These post-docs, if successful, would give me a non-zero change of finding a paid (non-fellowship) position in a university or a research institute. If I could not overcome the institutional selection for these positions, I could have found myself over 40 and stuck in a career limbo, like many older post-docs where I had my PhD. Not a very good prospect, not getting a job because of being too old, specialised and hopelessly academic.
I research you are only competitive when you are young and your rain is cheap. This is why some foreigners, who have a higher brain/salary ratio than natives, are so sought after.
How Apple Had a Spectacular Year.
Beware the Garden of Steven
It is only a mater of time untlil the lock down is in place. This is Evil Plan basics:
1. Launch the store
2. Increase acceptance because it's secure, convenient and apple branded. Brain wash as needed.
3. Wait a bit an profit.
4. Start tarpitting third party distibuted/downloaded apps and free sotware.
5. Profit even more!
All smooth sailing with happy mac heads and software makers.
If Apple was ever in the dominant position Microsoft has been, we would be lucky to have free software and comodity hardware at all.
KDE 4.5 Released managers with overlapping xterms, because they feel very hard-edged to the user, even after editing a 10-page config file written in obscure script, they still feel not quite right.
With 4Gb of ram and a dual core chip with an intel x3100, KDE 4 works fairly well, even with a galore of firefox windows and eclipse running on the background. When this system bogs down, it is usually firefox's fault
:)
Avatar Soars Into $1-Billion Territory
I would love to see the district9 aliens playing the role of the blue smurfs.
What Did You Do First With Linux?
I think it was about 95/96 I was an undergraduate student.
A friend of mine in the lab installed Slackware from floppies, complete with doom, on a pentium 120MHz. It was the only lab computer with a serious game. Linux seemed both alien and magical to a DOS/windows 3.1 user.
At the end of the year I was running c++ code on a Alpha station with RedHat 64bit installed, it was buggy (no X, console garbage) but faster and more useful than NT.
To think that it took me almost 10 years to come back to 64bit Linux on my workstation
:)
Why Do We Name Servers the Way We Do?
Depending on the year of deployment and relation to other servers and services, we have namespaces of minerals, godzilla monsters, fruit names, lord of the rings characters, etc...
Adds some fun to functionality
:)
Linux Desktop to Appear On Every Asus Motherboard
Everytime something new and sexy comes to desktop PCs that does not depend on windows or microsoft, microsoft loses power.
So now we may have web browsing and voip on power up with no need for explorer or windows. Soon we may have bios-knoppix or bios-ubuntu, with openoffice and support for external media. I bet that would make for some sleepless nights in Redmond. | http://beta.slashdot.org/~JBv | CC-MAIN-2014-41 | refinedweb | 1,066 | 71.34 |
All Things Tested Equally
In part 1 of this series, we created Deck and Card classes via tests. The starter test for the Deck class involved verifying that a deck contained 52 cards, and that the deck indeed contained each card as expected.
Listing 1 shows the test method from the DeckTest class we built last time. For each iteration through the dual-loop series, the test calls the contains method against the Deck object, passing in the current rank and suit.
Listing 1 testCreate method in DeckTest.
public void testCreate() { Deck deck = new Deck(); assertEquals(Deck.SIZE, deck.cardsRemaining()); for (Suit suit: Suit.values()) for (Rank rank: Rank.values()) assertTrue(deck.contains(rank, suit)); }
In the Deck class, the contains method simply loops through the ArrayList of cards, looking for a match on rank and suit, as shown in Listing 2.
Listing 2 Current version of Deck.
public class Deck { ... private List<Card> cards = new ArrayList<Card> (); public Deck() { for (Suit suit: Suit.values()) for (Rank rank: Rank.values()) cards.add(new Card(rank, suit)); } ... public boolean contains(Rank rank, Suit suit) { for (Card card: cards) if (rank == card.getRank() "" suit == card.getSuit()) return true; return false; } }
A better solution would be to implement the equals method on the Card class. Once we define equality for two cards, we can have the contains method simply delegate to the cards’ ArrayList.
We’ll tackle creating the equality method in two parts. In the first part, we’ll build the equality method incrementally by virtue of simple, sensible assertions. In the second part, we’ll ensure that it adheres to the contract for equality, as laid out in the Javadoc for the Object method equals. | http://www.informit.com/articles/article.aspx?p=437291 | CC-MAIN-2016-44 | refinedweb | 284 | 75.71 |
11628/differences-between-composer-network-and-composer-identity
I am learning hyperledger these days. I have a doubt. "What is the difference between composer network and composer identity.?
For permissions, you can read about the ACLs here ->
'Composer Network' represents the business network entity. 'Composer Identity' refers to a specific blockchain identity that is mapped to a single Participant - defined in a Participant Registry that is contained within the business network in question.
Registries maintain a particular type of view of an Asset, Participant . Registries are also maintained by Composer for Identity or Historical transactions. It allows someone in that business network (given the right authority) to see the current status and history of the ledger, and Registries classify that much like a database table might do - ie depends on the level of details required (eg. Backroom Traders (Participant), Front Office Traders (Participant), Metal Commodities (Assets), Agricultural Commodities (Asset) etc etc) - or could just be rolled up as 'Traders'(Participant) and 'Commodities' (Asset) types if less detail is required. The salient point is you store Participant - or Asset Instances - in their respective type registries.
See the tutorials for examples of Assets and Participants in action:
Hyperledger Composer is an application development framework ...READ MORE
To answer your first query.. Blockchain is ...READ MORE
Coins are cryptocurrencies that are independent and ...READ MORE
Hashgraph uses Superior distributed ledger technology. Hashgraph ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
When a block is mined, it is ...READ MORE
I had same issue.
I created card ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/11628/differences-between-composer-network-and-composer-identity?show=11647 | CC-MAIN-2020-40 | refinedweb | 290 | 50.23 |
Glassmaker
Vandals smashed in chemistry teacher Krista McClain’s car windows in the lot behind the Starbucks at Coldwater and Alcove. Her personal belongings and her school-issued laptop were taken.
Visual Arts teacher John Luebtow ‘s glass sculptures are on exhibit at a museum in Washington and in front of the Napa City Hall.
A3
Fall Sports preview C4
Sp
orts
Fall
By
Find out which players to watch.
Cro ss
Julius
Var s
Co
Pak the Retu prep girls rning aring’ and from fiden“Our boys top to high ce succe defen ’ crossfinish tive est to knowss d from their counes nas goinglevel in reall Kool intos in that last top try the yeartitles team state y the sberg ourour we as state“Wh spor can s are , we exce gives. seaso t. at sameen said. comp ‘are cham team Last can llent us n,” This getti we as . The “Our pion? does conhave yearbe with prog is ete it a progng doing team experama big on the is bette the But n’t is exce ram, Manto embr posidonethis capa seaso r mix ble need ctati head rightwhat testi ption y
untr
ity
y
hope mem ace . It state n we every s ons Joof of for ng will al. have yearkindwe’re to senb title. bersa new was athlethe to beco are beco all theseyour You’r retur grea tes best of focus a ach of me runn ’12, Cam n of the set of becoI can kids.body e out bunc ?’” Sharwork ed me t, team this girls chall but this i focus mes hope It’s and thereh of ? Areon a year. of “It is ing, both Chap year is peoppe said. ’ teamengenow mind push the that, ed? that for a noble not will comi us we Head le we bette a lead . we Are when is that who “As ng ’12 to froms.” stret pursIt is ing your will we the off and defen InvitThe ChapCoac r runn are secon ch last the uit. trem team be tryinno h Tim girls an Amy d their Thei ation mile d us place ers to say ’ exce succe g one team As endoself, centa r first al ’s first team llent Weis is a coac us Shar in state evenat the looki char ssfulour in d first pe the that . Valle of at year Vent meet .” hard t. h, ng, state we the meet WeisNike three ura est? areacter at said. y Park have will [for “AmyNike last senb Trac state If thing leagu on we we be year ach k girlstwo on Frid the Natilast ers,” rightand Trac do Thur e meet ],” and place onalsseaso ay, Seas Camk Nati said . sday, s won d Sept ide That i n and is Fifth Shar trainonals her fourt in Septis at . 10. ’s why the try “quit in 800mh at the pe said. . 16. Cres hard. 1 the teame a they the stronstate even Davi On boys ,” ’re and Aber last our do t ’11. ’ sideShar g, welld gel year, team every their“We are pe said. balan ’11 have the Davi lead- last The ced boys d Aber and With shot,a good top cross ’ team best trackcham ” gel runn -cou Shar core Shar year , this pions ’11 pe grou and ers nand pe of past hips said. p Kevion of very said. runn senio How talen“We ing year in both n team rs. “has cross ever, ted have in the besid It’s easil Shar kids. a very scho y coun es trophpe ” stronol’s been try has histo the ies g prog and othe ry,” medar goals ram, ls. for the
Pla yer
AmaNathaNs nda oN’s /ChroniC Aizu ss le ’13
Pre vi
ews
Ru
nners
davi faste d team st Aber on gel and since the ’11 fifth last boys has boys placeyear his ’ cross been he soph he ’ finish finish led omor coun the hungis the the in try e succe ry leade schoin state team year, to ss matc r of ol histo, the to of Befo the h thea veter ry. besta Weis re girls even an Now was senbthere ’ team team grea duo. the ach was . ter man InjurChap dyna the but ce ies us-n mic Chap more girlssligh hurt ikki duo, ustly Gore gore there rega form’ cross as ins n’s n a her idabl coun soph perfo ’12 freshe this try omor rphoTo man year will e, S by MAry form if be she roSe .
to Wa
tch
fiSSin ger And
Nikk Gore i n ’12 leich
Alex
enger
TiT most le of
def their enS runn
to Wa
tch
Whe fresh n Ama da man nda one Giac last she of olli was year,Aizu ss tinue had the alrea golf ’13 everbest dyna s to dy coac was stars mic bloss seenWolv callin h Lin-a Emil Melatrio om, . If erine g y Fires nie along she Aizu golfeher side will ss con-rs tein Borin estab form ’11. stein lishe a ’11 andd
ers e: The this year,girls’ inclucross
Ch
The
car break-in at starbucks
ro
ni Cl W e sen hile m iors. an Nowy of th the ese tea new m tea s wo ms n lea mus gu t pr e an ove d sta them te selve titles s in last the year, com mos ing t rel year. ied on
B11
Chels
ea
khaks ing In its seasosecon first hour will n, d matc i Caris playthe at leagu h girls since ished o Golf Alem ’ varsie preli Notr 8-2 finish soph Cour any ms ty ested omor e Dam last se. toda golf last be Thei team in es e. year, The y Flinton r secon more“We playi and losin teamat Tues have ng.. fresh El expe s ridge d g only finThe that day leagu playe men and rienc a lot Sacr Sept e matc to ’11 the can e have rs, team inter ed but n’t of new team bring but lost Hear. 7 hasn is h are had confi soph ’t died ond Last ,” Borinsomereall Mela severt. againwill as five At tryou dent st Dam in year nie muchoy al out.” that the the stein thing talen retur e. Borinsenio leagu team said. new ted ts “I’m them ning Aug. “the stein r e, looki to ’13 losin place playe 26, team this ng imprsaid. g to d secrs there year, forw and impo ove “But ” Notr were ard sever caus rtan on e our Ama to fully e it’s t putti teamnda beati al part ng. on Aizu ng everywher It’s need it of this one e you the the s ss summ has score game mostto er.” been so hopebework ing
us
By DaviD kolin the Last Miss year, feateLast ion the seasoLeag girls Scho d ’ tenn Cam ol West n, ue with CIF pbelllast lake the
e and and state Amy
MAry Weistitles roSe senblast fiSSin ach,year. to They ger/C defen will HRONI d theirbe CLE retur titles ning .
nis
is year and teama 10-0team be 4-14. Hall son. in Woo Kleintoug This in playo playerecorwon h dbrid d. ’11 ipateFor comp year the d ffs, train ge the Two said. deand in etitio Camquar but High lost team start terfin lost er. prac live ing, n, pbell any its graders tice ball the girls playe Hallals to startfirst uateand matcdrills of newThis r stret the “We ing doub d five Alanwill cour faciliyear, h playwith last alter ch, stron playelost singl les team year. na dle ts nate withthe parti shouties the dent g, rs a lot es play of Octo girls coac and we of playe but The s ld at s each hescon at be still peop rs. didn team Valle will In are a Tryo Studber. seaso comp othorde reall few week ’t lose havele last y prac Unti tiona n, r y goodof leted Colle tice day, for uts io City l the are year, someto prep for then l camp offici Wed three the Golf by ge. ,” incom all at , but playe are Klein ally nesd hour team andthe the The reall held The team midrs for the said.ing start ay, mage s stu-y by Wolv wereTenn atten Thei again ed and each Coac fall is. will ded tenn 18 r first st erine yeste Thur day held h Chri an last Palosagain Beves haverday sday. on is matc ops Simp . PracMon leagu Verdst Palos a Sept h is rly Hills tice Notr e es an . 14 Club e matc High Verd away High scrim Dam h . Schoes High gameScho is e at Tues ol ol. the day and Scho Sept . Brae Oct. their ol at Sava mar 5 again first girls nnah Coun st ’ tenn er de try she last Sava is Mon NathaNs divid adva seaso team nnah tesqu by uals nced n as ’s num de oN’s/ChroniC a freshber iou Mon reasoa playe for to the le ’13 girls tesqu not n one r semi man singl was this be to beliefrom ’ singl iou final . Addi es ’13 the fall. the teamve Cham es, but s in playtiona that inad was leagu ’s lly, num de e. ber Mon Therdefeae inted one tesqu e playe iou is no will r again
Pla yer
the
hronicle C to Wa
tch
CX
Harvard-Westlake School Los Angeles, CA Volume XX Issue I chronicle.hw.com
School bypasses Honor Board in math case
By Jordan Freisleben
chloe lister/chronicle
chloe lister/chronicle
chloe lister/chronicle
kicking off senior year: Head of Upper School Harry Salamandra urges seniors to be role models (top left). Seniors Gaby Cohen, Kelly Ohriner, and Natalie Kram serve themselves food catered by Wood Ranch BBQ and Grill (top right). Seniors reconnect in the quad before the start of their senior year.
INdepth
CIF reprimands, poor fan conduct lead to broad sportsmanship review
By Austin Block In response to CIF citations for fan and athlete misconduct last year, the Sportsmanship and Fan Behavior Review Committee recently developed a list of ideas to improve ethics in athletics. The committee presented these ideas, still in an early draft proposal form, to the Faculty Advisory Committee, the Prefect Council, and the Sports Council in the weeks before the first day of school. All three of the consulted groups have offered feedback. The committee will also consult with the Student Athletic Advisory Council at its first meeting in early September. No new rules have been instituted. The ideas remain only ideas and may or may not be implemented. “This is not something that a committee is doing [unilaterally],” committee chair Dietrich Schuhl stressed. “We’re trying to make this a community effort.” The first citation occurred in early March, when the boys’ soccer team and its coach were cited by CIF at the CIF final in Downey. Team members had to write CIF an apology and the soccer team was barred by the athletic department from participating in overnight tournaments this season. Later in the same month, fans at the girls’ basketball state championship game were cited for poor conduct. The committee was created shortly thereafter. “This [poor behavior at athletic events] is not the common thing but it’s not the uncommon thing either,” Schuhl said. “Citations and the notification from CIF came because the main officials for CIF were there and were like ‘wow, this is unacceptable.’ If the main CIF officials had come to all of our other basketball games they would have said ‘wow, this is unacceptable’ for many of our basketball games, and soccer games, and football and whatever.” The committee submitted 21 points in its initial draft, dividing them into four categories: ideas for the administration, for students, for parents, and for athletes and coaches. “These are ideas that we’ve gathered from talk-
ing to schools in our area, talking to various groups around campus, looking at the NCAA guidelines, the CIF guidelines for sportsmanship,” Schuhl said. After presenting the ideas to FAC and the Sports Council, Schuhl asked each member of both groups to rank the 21 provisions in terms of priority. Schuhl will compile this data and determine which points are considered most important. He said the committee will then bring the results back to FAC and “see which ones we administratively think we can do best and fastest.” The committee report said that the administration should publicly announce its commitment to sportsmanship to all coaches and faculty and remind the faculty that “adults are responsible for immediately correcting inappropriate behavior by students at all school events.” It also suggested the administration recognize incidences of good sportsmanship. It hopes to support positive, enthusiastic fan behavior by establishing a School Pep Band, integrating the Fanatics and cheerleaders, and instituting a “‘Back to School’ Pep-Rally/Tailgate” for the first home football game of the year. Another point opened the possibility of a reorganization of the Fanatics that would add student-elected positions and faculty advisers for the fan group. “I think in a lot of ways we can make it a lot more fun,” Schuhl said. “Let’s help these guys, but let’s do it constructively.” The second section of the report provides ideas for athletes and coaches. It mentions that all students and coaches could complete a short online sportsmanship program. It suggested that athletes and students could make a sportsmanship pledge at the beginning of the year, and that coaches and team captains let parents and athletes know in writing the team’s sportsmanship expectations. Other ideas include asking coaches to “make time for their team to cheer on another [Harvard-Westlake] team” and to videotape games to “review and respond to acts both positive and negative sportsmanship with their athletes.” The committee also brought up the possee sportsmanship, A8
Students who confessed to knowingly cheating by studying from previous years’ tests in last year’s Introduction to Calculus Honors classes cannot receive college recommendations from their calculus teachers and must complete four hours of community service. The administration bypassed the Honor Board and directly asked members of the class to confess after two informants told them that some students had possession of old tests similar to the ones used last year. All Introduction to Calculus Honors students were handed a note upon leaving their final exam in June to meet in Ahmanson Lecture Hall. The students were confronted by Head of Upper School Harry Salamandra, Chaplain Father Young and math teachers Kevin Weis and Jeff Snapp. At the meeting, students signed their names in one of three boxes to indicate whether they were involved in the cheating, uninvolved but aware of the cheating or completely unaware of the cheating. “The Honor Board had no way of knowing which kids, if any, were related to this so that’s why it didn’t become an Honor Board case,” Head Prefect Melanie Borinstein ’11 said. “Typically, this kind of thing would be an Honor Board case if we knew ‘this person did this’ or something,” Salamandra said. “In this situation, we didn’t have names.” Head Prefect Chris Holthouse ’11 said that, had the incident been treated as an Honor Board case, the consequences would have been significantly different. “It’s precedent for these things. You know cheating on a test is considered a major Honor Code infraction, and you know, in comparison, what they got was relatively light, so I think it would have been different,” Holthouse said. “I don’t what the outcome would’ve been, but the Board has always been very thoughtful and it’s nice to have student input into the situation. When you don’t have the Honor Board, you don’t get that,” Salamandra said. A student in Introduction to Calculus Honors who wished to remain anonymous said that the punishment given to students was not just. “The fact that they cheated is disrespectful,” the student said. “It’s not harsh enough. It’s a major Honor Code violation.” see cheating, A8
INSIDE World View:
A5
President Thomas Hudnut and Head of School Jeanne Huybrechts attended an international educators’ conference in China.
creative streak:
Hannah Rosenberg ’11 will enroll at Harvard-Westlake and Otis this school year to pursue her passion for design.
B12
their
ding coun juniotry team rs Cam won i Chapleagu
Gir ls’ T en
C4AUG. 31, 2010 Gir ls’ G olf
By
Ashley khakshouri/chronicle
A2 preview
The Chronicle Tuesday, Aug. 31 2010 Volume XX Issue I
jordan freisleben/Chronicle
Julery: (From far right) Rebecca Katz ’15 sells a bracelet with friends Alexis McCarthy ’14 and Danielle Brody ’15 to Jason Park ’14 by the Encino Menchies at her
news
A5 A6 A8
Jewels for Jules fundraiser last Saturday. Proceeds from Jewels for Jules will go to the Julia Siegler Memorial Fund. Siegler ’14 was fatally struck by a car in February.
Forty-seven upper school students failed to do their community service. Science teacher Chris Dartt won the Kogan Award for Innovation. Scott Becker ’05 donated $500,000 to Harvard-Westlake. saj Sri-kumar/Chronicle
of f
beat
features+a&e saj Sri-kumar/Chronicle
B2 B4 B9
Students fast for Ramadan while playing varsity sports. Jordan Freisleben ’11 documented earthquake-ravaged L’Aquila.
By Eli Haims
Students attended performing arts programs over the summer.
sports
sade tavangarian/chronicle
judd liebman/Chronicle
ontheweb Spotlight: Ben Sprung-Keyser ’11 is the first junior in 20 years to win first place in the National Forensics League tournament.
C1 C7 C8
Varsity football moves back into the Mission League. Six varsity track runners went to the first-ever Nike Track Nationals. Q&A with athletes Cami Chapus ’12 and Amy Weissenbach ’12.
chronicle.hw.com
video sade tavangarian/Chronicle
podcastsvideosphotosblogspodcastsvideos
and
Saj Sri-Kumar
The Munger Science Center sustained minor injuries in a traffic accident last Thursday. A truck belonging to JR Lighting, Inc. was dropping off lighting equipment for the Senior Parent-Faculty Barbeque, which was happening later that evening. On its way out, the truck’s driver reversed away from the quad area when the cargo lift struck the side of the building’s face, scraping and denting the concrete and paint. Maintenance staff member David Reyes, who was surveying the damage after the accident, estimated that the total repair cost would amount to $500 and that it would take about two days to fix. It was not immediately apparent who would have to pay for the damage.
new beginnings There are three additions to the school family with the births of Parker, son of science teacher John and Major Gifts Officer Casey Kim, Valerie, daughter of Director for Alumni Relations Susan Beeson ’96, and Leo, son of Middle School visual arts teacher Katie Palmer and her husband, new upper school visual arts teacher Dylan Palmer.
Aug. 31, 2010
News A3
The
Chronicle
Laptop, personal items stolen from science teacher’s car By Mc-
Clain.”
Admission yield jumps seven percent By Daniel Rothberg The school’s yield jumped from 77 percent to 84 percent this year, making it the highest yield since 2003, Associate Director of Admission and Enrollment Management Davin Bergquist said. As a result of the high yield, no students were accepted off the wait list this year, he said. In the past three years, the yield for students entering in the fall has ranged from 77 percent to 79 percent. “We always hope for a specific number, both at the Middle School and Upper School,” Head of School Jeanne Huybrechts said. “You would like it to be a science, but it’s really an art. The fact of the matter is, one never knows how many kids are going to accept our offer.” While the percentage of applicants that accepted Harvard-Westlake’s invitation to enroll in the 2010-2011 school year increased significantly, the total number of incoming students increased only slightly from last year, Bergquist said. In order to determine the appropriate
“
When SOME OTHER SCHOOLS ARE SUFFERING FROM DROPS IN ENROLLMENT, PEOPLE SEEM TO WANT TO COME TO SCHOOL HERE.”
—Jeanne Huybrechts Head of School
eli haims/chronicle
Bronze wolverine: Artist John Kobald puts the finishing touches on the middle school wolverine statue he sculpted. A second one was installed at the Upper School.
Statues of wolverine added to upper, middle campuses By Rebecca Nussbaum Two identical bronze wolverine sculptures were unveiled at the Upper and Middle Schools at the opening ceremonies this morning. The school installed them on stu-
School Yield In 2010 the number of accepted students who came in the fall increased by 7 percent.
2006
82%
2007
79%
2008
78%
2009
77%
2010
84% Graphic by Maddy Baxter source: Davin Bergquist
number of acceptances to send out, the Admissions Office uses a formula that considers several factors, including historic yields, grade level and gender, Bergquist said. In addition, a buffer is factored into the formula to avoid over-admittance. “We applied the formula and it came out on the high side,” Huybrechts said. “It’s not really huge but it’s a few more students than normal.” Huybrechts, Gregory and Bergquist all believe that this year’s high yield is indicative of the extent to which students are attracted to attend Harvard-Westlake for the unique experience that it provides. “When some other schools are suffering from drops in enrollment, people seem to want to come to school here,” Huybrechts said. “It is probably a statistical blip…but the fact is, our yields are the envy of most other independent schools.”
dents may treat the statue as a meeting place on campus. The bronze sculptures were funded by Alan Casden (Aaron ’99),.
School to punish Coldwater speeders By Megan Kawasaki Effective this year, students caught speeding along the middle lane of Coldwater Canyon Avenue or performing other illegal driving maneuvers in the morning could have their parking privileges revoked. More police vehicles will be stationed along Coldwater Canyon Avenue and will cite those who speed through the center lane or side streets, Head of Security Jim Crawford said. All members of the school community are also encouraged to notify the school if they see any reckless driving. Teachers, students, and faculty members should understand that speeding and other illegal maneuvers are unsafe since by doing so, they not only endanger themselves but somebody else, Harry Salamandra, Head of Upper School, said. Hazardous student driving has repeatedly caused trouble for faculty and staff, and the potential for accident-related injury is significant, said Rob Levin, Chief Financial Officer, said. The policy was implemented due to constant complaints about students racing up Coldwater Canyon Avenue. “Students who steam down the center lane prior to the turn pocket run the risk of striking vehicles whose drivers have duly waited to reach the pocket prior to turning [into the school],” Levin said. While speeding and other dan-
gerous maneuvers such as illegal u-turns are concerning issues, the school is mainly trying to encourage safe driving habits among all members of the community. “Don’t compromise yours or others’ safety to get [to school],” Salamandra said. Even if people are performing these driving habits in order to get to school on time, it is still unsafe. “There are ways to deal with running late, and it’s not the end of the world if you’re stuck once in a while. How much time are you really saving by doing one of these maneuvers?” Salamandra said. Students, especially those who have requested parking privileges, should recognize the risk of accidents and drive in a safer manner, Levin said. Any students who drive recklessly can be subjected to an expensive speeding ticket or possibly be barred from parking if poor driving habits continue. If they do not consistently drive well, they could be asked to stop driving to school. These punishments will have an impact on the driving habits of students, Upper School Attendance Coordinator Gabe Preciado said.Individual meetings will also be set up between students and deans where safe driving practices will be discussed. “We’re always looking to better our community and better our processes here at the school and move in a direction where we’re improving every year instead of staying with the status quo,” Salamandra said.
A4 News
Aug. 31, 2010
The
Chronicle
Greco receives faculty award for dedication
Prefect Planning
By Chanah Haddad
Jamie temko
Serious stuff: Junior Prefect Katie Price ’12, (from left) Director of Student Affairs Jordan Church and Junior Prefect David Olodort ’12 participate in a planning meeting to prepare the agenda for the coming school year during their retreat earlier this month. nathanson ’s/chronicle she won the award. Marty Greco .”
Middle school student scores 5 on AP Caluculus BC exam By Ally White
and
Rachel Schwartz
Fourteen-year-old Aaron Anderson ’14 received a five on the Advanced Placement Calculus BC exam May 5. Anderson prepared for the exam by taking a Calculus BC course through Johns Hopkins online Center for Talented Youth as an independent study course during eighth grade mentored by former math teacher Rod Huston and math teacher Dan Reeves ’94.
Anderson said that he had not shown much promise in math when he was young because memorizing multiplication tables did not interest him. But once his grandfather began to teach him basic algebra in second and third grade, it became clear that math was a strong suit for him. Anderson’s father then bought him a set of algebra CD-ROMs to teach him math. By fourth grade, Anderson had completed algebra I and II, and by the end of sixth grade, Anderson had gone through geometry, trigonometry, and Calculus AB, all outside
Installations and additions E made to Upper School campus
“
I TEND TO THINK MATHEMATICALLY. I JUST LIKE FINDING THINGS OUT AND MATH IS AN EFFICIENT WAY TO DO SO.” —Aaron Anderson ‘14
of school. This past summer, he started linear algebra and will be continuing with it and multivariable calculus as independent study, which he said “should get me through the end of ninth grade.” “I tend to think mathematically. I just like finding things out and math is an efficient way to do so,” Anderson said.
The security fence is meant to make it more difficult for people to enter the campus undetected.
This summer, several improvements and additions were made around the school. A security fence and cameras were installed, Ahmanson became a multi-media center, the campus is in the middle of a complete computer backbone re-wiring, a trophy case was installed on the third floor of Chalmers, new computers were installed in Weiler Hall and the Kutler Center entered the design phase.
A
Improvements to Ahmanson include new speakers and a new projector.
C
The computer backbone re-wiring by Dave Ruben and his crew required a haz-mat chamber to contain asbestos.
F B
A trophy case was added to the third floor of Chalmers for math trophies and awards.
D
Mudd Library will be renovated in order to serve as the permanent home to the Kutler Center and a bridge to Seaver is being designed to physically and symbolically link two different departments.
Thirteen computers were added to Weiler for use by the Chronicle and Vox staffs.
photos by Alex Gura and eli haims Graphic by eli haims
Aug. 31, 2010
News A5
The
Chronicle
Foreign outlook: Hudnut watches as Headmaster of Winchester College Dr. Ralph D. Townsend, Principal of High School Affiiliated to Fudan University Fangxian Zheng, and Principal of Beijing No. 80 High School Shulin Tian sign an agreement (left), and he sits on international board of high school educators (right).
Hudnut, Huybrechts discuss high school education at Chinese conference By Alice Phillips
President Thomas Hudnut and Head of Upper College, which was the first English-speaking school in WLSA, nominated Harvard-Westlake. The aim of the conference was for principals from all schools to exchange ideas and engage in discourse about the different educational systems around the world, Hudnut said. “One of the best things I got out of the experience was getting to know some headmasters from other English-speaking schools,” Huybrechts said.
Students fail to perform community service By Chloe Lister Forty seven upper school students had yet to complete their community service requirement upon the last day of 20092010
“If our students ever wanted to do some sort of collaborative exercise with students in China I now have some friends who are Chinese school administrators.” The Chinese system is exam-driven, meaning principals must tailor their curricula to one test that determines a high school student’s eligibility for and placement in college. Hudnut said that teaching to a placement test inhibits schools from promoting the creativity, critical thinking and individual initiative that is valued at schools such as Harvard-Westlake. “I think all of us visitors sensed the frustrations that the principals have with their system that mandates the preparation of students for one particular test and the straight-jacket that that really puts on the educators,” Hudnut said. “The Chinese system stresses one-size fits all conformity that is at odds with human potential.”
Community Service As a result of not completing the community service requirement, 47 students could not pick up their books or receive their schedule.
47
upper school students had not completed their requirement on June 10
15
current 9th graders
8
graduates
4
students had not completed the requirement as of August 27. graphic by maddy baxter and Rebecca nussbaum.”
jeanne huybrechts
Although WLSA is a fledgling organization, Hudnut said that a Chinese delegation plans to visit Harvard-Westlake when they come to the United States in October. “What we would like to see come out of this is an identified topic or research project that teams of students from schools in various parts of the world could work on, then they would come together at the end of the school year in a culminating exercise,” Hudnut said. Huybrechts also spent time in Singapore prior to the WLSA conference.
Attendance at summer progam hits record high By Auistin Lee With an increase of around 10 percent from last year, the Harvard-Westlake Summer Program had the highest class enrollment in its history this summer. A total of 740 students attended this year, according to Director of Summer Programs Jim Patterson, and they participated in programs from the Gold Medal Sports Camp to SAT preparation classes and coming from both Harvard-Westlake and other schools in the area. The total class enrollment was 971.5, compared to the 700 students and 880.5 enrollments of last year, with the .5’s coming from half enrollments in a sports camp and the Conservatory. The 10 percent growth of this year is actually one of the smallest growth rates of the past few years for the program, with numbers usually ranging from above 10 percent up to 15 percent. This constant growth for the past few years is a result of an expansion of courses offered by the program, according to Patterson. Among the classes added was a second session to the college essay writing class, allowing students to get a head start on what gives “a lot of pressure” to students, Patterson said. Other new classes were Screen Writing, Advanced Film, Figure Drawing, Oil Painting, Digital Arts and Graphics Design and Digital Photography. Alongside the expansion of courses, the summer school has been changed so that most of the programs are offered over the
“
the three areas which we are strong at in the school year are the areas which i’d like the summer program to be strong at,” —Jim Patterson, Director of Summer Program
same time period, which has added a “vibrance which [the program] did not have six to seven years ago,” Patterson said. This growth of the program started in 2006 with the addition of the Gold Medal Sports Camp, said Patterson, which caused an increase in the enrollment of the sports program from around 300 to 500 attendees. Following this expansion of the athletics program, the arts, from performing to visual arts, experienced a burst of expansion, spearheaded by the expansion of the film camp, and followed by expansion in the performing arts, with the Conservatory, and the other visual and fine arts. In the coming years, Patterson hopes to expand in the the third and final remaining field of the summer programs, academics, which he feels is the area in which the program is lacking. “The three areas which we are strong at in the school year are the areas which I’d like the summer program to be strong at,” said Patterson.
A6 News
Aug. 31, 2010
The
Chronicle
inbrief School to issue parking stickers for campus lots Holographic parking stickers will be issued to students, parents and faculty members to identify their cars when parked in the school’s lots, Head of Security Jim Crawford said. The new permits, which will be affixed to windshields of the cars, will allow campus security personnel to recognize authorized cars from a greater distance and in many light conditions. Families will be sent a few stickers for the cars that will be driven to school most often. Crawford said that cars driven to school only on occasion will not need a sticker if parked in an assigned student parking spot. —Saj Sri-Kumar
Student sells jewelry in memory of classmate Rebecca Katz ’15 hosted a jewelry sale for charity to honor the memory of Julia Siegler ’14 who died on Feb. 26, when she was hit by a car while crossing Sunset Boulevard. Katz planned the event Jewels for Jules to spread her story and to raise money for Siegler’s favorite charities. On Aug. 28, Katz set up the sale on the corner of Ventura Blvd and Dixie Canyon Ave, where friends and passersby came to buy her handmade jewelry. She made about 90 pieces, with some contributions from April Rosner ’10. The proceeds from Jewels for Jules are going to Harvard-Westlake and University Synagogue. Siegler’s parents chose them because “those were the places where Julia spent most of her time,” Katz said. —Ingrid Chang
Saj Sri-Kumar/chronicle
Showing the program: Dartt displays his computerized planner. Several upper school faculty members have been using the computer program, which automatically creates a schedule for the entire school year with minimal human input.
Dartt honored for computer program By Saj Sri-Kumar
Upper school science teacher Chris Dartt received the Kogan Family Award for Innovation in Teaching for his work designing a computerized planning calendar for upper school faculty. The program was the product of four years of work. He initially created a simple Microsoft Excel spreadsheet for himself so that he could manually input his lecture schedule. Over the years, he programmed the spreadsheet to do more and more things automatically. Dartt estimated that he spent three months working on the program over the course of the four years. Most recently, Dartt added the ability to export the program to Microsoft Outlook, allowing teachers to read their schedule on their smartphones. Dartt was initially approached by upper school science department head Larry Axelrod, who asked Dartt if he could use the program. Dartt later distributed it to the entire upper school science department and later the entire upper school faculty. Head of School Jeanne Huybrechts said that since he re-
Middle school PE to group all seventh and eighth graders By Saj Sri-Kumar
Armstrong leaves post in Middle School PE Middle school physical education teacher Adia Armstrong has left Harvard-Westlake for Tampa Bay, Fla. Her husband was offered the position of head director of a sport performance facility, according to Middle School Athletic Director Darlene Bible. “I will miss her great nature. She was always upbeat and willing to help others,” Bible said. —Michael Aaronson
Rockenbach to teach at Wildwood School Leslie Rockenbach left the Upper School History Department this summer to pursue a teaching job at Wildwood School. Rockenbach taught World and Europe II, United States History, and Choices and Challenges. —Chanah Haddad
Alumni create Wolverine blend tea The Prohibition Wolverine Tea had its inaugural taste test on July 28 in Los Angeles. Alumni gathered to sip the collection of different spices, fruits and juices aptly named the “Possunt Quia Posse Videntur Blend.” A venue on Hollywood and Highland, h.wood, housed the tea tasting for roughly 30 alumni. H.wood is owned and operated in part by Sameer Gupta ’99 and John Terzian ’98, the former being the tea chef who created the drink. Courtney Quinn ’01 coordinated this event as organizer of the alumni happy hours, which happen a few times each year. —Evan Brown
leased it to the faculty, “scores of us have been using [Dartt’s planner].” The Kogan Award was endowed by Mark and Elizabeth Kogan (Ben ’11, Eli ’13) to foster innovation and acknowledge the most interesting teaching initiatives. When announcing that Dartt had won at the faculty meeting last week, Huybrechts acknowledged all of Dartt’s technological innovations, saying that he “uses technology in extraordinarily creative ways to enhance classroom teaching.” Dartt was the first recipient of the cash award since it was endowed. However, upper school science teacher Karen Huchinson and middle school math teacher Darin Beigie both won the award when it was created last year, before it was endowed by the Kogan family. Last spring, department chairs submitted nominations for the award to Huybrechts, who selected Dartt. Huybrechts said that she planned on having the Faculty Academic Committee vote on the recipient next year instead of choosing the recipient herself. Dartt said that he did not find out that he had won until he was presented with the award and that it came as a surprise.
Courtesy of Jon Wimbish
Mission Accomplished: Wimbish and Oxelson smile after completing the Mud Run at Camp Pendleton.
Two upper school deans compete in ‘Mud Run’ at Camp Pendleton Byannualush.
Middle school physical education will continue to be sorted into groups based on factors such as athletic performance and cooperation, continuing a system started last year with seventh grade students. Students participate initially in an “assessment phase,” during the first semester, Head of Athletics Audrius Barzdukas said. Students take seven core classes where they are taught by different coaches. At the end of the first semester, the coaches meet to discuss the students individually and sort them into three groups according to a number of factors, including athletic ability, cooperation and willingness to try harder. Middle School Physical Education Department Head Kimberly Hieatt said that while the coaches weighed each of the factors equally, they had trouble combating the perception that the groups were sorted solely based on athletic ability. The system was started last year for the seventh grade alone. Hieatt said that it is being expanded to apply to both seventh and eighth grades this year. She said it is unlikely that it would ever be expanded to ninth grade or the Upper School physical education classes because those classes are too small to separate into groups. The new system makes it easier for the shyer student to thrive, Hieatt said. She said that the coaches observed that when they were placed into the groups, they were more assertive and participated more. While the system is supported by most of the physical
nathanson ’s/chronicle
Audrius Barzdukas
nathanson ’s/chronicle
Kimberly Hieatt
education faculty, it has some critics, Hieatt said. Some of the faculty believes that the system “pigeonholes” the students into the set groups and restricts their ability to choose the physical education classes they take, as the system functioned previously. Hieatt said that last year there were some students that felt like they were not placed in the group that they belonged in. Hieatt said that there were some students that, while athletically talented, were unable to cooperate with the coach and their peers and were not placed in the top group as a result. “They have to share and have other leadership qualities,” Hieatt said. However, there were only “about a dozen” students who had problems with their group assignments, Hieatt said. Students who complained were told why they were not placed higher and were told that they were eligible to move up if they improved in those areas. Hieatt said that the program was overall “quite successful” but said in the future the physical education department may revert to the old system where students choose their classes based on interest if the department finds flaws with the new system.
Aug. 31, 2010
The
Chronicle
School says use of old tests is cheating from cheating, A1 Another student in the class who wished to remain anonymous said that the cheating incident should not be considered a major infraction. “I don’t think that’s a horrible thing,” the student said. “It’s their own fault if they don’t change the tests from year to year. They gave them back to the students, so it was like free information. It was never specifically told to them that they couldn’t use them.” Students should have come forward once they noticed similarities between the tests, Borinstein said. “I think that there’s a difference between looking at your sibling’s test and the point where it becomes something wrong is when you get the class that day, you take the test, you see the question and say ‘It’s identical to the one I had at home,’” she said. “The thing you’re supposed to do is tell your teacher ‘I looked at the test from last year, I thought this was fair game, I thought you changed the test, but this is identical.’ But because they continued to use the test and see that it was the same thing, that’s when it became a problem,” Borinstein said. Salamandra said that if there’s free information available to all students, they should be allowed to use it. “Me, personally, I feel if that there’s information out there and students have nathanson ’s/chronicle it and it’s available to everybody, it’s fair. J. Young I wouldn’t want a situation, personally, if only a few of the kids had it and others didn’t,” he said. “But if there’s information that’s available and it’s open to everybody, yeah, that is fair game in that respect, I would think,” Salamandra said. Clearing the conscience of the students was a priority for Young and Salamandra as opposed to giving a harsher punishment, Holthouse said. nathanson ’s/chronicle “What they felt was more of a realistic Harry option and something that would benefit Salamandra the students more would be to come clean,
“
Youv’e got to give people some credit for coming forward and admitting that they do something.”
—Harry Salamandra Head of Upper School
get the weight off their shoulders, they thought that they’d have a better time achieving that, without the strictest of punishments,” Holthouse said. Salamandra said that the fact that students came clean of their violation should be given consideration. “You’ve got to give people some credit for coming forward and admitting that they do something, too,” he said. “If you do something and we don’t know that you did it, or we just hear from someone that you did it, and you walked in this door and said ‘I gotta tell you something, let’s close the door’ and you admit to me that you did, I have to give you credit for that,” Salamandra said. “I think it’s important, because if I say ‘thank you very much’ and I give you the same punishment you would have gotten if you wouldn’t have walked in the door and I tracked you down, I’m concerned that we would be sending a message to you that it’s probably better just to shut your mouth next time.” While the tests were handed back by the Introduction to Calculus Honors teachers in previous years, Young said the math department is not at fault for returning the tests without changing them from year to year. “That’s the version of the old argument if you leave your keys in the ignition and the car is stolen, it’s your fault,” he said. “I have more of a Pollyanna kind of view when it comes to our community. I would love to work and live in a community where we are able to do things like that and still have the trust of students to not violate that. I think the mere fact that they handed the tests back puts them in the position that ‘it’s their own fault’ kind of thing – I don’t agree with that.”
Departments add many new courses By Eli Haims In the past four years, numerous new classes have been added to the curriculum, ranging from Advanced Placement Chinese to Studies in Scientific Research. The foreign language department has added AP Chinese, Directed Studies in Greek, Directed Studies in Italian, French Literature Honors and Latin Literature Honors. The two honors literature courses were created to replace AP French Literature and AP Latin Literature, which
were canceled by the College Board due to a lack of interest. Simona Ghirlanda, who designed and teaches French Literature Honors, was appalled when the class was cut, but believes that the new class has been a huge success. The history department added Directed Studies in Historical Research to their course listing last year. The class will be larger this year than last year, but it will still remain smaller than most other classes. It will be taught in a seminar style. The math department has replaced AP Computer Science AB with Honors
Advancement Changes Advancement Officers take on new roles for the coming year.
Jill Shaw
nathanson ’s
Director of Communications Shaw coordinates communication for the school with direction from the President, the Head of School and the Chief Advancement Officer.
Susan Leher Beeson ’96
nathanson ’s
Director of Alumni Relations Beeson’s responsibilities entail focusing on increasing the school’s visibility with alumni through programming and affinity groups.
Greg O’Leary
nathanson ’s
Director of Alumni Giving O’Leary is tasked with continuing to build alumni support and to create a structure similar to the Parents’ Association Annual Giving program.
Michael Bornstein ’97
nathanson ’s
Major Gifts Officer Bornstein is temporarily replacing Casey Kim who departed the office on maternity leave in June. Bornstein works with major donors. Graphic by Eli Haims, Rebecca Nussbaum, Lara Sokoloff and Saj sri-kumar
Computer Science: Design and Data Structures. AP Computer Science was also cut by the College Board due to a lack of enrollment. Meteorology, Studies in Scientific Research and Geology Honors have been added to the list of courses offered by the science department. Larry Axelrod, the Upper School Science Department Head, said that SSR, which used to be a directed studies course, and Geology Honors have been the most successful. “The enrollment was quite high and the classes are very successful and popular,” he said.
Summer Science Program names asteroid for Kutler By Eli Haims A group of students and faculty from the Summer Science Program named an asteroid after Brendan Kutler ’10, who was o attend the program in 2009. Kutler was a senior when he died in his sleep in December 2009. After learning of Kutler’s death, Davis came up with the idea to name an asteroid after him. “With the passion that the kids have for asteroids, I thought it would be appropriate to name one after him,” Davis said. Davis contacted one of his colleagues who discovered an asteroid, and asked him if the asteroid could be named after Kutler. Kutler’s classmates at SSP were then contacted to write a formal citation for the asteroid, which includes the name and number of the asteroid and a brief summary of Kutler. The summary describes him as having “lifted fellow Summer Science Program alumni with his brilliance and selflessness, upbeat attitude throughout their asteroid orbit determina-
tion project.” The citation was then submitted to and approved by the Committee for Small Body Nomenclature. The program, which was started in 1959 in response to the launch of Sputnik, is a highly intensive six week program that focuses on math and science for 72 rising high school seniors. SSP is an independent nonprofit corporation, with ties to New Mexico Institute of Mining and Technology, California Institute of Technology, and Massachusetts Institute of Technology. It is held on the campus of the New Mexico Institute of Mining and Technology in Socorro, N.M., and at Westmont College in Santa Barbara. By the end of the program, teams of three students write a research paper predicting the orbit of an asteroid around the sun. The students take approximately six hours of classes a day in order to learn the mechanics they need to predict the orbit, according to Donald Davis, the Academic Director of SSP in 2009.
News A7
inbrief
Change in e-mail system to protect student privacy In order to protect the privacy of students and update the school’s software, a new e-mail system has been implemented, Director of Computer Services Dave Ruben said. All student e-mail addresses have changed except for the senior class’s (in order to avoid confusion when contacting colleges). Instead of the lastname.firstname.year@hwstudents.com style email, they now read firstInitial. lastname.#@hwemail.com. The number differentiates students with the same first initial and last name. —Maddy Baxter
Adviser chooses VOX editors for 2010-2011 Gaby Cohen ’11 and Ali Nadel ’11 were appointed editors-in-chief of the 2011 VOX, while Justin Cohen ’11 was appointed chief executive editor by yearbook advisor Jennifer Bladen. The editors-in-chief manage the staff, while the Chief Executive Editor ensures that the yearbook staff meets their deadline. “Gaby is a natural leader. Everyone seems to do whatever she says,” Bladen said. “Ali and Justin have incredible yearbook knowledge about the process.” —Nick Pritzker
Two students to debate in tournament at Vassar Two students from the debate team will go to Vassar College to participate in a four day round robin debate this weekend. Schools throughout the country are invited to bring two students to attend. Upper school debate team coach Mike Bietz chose Brendan Gallagher ’13 and Adam Bennett ’12, to participate. The topic of the tournament is: States ought not possess nuclear weapons. —Megan Ward
Graduates’ research to be printed in science journal The American Journal of Physics will feature a research paper in its October issue written by two students in the Studies for Scientific Research class. The paper, entitled “New experimental method of visualizing the electric field due to surface charges on circuit elements,” was submitted in April 2009 by Rebecca Jacobs ’09 and Alex de Salazar ’09 with the support of science teacher Dr. Antonio Nassar. “Harvard Westlake is the only high school in the nation, perhaps in the world, published in the American Journal of Physics,” Nassar said. —David Lim
Santiago leaves school to ski in Boulder, Colo. Narciso Santiago of computer services completed his 11th and final year of service at HarvardWestlake this past June. Santiago said he moved to Boulder, Colo., to try something different. “I have some family out here, plus I miss having some proper winters,” Santiago said. “I grew up in the Midwest and I really miss the snow.” Santiago will take advantage of the cold weather with a season pass to ski in Vail, Colorado. —Elana Zeltser
A8 News
The
Chronicle
Recent graduate donates $500,000 By Vivien Mao
After selling his company to Google for about $70 million, Scott Becker ’05 donated $500,000 to Harvard-Westlake. The money will go towards the STEM (Science, Technology, Engineering, and Math) program and support for faculty, although the details are still being figured out. “This is truly an extraordinary gift from a young alum. This is the largest commitment made by a 23 year old alum of Harvard-Westlake,” Chief Advancement Officer Ed Hu said. Becker founded Invite Media, a company which sells online advertising space to businesses, in his sophomore year of college at the University of Pennsylvania with three friends. He had always been interested in computer technology. For example, his senior project at Harvard-Westlake was to create a social networking site called “Friendzee” that would rival MySpace. Some of his past projects include “Charlie’s Travels,” a blog for Charlie Melvoin who travelled around the world, the Madison Radiology Web Appointment System, which created a program for patients to schedule appointments online; and “Web Crawler,” which can analyze Social Networking Applications. He even launched a DVD rental site. At Penn, he created a social networking site specifically for the students; the site reached 2500 members within two months of creation. He then launched a multilingual so-
cial networking application for college students living in Europe and South America. Always loyal to his school, Becker helped enhance life at college by creating a Penn food cart ordering website as well as an online used textbook marketplace. He also set up a searching interface for two classes, Dr. Lyle Ungar’s Medline Database class and Dr. Susan Davidson’s Principles of Information Systems classes. He graduated in 2008 with a major in Computational Biology and was a candidate for a Bachelor’s Degree of Science in Engineering. It was at Harvard-Westlake that he met the many teacher who would become a large supporting factor in his future career. “It’s inspiring how much energy my [Harvard Westlake] teachers had toward teaching. Most of my college professors didn’t compare,” Becker said, as quoted from Harvard-Westlake Online. Though he has sold his company, Becker still plans to continue working with subjects he is passionate about, including biotechnology and pharmaceuticals. He hopes that his donation to Harvard Westlake can further research and education for the future. “I see this as more than a way to show my appreciation for Harvard-Westlake; I see it as an investment in our future. I know H-W students are going to be building the best products, technologies, films, companies, treatments, books, and disease cures. My gift will help bring these great things to life sooner,” Becker said.
Aug. 31, 2010
courtesy of Sam Wasson
nationally known: Author Sam Wasson’s ’99 recently published book “Fifth Avenue, 5 A.M.” was placed on the New York Times bestseller list.
Alumnus’ book places on national bestseller list screaming and laughing at once. I was in my room and my editor called me screaming into the phone and I could barely understand what she was saying, but I knew it had to be something good,” Wasson said. Wasson’s previous book, “A Splurch in the Kisser: The Movies of Blake Ed-
wards”, addresses the work of director Blake Edwards, who directed “Breakfast at Tiffany’s” along with many others, such as “The Pink Panther” series, “Days of Wine and Roses”, “The Party” and “Micki and Maude.” During his research for “A Splurch in the Kisser: The Movies of Blake Edwards,” Wasson decided to write “Fifth Avenue, 5 A.M.” “When it came time for the next project, writing on ‘Breakfast at Tiffany’s’ itself was the next step. I was amazed when I was doing research on Blake Edwards at the makings of “Breakfast at Tiffany’s.” “Fifth Avenue took me about a year of research and writing and rewriting,” Wasson said.
Sportsmanship committee issues ethics draft proposal from sportsmanship, A1
Wolverines Eat Pizza From Mama’s and Papa’s !!!
sibility of a Captains Committee to improve student leadership and sportsmanship. Athletic Director Terry Elledge said he believes poor fan behavior is a much bigger issue than poor sportsmanship. “It’s the behavior of the people that are watching the games [that is the problem] no matter what you’re talking about,” Elledge said. “I hear people out of line at softball games, I hear people out of line at soccer games, I hear people out of line at baseball games, so I think that is the bigger issue in my opinion.” The committee finished the draft with five last points, four for students and one for parents. It highlights the need to announce “sportsmanship expectations” to the student body at the beginning of the year and suggests that a student reiterate these expectations before all home games. It says the Fanatics could, in conjunction with the student body, write a “Fan Code of Behavior” to be posted around our athletic facilities. It also hopes to inform parents of sportsmanship issues and set up standards for parental behavior at games as well. “This is not a final decision. We are consulting the Prefect Council, Student Athletic Advisory, Sports Council, faculty and all that,” Schuhl said. “The best thing we can do at this point is to say that this is a discussion and this is something we’re working on and you
are going to hear about it throughout the year.” Head Prefect Melanie Borinstein ’11 said the Prefect Council completely supports the general goals and intentions of the committee but has mixed feelings about the specific suggestions. “I think we found certain things that we think would be more effective or realistic in it. There’s a wide range of what we agree and disagree with and I think that’s why we’re glad they came to us to talk about it because we are the students’ representatives,” Borinstein said. “I think that we’re just going to give our input and they can do what they want with that. We have a wide range of feelings toward it… None of the proposals are bad there just are ones that are maybe more effective and more likely to be liked by the student body.” Head of Athletics Audrius Barzdukas expressed his support for the committee and its draft proposal as well. “I think that virtually every school in the country would love to have our fan support and our sportsmanship,” Barzdukas said. “This is just an opportunity for us to just take a look and see what we can improve.” “When you look at Harvard-Westlake, you think of Harvard-Westlake as being at the top,” Elledge said. “I don’t feel we’ve been at the top there [sportsmanship and fan behavior] for a while and I think we should be, we can be, we ought to be. Everybody looks to us for our athletic success, our academic success, why shouldn’t they look to us for a model for behavior?” I Aug. 31,jan Sri-Kumar Infographic Editors: Maddy Baxter, Eli Haims Assistants: Wendy Chen, Carrie Davidson, Molly Harrower, Camille Shooshani, Megan Ward Opinion Managing Editors: Noelle Lyons, Jean Park Section Heads: Alex Gura, Chanah Haddad, Anabel Pass, Gabrielle Franchina, David Lim, Michael Rothberg, Elana Zeltser Science & Health Editors: Claire Hong, Nika Madyoon Centerspread Editors: Camille de Ry, Arielle Maxner Arts & Entertainment Editors Jessica Barzilay, Justine Goode Arts & Entertainment Assistants: Maggie Bunzel, Bo Lee, Aaron Lyons Photography Assistant: Cherish Moezian, Micah Sperling, Ally White Chronicle Online Managing Editor: Vivien Mao News Update Editors: Evan Brown, Hank Gerba, Sanjana Kucheria Opinion Update Editor: Victor Yoon Feature Update Editors: Julius Pak, Nick Pritzker A&E Update Editors: Tiffany Liao, Meagan Wang Sports Update Editors: David Gobel, Judd Liebman Mulitmedia senior members of the Editorial Board. Advertising questions may be directed to Business Manager David Burton at (818) 481-2087. Publication of an advertisement does not imply endorsement of the product or service by the newspaper or the school.
GRAPHIC BY INGRID CHANG
Stand by the Honor Board
I.
The responsibility is ours
H
arvard-Westlake is littered with committees. And as if there weren’t already enough committees to keep track of on the upper school campus before this year, we can now add the sportsmanship review committee
to that list. The sportsmanship committee’s proposals to change the culture of conduct at sporting events are likely to draw the ire of at least a few students. This committee is part of a trend of increased faculty involvement in student affairs to combat what is perceived as a sagging culture of student conduct. Another example of the trend is the policy against using cell phones in buildings, which was put into place last year. While the general reaction of the student body cannot be judged at this early stage in the year, it is hardly a reach to assume that many of the school’s proposals, like the sportsmanship proposal, will not exactly be greeted with open arms by students. Students may disapprove of the specifics of the faculty’s decisions, but no matter how valid our arguments are, they fail to address the more important point. If the reforms of the faculty and administration so often prompt moaning and groaning from the majority of the student body, why do we students force them into action in the first place? Rather than criticizing the faculty and administration for their decisions, we should take matters into our own hands and preempt the need for intervention. As the new school year begins, we should make a vow to take responsibility instead of playing the
blame game. Besides, righting most of our day-to-day wrongs should not even be difficult. Let’s start with the most easily improvable daily transgression on campus: cleaning up trash (or the lack thereof). Maybe we could just each dump our lunch garbage into the bins. It is the same easy fix with the cell phone problem. To resist the temptation of answering a friend’s text message, simply turn off your phone prior to an assembly or put it in your backpack before class. Last but certainly not least, there is the issue of conduct at athletic competitions. We can be passionate when cheering on our friends and classmates. Even a degree of rowdiness should be acceptable at times. But once we cross the line and shout overly insensitive comments, we only make matters worse for ourselves. By default, we put matters in the hands of those with whom we so often disagree. And when the faculty and administration need to get involved, it means they have lost a degree of faith in us students to do the right things on our own and carry ourselves in the proper manner. In the end, the actions of the faculty and administration are always more drastic than what students are comfortable with. Yet drastic changes could be prevented simply by doing the little things first.
Aug. 31, 2010
Chronicle
The
A10 Opinion
Taking a hand
Chloe Lister
A
“
But Most of us have gotten so caught up that we forget the kind of people we have at our disposal.”
s the last minutes of my sophomore year ticked away, I was preoccupied with thoughts of sunshine and freedom from any sort of schoolwork. While my friends hopped onto planes with destinations like Paris or Beijing, I would stay at home to return for my second year as a counselor at a day camp. They seemed sweet enough at first; but I learned firsthand how terrible 13 seven to nine-year-olds could be, pigtails and all. At the beginning of every day, the senior counselors would retreat for 20 to 30 minutes to their attendance meeting, when junior counselors have full reign of the group to play games and get everyone excited for the day. This period quickly became my favorite part of camp; the more confident I was, the more fun we had, and that was the time when I really felt like I bonded with them. One day, my senior counselor had her evaluation with the camp director. That meant that I’d have an additional hour with the group, when I didn’t have anything planned. My group started off strong, but one by one, the children trickled out of whatever game we were playing to sit off to the side and whine about how bored they were. They could only throw dodgeballs or chant “cut the pie” for so long. Once there were more girls sitting out than those playing, no amount of “hey, listen up” could get them to focus. By chance, one counselor happened to walk by, and, despite my own reluctance, I asked for his help. Within seconds he had all my girls enraptured by his instructions for a game usually only played by the oldest groups; he “wasn’t sure” if they’d be mature enough to handle it. All 13 of them were up, laughing and shrieking with delight at all the fun they were having. I learned something that I can carry with me during junior year: that I don’t have to do everything alone. At school it’s encouraged to be independent, which is a good thing when it comes to preparing for our lives ahead of us. But most of us have gotten so caught up that we forget the people we have at our disposal. Just like I was able to reach out to someone with more experience with children than me, we have experts in countless fields to guide us. With the start of the school year comes all the tired clichés about starting fresh, but they’ve only become clichés by being such enduring truths. I hope that we all will be able to go out of our comfort zones this year and remember that we can always ask for help.
CHANAH HADDAD AND ANABEL PASAROW/CHRONICLE
Oh brother! I
Noelle Lyons
see him at home. I drive him to school. And when I walk through the quad with my friends, he’s there. Having a younger sibling on the same campus is a big change compared to our previous seven mile separation from the Upper School to the Middle School. Our two year age difference has always kept us at a relatively close, but not too close, distance from each other. Only one out of my five years at Harvard Westlake so far have I ever been on the same campus with Aaron, and this 2010-2011 school year is going to be the second. The first time was when I was in ninth grade and he was in seventh. I was just starting my freshman year, and he was the cute new seventh grader everyone fawned over. My friends already knew him, because to them he was my little brother and the resemblance was undeniable. Except for the age and height difference, it was easy to spot one of us in a crowd. We took the same bus to the Middle School, but sat at complete opposite ends with our friends from our own grades. Everything changed when he was still at the Middle School in eighth grade and I was at the Upper School in 10th grade. Instead we were now dropped off at the bus stop by
our mother and quickly went our separate ways. It was only after school when the bus dropped us back off at our original spots that we saw each other again. This had been our daily routine for the past two years. Yet, once again I will be seeing him during the eight hour school day now that I’m a senior and he is a sophomore. Nevertheless, he’s still the little brother everyone compared me to before. However, now that I have my license and a parking spot at the school, I can drive both Aaron and me to where we need to be every morning. Instead of talking to our friends on the way to school like we usually did on the bus, it’s only Aaron and me sitting in the car making conversation. I can give him advice on homework and classes I’ve already taken, as well as teachers I’ve previously had. And even when we don’t have much to say, there is still music blasting from the radio to fill the silence. When we finally arrive at school and go to class, there will still be those moments in the hallway where I can see him out of the corner of my eye and give him a wave. Now knowing there is someone related to me on the same school campus gives me a sense of awareness I didn’t know I had.
Enjoying the unexpected M
illions of songs have been written about the joyous days of summer. Come the start of June, commercials, stores, or perhaps even your own iPods constantly blare the occasionally sub-par instrumentals but entirely fitting vocals of songs like Alice Cooper’s “School’s Out” and Nat King Cole’s “Those Lazy Hazy Crazy Days of Summer.” However, these songs harken back to the summers of old, at least for the majority of my peers and me. Summer is no longer about relaxing and unwinding after a grueling nine months of all-nighters, double period calculus tests, impossibly long layout weekends, and hours upon hours of unrelenting cross country and track practices ( I may still be a little jaded from junior year…). Now, the summer months are stuffed full of jobs, internships,
Mary Rose Fissinger fall sports practices, summer classes, far-away programs and camps. The knowledge that college applications are not only made up of grades and extracurriculars during the academic school year, but also your activities during the summer leads to not-sorelaxing vacations for many students. I believe that my summers have become much more memorable and fulfilling ever since I started filling them with structured activities. For example, this year my summer consisted of early morning cross country practices four times a week and a four week stint teaching sixth through eighth graders math at my elementary school, a gig I would not have traded for the world and one that may even have impact on my future goals. The plain truth of the matter is that most people end up really enjoying what they fill their summers with.
I don’t want to suggest that, were it not for college applications, students would be entirely unproductive all summer. But let’s face it: Harvard-Westlake is a pretty demanding place. So it’s natural that when summer rolls around, we want to revel in the leisure of waking up later than 6:30 each morning and not having to constantly go over the checklist in our minds of assignments and when they’re due. Most of us still get a week or so of these luxuries. But then it’s more early mornings, responsibilities, and long days. I, for one, can’t complain. Doing nothing all summer can get boring; it’s nice to be productive. And nothing says productive quite like running nine miles at seven in the morning, especially when it’s followed by explaining the concept of sales tax to a seventh grader.
I had spent the entire month trying to get the kids excited about math, which turned out to be quite the challenge since practically 100 percent of the students were there only by decree of their parents. They’d enjoyed the casual, fun atmosphere of the class but drudged through the actual work. On that final Wednesday, after several examples of factoring polynomials, one of the girls in the front row lit up. “Wow,” she said. “I get it! That’s really cool.” I was very pleased that she finally understood what I meant when I said “math is cool.” If you’re reading this and thinking to yourself, “Wow, this girl is a huge nerd,” you are entirely correct. The fact that I was able to communicate some of my love for learning to one of my students was by far the most rewarding moment of my summer.
Aug. 31, 2010
Letters
The
Acting like champions
I jordan freisleben/CHRONICLE
editors: alice Phillips ’11 and Daniel Rothberg ’11 take a break from layout.
We’ll keep you posted
Twitter. RSS readers. iPhone applications. Facebook news feeds. This is how we consume information in the 21st century. Gone are the days of breaking news being delivered to your doorstep each morning by the newspaper boy. Even as a high school newspaper, we must evolve with the times. As dailies across the country have become more and more obsolete, so it follows that a monthly high school paper would have been left behind long ago. So our point? The Chronicle needs to keep up. Starting now, not only will our website serve as a modern means to access our coverage but it will serve as a dayto-day conduit for the latest news at and around Harvard-Westlake. Thanks to Web Manager Lillian Contreras’ tireless efforts, we are launching two blogs, “the quad” and “GO BIG RED,” to efficiently deliver the latest in campus and sports coverage, respectively. Instead of having to navigate the full Chronicle website on a smartphone screen, you can load a continuously updated web page (conveniently linked from our website’s home page) for your Harvard-Westlake news. But our emphasis on instant news doesn’t mean we will sacrifice accuracy or news judgment just to get blog post or an article on the web. We are still The Chronicle, with all of the adjectives that bears, we are just The (faster, better, more timely) Chronicle. —Alice Phillips ’11 and Daniel Rothberg Editors-in- Chief
n both scholarly endeavors and in athletics, Harvard-WestlakeWolverines have distinguished themselves in local and national contests, competing honorably and with grace. In just the last few years, Harvard-Westlake has been home to International Science Olympiad medalists, nationally recognized debaters, and state championship athletic teams. A few weeks ago, the California Interscholastic Federation recognized the top 10 girls’ athletics programs in Southern California. Citing State and Southern-Section championships in girls’ basketball, cross country, soccer, and track and field, CIF placed our girls’ athletics program at the top of the list, awarding it the CIF Commissioner’s Cup for 2010. There are Harvard-Westlake students who have earned the right to call themselves champions, and their outstanding achievements and stellar reputations reflect on the school and make us all look good. All champions are winners, but not all winners are champions. There’s a big difference between being a winner and being a champion. You can’t become a champion by earning the highest score on an exam or by winning a single game – or even by winning many games. And champions can quickly lose their status: Think of the “champion” who wins and then acts like a fool! Winning is merely an outcome – at its most basic, one of two outcomes in any competition: win or lose. Becoming and being a champion is not an outcome; it is a process, a way of acting, a way of behaving. True champions are relentlessly positive and gracious always. True champions respond to a challenge with dignity. They rise
T
he, incre-
The Chronicle evaluates recent campus developments.
A C-
above the fray, don’t involve themselves with the pettiness that can accompany longstanding rivalries. Aware of their strengths and their weaknesses, champions display confidence and humility don hagopian/chronicle in equal measure. Harvard-Westlake is commonly regarded as a “school of champions,” and so it was disappointing when, last year, the California Interscholastic Federation (the same CIF that just awarded us the Commissioner’s Cup) cited our school for unsportsmanlike conduct during two of our competitions. Some of our fans – students and athletes – behaved poorly at those games, and while it would be easy enough to marginalize the incidents (only two competitions among hundreds that took place last year), we will instead seize upon this as a teaching opportunity. This year, in class meetings and faculty meetings, we will decide for ourselves what good sportsmanship means at Harvard-Westlake and recommit to supporting our scholar-athletes in the most positive way possible. Our students’ achievements have given us the right to call ourselves champions: Harvard-Westlake Champions. We all benefit from that reputation and have the responsibility to maintain it. To BE a champion means to live the life of a champion, to act like a champion – at athletic competitions and in our everyday interactions with each other. Our motto for this year, then, is Act Like Champions.
— Jeanne Huybretchs, Head of School
Taking smaller steps for change
makinggrades The Kutler Center will be built to connect the library and Seaver.
Opinion A11
Chronicle
B+
Locker selection was online this year.
F
Sophomore and Junior e-mails and passwords were changed during the summer.
School starting before Labor Day.
mental
Chloe lister/Chronicle
student leaders: Head Prefects Melanie Borinstein ’11 and Chris Holthouse ’11 hope that the 2010-2011 school year brings more freedom for students.
wolverinecontest
Our new statues depict a real wolverine in nature. Don’t we also need a sportier, perhaps less life-like mascot?
Calling all artists: Don’t you think it’s time that Harvard-Westlake had a proper logo to appear on clothing and other merchandise? Submit an original piece of artwork depicting your idea of what our Wolverine mascot should look like to chronicle@hw.com or to Weiler 108. All entries are due by Sept. 30. Winners will be announced before Homecoming. *All submitted artwork will be property of Harvard-Westlake
exposure
Aug. 31, 2010
filling in the pieces Jim Doughan Middle School
A12
Nine new teachers join our campus this fall. From pottery teacher to biology teacher, each one helps to fill in the blanks on our campus. Pentti Monkkonen Middle School
Acting and drama workshop
Pottery teacher
Fun fact: has worked with the LA Comedy troupe The Groundlings
Fun fact: taking over for Katie Palmer while she is on maternity leave. Preparing for his exhibition in Basel, Switzerland
Susannah Gordon Middle School 8th grade Integrated Science II and 9th grade biology
Celia Goedde Upper School
Fun fact: came back to teaching after a stint as a science writer because she “missed working with the kids”
US History and The World and Europe II Fun fact: loves opera music Alex Krikorian Middle School
Stephanie Portal Middle School
7th grade science and 8th grade debate teacher
French and Library and Technology teacher Fun fact: attended La Sorbonne in Paris, majoring in French literature
Fun fact: Looks to create a club dedicated to dinosaurs
Isaac Laskin ’98 Middle School 7th grade geography and culture, 9th grade The World and Europe I Fun fact: has already finished his lesson plans Florence Pi Middle School
Dylan Palmer Upper School
7th grade Integrated Science class and 9th grade biology
Introduction to Ceramics, 3-D Art, and Glass
Fun fact: was tracked down and offered a job this summer while she was in South Africa
Fun fact: has done a project involving a football post at the Upper School
graphic by Ingrid Chang and Mary Rose Fissinger
all photos Nathanson’s/Chronicle
Eatures F the
Chronicle Volume XX Issue I Aug. 31, 2010
Besides sunning on the beach and sightseeing in museums and ancient ruins, summer globetrotting took students to farflung places to attend expos and sporting contests. B6-B7
Shanghai Los Angeles
Barcelona
Johannesburg
B2 Features
Aug. 31, 2010
The
Chronicle
The Hijra
Muslim students who observe Ramadan have to fast while playing varsity sports.
balancing act
By Sade Tavangarian
“I don’t get treated differently, the coaches are aware so I do take breaks every now and then, but it’s pretty much the same.” Fateh also participated in Hell Week, which also overlapped with the Ramadan calendar this year. “It [Ramadan] was truly a whole new meaning when it came around this year because the calendar goes back every year depending on the moon. This year it went back 11 days and hell week made it a lot harder to fast, which is why my coaches decided it was not best for me to sleep over during Hell Week so I can get rested, eat at 4 a.m. , and get ready for practice,” said Fateh. “The coaches have been really supportive about my situation. It is also helpful because my best friend Adel has basketball training so we hang out a lot during this time. It is easier when you have someone else in the same situation as you. My family also fasts with me.” Aside from playing football, Fateh prays five times a day. “It is good that you fast but you also have to pray. When you pray more it helps purify people and allows you to do better deeds.” Kamal also fasts during basketball training. The point of Ramadan for him is to learn about patience and humility. —Adel Kamal ‘11 “I try to make a point that it shouldn’t be a handicap. They understand that and naturally they give lenience towards what I do. They don’t give up on me,” Kamal said. He has been fasting every year since he was seven and finds it easier now because his entire family joins him. “It’s part of your religion. It’s not optional unless you are sick and it shows dedication,” Kamal said. He fasts for 30 days from sunrise which is about about 4:307:45 a.m. until sunset at 7:45 p.m. During the day you must reframe from food and drink, pray, avoid profanity, and stay on the right path,” said Kamal. Kamal believes fasting helps him in basketball training because in comparison to when he is fasting, the season feels so much easier. “Once you fast you can’t do anything about it. You have to fight through it. It is the time to bring goodness for yourself and focus on your religion and drain out distractions,” Kamal said. “People think it’s a grueling experience, but its not that bad. You try to keep your mind off it. I think of it as missing lunch,” Kamal said.
I
t’s 100 degrees Fahrenheit outside and the football team is practicing during their second “two a day.” As the team breaks for water after practicing a play, something appears to be wrong in the picture. All the players run to take a water break while one player watches his teammates quench their thirst in the hot summer sun. In fact, he can’t eat or drink any substance from sunrise to sunset because he’s fasting for Ramadan. Shortly the break ends, and as the football players begin their new play, his teammates look at him in awe. Noor Fateh ’11 and Adel Kamal ’11 are both devout Muslims who celebrate Ramadan and happen to have varsity sport practices during their time of fasting. Ramadan is the ninth month of the Islamic C a l e n d a r, —Noor Fateh ‘11 also called Hijra, and is a 30 day period during which Muslims fast from sunrise to sunset. Fasting includes refraining from eating, drinking, and sexual relations. Ramadan began on Aug. 11 and ends Sept. 9, clashing with Fateh’s intensive football training and Hell Week and Kamal’s basketball training. Fateh’s typical morning schedule includes waking up at 4 a.m. to eat a big breakfast his mom prepares. He eats and drinks, and prays, and becoming fully hydrated to start an early morning practice. “It’s been over 100 degrees on the field and I can’t have any liquid so the trainers help me out by giving me a lot of wet towels to cool down. The trainers understand my situation and are a big help,” Fateh said. “I thought I would get lightheaded or quit, but I’ve been keeping up and I’m staying strong so far. It’s a good feeling you went the whole day without eating or drinking because you’ve held it throughout the day,” he said. Fateh set a goal to push himself this year and practice Ramadan the full 30 days. He started to fast around the age of 10, but due to his intense sports schedule it has been tough to follow through. However, Fateh said, “now I realize it’s important that I do this because it is an important time of the year for Muslims.” “Last year when I fasted during Ramadan I struggled. I did it for two weeks then I gave in. The point of Ramadan is to teach patience and I thought it was important for that I could fast the full 30 days this year to teach me what I had strayed away of last year,” said Fateh.
“
It’s been over 100 degrees on the field and I can’t have any liquid.”
“
Once you fast you can’t do anything about it. You have to fight through it”
Ramadan:
the breakdown This year Ramadan began on Aug. 11 and will end on Sept. 9.
<<
Ramadan, also called Hijra, is the ninth month of the Islamic Calendar.
<<
Eid ul-Fitr marks the end of the fasting period of Ramadan or the end of the lunar period. Eid ulFitr means the Festival of Breaking the Fast.
Most Muslims fast for 30 days. Fasting includes refraining from eating, drinking, and sexual relations from sunrise to sunset.
Iftari, a big evening meal with extra sweet and savoury foods, but still a balanced diet, is served after the sunset prayer.
<<
Food is donated to the poor. Everyone puts on their best outfits. Communal prayers are held during Eid ul-Fitr.
<<
<<
Fasting is intended to teach Muslims about patience, humility, and spirituality.
Praying is a vital component and Muslims have to offer more prayer than usual. Infographic by Sade Tavangarian Source: Ramadan awareness campaign
Aug. 31, 2010
Features B3
The
Chronicle
johannessen courtesy of Martine
courtes y
an of Jonath courtesy
of Sabr ina Isk anda
Iskandar
r
Keith Leon a from View po
rd III ’13
int School Interests : football “I felt tha , basketb t Harv all a better fi ard-Westlake wa s t fo r m e as I am intereste d in spor ts w hile still having g ood acad emics.”
ar ’13 Jonathan IskanScdhool Mirman
from tics, fencing Interests: robo rent and s] is very diffe “[The campu ts of stairs.” big and has lo
court e sy o f Ada m gro ss
courtesy of theo mies se
Adam Gro s
from Oakw
s ’13
ood Schoo
Interests l : guitar, basketb “I’m look all ing forw ard to meeting new peo ple.”
court esy of Sarah
ing
sperl
marko witz
Micah esy of
court
courtesy of Niki Zoka
HELLO
my name is...
(returning)
Jeffrey Bu ’12 igh School from Arcadia H
nnis Interests: te has a more e] ak tl es “[Harvard-W on and a ti la t popu open studen vironment.” healthier en
Chronicle
The
B4 Features
Aug. 31, 2010
Jordan Freisleben/chronicle
courtesy of Jordan Freisleben
Jordan Freisleben/chronicle
Jordan Freisleben/chronicle
shaky grounds: A memorial to a victim of the earthquake in l’Aquila lays in front of rubble (at top). Freisleben ’11 conducts an interview with a victim’s advocate (at right). The now vacant quarter of l’Aquila once housed 20,000 residents (below). A tower is under construction after damages from the quake (above). An Italian flag hangs over a hole in the wall of a building with the phrase “Jemo ’nnanzi” meaning “We keep moving forward” (center). Jordan Freisleben/chronicle
Remembering
a forgotten town
By Camille
de
Ry
Winner of the Junior Summer Fellowship award, Jordan Freisleben ’11, left L’Aquila, Italy in June with the devastation of an earthquake pulling at her heart’s strings. More than a year and a half after a 6.3 Richter scale earthquake hit the small town of l’Aquila in the region of Abruzzo, Freisleben found it still in shambles, filled with rubble, debris and with little to no building efforts made since the earthquake. Tens of thousands were still left homeless and the majority of the city was closed off, Freisleben said. Every year the school rewards one student a grant to travel to a destination of his or her liking to explore a topic of choice. Freisleben, who was interviewing residents to create an investigative report on the aftermath of the quake, stayed in a small hotel in l’Aquila. She was the only tourist staying in the 50 room hotel. The others were displaced residents whose stay was subsidized by the government. Arriving with her camera, laptop and suitcases, Freisleben barely had enough space in the tiny little room for herself and her stuff, she said. “Can you imagine the displaced residents living there? With a family? It was heartbreaking,” Freisleben said. The historic center of the town was demolished. Only one street remains open. The heart of the center, the main plaza in the historic part of the town is partially closed off, Freisleben said. Freisleben interviewed several Italians who were affected by the earthquake. Some were left without a home and living in small pensiones, which are small hotels. Her subjects varied from local officials to university students.
Junior Summer Fellowship winner Jordan Freisleben ’11 found no signs of recovery in a central Italian village more than a year after a catastrophic earthquake.
One of Freisleben’s subjects was a journalist who was a student when the earthquake hit. She was left with no personal belongings; she was forced to leave everything behind, running out of her home at 3 a.m. wearing pajamas. Freisleben interviewed a 17-year-old student whose house was demolished in the earthquake. No one has made an effort to help give him a home, and Freisleben met him while he was protesting local officials by himself. Another compelling interview was with another young Italian subject who is a victim’s advocate. This organization is against the government’s lack of help and action in Abruzzo; they take in displaced residents in order to advocate on behalf of the people to work towards getting people housing instead of waiting around for the government who has neglected to help. Dissatisfaction among the people of l’Aquila is universal, Freisleben said. Freisleben explained that the government’s lack of response in l’Aquila is due to the lack of initiative to rebuild the city. With little tourism and no historic structures that receive money from tourism, l’Aquila is not a priority in the government’s eyes, she said. “Italy is not a third world country, so you would think the disaster could be handled in a smaller amount of time,” Freisleben said. Compared to other parts of Italy, Abruzzo is regarded as one of the poorer regions of Italy simply because it doesn’t garner tourism. One of Freisleben’s interviews revealed that Italians do not believe that they can count on other countries for aid when their own country will not help victims and rebuilding. People were living in tents for months after the earthquake and there was inefficiency in housing.
“The main question became to find a united effective way to overcome the aftermath,” Freisleben said. If this were Florence, the situation wouldn’t be like this – l’Aquila isn’t known at the international level, people pushed it aside, said one of her interviewees. “Even Italians say, ‘Where is l’Aquila?’ because they forgot it ever happened,” Freisleben said. Freisleben said many residents suffered from post traumatic stress disorder because of the devastation. “Older and middle aged people have worked their entire lives and lost everything with no way to recover it,” she said, “They feel anger and frustration as they continue to be ignored by the media. A year and a half has gone by and the region continues to look as it did on the day of the earthquake. People aren’t sleeping, some are sleeping fully clothed with fear they’ll have to get up and evacuate.” Leaving the small town, Freisleben said she felt a lot of guilt. She said she had acheived her goals; however, leaving a town in shambles with crushed buildings, crushed schools, no culture, no economy, to return to a beautiful school, an undamaged home, a personal room, left her upset. “People have lost everything – their home and families – I’m coming back to my family and my home without any problems,” Freisleben said. What she called the most culturally enriching experience in her life left her wanting more. Freisleben wants to go back to Italy as soon as possible. With arguably no money to rebuild, Aquilani say it’s a political problem that plagues l’Aquila. Freisleben plans to advocate political awareness and continue her efforts to help the devastated town that touched her heart forever.
Aug. 31, 2010
Features B5
The
Chronicle
High Stakes By Catherine Wang
Meet Zoe*, one of five seniors ready to share her tale of the college admissions process to Chronicle readers in the next eight issues. Zoe has wanted to go to New York University since she was seven. She will apply to the university’s Tisch School of Arts. She has a clear career path in mind – one she will pursue regardless of the school she ends up attending. She has attended summer programs related to this career for the past two summers, and she hopes her passion will be evident to NYU. When asked what draws her to NYU, she replied: “the location. There are lots of resources available, and I can be inspired by a lot of individuals.”
If Zoe is not accepted to NYU in the early pool, she will apply to a number of urban schools that have strong arts programs, including University of Southern California, Chapman University, Emerson University and Loyola Marymount University. During the summer, Zoe began working on her college essay. Tisch School requires supplementary materials, including a portfolio, so she will be busy compiling her work over the next two months. “Of course I’m really nervous [about the college admissions process], but I think everyone is. I just want to know where I am going to go, so I’m excited about that.”
Carter:
the Brain
As of now, Aiden* does not want to apply to any school early. “There really isn’t a school that stands out to me as a best choice,” he said. “I want to have more time to think about it. I don’t want to be tied down to any school.” Aiden’s academic interests include history and science, but his academic interests have not particularly affected his college search. “I’m looking at the school on a whole,” he said. He is interested in attending a large school “comfortably” close to a city. Location in the country is not a major factor to him. Schools he is interested in applying to include University of Southern California, University of Michigan, Northwestern Univer-
Alexis:
the Athlete Madison*, who describes herself as very “chill and relaxed” about the college admissions process, knows what type of school she wants to attend: small, diverse, strong in performing arts, and on the East Coast. Right now, she plans on applying to Wesleyan University early decision. Her intended major is a popular one at the school. “Everyone there has a great appreciation for the arts,” she said. Madison visited Wesleyan early in the summer and loved its rural location. “But I mean, it’s only an hour and a
Chapter 1: Five superhero seniors begin their missions to conquer the college admissions process, ready to battle the evil forces along the way.
Carter, who wants to major in applied math or physics, will apply early to Massachusetts Institute of Technology, California Institute of Technology, and University of Chicago, none of which are restrictive. The three schools all have strong math and science departments, and MIT and CalTech both have better acceptance rates for early application, he said. There are schools he will apply to regular decision that he wouldn’t consider “safeties,” such as Harvard, Princeton, and Stanford. Unlike Harvard and Princeton, Stanford does offer early application, but Carter does not like that it is restrictive.
Zoe: the Artist
“I guess I’m weird in the sense that I don’t care about a lot of factors,” he said. “The Jumbo Tour during spring break taught me that I could be happy at a school in any location or any size.” Carter has yet to decide what safety schools he will apply to if he does not get into any of the three schools. Asked about his thoughts on the college process, Carter replied: “I guess there’s this abstract entity looming over all of us that’s the college we want to apply to. We’ve never talked to this entity, we don’t know its desires or its intents, but we’re required to appease this entity.”
sity, and Duke University. University of Pennsylvania has caught his eye as well, but he considers it as a “reach” school. Aiden has a hand in many extra-curricular activities. He is a school club president, athlete, and a member of numerous school and non-school related organizations, including Model United Nations and Student Ambassadors. He has also held several volunteer jobs. But what Aiden hopes will set him apart as an applicant most is his ethnicity and socioeconomic background. Over the summer, Aiden began filling in the Common Application and brainstorming essay topics. “I’m just trying to find a topic that will get across who I am in one essay,” he said.
Alexis*, a high-level athlete, is being recruited by several Division I colleges. For her, what matters in a school is its athletics; she hopes to attend a school with a strong athletic program. She is also interested in studying sports medicine. “I want the school to really care about athletics, and that people are unified,” she said. Over the summer, Alexis sent e-mails and films of her playing her sport to various coaches. “Recently, coaches began being able to call us, so we’ve been talking,” she said.
half away from the city,” she said. As for safety schools, Madison is thinking about Syracuse University and Boston University, both of which have strong performing arts programs. She also has “connections” at both schools. “I would love to go to either of them,” she said. “I’m going to try really hard to get into the schools I want to go to, but I know I’ll be happy wherever I go.” Madison is looking forward to the college admissions journey ahead of her. “Everything is meant to be. I honestly believe that,” she said. “Where you end up – you have to embrace it.”
Aiden: All-around
Alexis is in contact with Emory University, Saint Mary’s College of California, and University of Maryland, Baltimore County. Alexis’s application process will differ greatly from that of most applicants. She has already taken unofficial visits to five schools, and in the fall she will take several official visits, meaning the school pays for the trip. She has already confirmed her trip to St. Mary’s and UMBC. “It’s stressful, but exciting,” Alexis said. “Hopefully, I’ll have signed a letter of intent in November and will be committed somewhere.”
Madison: the Performer
* names have been changed ILLUSTRATIONS BY MELISSA GERTLER
B6 Features
The
Chron
Worldwide spectator Courtesy of Jonathan Chu
Better City, Better life: Jonathan Chu ’12 visits the World Expo in Shanghai.
Cultures commune in China By Justine
goode
As a visitor to the Shanghai World Expo, Tiffany Liao ’12 was able to experience a global expedition over the course of few short days, and without leaving a site two square miles in size. During her visit, she sampled Peruvian purple corn juice, got a henna tattoo from Qatar, watched Tibetan monks dance, and even encountered a giant robot baby from Spain. The theme of the exposition is “Better City – Better Life”, and has an official theme song sung by Jackie Chan. Shanghai beat out cities in South Korea, Russia, Mexico and Poland to become the site of the 54th World Expo. With pavilions representing 192 countries and a projected 100 million visitors in total, the Shanghai World Expo bears the distinction of being both the most expensive and largest World’s Fair in history. Liao said that the most popular pavilions included
China and Saudi Arabia, the latter of which had a 12-hour wait time for those in line. Less popular with the crowds was the United States pavilion, which featured a video montage of Americans attempting to correctly pronounce the Mandarin greeting “ni hao”. Elaine Tang ’12, had the opportunity to volunteer at the Expo through a program sponsored by two Chinese universities. “All of the architecture was really cool, especially Saudi Arabia’s ‘moon boat’,” she said. Relics of past fairs can still be seen all over the world, including the Space Needle (Seattle 1962), Disney’s “it’s a small world” ride (New York 1964), and the Eiffel Tower (Paris 1889). Jonathan Chu ’12 preferred the UK pavilion, or “Seed Cathedral”, a building with 60,000 spikes jutting out of it from all angles. “Although it wasn’t the largest, the inside was spectacular,” said Chu.
Courtesy of elLA Marks
victorious: Hunter Stanley ’13 (left) and Jake Feiler ’13 (right) celebrate.
Joining Spain’s victory celebration By Caitie Benell Fireworks exploded in the streets as people ran through with flags held high, singing songs and celebrating all night long. A parade in Madrid, and parties all week long brought Spain to life just because of one victory. Many Harvard-Westlake students were in Spain during the Spanish National soccer team’s exciting success at the World Cup. Some were a part of the Oxbridge summer program and others on vacation. “The real celebration lasted all night and Spain was crazy for at least another week,” Hunter Stanley ’13 said. Spain’s celebrations became so extreme that students enrolled in the Oxbridge program had to stay inside their residence for the night. Because of all the excitement and people out in the streets, the administrators of Oxbridge didn’t want any of
their students to get injured or lost. However, just below their windows, they heard singing, honking horns and screaming. “Me and my friends opened up our windows and started cheering with random people driving down the street,” Mikaila Mitchell ’13 said. The students were able to resume their normal activities the next day, but parties still raged on for the entire week. “It just seemed like the whole city was excited and that even though the people weren’t all one, the city just felt more alive.” Jake Feiler ’13 said. Before Spain emerged as champions, people dressed up in jerseys and wore Spain’s colors to watch the game, which had been all anyone could talk about. “Spain celebrated for at least a week, but even after that there were posters and Spanish flags up all over the city congratulating them,” Jake Feiler ’13 said.
Features B7
nicle
rs
Summer travels center on sporting and entertainment spectacles all around the globe.
Comic-Con attracts many fans By Olivia Kwitny From programming and anime to the Independent Film Festival and games, the comic convention in San Diego, California lured over 13,000 fans, including comic creators, celebrities, gaming pros, and many Harvard-Westlake students. Students were excited to meet actors from their favorite shows. Timmy Weston ’11 said, “It was really cool to get to meet Vinnie Jones and Summer Glau.” The show’s guest lineup comprised some of the world’s most talented creators in the world of comics, ranging from the most in vogue to the international and allied branches of the industry. Some of the celebrities who attended the event were Angelina Jolie, Bruce Willis, and Tina Fey. “It was huge,” said Brian Harwitt ’11. “It took me 30 minutes to walk from one end to the other.” Some of the booths in what some call “Hollywood’s Geek
Week” included the ever-popular “Star Wars” booth, featuring characters from “The Clone Wars,” a Thor-themed one that had a larger than life throne of Odin and for TVgoers the ABC TV show “No Ordinary Family,” displaying a prop car with hydraulics underneath, so fans could get a picture of themselves lifting a sedan. “I really enjoyed the Vinyl Toy Booths, like Kidrobot, Munky King, Mega 64, and Super 7,” Justin Bretter ’11 said. “Being able to see the different TV show panels was awesome. Especially, my favorite TV show, “Psych”. One of the main characters in it even tap danced,” said Harwitt ’11. Alongside Comic-Con’s eclectic variety of booths and panels, the expo also featured an eclectic art show, where drawings, paintings, jewelry, and sculpture are present. It contains works of both amateurs and professionals. “It’s the perfect place for a teenage guy — video games, art, TV shows, comic, movies. I didn’t even know where to begin when I got there,” Weston said.
Courtesy of Hannah Lichtenstein
waka waka: Hannah Lichtenstein ’13 sits and watches a Netherlands game in South Africa.
Witnessing World Cup firsthand By Michael Rothberg
The roar of passionate soccer fans shouting and cheering echoed violently throughout the stadium on a chilly day in Johannesburg, South Africa. On the field, the opposing teams scrambled for control of the ball. Ty Gilhuly ’13 was watching the game intently, when suddenly one of the players took a wild shot towards the corner of the goal and scored. Instantly, all 50,000 people stood up and the entire stadium erupted into pandemonium. From June 11 to July 11, several HarvardWestlake students visited South Africa to attend the 2010 World Cup. Hannah Lichtenstein ’13, an avid soccer fan, attended both the 2006 and 2010 tournaments. “It was amazing. Even though everybody was
rooting for different teams, there was a positive energy in the stadium,” she said. After 23 exhausting hours of travelling, Gilhuly arrived in South Africa. He attended six games, his favorite being Brazil versus the Ivory Coast. “I have never seen anything like it. The fans were ecstatic and the players were phenomenal,” Gilhuly said. Coincidentally, Gilhuly ran into his soccer coach, Freddy Arroyo at one of the games. “Being in the stadiums during these games was electrifying! The atmosphere and euphoria from fans was amazing, especially with people blowing their Vuvuzelas [noisemakers] nonstop,” Arroyo said. “The World Cup was a great success and we were all lucky to witness it,” Gilhuly said.
gRAPHIC bY jOYCE kIM AND oLIVIA kWITNY
B8 Features
The
Making models By Claire Hong
M
Aug. 31, 2010
Chronicle
elissa Gertler ’11 spent hours building a cardboard chair, only to have it crushed by her class instructor. As part of the architecture program she attended at the University of Southern California, Gertler was required to make a chair with only cardboard that could withstand 150 pounds. To determine whether her chair passed the test, the instructors nathanson ’s/chronicle sat on it, trying to break it. Melissa Gertler’11 “Mine only somewhat survived,” Gertler said. Gertler was one of three seniors involved in architecture projects this summer. She spent two weeks in the program, working 11 hours a day: nine for architecture and two for drawing. During the program, Gertler went on two field trips with her class, where she visited renowned buildings such as the Walt Disney Concert Hall, the Bradbury Building, the Getty Center and LACMA. Gertler said she wanted to try out architecture because “in the middle of junior year, I realized that I had absolutely no idea what I wanted to study in college.” Gertler said that she had always been interested in art and so decided to sign up for the summer
Working in the architecture field during the summer gave three seniors a different perspective of the possible career option. COURTESY OF BEN KOGAN
program at USC. Although she plans to keep her options open, the program convinced Gertler to apply to most colleges to major in architecture. Ben Kogan ’11 learned about Chicago’s architectural history as an intern this summer at the Chicago-based firm, 4240 Architecture. His internship lasted for four weeks, during which he worked 10 hours every week day. His first few days were spent making small nathanson ’s/chronicle changes to building blueprints in AutoCAD, software created for Ben Kogan ’11 3-D design. The majority of his time was spent working on a scaled architectural model. He was responsible for creating parts of the model, such as the walls and windows, based on a set of drawings. Kogan’s interest in applied sciences, design and visual arts persuaded him to look into architecture, which incorporated all three subjects. His trip to Chicago spurred on his interest in architecture. “My experience this summer has given me a new appreciation for buildings,” he said. Although he is still undecided in his career choice, he said architecture will be an option. Looking back at his experiences, Kogan believes his favorite moment was when he asked one of the architects what interested him in the field.
“His hands became animated as he talked,” Kogan said. “He seemed to be shaping the air into buildings with his fingers at the same time he was explaining how architecture is the transformation of ideas into concrete, tangible forms.” Luna Ikuta’s ’11 love of art led her to explore architecture. She nathanson ’s/chronicle attended the Otis College of Art and Design’s Summer of Art pro- Luna Ikuta ’11 gram, specializing in architecture. “I wanted to try it because I love art and I’m good at math, so I thought architecture could be a good fit for me,” she said. The program was held in July and classes were seven hours a day. The program featured both architecture and drawing classes. “It was my first time taking drawing lessons, and I ended up really getting into it,” she said. In her architecture class, Ikuta created floor plans and sketched elevation plans based on her building designs. She also built models of her building. Three projects that were assigned to her were to build a kiosk, a beach club and a skyscraper. Ikuta said she loved the program and that it will definitely influence where she wants to attend college. “It was great to discover something that I never knew I loved,” she said.
Trying out military life By Mary Rose Fissinger At 4:30 a.m., Rachel Katz ’11 woke up to a piercing horn blowing outside. However, she was not alarmed in the slightest. She had been awakened in a similar manner every day for a week now and knew what to expect. As she rose, dressed in the appropriate uniform, made her bed, and arranged herself in the stance mandatory for morning inspections, the yelling started. “Cadet candidates, have you conducted hygiene, are your shirts tucked in, hospital corners made? I’m coming in whether you’re prepared or not!” Moments later, a sergeant entered through the door, and conducted a thorough inspection of Katz’s uniform, stance and room. Once she passed the inspection, her day could officially begin. Katz was one of three seniors who spent the summer at a military academy. Though not your traditional summer vacation, Katz found her one week stay at West Point, also known as the United States Military Academy, to be an amazing and enlightening experience. “There was a part of it I absolutely embraced,” she said, “and I enjoyed the challenge. It was incredible.” Katz has been interested in applying to West Point for college for some time now. The application process began in December of her junior year, and differs greatly from the average application. There are “rounds of elimination,” as she referred to them, and, after a few rounds, the remaining applicants (roughly 10 percent of the original pool, she said) are invited to the summer program where “you live the life of a cadet for a week,” she said. Mitchel Oei ’11 and Catherine Wang ’11 had a similar experience this summer, each spending a week at the United States Naval Academy at Annapolis. Oei learned of the program through a friend, and Wang was drawn to it through a brochure the Academy had sent her. “There was an astronaut on the cover, and I want to be an astronaut,” she said, laughing. Katz, Oei and Wang all had similarly structured days. Early wake up calls, meals, classes, study hall, exercising, and the occasional field trip or speaker. “There is no down time whatsoever,” Wang remarked. However, that did not seem to bother any of them. “It kind of seems intense, but overall it was a really enjoyable experience, and the programs
“
before, i didn’t even know anything about the armed forces, let alone the navy.”
—Catherine Wang ’11
were really interesting,” Oei said. His classes were mostly math or science related, including an ocean engineering class in which he learned how to build structures in the water. For his oceanography class, he recalled, one day his class went out to the Chesapeake Bay on a patrol boat and took water samples to analyze. After their experiences, both Oei and Wang are planning on applying to the Naval Academy. While Oei had considered this as a possibility before, it was a completely new idea for Wang. “Before, I didn’t even know anything about the armed forces, let alone the Navy,” she said. To be admitted to the Naval Academy, a student must show aptitude and promise in the three areas of the Academy’s triple mission: mental, moral, and physical. In addition to submitting grades, test scores, and essays, prospective students must pass a physical exam of two parts. Wang’s decision to apply is a testament to how fully the summer program affected her. She had applied for the summer program simply to broaden her horizons. “I thought I’d never have the opportunity again, and I wanted to see how these people live,” she said. Katz’s experience at West Point also helped to broaden her horizons, but with different consequences. Despite her positive experience this summer, she is now unsure if West Point is the right college for her. “I’m more conflicted… Some truths were brought to light that I had deluded myself into obscuring from view,” she said. She now must decide between West Point Academy and a small liberal arts college, the other setting she knows she would enjoy for the next four years. “I know whether I end up there or at a liberal arts college, something in me won’t be satiated,” she said.
COURTESY OF RACHEL KATZ
Attention: Rachel Katz ’11 (left) stands with her squad and sergeant during her stay at West Point over the summer.
Keeping military time
Rachel Katz’s ’11 schedule at West Point
0430 0445 0500 0615 0730
Reveille
The wake-up call is played on horns.
Room check
Sergeants inspect the cadet candidates’ rooms and uniforms.
Physical training
Cadet candidates complete obstacle courses and run.
Breakfast Formation
Roll call is taken and the cadets salute and stand in units.
0800
Morning seminars
1200 1300
Lunch
1630
Afternoon seminars Military training
Cadet candidates practice throwing grenades and shooting.
1800 2000
Dinner
2100
Intramural sports
2345
Taps
0030
Lights out
Study hall
Trumpets sound to end the day. SOURCE: RACHEL KATZ GRAPHIC BY ALLISON HAMBURGER AND CLAIRE HONG
Aug. 31, 2010
A&E B9
The
Chronicle
photos Courtesy of Christopher Moore
JAZZ HANDS: Ariana Lanz ‘13 rehearses for a class performance.
Stage fright: Students from all grades who participated in the Summer Intensive Acting Workshop gathered
Taking the stage
By Jessica Barzilay
and
Luke Holthouse
Standing in front of 24 of his peers, Noah Ross ‘12 leaned in to give his friend Daniele Wieder ‘12 a kiss. Summer romance? No. Summer Intensive Acting Workshop? Yes. Twenty-six Harvard-Westlake students participated in the Summer Intensive Acting Workshop, a three-week program held in Rugby Theatre in addition to the Dance Studio, Drama Lab, and several classrooms in Rugby. The main directors of the program were Chris Moore, Upper School Performing Arts teacher, Rees Pugh, Upper School Performing Arts Department Head, and Daniel Faltus, Director of the upcoming Upper School musical, Pippin.
for a group picture after three weeks of experimenting in and learning about all different forms of performance art.
26 take a final curtain call for the Summer Intensive Acting Workshop.
A total of 28 students and 31 instructors, directors, and teachers were a part of the program. From 9 a.m. to 4:30 p.m. every Monday through Friday, students participated in over 20 different workshops practicing theater skills such as stage combat and wordless communication. The program featured two evening theater field trips. Students saw “The Lieutenant of Inishmore,” a comedy about an Irish terrorist trying to avenge the death of his cat, and “The Importance of Being Earnest,” the story of a man living a scandalous double life. The students also put on two productions over the course of the three weeks, putting their new skills to work.. The first of performance on July 9 presented 13 different scenes or short plays , and the second on
July 10 showcased the 20 different workshops. For some students, one of the highlights of the program was the opportunity to branch out socially in a way that only the intensi-ve acting workshop would allow. “One of my favorite parts was spending a lot of time with people I wouldn’t normally hang out with,” Olivia Schiavelli ’12 said. Other students enjoyed experimenting with different forms of performance art. For example, Daniele Wieder ’12 dabbled in styles she had never before tried, such as the Fosse style of dance. “I got to figure out things I really like in theater and even the things I didn’t like as much I got an appreciation for,” she said.
Music fills hills at Idyllwild Arts By Alex Gura
Courtesy of Starr Wayne
Orchestrating Art: Laurel J. Wayne ‘13, May Peterson ‘13, Emma Peterson ‘11, Leah Shapiro ‘13, Anna Wittenberg ‘13, Lizzie Pratt ‘11, Meghan Hartman ‘12 and Jake Chapman ‘12 (from left) studied at camp.
Campers call Interlochen ‘life-changing’ By Nika Madyoon It started as a shaving cream fight. One thing led to another, and paint was being flung every which way. Everyone was bathed in color, running back and forth and screaming at the top of their lungs. It turns out students do more than practice music at band camp. It seems that no matter who you ask, a summer at Interlochen Center for the Arts in northern Michigan is described as the best summer of one’s life. Many memories like this one, recounted by Lizzy Pratt ’11, were made this summer at Interlochen in northern Michigan. The world-renowned camp, which attracted students from 49 states and 46 countries this year, provided an unforgettable experience for the 11 Harvard-Westlake students who attended. The camp is known for its high caliber and intensity and also for its ability to make artists of every field better at and more passionate about their skill. Middle School Performing Arts teacher Starr Wayne, who spent six summers at Interlochen as a student and accompanied students there this year, regards the institution very highly. “In the world of classical music, it is the premier educational summer program in the country for middle and high school students.
The level of every art—music, dance, theater, creative writing, film, and visual arts — is unbelievably high,” she said. She enjoyed this summer especially because she was able to see her students soak in the experience. Upper School Performing Arts teacher Shawn Costantino attended Interlochen as a student the summer before his senior year of high school. “To me, Interlochen was one of the most life changing opportunities I’ve ever had. I was around great musicians, many of whom were better than me and I gained a large exposure to college recruiters that until that time had never heard of me,” he said. According to the Interlochen website, “Each summer, 2,500 students come to Interlochen to train intensively with renowned instructors, producing more than 400 presentations in music, theatre, dance, visual arts, creative writing and motion picture arts.” Pratt has been spending her summers at Interlochen since sixth grade, almost always focusing on playing the bassoon, although she did try a creative writing program one summer. Meghan Hartman ’12 also had only good things to say about her summer at Interlochen. The three summers she has spent there have dramatically improved her
technique and ability in playing the cello. “The teachers are absolutely incredible and so accomplished and really help develop my technique and tone,” Hartman said. Interlochen always kept Hartman busy and on track. Hartman explained that playing music with others was a one-of-a-kind experience that allowed for the development of strong bonds between friends. “You really do develop a close bond between people because you’re playing music together and sharing your emotions and thoughts while playing. It’s really unique to communicate via music,” she said. This artistic means of communication was particularly useful when it came to associating with the international campers who didn’t speak English very well. said Hartman. She joked that her only complaint was the excess of mosquitos and bugs at the camp. “The things you learn about your passion for arts and music are beyond anything I can explain verbally. It is truly one of the most amazing and special places on earth,” Costantino said. It’s no wonder that Pratt saw an auditorium filled with bawling students once the final concert, Les Preludes, came to a close. “None of us wanted to leave,” she said.
From performing in Broadway musicals to playing Baroque classics, upper school students participated in a variety of musical and theatrical subjects at Idyllwild Summer Arts Camp. This year, nearly a dozen students from Harvard-Westlake attended Idyllwild where Rodger Guerrero, Upper School Vocal Director, was one of the seven conductors for the Idyllwild High School Choir. Students including Sophia Penske ‘13 and Eric Slotsve ’11 said their skills were dramatically improved after attending Idyllwild. “Spending the two weeks singing with Chapman University students helped me with pretty much everything about singing,” said Slotsve. “I picked up techniques that they were teaching and my sight singing skill went up quite a bit.” Slotsve first learned of the camp in an e-mail from Nina Burtchaell, Head of the Middle School choir, during the summer between freshman and sophomore year. “Since I loved being in Madrigals that year, I looked into it and it seemed like a really neat thing to try out” Slotsve said. Slotsve ended up joining the high school choir program at Idyllwild and has been attending for the past two summers. For Penske, it was the content that drew her to the program. “We would dance in the morning until 12, have lunch, sing until five, have dinner, and then sing for another hour,” Penske said of her daily schedule. She said the final show, which included selections from a compilation of musical numbers, such as “Shrek the Musical” and “The Lion King”, was her favorite part of the camp. For many, though, the Idyllwild experience was primarily about the people. “You get to bond with kids around your age from all over the country, and out of the country, on the basis of a love for music,” Slotsve said. One of the best things about this year’s choir, according to him, was its small size. Though usually made up of about 150 kids, this year the choir included around 100 choir students, and fewer college students this year. For Hannah Schoen ’12, it was the attitude of the kids that shone. “All the kids gave their best and were so into it,” she said, “even the ones that weren’t as talented had something to contribute.”
B10 A&E
Aug. 31, 2010
The
Chronicle
LIVE
from the Oak Room
Hank Adelmann ’11 and Jordan Bryan ’11 perform a live show with their jazz group in Pacific Palisades.
By Joyce Kim
[Shawn] Costantino who has given us the experience of playing at local restaurants like Drummer Jordan Bryan ’11 and bassist Vitello’s and Vibrato as part of our school Hank Adelmann ’11 performed in their first combos over the past few years.” jazz show at the Oak Room in the Pacific Bryan credits landing the job to a comPalisades last Wednesday. bination of his mother’s promotional skills “Without a doubt, it was the best experi- and owner of the Oak Room Jansen Lashence of my summer and recent life,” Bryan ley-Haynes’ generosity. Bryan had sent in a said. recording of the group, and Lashley-Haynes Bryan and Adelmann were joined by pia- offered them the date. nists Isaac Wilson and Micah Gordon, both “These kids rock. We actually had the students at Windward School. best night in nine months,” Lashley-Haynes “Everybody in the past couple of months said. has really stepped it up to a new level. Jordan, When it came to choosing a set list, the Micah, and Isaac are musicians were already some of the best mufamiliar with a number sicians I know, which of widely known songs, These kids Rock. made playing live mostly from a collecWe actually Had the tion of jazz songs called music with them exhilarating,” Adelmann the Real Book. ThereBest night in Nine said. fore, one rehearsal was The first gig was sufficient for their two Months.” such a success they a half hour show. —Jansen Lashely-Haynes, and“Basically have been rehired to Real owner of the Oak Room Book tunes make up play at the Oak Room the third Wednesday the bread and butof every month. ter of a jazz set because one really only has “Due entirely to our wonderful supporters, the right to call themselves a jazz musician the Oak Room reported the best Wednesday if they know a fair amount of these songs,” night business they have had in six months, Bryan said. so I believe that is a huge part of our getting Most of the songs performed were by jazz rehired,” Bryan said. “Going into the school musician Miles Davis. year, we obviously don’t expect those kind of “We played a lot of jazz standards, some numbers on a consistent basis, but it was a with twists, we all love these tunes and have great start and we’re going to try to keep a all played them many times before,” Adelsteady flow of people coming into the restau- mann said. rant in the coming months.” In preparation for future shows, “we’re Although the show was not affiliated with looking forward to expanding our set list the Harvard-Westlake Music department, and exploring more complex arrangements Bryan said, “I have to give a lot of credit to in future shows,” Bryan said.
“
joyce kim/chronicle
Rehearsal: Jordan Bryan ‘11 and Hank Adelmann ‘11 prepare for their performance at the Oak Room in the Pacific Palisades.
‘Pippin’ auditions to start Thursday By Emily Khaykin
courtesy of cyndy winter
native beats: Margalit Oved sings and drums for attentive dancers at the Summer Dance Intensive.
Dance Magazine covers summer workshops taught by internationally acclaimed performer By Jessica Barzilay Internationally acclaimed dancer, choreographer and singer Margalit Oved performed a collection of her ethnic dances at the Summer Dance Intensive July 27, as a reporter from Dance Magazine looked on. The magazine contacted performing arts teacher Cyndy Winter in order to catch a glimpse of Oved, Winter’s former teacher, at work. Oved led workshops at Winter’s yearly summer course, a program she has been running for several years and one that features a multitude of other elite guest artists. Winter works all year to recruit a variety of “the most talented and interesting dance artists” for the Summer Dance Intensive, she said. This year’s program represented styles as diverse as Yemenite, African, Urban Latin, salsa, capoeira, modern and contemporary, each taught by different guest specialists. “I believe that the more styles and philosophies of dance young dancers are exposed to the better. Opening their eyes to new ways of moving and thinking
about dance, dance artists, and the world is important to their growth as performers and choreographers,” Winter said. Oved first dabbled in the field of Israeli folk dance, before touring the world as the Inbal Theater Company of Israel’s prima ballerina. After dancing in such venues for 15 years, Oved began what would become a 22 year career as a lecturer for modern and ethnic dances at the University of California, Los Angeles. She both taught students in the classroom and choreographed pieces for the university’s dance company. Later on in her career, Oved appeared in films as a guest dancer before debuting her one-woman show, a four-part experience comprising of dance, theater, and music. Following the overwhelmingly positive press response to this show, she founded the Margalit Oved Dance Theater Company, the enterprise responsible for first introducing her to Winter. Winter toured internationally as the lead dancer at Oved’s company for many years. Even after her stint with the company Winter continued to dance with Oved, whose career as an artis-
tic director and artist took her all over the world, from Israel to Europe to the United States. A writer from Dance Magazine approached Winter and requested permission to observe Oved at work teaching the students at the Intensive. Oved shared a selection of her ethnic dances from her time with the Inbal Theater Company, as well as performing pieces on the drum as she sang. She also recited a portion of her acclaimed ballad “Through the Gate of Eden.” Oved’s son, Barak Marshall, whose company performs around the globe, taught the afternoon session as well. “She is really inspiring and she has her completely own style,” Fredel Romano ’11 said of Oved’s lessons and performances. The reporter was impressed with the students and the Intensive, and she expressed interest in returning. The article featuring Oved will likely run in the October issue of Dance Magazine, a publication circulated throughout the dance world since 1927. “She is a great treasure and I am so happy that my students are able to experience her both as artist and as teacher,” Winter said.
Auditions for the fall musical, “Pippin,” will begin Thursday in the choral room and dance studio. Audition materials are available on the Performing Arts Department website at. The show will go up in Rugby Auditorium the first weekend in November. The musical “Pippin” centers on a young man who is at a crossroads in life. A recent graduate of the University of Padua, the young man, Pippin, forgoes future academic study in order to go on a journey to find, as Pippin says, “something fulfilling” to do with his life. Yet, Pippin is actually Prince Pippin, the son of Charlemagne. Although the musical does not actually take place in ninth century Rome, the time period serves as a metaphor that continues throughout the production, the ordeals and choices that Pippin undergoes in his journey could apply to any time period. The story is told in a theatrical sense, with a group of players, or actors, and a narrator following the main characters throughout the musical. “‘Pippin’ has long been on our list [of musicals] over the years,” said Performing Arts teacher Ted Walch, who is also co-director for “Pippin,” “After much discussion with other members of the Performing Arts department, especially co-director Michele Spears, we decided to do it.” The show’s music and lyrics are by Stephen Schwartz, and the book was written by Roger O. Hirson. This year Daniel Faltus will serve as music director for “Pippin,” having also been music director last year for “City of Angels.” Faltus is both a well-known pianist having played at the Kennedy Center, Radio City Music Hall, and Lincoln Center’s New York City Opera, among other places, and experienced vocal coach and an actor. “I love the show,” Kathryn Gallagher ’11 said, who is planning to audition for the roles of either Catherine or Fastrada, “It’s different, and although I definitely enjoy more contemporary shows, as I was listening to the music more and more, I think it was a really great choice.” “I think it is best summarized this way,” Walch said, “when you’re young and green, the world looks easy and ripe for exploring; as you actually face that world, you find that it’s not as easy and breezy as you thought. When all is said and done, all you have is you.”
Aug. 31, 2010
A&E B11
The
Chronicle
Sculptor makes waves with linear glass pieces By Ingrid Chang Visual Arts teacher John Luebtow describes art as a lifelong philosophy; he has been working on his Linear Form Series for 35 years. One of his pieces from the series was chosen to be displayed in front of City Hall in Napa, California as a part of a government-funded program to promote public art. Another series of his called Ode to Friedrich Froebel was displayed this summer at the Museo Gallery in Langley, Washington. Luebtow’s piece from the Linear Form Series was chosen to be one of 10 in the public art program. The 12-foot tall sculpture was made from a steel I-beam and bent glass that he shaped in a 1400 degree kiln. The piece is a part of a series in which he explores the concept of how “line defines form and form defines line,” Luebtow said. “I started with drawings from the female
nude. There is a contour line, and I made sculptures that deal with that shape,” said Luebtow. “The other parts of the forms create lines too, so I would take that line idea and make sculptures looking like that by bending glass.” About a dozen of Luebtow’s pieces from his Friedrich Froebel series were on display at an invitational exhibition for glass artists at the Museo Gallery. They are all glass sculptures that he made over the course of the last three years. The series is an ode to Friedrich Froebel, the man who is credited with inventing kindergarten and changing childhood education as well as influencing abstract art with his breakdown of basic shapes and color. Luebtow’s work in the Museo Gallery was on display for the month of July. His sculpture in Napa is being exhibited from July 2010 to July 2011.
john luebtow
glasswork: One of Luebtow’s many sculptures was chosen to be displayed in front of City Hall in Napa, California until July 2011.
Popp prepares for collaborative show By Nick Pritzker
nika madyoon/chronicle
Visual Arts teacher Nancy Popp will exhibit one of her art installations at Cal Poly Pomona on Nov. 9. Her art will be exhibited at the W. Keith and Janet Kellog University Art Gallery, which exhibits art from students at the university and art from communities in the greater Los Angeles area and surrounding Pomona. She was invited to exhibit her art by the curator of the gallery, John O’Brien, who taught her when she was getting her bachelor’s degree from the Art Center College of Design in Pasadena. “It’s actually really nice to get invited by someone who already knows
my work,” she said. The art show is called “Crisscrossing” and will feature artists who create collaborated exhibits. Popp said she knows most of the people who have exhibits in the show because they are friends, former teachers, and former classmates. “It is really exciting to work with people who you admire, respect, and care about,” she said. Popp is collaborating with her friend and colleague of seven years, Denise Spampinato, who Popp says is “super brilliant.” Popp said that she was especially excited to work with Spampinato because they “approach the same subjects from really different
perspectives.” Popp and Spampinato have been working on their exhibit since March. Popp said that they both work with urban space, or “the space of the city” to make their art. “I hope to use the gallery in the same way that I would use the city,” she said. They are building a large installation with multiple parts. Popp wants to cut out text from photo paper with a laser cutter, she said. “It should be text that is meaningful and binds our work together,” Popp said. They have been reading philosophy to find text that binds them together.
Teacher completes same assignment as students By Jordan McSpadden During the Summer Film Camp, Upper School Visual Arts Department Head Cheri Gaulke decided to do the same exercises that she assigned her film students, so she wrote a screenplay for a short film titled “Knowing Poppo.” “I think it’s important that teachers do what they ask their students to do and this was me doing that. As an artist I don’t usually make narrative films. I work more experimentally, so this was a new experience for my own work,” Gaulke said. Gaulke said the film is “about a teenage girl that goes to stay with her grandfather after her grandmother passes away. The
grandfather is deeply depressed and the girl must use her wits to bring him out of his depression.” “Knowing Poppo” was inspired by Gaulke’s recent family events, revolving around the unexpected death of her mother-in-law. The short film was shot in 13-1/2 hours at Gaulke’s father-in-law’s house. Gaulke plans to enter her film into many film festivals. During the film camp, Gaulke and John Glouchevitch ’06 produced four student films from screenplays that were written in their program. In addition to these four films, she imagines that more students’ films will be produced in classes this upcoming
school year. Gaulke’s partner, Sue Maberry and her daughter, Marka Maberry-Gaulke ’12 were the producers of the short film. Her other daughter, Xochi Maberry-Gaulke ’12 co-starred alongside professional actor Ray Guth. Gaulke also hired Joe Sill, a young cinematographer whom she first met two years ago when he attended Irvine High School and his music video was chosen for the Harvard-Westlake Film Festival. Sill now studies film at Chapman University. “John is an amazing screenwriter, teacher and facilitated a number of amazing scripts this summer,” Gaulke said. nika madyoon/chronicle
Chronicle
The
B12 Features
Aug. 31, 2010
Brushstrokes: Three of Rosenberg’s preliminary sketches for her fashion designs.
doubling up
A passion for fashion leads a senior to divide her time between the Coldwater campus and Otis College of Art and Design. By Ashley Khakshouri
H
annah Rosenberg ’11 decided to pursue her passion for the arts by enrolling in both Harvard-Westlake and Otis College of Art and Design this year. Rosenberg said she was always interested in art and realized that she wanted to work in the fashion industry in the ninth grade. “As its own form of art, it really just seemed to fit, and has turned out to really be one of my true passions in life,” Rosenberg said. She spent the past two years working as a design assistant for Katy Rodriguez, business owner and designer. Now Rosenberg is in charge of the public relations as well as online resources. Rodriguez co-owns the bi-costal vintage boutique Resurrection where Rosenberg also handles the public relations and website. She does everything from running downtown to pick up fabric to helping with production and business details of the company, she said. She also helps stylists with the pulls for editorial or red carpet looks, photographs the vintage couture for Resurrection, and designs the collection with Rodriguez twice a year. After realizing her portfolio was nowhere near the level it needed to be for the schools she was interested in, Rosenberg thought it would be best to enroll in an arts school as well as Harvard-Westlake so she could build a competitive body of work, she said. “I decided sometime last year that dual enrollment at an art school would be a good idea. I was looking at Art Center College of Design as well in Pasadena but Otis just had the easiest program to work with and it’s such
Ashley Khakshouri/chronicle
Sew it up: Hannah Rosenberg ’11 alters a dress of her original design (from top); sitting on her floor, Rosenberg displays figure drawing pieces from her portfolio; Rosenberg works at her sewing machine on a new garment. a great art school.” Rosenberg initially suggested the idea to her dean, who then convinced the school to allow it. “I have spent years at Harvard-Westlake preparing for a future which doesn’t suit me and I have no intention of following along with, so it made much more sense to start focusing on my real interests,” Rosenberg said. Despite her unconventional decision, her family is supportive, as are her friends who enjoy the perks of having a friend in the fashion business, she said. At Harvard-Westlake, she will be taking classes for four periods. Rosenberg has night classes at Otis three nights a week from 7 p.m. to 10 p.m. with open studio until 1 p.m. During night classes at Otis, Rosenberg will take observation drawing, figure drawing, oil painting, and textile design. Rosenberg hopes to gain access to studios, so she can have the oppotunity to create some solid bodies of work for her portfolio as well as having access to the studios so she can finally have the time and the opportunity to create a sizeable portfolio. Her goal for the future is to attend Central St. Martins in London, one of the world’s top design schools, and to later start her own brand or work for a design house, she said. Rosenberg’s style is still evolving but she mostly tends to design high-end women’s wear. However, she said she doesn’t have a set target group of customer’s yet. Her inspiration changes with everything she designs, she said. “For each collection, I make an image board as inspiration,” Rosenberg said. “It helps to clarify the process and it shows how my inspirations are translated into the garments themselves.”
ports S
International star Christina Higgins ’11 competed in Singapore for the United States Youth Olympic volleyball team in August.
the Chronicle Volume XX Issue I Aug. 31, 2010
C3
New senior to join varsity basketball team Shooting guard Danilo Dragovic grew up in Serbia and attended San Marcos High School last year. By Charlton Azuoma
“We really have to understand every play and know all of our reads to make up for our size.” The Wolverines qualified for the Mission League after placing third in the Del Rey League last year behind Cathedral and Serra. They played in the Del Rey League for the past four years after moving down from the Mission League before the 2006-2007 season. In the final two years of their previous stint in the Mission League, the Wolverines won only one out of ten league games. “We are in a new and improved Catholic league, and they are usually the biggest and toughest around,” Eumont said. “In order to win in the Mission League, the team will have to play close to perfect,” Eumont said. The team opens Mission League play Sept. 10 versus Fairfax. “We have a new mission… to win in the Mission League,” Eumont said. “We can’t make mistakes: we must catch all passes, run through the right hole, make the proper tackle and play hard until the whistle blows.” see FOOTBALL, C7
see DRAGOVIC, C7
Daniel Kim/chronicle
Football prepares for return to tough Mission League The varsity football team will face many more challenges this year, including playing in a new league and filling the spots of numerous key players that graduated last year. The seniors that led the team last year have left big cleats for the new starters to fill, Head Coach Vic Eumont said. Because the team lost a lot of top players, it will be difficult for them to reach the level that the 2009 team did Eumont said, but he said he expects his team to do just that. “We have potential, but we’re far from being as good as we were last year at this stage,” Eumont said. In addition to the losses of many seniors, injuries have crippled both the offense and the defense, especially a torn ACL suffered by defensive back Nicky Firestone ’11. Starting the season in a more difficult league, the Mission League, could expose potential weaknesses even more. “We’re not the biggest team or the strongest team,” starting quarterback Max Heltzer ’11 said.
CIF honors girls’ athletic program Last year’s program was awarded the Commissioner’s Cup for best girls’ program in the Southern Section. By Abbie Neufeld CIF Souther Section named the Wolverine girls’ sports program the best in Southern California with the award of the 2009-2010 Commissioners Cup. HarvardWestlake has previously received the title twice. Harvard-Westlake finished with 18 points, six points ahead of both runners-up, Chadwick
Austin Block
A little over a year after moving to the United States from Serbia, Danilo Dragovic ’11, younger brother of UCLA basketball standout Nikola Dragovic, will be joining the class of 2011. Danilo Dragovic attended a specialized economic high school in Serbia for two years and was playing for a small privately owned basketball club in Belgrade before transferring to San Marcos High School in Santa Barbara for his junior year. “The reason why I didn’t come straight to Harvard-Westlake is because I learned too late about the school,” he said. “My brother and family were already working with Santa Barbara and San Marcos, but it [Harvard-Westlake] definitely seemed like a great option for my last year of high school.” Though always eager to come to the United States, Dragovic admitted that it was a little difficult at first because he wasn’t used to American culture. “I struggled the first two months because, you know, the people, the system, and the language were all different… I just tried to study hard until I got used to it… It’s hard to be without your parents for so long,” he said. Dragovic was born in Montenegro. He moved to Serbia at age 10, though the region that encompasses both nations was at the time unified as a single country: Serbia and Montenegro. He said that there are a lot of similarities between California and Belgrade, Serbia. He spent his first year stateside living with a host family but was unable to play varsity basketball for his school because of CIF transfer restrictions. He had to play JV basketball instead. The Dragovic family is not only a basketball-loving family, but it’s also an education-oriented family. Dragovic is a talented basketball player, but Los Angeles Times sportswriter Eric Sondheimer also described him as a student with “outstanding academics.” Dragovic was very impressed by the balance of strong academics and a competitive athletic program at Harvard-Westlake. “[Harvard-Westlake] is a great program,” Dragovic said. “Harvard-Weslake has amazing academic and basketball achievements and that is what made me interested in the school. To have [the] opportunity to play basketball and get a good education are two [of the] most important things in my career.” After hearing about Harvard-Westlake from his brother, he decided to transfer. In late June, the 6’5” Dragovic played in a tournament with the basketball team in Fairfax. He then toured the school with Head of Athletics Audrius Barzdukas.
a cut above: Defenders chase quarterback Max Heltzer ’11 in an August practice. Heltzer will lead the Wolverines as they rejoin the Mission League after a four year stint in the Del Rey League.
By Judd Liebman
and
and St. Margaret’s. Points are awarded based on the number of championships and other final appearances. Five points were awarded for each of the three Southern Section championships won in cross country, basketball, and soccer and another three points were awarded for track and field’s runner up finish. Basketball and cross country went on to win state championships as well. Athletic director Terry Barnum said this award is the result of hard work over the past years. “This speaks to the commitment and dedication of our coaches and athletes,” Barnum said. He also said he thinks this
award suggests a very bright future for girls’ athletics at Harvard-Westlake. Head of Athletics Audrius Barzdukas agreed about the program’s bright future. “You can count on HarvardWestlake being among them in the near and long term,” he said. He said he believes key changes in the Middle School coaching program were a big part of this successful year. “Every championship team benefited from veteran leadership that had received great coaching as seventh, eighth, ninth, tenth and eleventh graders. We succeeded this past year because hard work over the long-term always pays off.”
INSIDE Phenom Kicker:
The starting kicker for the Wolverines, Will Oliver ’11, is the 16th best senior at his position in the nation. He also plays soccer, lacrosse and ice hockey competitively.
C6
Alec Caso/chronicle
runners’ world:
Amy Weissenbach ’12 and Cami Chapus ’12 describe the feeling of being state champions, assess their strengths and weaknesses, and discuss the upcoming season and their friendship.
C8
PHotos Reprinted With Permission of Kimberly Britts
C2 Sports
Aug. 31, 2010
The
Chronicle
& Figures
School-wide change or simple rules?
Facts By Shawn Ma
Harvard-Westlake’s rank on calhisports.com’s list of the best Division IV athletic programs for the past year. State titles in girls’ cross country and basketball along with a strong boys’ basketball season helped Harvard-Westlake capture its third California School of the Year selection.
1 10
The combined number of countries that fencer Emma Peterson ’11, and water polo player Ashley Grossman ’11, have travelled to for competitions in the past year, including Brazil, Russia, Cuba, and Sweden.
The speed at which Lucas Giolito’s fastball was gunned at while pitching at the Area Code Tournament in Long Beach. Giolito was pitching major league speed before he even got his driver’s license.
96
This Month in Wolverine History
W
hen I picture an athletic event, I picture us versus them. One team versus another. Not only do I picture two teams clashing, I picture two student bodies clashing. For the duration of the game, everyone is out for blood; both the fans and the athletes will do anything to win. There is a sea of the Harvard-Westlake red, black, and white joined together either cheering or heckling the other team. On the other side, the other school’s fans are unified against us. Us versus them. The Wolverines against the rivals. It doesn’t matter who the other team is, all that matters is that we win. A proposal from the Sportsmanship and Fan Behavior Review Committee says this picture “creates a contrarian environment.” The committee is right: this environment is contrarian. But what is an athletic event supposed to be? Do they expect a Loyola basketball game to be anything but a “contrarian environment?” The purpose of the committee is to improve the disrespectful behavior of all students and the school’s reputation. But the fact that students get so riled up about games shows that, if anything, our school community is being strengthened by the rowdy games because they pull the students together behind a team for one cause: winning. California Interscholastic Federation cited HarvardWestlake twice last year; once for bad fan behavior and once for poor player and coach behavior. These incidents spurred the administration to rethink the environment at athletic events and to ultimately decide that the unruly behavior or conduct at sporting events needed to be
Judd Liebman controlled. I agree with the intention of the committee. Behavior at some games did get out of control last year and needed to be reined in. The reputation of the school is at stake, and people do judge us for our actions continuously. However, a drastic change is not what we need. The unwavering support of our teams needs to be commended; there is no need to implement many drastic changes into our community. Each and every student knows how to act respectfully. Every single person at this school knows what sportsmanship is and what sportsmanlike conduct is; however, this committee is definitely a necessity. Making sure that our school is viewed in a way that reflects well upon us should be a priority; however, this task needs to be done in the right way. The committee proposes many small but important changes to be made to the athletic event environment. A lot of these changes are necessary and will be effective in improving the fan and athletes’ behavior during sporting events. Proposed changes that will be useful include having faculty attend all games in order to regulate fan behavior as well as hosting a student tailgate to give students a venue to positively support our teams without slandering the rivals. Although the committee proposes many good changes, some changes go too far and will not be effective because they will become the joke of the fans. The committee proposes that each athlete and coach complete an online sportsmanship program in order to better their sportsmanship knowledge. In theory this program will be beneficial, but realistically, this would give
more work to already stressed and sleep-deprived studentathletes. The idea and intent of the committee is phenomenal; the specifics are not so good. Some of the proposed changes will not only be ineffective, but will be annoying as well. The tediousness of some of the suggested actions will lead to students viewing the committee as more of a burden than an effective way to change fan behavior. Here’s what the committee needs to do: there need to be rules posted on the field and in Taper Gym. Before each game, Head of Athletics Audrius Barzdukas, needs to get up in front of the crowd, remind the fans of the code of conduct, and give the Fanatics and parents fair warning that if they act inappropriately they will be ejected. Students need to be warned that they will be punished and the rules will be enforced. Another way the committee can quell the rowdiness is to encourage faculty to sit close to the Fanatics in the stands. These adults will have the ability to rein in the fans before they get out of control. Everyone knows how to act with propriety; however, whether consciously or unconsciously, we all choose to stray from our morals and act impetuously. These teachers will help prevent a stampede of citations and a flurry of ejections. While we all know right from wrong, we sometimes get caught up in the moment and lose focus on the big picture: keeping our heads when no one else can. The overall message of the committee will be just as effective as it is important. However, the committee needs to be careful in choosing the correct resolutions to implement.
gameof themonth
football
Reprinted with Permission of darlene bible
AGE is just a Number: Dara Torres ’85 dives in to swim the anchor leg of the medley relay at the 2008 Beijing Olympics. She led her team to a silver in this competition in addition to winning two silvers individually, becoming the oldest Olympic swimming medalist of all time at 41.
August 2008 By Micah Sperling Dara Torres ’85 became the first American ever to swim in five Olympics, winning three silver medals in Beijing, and tied with Jenny Thompson for most medals ever won by a female swimmer (12). At 41, she is the oldest swimmer ever on the US team. Eight years earlier, in the 2000 Sydney Olympics, at the age of 33, she had already become the oldest American swimmer to ever win a gold medal. Torres swam at Harvard-Westlake for Darlene Bible, Torres set CIF swimming records that stand to this day and competed in her Olympics while still a junior.
when Friday, Sept. 3 where Venice High 13000 Venice Blvd. Los Angeles
VS. The Wolverines will get an indicator of their readiness for the challenging Mission League when they face a talented Venice team in their season opener. Venice is coming off a 10-2 season, better than the Wolverines’ 7-4 mark from last year. If the Wolverines can pull out a win, it will be a big momentum boost for the rest of the year. It should be interesting to see how quarterback Max Heltzer ’11 performs without his top three receivers from last season, and how the defense plays minus Nicky Firestone ’11 (torn ACL).
Aug. 31, 2010
Sports C3
The
Chronicle
Higgins helps United States win silver medal
Volleyball star Christina Higgins ’11 represented the United States Youth Olympic team in Singapore. By Chelsey Taylor-Vaughn
Reprinted with Permission of Kimberly britts
Blazing Ahead: Amy Weissenbach ’12 sprints ahead of her competition at the Nike track Nationals. Weissenbach won the 800 meter event at the tournament. She was one of eight Wolverines who competed.
Girls’ track places 10th at Nike track nationals By.
Boys water polo team plays with Italian host team in Imperia, Italy By Daniel Kim During the summer, Head Water Polo Coach Robert Lynn and the boys’ varsity water polo team packed their bags and went to Italy to gain a new perspective on water polo. The teams left for Italy on Aug. 5 and spent two weeks there. They engaged in vigorous training and spent around five to seven hours in the pool every day playing and working with their Italian host team, Imperia. Unlike in America, water polo is considered one of the top sports in Italy. Members of the varsity water polo teams continually trained and practiced to advance their understanding of the game while also bonding with their teammates. “They’re ahead of the game and that’s why we went there,” Coach Lynn said. “In Italy, water polo is work for them, not fun.” Now the boys’ team seems more focused during practice and weight training, both the coach and weight trainers said. “That rhythm we were in was what we wanted. It was the whole reason for going there as well as competing with the Italian team there to help us gain some experience,” Lynn said.
Imperia’s players were around the same age as those on Wolverine water polo team but there were some older professional players that played on the team as well. “There’s a mountain of work that needs to be done with [the boys’ team] and we’re on the base of the mountain walking up,” Lynn said. “If you really want to play this sport at a high level, you’ve got to be willing to sacrifice and change and work.” Though teams like Newport and Loyola may worry the boys’ team, the coach has a positive outlook on the new season with the new team. “We aren’t going to cower down. We’re going to fight, and by fight I mean outwork, out-understand, and be disciplined and protect each other,” Lynn said. The new younger boys’ varsity water polo team has a lot of work ahead of it if it plans to make it as far as the team made it last year. Coach Lynn plans on keeping the team training consistently and maintaining the same attitude that they brought back from Italy. “Our approach is that we are going to be fearless,” Lynn said. “We’re ready to work hard and we’ll face any challenges that will come our way.
Reprinted with Permission of Ryan Gould
polo play: Water polo players Tobey Casillas ’11, Griffin Morgan ’13, Brian Graziano ’12 and Tyler Greeno ’12 take a break from the game and spend some time together on an Italian beach.
Fall Varsity Previews
Cross Country By Julius Pak Returning from top finishes in the state, the girls’ and boys’ cross country teams are preparing to defend their top titles. “Our success from last year gives us confidence to know that we can compete on the highest levels in our sport. This is a big positive going into our season,” program head Jonas Koolsbergen said. “Our expectations are really the same. The team needs to become as excellent as it is capable of the best team we can be with this mix of athletes this year. Last year is done. It was great, but now we have to embrace a new set of challenges.” Many members of the girls’ team from last season will return this year to defend their state title. Cami Chapus ’12 and Amy Weissenbach ’12, both coming off an excellent year of running, will lead the girls’ team. “It is not a stretch to say that we have two of the better runners in the state [for girls],” Head Coach Tim Sharpe said. Chapus placed first at state last season and second at the Nike Track Nationals in the 1 mile event. Weissenbach placed fourth at the state meet last year and won her 800m event at the Nike Track Nationals. “Amy and Cami train hard and do everything right. That’s why they’re our team leaders,” said Sharpe said. Fifth in the state last year, the boys’ team is “quite a strong, well-balanced cross-country team,” Sharpe said. The top runners on the boys’ side are David Abergel ’11 and Kevin On ’11. “We have a good core group of seniors. It’s their last shot,” Sharpe said. With championships in both cross country and track, this past year “has easily been the best year of running in the school’s history,” Sharpe said. “We have a very strong program, and very talented kids.” However, Sharpe has other goals for the team besides trophies and medals.
David Abergel ’11 has been the fastest on the boys’ cross country team since his sophomore year, and last year he led the team to a fifth place finish in state, the best boys’ finish in school history. Now he is the leader of a veteran team hungry to match the even greater success of the girls’ team.
David Abergel ’11
Before there was the ChapusWeissenbach dynamic duo, there was the Chapus-Nikki Goren ’12 duo. Injuries hurt Goren’s performance slightly as a sophomore, but girls’ cross country will be more formidable this year if she regains her freshman form.
Nikki Goren ’12
photos by mary rose fissinger and alex leichenger
mary rose fissinger/chronicle
Title defense: The girls’ cross country team won league and state titles last year. They will be returning most of their runners this year, including juniors Cami Chapus and Amy Weissenbach, to defend their titles.
Girls’ Tennis By David Kolin
When Amanda Aizuss ’13 was a freshman last year, golf coach Linda Giacolli was already calling her one of the best Wolverine golfers she had ever seen. If Aizuss continues to blossom, she will form a dynamic trio alongside established stars Melanie Borinstein ’11 and Emily Firestein ’11. Nathanson ’s/chronicle
Amanda Aizuss ’13
Girls’ Golf In its first match since finishing second at league prelims last season, the girls’ varsity golf team will play Alemany today at El Cariso Golf Course. The team finished 8-2 last year, losing only to Notre Dame. Their second league match will be on Tuesday Sept. 7 against Flintridge Sacred Heart. The team lost several senior players, but Melanie Borinstein ’11 is confident that “the team hasn’t died out.” At tryouts Aug. 26, there were five returning players and several
While m seniors.
Runners to Watch
“What team doesn’t hope to become a state champion? But what we’re focused on is ‘are we doing the right kind of work? Are we getting better every year?’” Sharpe said. “As a program, we have a bunch of people who are exceptional. You’re out there pushing yourself, testing your body and mind. It is tremendous for these kids. It’s a noble pursuit. As a coach, all I can hope for is that the team character becomes that when no one is looking, are we focused? Are we trying our hardest? If we do that, we will be successful.” The team’s first meet will be the Seaside Invitational in Ventura on Friday, Sept. 10. Their first of three league meets is at Crescenta Valley Park on Thursday, Sept. 16.
Player to Watch
By Chelsea Khakshouri
Chron
The
C4 Sports
sophomores and freshmen interested in playing.. “We have a lot of new sophomores that haven’t had as much experience but are really talented and can bring something new to the team,” Borinstein said. Last year the team placed second in the league, losing to Notre Dame. “I’m looking forward to beating them this year,” Amanda Aizuss ’13 said. “But our team needs to improve on putting. It’s the most important part of the game because it’s where you score so hopefully everyone has been working on it this summer.”
Last year, the girls’ tennis team won the Mission League with a 10-0 record. Last season, the team played defeated Westlake and Woodbridge High School last year in playoffs, but lost to Campbell Hall in the quarterfinals of CIF 4-14. This year Campbell Hall will be tough competition, player Alanna Klein ’11 said. Two starters and five alternates on the team graduated last year. The team lost its first doubles team but didn’t lose any starting singles players. “We lost a lot of people last year, but the players we still have are all really strong, and a few of the incoming students are really good,” Klein said. In order to prepare for the fall tennis season, some players attended an optional camp held by Coach Chris Simp-
son. For training, the girls stretch, participate in live ball drills with the coaches and practice match play with each other. This year, the girls will practice at new facilities at Valley College. The courts should be completed by the middle of October. Until then, the team will play at Studio City Golf and Tennis. Tryouts for the team were held last week for three hours each day on Monday, Wednesday, and Thursday. Practice officially started yesterday. The Wolverines have a Sept. 14 scrimmage against Beverly Hills High School. Their first match is an away game Sept. 18 against Palos Verdes High School at Palos Verdes High School and their first league match is Tuesday Oct. 5 against Notre Dame at the Braemar Country Club.
Player to Watch Savannah de Montesquiou ’13 was the girls’ tennis team’s number one singles player last season as a freshman. Additionally, she advanced to the semifinals in league individuals for girls’ singles, but was defeated by a player from Chaminade. There is no reason to believe that de Montesquiou will not be the team’s number one player again this fall. Nathanson ’s/chronicle
Savannah de Montesquiou ’13
Sports C5
nicle
many of these teams won league and state titles last year, most relied on their Now the new teams must prove themselves in the coming year.
Girls’ Volleyball By Austin Lee Following a year dominated by the senior class’ offensive skill, the varsity girls’ volleyball team is aiming to play at the top of its game and to get a championship banner on the wall, Head Coach Adam Black said. The team’s first game will be a home scrimmage against Thousand Oaks on Sept. 7. Last year, the varsity volleyball team got to the second round of the CIF playoffs and earned a league record of 10-0 and an overall record of 20-9, but the team relied heavily on seniors such as Meg Norton ’10, leaving a rather large hole for this year’s varsity team members to fill. However, the team is keeping its focus on this coming season rather than looking back on last year and is working to achieve the best that they can, Black said. “It’s just a natural process,” Black said. “We’re trying really hard to focus on ourselves and not worry too much about last year.” Black sees this year’s team as a very cohesive group, with players with varying strengths that complement each other on the court. “I think everyone has different strengths that work well,” Black said.
Boys’ Water Polo
“We have people that can attack the ball but they aren’t going to attack very well if we don’t have people that can pass very well.” The team is hoping to make sure everyone is working at the top of their performance in order to achieve their goal of getting to and winning the CIF Championship which eluded them last year. “There was a good group last year and there’s a good group this year as well,” Black said. “We’re going to keep on going forward.”
Player to Watch Christina Higgins ’11 will assume the role of Meg Norton ’10 as volleyball’s superstar player. After competing for the silvermedal winning United States Youth O l y m p i c Team in Singapore over the summer, the 6’2” Higgins is more than ready to Nathanson ’s/chronicle dominate the Mission Christina Higgins ’11 League.
By Alec Caso
Coming off a season that ended in 10-5 loss in CIF quarterfinals to New Harbor High School , the boys’ water polo team will open this season against La Cañada Sept. 21. The Wolverines will play their first league game against Crespi Oct. 5 at home. The team will play school rival Loyola twice but will play one fewer league game in total. The team will also be playing two new teams, Cathedral and Ventura, outside of league this season. Last year’s team ended last season with a 6-2 league record and a 14-10 overall record. Both of the team’s league losses were to Loyola. The team won five of its eight home games. Only one of the three
losses at home was a league game. “Last year, the team was nervous when playing at home and they seemed to play tougher games in away games, so that needs to be changed,” Lynn said. The team spent some time practicing over the summer in Italy. The team hoped that by going to an environment where water polo is a more recognized and played sport they could better their game and team tactics, Lynn said. After losing many key seniors from last year’s team, Lynn knows the team will need even more training before and during the season. “We are going to be fearless,” he said. “But we’re not going to be ignorant to the fact that we have a lot of work to do. We’re ready to work hard and we’ll face any challenges that will come our way.”
Daniel kim/chronicle
working the ball: Brian Graziano ’12 prepares to pass during a practice. He and other juniors will step up to replace last year’s seniors.
Player to Watch
Daniel kim/chronicle
FIGHTING TO WIN: Milena Popovic ’11 and Lucy Tilton ’12 reach for the ball during a practice. The team went undefeated in league last year.
Nathanson ’s/chronicle
Henry McNamara ’13
A freshman on varsity last season, Henry McNamara ’13 watched his older brother James ’10 and several other seniors lead the water polo team in its first year under coach Robert Lynn. With those seniors gone, he is now the standout on a young team that needs to show progress in Lynn’s second year on the job.
Girls’ Field Hockey By Chelsey Taylor-Vaughn Now that the summer and training season are officially over, the varsity field hockey team has set high goals for its upcoming season. Head Coach Erin Creznic said that even though they lost a lot of seniors, they still have a senior heavy class that “is a stronger class than last year’s seniors.” There are a few new additions to the coach staff including alumna Katie Wong ’05, who was coached by Creznic, and Sarah Owen, who played for the field hockey team at Miami University of Ohio. During the summer, players mostly trained on their own or attended field hockey camps, but they all came together again in
August for tryouts and practices. The team participated in what Chelsea Edwards ’12 called a “hazing” process, where the upperclassmen initiated the lower classmen by going out to Roscoes and Venice Beach. Although the players and Creznic disagree on what the team bonding session was called, Creznic said they all agree that “team bonding is just as important as practice. With a girl sport, if they aren’t getting along off the field they’re generally not getting along on the field,” Creznic said. For the final week of the summer, the team prepared for its upcoming trip to St. Louis to compete in a tournament against 40 teams from across the country “There is better competition in St. Louis, and it’s a great time for
our team to gel and start playing together before we hit our games that count,” Creznic said. The starting goalie Adrianna Crovo ’11 was chosen to be one of two goalies from across the country to play for the national team, which has never happened in the schools history for field hockey. She will represent the United States in Argentina, among other places around the world. The team’s toughest competition is Glendora, Huntington Beach and Newport Harbor. “Of course we want to win it all, but first start with league and then we’ll go to playoffs and hopefully do well there,” Creznic said. The team’s opening scrimmage is against Newport Harbor on Sept. 7. The first league match is against Glendora on Sept. 28.
Player to Watch
courtesy of erin creznic
Adrianna Crovo ‘11
Dominant in goal all season long, Adrianna Crovo ’11 was one of the main reasons field hockey advanced to CIF playoffs in a season that was supposed to be a rebuilding year. One of two goalies chosen for the United National Team, Crovo will be the leader of a tight-knit group of returning players that hopes to surprise everyone once again in the fall.
C6 Sports
Aug. 31, 2010
The
Chronicle
Kicking’s a habit One of the top senior kickers in the nation, Will Oliver ’11 has various big-name colleges in hot pursuit of his football talents. By Alec Caso
B
Alec Caso/Chronicle
well-rounded: Four-sport athlete Will Oliver ’11 is an elite kicker being pursued by the University of Virginia and other Division I programs.
eing the 16th ranked senior football kicker in the country can be daunting, but for Will Oliver ’11 it is just part of life. When Oliver began kicking in ninth grade, it was simply a fun adventure into something new. By the time he was done with the season, he knew he had found his passion. Oliver has always been a multi-sport athlete; soccer, ice hockey, tennis, and lacrosse are all sports he has spent serious time playing. But it was not until his coach, after noticing his remarkably strong soccer leg, asked him to kick for the ninth grade team that football became his priority. Unlike many athletes who fear injury in “off-season” sports, Oliver continues to play as a varsity starter for the school’s soccer and lacrosse teams. He also continues to play ice hockey outside of the HarvardWestlake athletic program. Oliver is committed to not giving up his other passions for his chances in football. He doesn’t want to fall into the trap that he feels so many athletes fall into, the trap of becoming a one sport athlete to save themselves for the sport that they want to take into college. “I don’t want to give up my other passions because I’m good at football. You can still play other sports,” Oliver said. He became a starting varsity kicker in his junior year. He made six out of eight field goal attempts at distances of 46-51 yards, professional level distances. By comparison, Chargers kicker Nate Kaeding, who tied for the most made field goals in the NFL last season, also had six out of eight field goals from 40-49 yards. Oliver’s range has extended past 50 yards as he has made at least two field goals at that distance in games. Oliver was also the starting kicker for kickoffs; 46 out of his 58
kickoffs were touchbacks. He spent much of this past summer improving his game, visiting colleges, and keeping in touch with coaches across the country. He went to kicking camps at University of Southern California, the University of Virginia, the University of North Carolina, and Cal State. All of these camps were geared towards the top kickers in the nation. Camps ranged in size from three to four kickers at Virginia to around 100 kickers at USC. While most of the time that Oliver spent at each camp was dedicated to kicking instruction, it also offered a perfect opportunity to meet top coaches and get into the recruiting process. The coaches at Virginia told Oliver that he was their number one choice at the camp. “It offered me an opportunity to work with coaches at each school. This also helped get an idea of what other coaches were looking for,” Oliver siad. He has been offered a preferred walkon spot on the Virginia team. Oliver is also talking with coaches from Michigan and Washington; however, they have made no offers. The Virginia team has 25 scholarship spots and five preferred walk-on spots. Most kickers are offered spots as preferred walkons as schools will hold their scholarships for other positions. An inspiration for Oliver has been Head Football Coach Vic Eumont. Eumont has demanded that players seriously commit to the program by stressing attendance and hard work, Oliver said. “It’s not like other sports where you can make a good excuse and skip practice. They don’t want to hear your excuses, you’re expected to go. It’s been really good for me, especially as a kicker,” Oliver said. Oliver hopes to take his career in kicking all the way to the NFL, but he is committed to getting a good college education.
Wilson chooses Stanford over St. Louis Cardinals By Austin Lee Baseball player Austin Wilson ’10 passed on offers from the St. Louis Cardinals in favor of going to Stanford University. Wilson, a four-year varsity outfielder for the Wolverines, was drafted in the 12th round by the Cardinals in the Major League Baseball draft on June 8 in Secaucus, New Jersey. Having committed to Stanford earlier in the year, Wilson fell from being a possible first round pick in the draft to being a 12th round pick due to concerns that arose about his signability after he committed to Stanford.
“It was kind of hurtful to see my name called relatively late in the draft because I was a projected first round pick, but letting teams know I was going to school came with the effect of me getting drafted later,” Wilson said. Wilson plans to go professional after his junior year, but hopes to meet many new people and “win a college world series” in the meantime. “I’m very happy with my decision,” Wilson said. “There is essentially no price tag on any college experience and Stanford is an exceptional institution with a very talented baseball team.” Wilson and the Cardinals had an Aug. 16 deadline to agree to a contract.
Reprinted with Permission of the deTroit News
The Show: Brennan Boesch ’03 has slumped since his outstanding first two months as a big leaguer, but he remains Detroit’s starting rightfielder.
Boesch contends for MLB Rookie of the Year award By Alex Leichenger Despite his recent struggles, Brennan Boesch ’03 remains a front-runner for the American League Rookie of the Year award, which will be announced after the postseason. Boesch was named the American League Rookie of the Month in both May and June after being called up from Triple-A Toledo by the Detroit Tigers in late April. Boesch, a rightfielder who bats and hits left-handed, hit .345 with three home runs and 15 RBIs in 28 May games and .337 with eight home runs and 23 RBIs in 27 June games. Though he was a standout outfielder at the University of California, Berkeley and the Tigers’ third round draft pick in 2006, Boesch’s torrid start still
came as a surprise to many baseball experts. Boesch did not make the 34-man AL roster for the All-Star game July 13, but at that point many experts believed he was worthy of a roster spot. Sports Illustrated baseball writer Tom Verducci even wrote that Boesch should have been a starter in the AL outfield. Boesch began to fade badly after the All-Star break, seeing his batting average fall from .342 before the break to .270 as of Aug. 28. He had a home run drought that started in early June and did not end until an Aug. 6 home game against the Los Angeles Angels. Boesch was a member of the Wolverines’ 2003 state championship runner-up team.
Aug. 31, 2010
Sports C7
The
Chronicle
Football begins season on Friday from FOOTBALL, C1
Daniel Kim/chronicle
Practice makes perfect: Head Coach Vic Eumont said there is little margin for error as the Wolverines move back to the Mission League, where they struggled in previous years.
New basketball player expected to start at guard from DRAGOVIC, C1 “He’s a super respectful, super polite person, and it was very refreshing walking around campus with him,” Barzdukas said. “I’m excited to see a kid that excited. “To see him in Blaise Eitner’s classroom, with the lizard and stuff … seeing the sculpture area, seeing the dark room … he was super fired up, super excited, like ‘wow, I get to go to a place like this.’” “I have a lot of interest[s] for the future, but right now I am focusing to get a feeling [of] what could be the right thing to choose for my college degree,” Dragovic said. “I like track and field. I actually did it last year. It is interesting but I am not sure if [I] would want to do it this year. “I love arts besides sports, like painting, drawing and writing sometimes, so maybe I will continue doing some of those activities.” Dragovic said he had no problems fitting in with players on the team because he is already familiar with a few of them including Zena Edosomwan ’12 and Damiene Cain ’11 from club basketball. “I already know some of the people
on wthe team because I’ve played with some of them before… It’s a great opportunity to play with all of those guys …I think they’re all really great guys,” Dragovic said. After only a few games with his new team, his teammates already enjoy playing with him. “He’s a great teammate and a phenomenal passer. His basketball IQ is very high,” teammate Josh Hearlihy ’12 said. The team was in need of perimeter shooters like Dragovic; the majority of its scoring last year came from post players Cain and Erik Swoope ’10. Cain will be back this year, but Swoope is gone. “[Dragovic] is a great outside shooter and a perfect piece to the puzzle that is our team,” Jordan Butler ’11 said. “He’s a funny kid. He has a great personality. I think we’re going to really do well this year [with him] and we could win league again.” Dragovic is eager to join the Harvard-Westlake community. “I’m totally excited for many reasons,” Dragovic said. “I will get a chance to meet new people, learn new things and hopefully our basketball team will have a lot of success.”
In order to meet these requirements, Eumont had his team scrimmage constantly over the summer. In addition to the practice games, the team played in two tournaments over the summer, including one at UCLA. The Wolverines faced Venice High twice during the UCLA tournament, splitting the two game series. The team will meet Venice High School again on Friday in the season opener. “Venice is well-coached and they have great athletes… that’s a bad combination,” Eumont said. Heltzer and Eumont agreed that leaving everything on the field is the most important goal for the team. “One of our mottos this year is YAC which stands for yards after catch,” Heltzer said. “Obviously you want to catch the ball first, but after that, bursting up the field picking up extra yards will be super important.” Individually, Heltzer has been working rigorously on his running game. Adding a strong run game to his arsenal of throwing skills will open up passing lanes because defenses will be timid to drop into full pass coverage if he is a threat on the run. This addition of a running game is a part of a full offensive transformation. Last year’s three leading receivers all graduated. Offensive Coordinator Dave Levy has been helping Heltzer improve his mobility so he is more unpredictable to defenses. “[Heltzer] understands that a quarterback can win with his arms, but if he can also win with his feet if he has both weapons, they can’t afford to play him deep or rush him every time,” Levy said.
quicktakes
summer sports news
Cross Country goes on retreat to Big Bear The cross country team ended their summer and began their fall season at Big Bear. The team’s retreat to Big Bear debuted in the summer of 2007 and continued the next summer, but was cancelled last year. Most runners on the team attended this year’s weeklong training session, which doubled as a way for the team to meet.
For most of the athletes, their reason to go to Big Bear was not to train hard and prepare for the season, but to spend time with their teammates and enjoy their last week of summer. Head Coach Tim Sharpe, assistant coach Terri Bricker and Chef d’Equipe Geoff Bird accompanied the team on its weeklong retreat. —Meagan Wang
Several Wolverines compete in Maccabi Games Each year, young Jews with various athletic abilities participate in the Maccabi games. The games are held in three or four different cities across the United States. Several Harvard-Westlake students participated in the games, including Laurel Aberle ’13, Sam Sachs ’14,
Brian Ginsburg ’14, JJ Spitz ’15, Myles Pindus ’15, and Michael Vokulich ’14. This year, the games took place in Denver, Baltimore, Omaha, and Richmond, allowing athletes from all across the country to participate at the location nearest to them. —Michael Aronson
Senior trains and races in Santa Barbara triathalon Alanna Klein ’11 trained every day to prepare for the sprint course of last Sunday’s Santa Barbara Triathlon. Klein first heard about the event from George Sandler ‘11, who has competeted in three triathlons. Klein got a personal trainer to help her prepare for the event.
“It was a really great experience. It was challenging yet fun at the same time. I used to hate working out but the doing the triathlon has in a sense motivated me to exercise as much as I can. I will definately do more triathlons in the future,” Klein said. —David Kolin
NBA stars head to Hamilton Gym to work out
An Industry Leader since 1980 Start Driving immediately upon completion of Driver Ed. Safest Driving School in Southern California since 1994 Outstanding, Informative, and Educational Drivers Education Classes Our fleet of cars are safe, fun, easy to drive, and mostly new or late models. Our Instructors are Professional, Friendly, Patient and EXPERIENCED EXPERTS! For the past 30 years private one-on-one Lessons with the same INSTRUCTOR! Tens of thousands of well Trained graduates AK YOUR FIRENDS WHO THE BEST IS! To be the best! Train with the Best! At Dollar Driving School Location Woodland Hills: 22311 Ventura Blvd. #119
REMEMBER DRIVER ED. & TRAINING STARTS AT 15 NOT 15 1/2 CALL ABOUT OUR SPECIAL! We offer the only computer based On Line Driver Ed. Certified by the Driving School Association of California
Named #1 Safest Driving School in S.CA for over 10 years per the National Safety Council START NOW! Enroll Today on the web www. dsac.com/dollar
CALL FOR DETAILS! (310)
275-0189 (818) 264-0555
NBA stars Derrick Rose, Tyreke Evans, and O.J. Mayo held a morning workout in Hamilton Gym in July. The idea was first presented to the Head of Athletics Audrius Barzdukas by Jason Glushon’03, a former Wolverine baseball standout who currently works as a sports management associate. After a quick warm-up, the players went through a series of pull-up jump shots, ball handling and conditioning
drills. The team concluded the session with several impressive dunking drills. All three players were invited to the Team USA training camp in Las Vegas this summer, but only Rose survived the cuts to make the final roster. Several other NBA players have worked out at the upper school in past summers, including Baron Davis and Tony Parker. —Shawn Ma
Standout freshman joins basketball team The boys’ basketball team will be gaining 6-foot-7 freshman, Derek Newton ’14. He attended Sierra Canyon Middle School. With his performances at the CaliforniaPreps.com/Slam showcase,
Newton demonstrated his ability on the court. Following 26 points in his first game, Newton scored 28 points and 10 rebounds for his team in the second game. —David Kolin and Evan Brown
C8 Sports
The
Chronicle
Going the distance... with state champions
Aug. 31, 2010
Amy Weissenbach and Cami Chapus In addition to being the top two runners on last year’s cross country state championship team, Cami Chapus and Amy Weissenbach both have the distinction of winning individual state championships. Chapus won the cross country state title, and Weissenbach claimed the 800 meter state title during track season.
By Chelsey Taylor-Vaughn and Abbie Neufeld
Q A
Is there any competition between the two of you?
Chapus:
Amy and I have become such great friends, especially through the amazing experiences. When it’s race time we both are able to push each other and help each other. Not only us two, but we work together to push the rest of them team as well.
Q A
Weissenbach:
Q A Q A
Weissenbach: It is incredibly exciting. It was so frustrating to sit injured through almost all of my freshman track season, so it feels amazing to have come back and had such an absolutely perfect year.
What are you looking forward to accomplishing this season?
Weissenbach:
I’m hoping to drop my times from cross country significantly, take part in another team cross country state championship, and do some damage to my 1600 PR. I think that our track team needs to win CIF this year after we missed out last season by three points. I’d also like to drop my 800 time a bit more, and hopefully win another state championship.
Chapus:
An important strength to me is mental toughness. Track and cross country take a lot of will power and desire to run well and do the work. One of my weaknesses is time management. My day is basically based around when I run and get my workout in.
Weissenbach:
It’s so great to have such an amazing runner as a training buddy. Cami and I definitely push each other both at practice and in races, and I think it has helped us both run much faster.
How does it feel to be the second track and field state champion in school history?
What are some of your strengths and weaknesses as a runner?
I think that my main strength is that I have a solid kick, which is mostly due to sprint work with Coach [Quincy] Watts. I also really hate losing, which helps in a race. And I think that a weak area right now for me is long distance strategy.
Q A Q A
What’s the difference between winning a team championship and an individual one?
Chapus: Individual championships are a more personal achievement. An individual championship is something that you are proud of for yourself and that you earned. Team championships bring a whole different glory that is shared by everyone. Winning both last year was an honor individually and as a team.
Are you playing soccer this year? Which one do you like better, soccer or track?
Weissenbach: I love soccer. I have been playing since I was 4. Just this year I’ve decided to take a break and focus on running.
Alex leichenger/chronicle reprinted with permission of kimberley britts
Daniel Kim/chronicle | https://issuu.com/hwchronicle/docs/chronicle_aug | CC-MAIN-2017-04 | refinedweb | 32,416 | 68.4 |
Jobs
A Job creates one or more Pods and will continue to retry execution of the Pods until a specified number of them successfully terminate. As pods successfully complete, the Job tracks the successful completions. When a specified number of successful completions is reached, the task (ie, Job) is complete. Deleting a Job will clean up the Pods it created. Suspending a Job will delete its active Pods until the Job is resumed again..
If you want to run a Job (either a single task, or several in parallel) on a schedule, see CronJob. also needs a
.spec section.
Pod Template..24 [stable]. The index is available through three mechanisms:
- The Pod annotation
batch.kubernetes.io/job-completion-index.
- As part of the Pod hostname, following the pattern
$(job-name)-$(index). When you use an Indexed Job in combination with a Service, Pods within the Job can use the deterministic hostnames to address each other via DNS.
- From the containarized task, in the environment variable.
restartPolicy = "OnFailure", keep in mind that your Pod.
Job termination and cleanup
When a Job completes, no more Pods are created, but the Pods are usually.
Clean up finished jobs automatically.
TTL mechanism for finished Jobs
Kubernetes v1.23 [stable].
It is recommended to set
ttlSecondsAfterFinished field because unmanaged jobs
(Jobs that you created directly, and not indirectly through other workload APIs
such as CronJob) have a default deletion
policy of
orphanDependents causing Pods created by an unmanaged Job to be left around
after that Job is fully deleted.
Even though the control plane eventually
garbage collects
the Pods from a deleted Job after they either fail or complete, sometimes those
lingering pods may cause cluster performance degradation or in worst case cause the
cluster to go offline due to this degradation.
You can use LimitRanges and ResourceQuotas to place a cap on the amount of resources that a particular namespace can consume..24 [stable]
When a Job is created, the Job controller will immediately begin creating Pods to satisfy the Job's requirements and will continue to do so until the Job is complete. However, you may want to temporarily suspend a Job's execution and resume it later, or start Jobs in suspended state and have a custom controller decide later when to start them..
Mutable Scheduling Directives
Kubernetes v1.23 [beta]
JobMutableNodeSchedulingDirectivesfeature gate on the API server. It is enabled by default.
In most cases a parallel job will want the pods to run with constraints, like all in the same zone, or all either on GPU model x or y but not a mix of both.
The suspend field is the first step towards achieving those semantics. Suspend allows a custom queue controller to decide when a job should start; However, once a job is unsuspended, a custom queue controller has no influence on where the pods of a job will actually land.
This feature allows updating a Job's scheduling directives before it starts, which gives custom queue controllers the ability to influence pod placement while at the same time offloading actual pod-to-node assignment to kube-scheduler. This is allowed only for suspended Jobs that have never been unsuspended before.
The fields in a Job's pod template that can be updated are node affinity, node selector, tolerations, labels and annotations.
Specifying your own Pod selector=orphan.
Before deleting it, you make a note of what selector it uses:
kubectl get job old -o yaml
The output is similar to this: that you know what you are doing and to allow this
mismatch.
Job tracking with finalizers
Kubernetes v1.23 [beta]
In order to use this behavior, you must enable the
JobTrackingWithFinalizers
feature gate
on the API server
and the controller manager.
It is enabled by default.
When enabled, the control plane tracks new Jobs using the behavior described below. Jobs created before the feature was enabled are unaffected. As a user, the only difference you would see is that the control plane tracking of Job completion is more accurate.
When this feature isn't enabled, the Job Controller
relies on counting the Pods that exist in the cluster to track the Job status,
that is, to keep the counters for
succeeded and
failed Pods.
However, Pods can be removed for a number of reasons, including:
- The garbage collector that removes orphan Pods when a Node goes down.
- The garbage collector that removes finished Pods (in
Succeededor
Failedphase) after a threshold.
- Human intervention to delete Pods belonging to a Job.
- An external controller (not provided as part of Kubernetes) that removes or replaces Pods.
If you enable the
JobTrackingWithFinalizers feature for your cluster, the
control plane keeps track of the Pods that belong to any Job and notices if any
such Pod is removed from the API server. To do that, the Job controller creates Pods with
the finalizer
batch.kubernetes.io/job-tracking. The controller removes the
finalizer only after the Pod has been accounted for in the Job status, allowing
the Pod to be removed by other controllers or users.
The Job controller uses the new algorithm for new Jobs only. Jobs created
before the feature is enabled are unaffected. You can determine if the Job
controller is tracking a Job using Pod finalizers by checking if the Job has the
annotation
batch.kubernetes.io/job-tracking. You should not manually add
or remove this annotation from Jobs.
Alternatives
Bare Pods.
Replication Controller.)
Single Job starts controller Pod maintains complete control over what Pods are created and how work is assigned to them.
What's next
- Read about different ways of running Jobs:
- Coarse Parallel Processing Using a Work Queue
- Fine Parallel Processing Using a Work Queue
- Use an indexed Job for parallel processing with static work assignment (beta)
- Create multiple Jobs based on a template: Parallel Processing using Expansions
- Follow the links within Clean up finished jobs automatically to learn more about how your cluster can clean up completed and / or failed tasks.
Jobis part of the Kubernetes REST API. Read the Job object definition to understand the API for jobs.
- Read about
CronJob, which you can use to define a series of Jobs that will run based on a schedule, similar to the UNIX tool
cron. | https://kubernetes.io/docs/concepts/workloads/controllers/job/ | CC-MAIN-2022-21 | refinedweb | 1,042 | 52.8 |
Automating your first localization handoff (Help Center)
This article describes how to use the Zendesk REST API to package the content of your Help Center so you can hand it off to a localization vendor for translation for the first time. You'll also learn how to automate the reverse process: publishing the translated content on Help Center after it comes back from the translators.
The article assumes you haven't localized any of your content yet and are starting from scratch. Support for multiple languages is available on the Plus and Enterprise plans of Zendesk Support.
The article is based on custom automation scripts the docs team at Zendesk uses to localize the Zendesk Support documentation.
The article walks you through the following tasks:
- Part 1: Developing a localization workflow
- Part 2: Setting up your scripting environment
- Part 3: Creating the initial handoff package
- Part 4: Publishing the translated content
Part 1: Developing a localization workflow
Before doing anything else, settle on a workflow for localizing your content. The Zendesk docs team uses the following basic workflow for getting content localized:
On handoff day, we download the HTML of the English articles and write them to HTML files.
We bundle the HTML files with our image files in a zip file, and then hand off the package to the localization vendor.
After the vendor returns the translated HTML files, we upload the translated HTML to the knowledge base.
Finally, we upload new or updated images to an offsite file server we use to host our images.
Most of our content is generated from DITA source files stored in Box and sync'ed to the writers' laptops. However, we use the Web content as our master for translation because it always has our most up-to-date content.
What's included in the handoff package
The initial handoff package described in this article consists of the following folders:
/handoff /current /graphics /README.pdf
The current folder contains the most up-to-date English HTML files.
The graphics folders contain the English source image files for the articles.
The readme file contains information for the translators. The document covers the following topics:
- Description of the folders containing the text and image files
- Any extra strings to localize not captured in the HTML files, such as category and section titles
- Any other notes, such as how to handle titles or cross-references
Managing images.
A file server also gives you more flexibility in terms of managing the images in localized articles. You can create and populate folders of localized images on the file server with a simple suffix to differentiate the languages. Example:
- user_guide
- user_guide_de
- user_guide_fr
- user_guide_ja
Then, in the localized articles, you can switch to the localized version of an image by changing the HTML
src attribute. For example, if the
src attribute of an English image is as follows:
src=""
then adding the "de" suffix to "userguide" displays the German version of the image:
src=""
You can make this change for all the images in all the German files with a simple global search and replace of "_guide/" with "_guide_de/".
Setting up your scripting environment
This article uses Python to help automate the localization process. Python is a powerful but beginner-friendly scripting and programming language with a clear and readable syntax. Visit the Python website to learn more.
All you need to write and run Python scripts is a text editor and a command-line interface like Terminal on the Mac or the command prompt in Windows. You'll need a few more tools to develop your localizaton scripts. This section describes how to get them.
Topics covered:
If you're interested in taking a deeper dive into Python after finishing this article, see the following free resources:
- Dive into Python 3 by Mark Pilgrim
- Think Python by Allen B. Downey
Install Python
The scripts in this article use version 3 of Python.
To install Python
- Go to and install the latest stable production version of Python 3 for your operating system.
You can test the installation by running
python3 --version on the command line. It should give you the Python version number.
Install Requests
The Requests module is a third-party Python library that simplifies making HTTP requests in Python. To learn more, see Requests: HTTP for Humans.
To install the Requests module
At the command line, enter:
$ pip3 install requests
That's it. The command downloads and installs the latest version of the module.
pipinstead of
pip3on the command line.
Install Beautiful Soup
Beautiful Soup is a Python library that provides tools for parsing, navigating, searching, and modifying HTML trees. The scripts in this article rely on the module to parse and modify the Help Center's HTML articles. To learn more, see the Beautiful Soup website.
To install the Beautiful Soup module
At the command line, enter:
$ pip3 install beautifulsoup4
The command downloads and installs the latest version of the module.
Install lxml, an HTML parser that works with Beautiful Soup:
$ pip3 install lxml
Beautiful Soup works with a number of parsers; lxml is one of the fastest.
Part 3: Creating the initial handoff package
In this part, you build a script that uses the Zendesk REST API to download the articles in your knowledge base and create an HTML file for each article. After running the script, you'll be able to hand off your content to a localization vendor for a cost estimate and translation.
The script assumes the content you want to hand off is contained in one category on your Help Center.
Script spec
Here are the basic tasks the script has to accomplish to create the handoff package:
- Download the HTML of the articles from the Help Center.
- Because the title of each article is not included in the article's HTML body, get the title from the API and insert it as an h1 tag in the article's HTML.
- Write an HTML file for each article.
Set up the folder structure
Create the following folder structure to store the handoff files and your scripts:
/production /handoff /current /graphics /scripts
Create the script
Save the script below as create_package.py in the scripts folder.
Important: When using the scripts in this article, make sure to indent lines as shown. Indentation matters in Python.
The script downloads the default-language "translation" of the articles from Help Center and writes them to HTML files in the handoff/current folder. The sections that follow describe how to change the settings and run the script, and how it works.
import os import requests from bs4 import BeautifulSoup subdomain = 'your_subdomain' # setting email = 'your_email' # setting password = 'your_zd_password' # setting session = requests.Session() session.auth = (email, password) session.headers = {'Content-Type': 'application/json'} locale = 'en-us' # setting sections = ['36406', '200122006'] # setting # ignore = ['23650177', '33992907', '44356063'] # setting ignore = [] file_path = os.path.join('..', 'handoff', 'current') for section in sections: articles = [] url = 'https://{}.zendesk.com/api/v2/help_center/sections/{}/articles.json'.format(subdomain, section) response = session.get(url) if response.status_code != 200: print('Failed to get articles in section {}. Error {}.'.format(section, response.status_code)) exit() print('\nSuccessfully retrieved the articles in section {}:'.format(section)) data = response.json() [articles.append(article['id']) for article in data['articles']] for article in articles: if str(article) in ignore: continue url = 'https://{}.zendesk.com/api/v2/help_center/articles/{}/translations/{}.json'.format(subdomain, article, locale) response = session.get(url) data = response.json() if 'error' in data: continue tree = BeautifulSoup(data['translation']['body'], 'lxml') meta = tree.new_tag('meta') meta['charset'] = 'utf-8' head = tree.new_tag('head') head.append(meta) h1 = tree.new_tag('h1') h1.string = data['translation']['title'] tree.body.insert_before(h1) tree.h1.insert_before(head) filename = '{}.html'.format(article) with open(os.path.join(file_path, filename), mode='w', encoding='utf-8') as f: f.write('<!DOCTYPE html>\n' + tree.prettify()) print('- Saved {}'.format(filename))
Change the settings
Replace the values for subdomain, email, and password:
subdomain = 'your_subdomain' email = 'your_email' password = 'your_zd_password'
For example, if your Zendesk Support URL is obscura.zendesk.com, then use 'obscura' as the value of your Zendesk Support subdomain:
subdomain = 'obscura'
The email and password are the same as the ones you use to sign in to Zendesk Support. You must be a Zendesk Support admin or agent with access to the content. To be safe in case your laptop is lost or stolen, enter the password value only when you run the script and then delete it when you're done.
Specify the locale of your default language:
locale = 'en-us'
You can get the valid locale value by looking at the URL of your Help Center in your default language:
You can also get a list of valid locales for your Zendesk Support account with the following curl request:
curl https://{subdomain}.zendesk.com/api/v2/locales.json \ -v -u {email_address}:{password}
Use the sections and ignore variables to specify the content you want to include in the handoff:
sections = ['21535856', '21825876', '33838271'] ignore = ['23650177', '24919921', '33992907', '44356063']
Use the sections variable to list all the sections to include in the handoff. If a section is not listed, the script ignores it. You can use the setting to skip sections that don't need to be translated, such as agent-only sections.
Use the ignore variable to list all the articles within the included sections that you don't want to include in the handoff.
If you don't want to ignore any articles, use the following statement:
ignore = []
Save the file.
Run the script
Navigate to your scripts folder with your command line interface.
Run the script from the command line as follows:
$ python3 create_package.pyNote: The dollar sign ($) represents the command prompt. Don't enter it.
You should get messages confirming that the articles were retrieved and saved to HTML files.
Check your handoff/current folder to confirm that it contains the new files. The folder should contain all the articles in the sections you listed, minus the articles you listed to ignore.
Open a few files in a text editor to confirm they contain the HTML for the articles. Check to make sure the title was inserted as an h1 tag.
How it works
The script performs the following tasks.
Import libraries and define variables
Import the libraries used in the script:
import os import requests from bs4 import BeautifulSoup
The
oslibrary is a native Python library that lets you work with files and file paths. You installed the other two libraries.
Specify the parameters for making requests to the Zendesk API:
subdomain = 'your_subdomain' email = 'your_email' password = 'your_zd_password' session = requests.Session() session.auth = (email, password) session.headers = {'Content-Type': 'application/json'}
The requests module is used to create a session object and set the authentication and headers for your HTTP requests.
Specify the locale of your default language:
locale = 'en-us'
Specify the section content to include in the handoff:
sections = ['21535856', '21825876', '33838271'] ignore = ['23650177', '24919921', '33992907', '44356063']
Specify where to write the HTML files:
file_path = os.path.join('..', 'handoff', 'current')
The location is expressed as a path relative to folder where the script runs -- in this case, your scripts folder. The path is ../handoff/current/.
The
os.path.join()function ensures the path is valid regardless of your OS. For example, in Windows, it expresses the path as ..\handoff\current\.
Fetch the article ids
The script needs to article ids to get the content of the articles.
Create a loop to iterate through each section in your sections list and create a list variable to store the article ids:
for section in sections: articles = []
On each iteration, you'll retrieve the ids of all the articles in the section.
Define the url to use for the API request:
url = 'https://{}.zendesk.com/api/v2/help_center/sections/{}/articles.json'.format(subdomain, section)
The url changes dynamically with each iteration. The
format()string method inserts (or interpolates) the values of its arguments in the placeholders (
{}) in the string.
The url points to the list articles endpoint, which is defined in the API docs as follows:
GET /api/v2/help_center/sections/{id}/articles.json
where
{id}is the section id. The endpoint fetches the metadata, including article ids, for all the articles in the specified section. Because you want to get articles from several sections, the script makes one request for each section in your sections list. The url will be different for each request. The section variable that's interpolated in the url provides a different
{id}value for each iteration of the loop.
Using the example values, on the first iteration the value of url is as follows:
Make the request and save the response:
response = session.get(url)
This simple statement makes a GET request to the API using the authentication and header parameters defined earlier. It fetches the metadata for all the articles in the section and assigns it to the response variable. For an example of the response, see the API doc.
Check for request for errors and report back:
if response.status_code != 200: print('Failed to get articles in section {}. Error {}.'.format(section, response.status_code)) exit() print('Successfully retrieved the articles in section {}:'.format(section))
According to the API doc, the API returns a status code of 200 if the request was successful. In other words, if the status code is anything other than 200 (
if response.status_code != 200:), then something went wrong. The script prints an error message and exits.
If the script didn't exit, it means a status code of 200 was returned and the script prints a success message.
Access the article ids in the response
At this point, the metadata for all the section's articles is contained in the response variable as JSON data. The script needs to decode the data and store the id of each article so that it can fetch the contents of the articles from the translations API.
Decode and assign the response to a new variable:
data = response.json()
The
json()function decodes the data returned by the API into a Python dictionary, which is a built-in data type. Python dictionary consists of one key named 'articles'. Its value is a list of articles, as indicated by the square brackets. Each item in the list is a dictionary of article properties, as indicated by the curly braces.
Create a list of article ids from the data:
[articles.append(article['id']) for article in data['articles']]
This is a Python list comprehension, a concise way of looping through a data collection to create a list. It's equivalent to the following snippet:
articles = [] for article in data['articles']: articles.append(article['id'])
The for loop iterates through each article in the data['articles'] list, gets the value of the article id, and appends it to the articles list.
Create a loop to iterate through the list of article ids:
for article in articles:
You want to loop through each article in the current forum to retrieve the article's content from the translations API.
Check to see if the current article id is on your ignore list:
if str(article) in ignore: continue
If the article id (converted to a string to avoid a data-type mismatch) is on the ignore list, the script skips the rest of the loop and gets the next article in the articles list.
If the article is not on the ignore list, the script fetches its content and writes it to a file, as described in the next sections.
Fetch the content of the article
In the Help Center API, the metadata and the content of an article are provided by different resources. You get the metadata from the articles API. You get the content from the translations API, which also includes the default-language content.
Define the url to use for the API request:
url = 'https://{}.zendesk.com/api/v2/help_center/articles/{}/translations/{}.json'.format(subdomain, article, locale)
The url points to the get translations endpoint, which is defined in the API docs as follows:
GET /api/v2/help_center/articles/{article_id}/translations/{locale}.json
The endpoint gets the content of the specified article for the specified locale.
In the url string, a different article value is interpolated at the second placeholder in the string on each iteration of the articles loop. The locale value is interpolated in the string at the third placeholder and doesn't change. Its value is defined at the top of the script, in this case
en-us.
Make the request, decode it, and save the response:
response = session.get(url) data = response.json()
Parse and modify the HTML
Before writing the article to a file, the script needs to get the title of the article from the data variable and insert it in the article's HTML as an h1 tag. Otherwise the translators won't know the title of the article.
The script should also add a meta tag that specifies a UTF-8 character set. Some browsers and localization tools might default to a different encoding without it.
The script manipulates the HTML using the Beautiful Soup library, which provides tools for parsing, navigating, searching, and modifying HTML trees.
Start by creating the Beautiful Soup tree (also known as making the soup) with the article body:
tree = BeautifulSoup(data['translation']['body'], 'lxml')
The article body is specified by the body property of the translation object in the API response.
Create a
<meta>tag and set its charset attribute to "utf-8" for browsers and localization tools:
meta = tree.new_tag('meta') meta['charset'] = 'utf-8'
The lines create the following HTML tag:
<meta charset="utf-8"/>
Create a
<head>tag and insert your
<meta>tag in it
head = tree.new_tag('head') head.append(meta)
The lines create the following tag structure:
<head> <meta charset="utf-8"/> </head>
Create a
<h1>heading tag with the article title:
h1 = tree.new_tag('h1') h1.string = data['translation']['title']
The article title is specified by the title property of the translation object in the API response. The lines create the following HTML tag:
<h1>Some article title</h1>
Insert the
<h1>tag before the
<body>tag, and the
<head>tag before
<h1>:
tree.body.insert_before(h1) tree.h1.insert_before(head)
Write the article to a file
The modified HTML in the Beautiful Soup tree is ready to be written to a file for the translators.
Specify a unique filename based on the article id:
filename = '{}.html'.format(article)
The name is based on the article id to ensure there are no duplicates. Example: 24919921.html
Write the article to a new file:
with open(os.path.join(file_path, filename), mode='w', encoding='utf-8') as f: f.write('<!DOCTYPE html>\n' + tree.prettify())
The snippet creates a new file in write mode (
mode='w') and writes the contents of the HTML tree to it.
The value of file_path is specified at the top of the script and points to your handoff/current folder. The script creates the files in this folder.
The
prettify()function converts a Beautiful Soup tree into a nicely formatted string with each HTML tag on its own line. A DOCTYPE tag is prepended to the HTML.
Print the results:
print('- Saved {}'.format(filename))
Prepare the readme file and hand off the package
You're ready to hand off the HTML files to a localization vendor for a cost estimate and translation.
Before you do, make sure to write a readme file that includes any extra strings that need to be localized. For the initial handoff, this includes the name of your Help Center, the title of the documentation category, and the titles of all the sections included in your handoff.
Part 4: Publishing the translated content
After a while, you get the translated content back from the localization vendor. The vendor should have returned translated versions of the articles, as well as the names of your Help Center, documentation category, and sections. This part describes how to publish the content in your Help Center.
Uploading translations of articles to Help Center is a fairly straightforward operation using the API. The problem is making sure categories and sections exist for each supported language before uploading the articles, especially on your first localization pass when they don't exist yet.
Any translated page must have a parent page translated in the same language. The page hierarchy is as follows: Category > Section > Article. For example, if you add an article translated in German, the article must be contained in a German section. The German section must in turn be contained in a German category. You can't upload an orphan article. For more information on the page hierarchy, see Anatomy of the Help Center.
When localizing your Help Center, it makes sense to start by adding localized versions of category landing pages, followed by section landing pages, followed by articles. This workflow guarantees that any new translated article has a section and category in the same language.
Topics covered in this section:
- Enable your supported languages
- Add the category translations
- Add the section translations
- Add the article translations
- Updating the article translations
Enable your supported languages
Before you begin, make sure you defined the languages in your Zendesk Support account. For instructions, see Selecting the languages you want to support.
After defining the languages for your account, enable them for Help Center as follows.
In Help Center, click General Settings in the tools panel on the lower-right side of the page.
On the General Settings page, select the languages you want to enable for Help Center.
Enter the localized Help Center name for each of your languages.
Click Update to save your changes.
Add category translations
Because you're only localizing one category, it's easier to add a category translation with the user interface rather than with the API.
To add translations of your category
After signing in as a Help Center manager, navigate to the category containing your docs.
Click Edit category in the tools panel on the lower-right side of the page.
Click to add a translation of the category from the list on the right side of the page:
Enter the translated name for the category.
(You did include the category name in the strings in your readme file to the localization vendor, right?)
Click Update Translation to save your changes.
Repeat for each supported language.
Add the section translations
This article assumes you included more than a handful of sections in your handoff package, so it uses the API to add section translations. The script is designed to read the translated titles from a csv file, so a little preparatory work is necessary.
Add the translated titles to a csv file
Create a csv (Comma Separated Values) file named translated_titles.csv in the scripts folder.
In a text editor, enter the following information on each line:
section_id,"title for first locale","title for second locale",...
The section ids should be the same ids specified in the sections variable in the create_package.py file. They're the sections you included in the handoff package.
Example for a Help Center being localized in German and French:
42453453,"Erste Schritte","Mise en route" 42535344,"Konfigurieren des E-Mail-Kanals","Configuration du canal des emails" 53434522,"Business-Regeln","Règles de gestion"
Rules:
- Add a row for each section you included in the handoff package
- Don't include a heading row
- Add a column for each translated version of a section title
- Make sure the title columns are in alphabetical order by locale. Example: de, fr, ja.
- Make sure there's no space before or after the commas that separate the columns
- Use double quotes for the titles in case they contain commas
Create the script
Save the script below as add_section_translations.py in the scripts folder.
This script creates language-specific translations for each section included in your handoff package. It assumes you created a csv file as described in the previous topic. The topics that follow describe how to change the settings and run the script, and how it works.
import csv import json import requests subdomain = 'your_subdomain' # setting email = 'your_email' # setting password = 'your_zd_password' # setting session = requests.Session() session.auth = (email, password) session.headers = {'Content-Type': 'application/json'} locales = ['de', 'fr'] # setting with open('translated_titles.csv', encoding='utf-8', newline='') as f: title_reader = csv.reader(f, delimiter=',') sections = {} for row in title_reader: titles = {} count = 1 for locale in locales: titles[locale] = row[count] count += 1 sections[row[0]] = titles for section in sections: url = 'https://{}.zendesk.com/api/v2/help_center/sections/{}/translations.json'.format(subdomain, section) for locale in locales: data = {'translation': {'locale': locale, 'title': sections[section][locale]}} payload = json.dumps(data) response = session.post(url, data=payload) print("Translation for locale '{}' created for section {}.".format(locale, section)).
locales = ['de', 'fr']
Save the file.
Run the script
Run the script from your command-line interface:
$ python3 add_section_translations.py
You should get a message confirming that translations were created for the sections.
Check the section in your Help Center to see if it contains the new translations.
Because the sections don't contain any articles yet, they're not visible to end-users, signed-in or otherwise. The sections are visible to agents and administrators.
How it works
Import the required libraries:
import csv import json import requests
Python has built-in support for csv files.
Configure the request parameters:
subdomain = 'your_subdomain' email = 'your_email' password = 'your_zd_password' session = requests.Session() session.auth = (email, password) session.headers = {'Content-Type': 'application/json'}
Specify the locales of your translated articles.
locales = ['de', 'fr']
Read the csv file:
with open('translated_titles.csv', encoding='utf-8', newline='') as f: title_reader = csv.reader(f, delimiter=',')
Store the translated section titles in a Python dictionary:
sections = {} for row in title_reader: titles = {} count = 1 for locale in locales: titles[locale] = row[count] count += 1 sections[row[0]] = titles
The first loop creates a dictionary of sections, with the section id as the key of each item. The locales loop creates a dictionary of translated titles for each section. The titles dictionary is assigned as the value of each section key (
sections[row[0]] = titles). The resulting value of sections might look like this:
{ '42453453': {'de': 'Erste Schritte', 'fr': 'Mise en route'}, '42535344': {'de': 'Konfigurieren des E-Mail-Kanals', 'fr': 'Configuration du canal des emails'}, '53434522': {'de': 'Business-Regeln', 'fr': 'Règles de gestion'} }
The titles have their own locale-specific keys to select them later.
For each section, add a section translation using the creating translation endpoint:
for section in sections: url = 'https://{}.zendesk.com/api/v2/help_center/sections/{}/translations.json'.format(subdomain, section)
For each locale, retrieve the section title from the sections dictionary, build the API payload, and make the post request:
for locale in locales: data = {'translation': {'locale': locale, 'title': sections[section][locale]}} payload = json.dumps(data) response = session.post(url, data=payload) print("Translation for locale '{}' created for section {}.".format(locale, section))
Each new translation is defined in the API payload as follows:
data = {'translation': {'locale': locale, 'title': sections[section][locale]}}
The script defines the locale and title for each section translation. The title comes from the sections dictionary created from the csv file:
sections[section][locale]
The expression identifies a value in the dictionary. The section and locale variables change as the script iterates through the loop. Using the example dictionary above,
sections[53434522]['de']resolves to the value of 'Business-Regeln'.
Note that because the new language-specific sections don't contain any articles yet, end-users won't be able to see them. Only admins and agents can see them at this point.
Add the article translations
The final step in the workflow is to add the article translations to Help Center.
Get the article files ready
Create folders for the translated files.
Create the following locale-specific folders in the handoff folder on your hard drive:
/handoff /current /localized /de /fr /script
Make sure the structure is identical relative to the scripts folder.
Add or remove the locale-specific folders for your supported languages. The locale folder names should be the same as the locales in the URL of Help Center.
Place the HTML files for each language in the appropriate locale-specific folder.
Make sure the HTML files from the vendor have the same file names as the default-language files. Example:
/handoff /current 22521706.html 27808948.html /localized /de 22521706.html 27808948.html /fr 22521706.html 27808948.html
Upload the localized image files to your image file server.
On the server, you should organize the images in locale-specific folders. Example:
/documentation /user_guide (existing folder with English images) /user_guide_de /user_guide_fr
You can use a file client such as Cyberduck to upload the images.
Change the image paths in the localized HTML files to point to the language-specific folder on the file server.
For example, if an image
srcattribute in a German article is as follows:
src=""
then add the "_de" suffix to "user_guide" to display the German image:
src=""
You can make this change for all the articles in your localized/de folder with a global search-and-replace of "_guide/" with "_guide_de/". Repeat for all your languages. For more information, see Managing images
Create the script
Save the script below as publish_package.py in the scripts folder.
The script publishes the translated articles to the appropriate language-specific sections in Help Center. The topics that follow describe how to change the settings and run the script, and how it works. publish_package.py
You should get messages confirming that each translation was created in Help Center.
Check your Help Center to see if it contains the new article translations in your language-specific categories and sections.
How it works
The script performs the following basic tasks:
- Read each file in each locale folder.
- Because the title of each article on Help Center is not included in the HTML body, grab the article title in the h1 tag in the HTML, and then delete the h1 tag.
- Create an article translation in Help Center with the translated HTML content.
Here are the details.
Import the required libraries.
import os import glob import json import requests from bs4 import BeautifulSoup, Comment
Define a function named main().
def main():
Unlike the previous scripts, this one defines a few custom functions. The
main()function is defined here but called on the last line of the script to make sure Python reads the other function definitions first.
Configure the request parameters.
You should be familiar with these lines by now.
Specify the locales of the supported languages:
locales = ['de', 'fr']
For each locale, grab, or glob, the names of all the HTML files in the ../handoff/localized/{locale} folder:
for locale in locales: print('Processing {} articles ...\n'.format(locale)) files = glob.glob(os.path.join('..', 'handoff', 'localized', locale, '*.html'))
The glob.glob() function in Python scrapes the contents of a specified folder. In this case, the function gets the names of all the html files (
'*.html') in the locale folder. The resulting value of files is a list that looks like
['../handoff/localized/fr/22521706.html', '../handoff/localized/fr/27808948.html'].
Define a variable to use later to slice off the file path to obtain the article id contained in the file name:
path_len = 22 + len(locale)
The value of file is a relative path and a file name. The path_len variable specifies the length of the relative path (always the same 22 characters), plus the length of the locale, which can vary. Examples, 'fr', 'en-gb'.
Start a loop to read the translated content in each file in the folder:
for file in files: print('Reading {} ...'.format(file[path_len:]))
The status message uses the Python slice expression,
file[path_len:], to print the name of the file. If the current locale is 'de', the expression slices the first 24 characters (22 + 2) from the beginning of the file string. For example, if the string is
'../handoff/localized/fr/22521706.html', then the expression produces
'22521706.html'.
For each file, create a JSON payload containing the file's translated content:
payload = create_payload(locale, file)
The create_payload() function is defined in the Functions section later in the script. It parses the translated HTML in the file, retrieves the article title from the h1 tag in the HTML, strips out the h1 tag, strips out any HTML comments for good measure, packages the HTML in a dictionary, and returns it as a JSON-encoded payload for the API request:
def create_payload(locale, file): with open(file, mode='r', encoding='utf-8') as f: html_source = f.read() tree = BeautifulSoup(html_source, 'lxml') title = tree.h1.string.strip() tree.h1.decompose() # Strip out html comments comments = tree.find_all(text=lambda text: isinstance(text, Comment)) for comment in comments: comment.extract() # Package the payload in a dict and JSON-encode it data = {'translation': {'locale': locale, 'title': title, 'body': str(tree)}} return json.dumps(data)
Use the JSON payload in an API request to create the article translation in Help Center:
url = 'https://{}.zendesk.com/api/v2/help_center/articles/{}/translations.json'.format(subdomain, file[path_len:-5]) post_translation(payload, url, session)
The script uses the following endpoint to create the article translations:
where
{id}is the id of the article to update. The script gets the id from the file variable:
file[24:-5]
The second number, -5, slices five characters starting from the end of the string, which removes the '.html' extension and leaves the article id.
The post_translation() custom function makes the request and checks for problems:
def post_translation(payload, url, session): response = session.post(url, data=payload) if response.status_code != 201: print('Status:', response.status_code, 'Problem with the post request. Exiting.') exit() print('Translation created successfully.')
Print the URL of the newly updated article:
print('https://{}.zendesk.com/hc/{}/articles/{}.html\n'.format(subdomain, locale, file[path_len:-5]))
The localized content is live. Help Center shows or hides the content in the sections based on the language setting of the end-user’s browser, or based on the language selector on Help Center pages.
Update the article translations
You might need to fix errors in the translated content and republish it. Make the edits in the locale folders in your localized folder and then run the script described below. The script updates the translated articles to the appropriate language-specific sections in Help Center. The topics that follow it describe how to change the settings and run the script, and how it works.
Save the script as update_package.py in the scripts folder. update_package.py
You should get messages confirming that each translation was updated in Help Center.
Check your Help Center to see if it contains the updated article translations in your language-specific categories and sections.
How it works
The script works like the create_package.py script, except that it uses a different endpoint and makes a PUT request instead of a POST request. See Updating translations in the API docs. If you're interested, see "How in works" in Add the article translations above.
Hi, Charles
Thanks for this post - my company has a goal to localize 60+ pages of Help articles into 4+ languages, and we’d like to find out a way to export English text in bulk, translate via SDL WorldServer GMS, and then import translated text in bulk.
Since I am a Program Manager, not a developer, though, I am unclear how to go about actually using the available Help Center Beta APIs – do we need to construct a technical framework to deploy the APIs on our side, before start using Zendesk APIs ?
Anyy plans to make any tools and services available for assisting in deployment of web APIs ?
As with many companies, we have the need, but no dedicated technical resources to actually execute on the designing and deployment of APIs, so I’d appreciate your insight.
Mira
Hi Mira,
The APIs are included with your Zendesk, and like Zendesk they live on the web. The APIs for the Help Center are in beta right now and you'll need to sign up to the beta, but you won't have to deploy them on your side.
The requirements for this article include a command-line interface like the command prompt in Windows or the Terminal in Mac. You also have to install a scripting language and a few libraries to work with the APIs. See [Part 2: Setting up your scripting environment]().
Try out (or get a technically minded colleague to try out) [Part 3: Creating the initial handoff package]() to get a feel for how it works. Copy the script, change the settings as indicated, and run the script from the command line. You can ignore the "How it works" section if it doesn't interest you. The script should export articles in bulk from your Help Center as HTML files.
If you'd rather have assistance, we offer a paid service. Contact [Zendesk Services]() for options and pricing.
Charles
Hi, Charles
Thanks for all the info, I appreciate it !
Mira
What is the best way to go about gathering all of the section ID's. It's not covered in the article anywhere as far as I can tell.
And... if you have to put the section ID's in the section array, what is the point of the ignore array?? Wouldn't you just leave out the ID's of the sections you don't want it to include?
A question about the "publish\_package.py": It seems the api it use only works once.
The second time we get: Status: 400 Problem with the post request. Exiting.
What API should we use, if we want to fix some errors in the translated file, and upload it again?
@Jason
The **ignore** array should list all the _articles_ within the included sections that you don't want to include in the handoff. If you don't want to ignore any articles, specify an empty array:
ignore = []
**Getting the section ids**
If you have less than 15 to 20 sections in the category, you can get the ids manually. Right-click the section title and open it in a new tab. The section id is specified in the URL.
If you have more than 15-20 sections, you can use a script and the API to get the ids:
```
import requests
# Set the request parameters
subdomain = 'your\_subdomain'
pwd = 'your\_password'
# Specify category id
category = 200142577 # change this value
# Do the HTTP get request using the Sections API
url = 'https://{}.zendesk.com/api/v2/help\_center/categories/{}/sections.json'.format(subdomain, category)
response = requests.get(url, auth=(email, pwd))
# Check for HTTP codes other than 200
if response.status\_code != 200:
print('Status:', response.status\_code, 'Problem with the request. Exiting.')
exit()
data = response.json()
# Print the section ids
for section in data['sections']:
print(section['id'])
```
@Xiaochen
I ran into the same 400 errors when trying to publish the articles more than once. If I remember correctly, the cause was trying to _create_ (through a post request) translations that already existed, which the API didn't allow. The solution was to _update_ rather than _create_, which you can do by changing the post request to a put request.
To change to a put request, change the session method and status code in following lines in the post\_translation() function definition:
response = session.**post**(url, data=payload)
if response.status_code !=**201**:
to
response = session.**put**(url, data=payload)
if response.status_code !=**200**:
@Charles
Thanks for your reply, but it seems the PUT method is not available, we will get 404 in return.
Maybe because this is a beta version and we are expecting it to official release : )
Sorry, Xiaochen, my mistake. The endpoint for updating is different than the one used for creating. See [Updating translations]() in the API docs. The endpoint takes a locale value. Also, a 'locale' value isn't needed in the payload.
I added a new section in the article to cover your use case:
- [Update the article translations]()
The section contains a new **update\_package.py** script that you can use. Thanks.
Charles
Okay, so I've set up the structure and successfully pulled down the articles, but none of the graphics came over.
Does the following text mean that I have to get the from the S3 cloud myself, or should this script pull them over automatically?
]()._
Hey Doug, the scripts don't bring down the images from the Amazon server. Sorry it's not clear in the article. Our images are already local, on the writers' drives in a couple of shared folders sync'ed to Box. We hand those off to loc directly -- no need to download. When it comes time to publish, we upload copies of the files to the server.
Hi Charles,
Um, okay. So how do I pull down my images since I don't have them local?
thanks,
Doug
We don't have a script for that, but it would involve getting all the img tags in the downloaded files, and then making HTTP requests to download the images like any other resource. I'd use Beautiful Soup to get the image urls:
```
tree = BeautifulSoup('html\_source')
images = tree.find\_all('img')
```
Then I'd grab the src attribute in each img tag and use it to make a request for the image file from the server using the Requests module:
```
for image in images:
src = image['src']
if src[:4] != 'http': continue
response = session.get(src, stream=True)
```
Note: I'm checking to make sure the first 4 characters start with http so it's a valid request url.
At this point, this image is in memory on your system. Next, I'd grab the filename from the src attribute and write it to file:
```
file_name = src.split('/')[-1]
with open(os.path.join(file\_path, file\_name), mode='wb') as f:
for chunk in response.iter\_content():
f.write(chunk)
```
One thing to be careful about: Most web servers only allow browsers to download images. So I'd set a header so my request looked like it's coming from a browser:
```
session = requests.Session()
session.auth = ('your\_email', 'your\_pwd')
session.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0'}
```
Hope this helps.
I'm circling back to this topic now that I have some breathing room. When I run the create_package.py it retrieves the articles but throws an error when it tries to write:
Traceback (most recent call last):
File "create_package.py", line 46, in
with open(os.path.join(file_path, filename), mode='w', encoding='utf-8') as f:
FileNotFoundError: [Errno 2] No such file or directory: '..\\handoff\\current\\203514393.html'
Any idea what's going on? I can shoot you my create_package.py if that would help.
thanks,
Doug
Hi,
In a straightforward Zendesk, it works great!
However, on a different, more complex ZenDesk Help Center, I get error:
Traceback (most recent call last):
File "create_package.py", line 38, in
body = BeautifulSoup(data['translation']['body'])
KeyError: 'translation'
I know for a fact that the category is set for translation, as is the section I want to create for translation.
What am I missing?
Thanks,
Gordon
Hi Charles, thanks for posting this. It's working pretty well so far. I'm having an utf-8 encoding issue with the create_package.py script.
I'm finding  symbols in weird places in the HTML output after I run the script.
I searched stackoverflow for some information.
When I inspect an article's JSON, in the metadata, it says is encoded as UTF-8. This stackoverflow article says that sometimes BeautifulSoup can get confused and encode things wrong.
One of the stackoverflow articles says to add a UTF-8 ignore line. I've experimented a bit, but I don't know enough about either soup or python to figure it out. Any ideas?
Am I missing something?
Thanks!
Hi Neal,
Encoding problems are a pain. Let's start with the basics. What application are you using to view the problem HTML? Sometime an app itself has trouble interpreting encoded characters. Have you tried opening the file in a different text editor? TextWrangler is a great free text editor for the Mac -.
Hi Charles,
There aren't any encoding issues when I view it in a Textwrangler or Atom. They only show up when I view it in Firefox. And when I selected an encoding by clicking View>Text Encoding>Unicode, the issue was fixed. More importantly, it's causing problems when I send it to my translation service. When I inspect the HTML, I notice there's an empty head element when I run the script as is. I'm not sure if that's the normal result, but that's the result I get.
I got halfway to a solution on my own. I added the head variable.
tree = BeautifulSoup('<html></html>')
head = BeautifulSoup('<head><meta charset="utf-8"></head>')
body = BeautifulSoup(data['translation']['body'])
title = tree.new_tag('h1')
title.string = data['translation']['title']
tree.html.append(title)
tree.html.append(head)
tree.html.append(body)
I know this is all wrong and it adds the meta tag in the wrong place, but even with the meta element inserted after the h1, it cleared up the encoding problem in Firefox. I'm going to experiment some more to figure out how to stick the meta in the head element. My working hypothesis right now is that there isn't an encoding issue, but Firefox/Chrome are guessing the wrong encoding. I'm going to add an encoding hint for the browsers and translation tools and see if that works.
Thanks for getting back to me so quickly!
Update: I have a solution for my encoding issue and I want to share it. My hypothesis was that FF/chrome was guessing the encoding wrong, so I added a meta tag element to tell the browser what encoding to use. That seemed to work. My last post put the meta tag in the wrong place. I learned a little more and figured out how to put it in the right place. :-)
I also added a DOCTYPE statement that identifies the HTML as HTML5, a title element that automatically includes the title from each article, and an en-us language attribute. It took me a long time to figure out that I couldn't stick the DOCTYPE statement in with the other append functions and that I had to stick it in as a string in the write function before it wrote the payload to the file.
If you use this code, you'll need to remove the title element from the HTML before you import the translated content into Zendesk. So, I included the code I modified for publish_package.py and update_package.py. I added tree.title.decompose() at the end to remove the title element and its contents.
Thanks for sharing this code and this article. I'm kind of a novice at this but your explanation really helped me understand what was going on in the code enough to modify it.
This is great information, Neal. Thanks for sharing.
Charles,
Thanks so much for posting these scripts and explaining them so well. We'll probably localize our KB into eight languages, which would have been a copy-paste headache. This is the automated solution I was hoping to find, and probably wouldn't have come up with myself (at least not for a long time!) since I'm not a programmer.
Please sign in to leave a comment. | https://help.zendesk.com/hc/en-us/articles/229489108-Automating-your-first-localization-handoff-Help-Center- | CC-MAIN-2017-51 | refinedweb | 7,946 | 55.74 |
AWS Cloud Operations & Migrations Blog
Using Amazon CloudWatch metric filters and alarms to monitor logs on SonicWall Firewall
In this guest post, Marcin Gornik – Director of IT at Tommy John Inc discusses how they used CloudWatch Metric Filters to monitor their SonicWall Firewall system to better secure their infrastructure.
TommyJohn, a clothing design and manufacturer company, uses Amazon CloudWatch to monitor their SonicWall firewall devices. This blog discusses why CloudWatch was selected as a monitoring solution and information detailing how it was configured.
Overview
TommyJohn uses SonicWall Firewall software to secure their network from external security threats. Continuously monitoring and managing the firewall devices on a regular basis is a critical daily task for the company’s security engineers. Also important is the task of analyzing the logs generated and performance characteristics, in order to identify potential gaps in the setup. The team wanted to identify a solution that is concise, meets technical and business needs, simple to set up and easier to maintain.
After assessing various options, the IT team at TommyJohn decided to use CloudWatch, because it met the business and technical requirements, including:
- Near real-time log monitoring
- Notifications
- The ability to further automate actions based on monitoring events
These benefits improve visibility into the functioning of SonicWall Firewall software, and help the organization protect its assets from unwanted harm. In the era of data privacy, regulations, and compliance, maintaining data security and integrity in an organization is key. Both large and small organizations employ various security measures, including deploying firewall software inside their networks, to enforce network security policies and manage network traffic. Network administrators who manage firewall software must be well equipped with advanced monitoring tools to ensure that the firewall rules are working as intended.
Solution
This section demonstrates how we at TommyJohn set up SonicWall Firewall log ingestion to CloudWatch Logs.
The assumption is that:
- You are already aware of the basics of Amazon CloudWatch and IAM roles and policies.
- You are using SonicWall Firewall OS 6.5 or higher.
- Your firmware version is 6.5.4.4 or higher.
Create a Cloudwatch LogGroup and LogStream
First, we created a new LogGroup and a LogStream for SonicWall Firewall Logs to ingest into CloudWatch. It is a good idea to group relevant LogStreams into LogGroups for better organization and querying logs effectively. To accomplish this, we followed the below steps:
- Log in to the AWS management console and navigate to CloudWatch Logs.
- Select Create log group under the Action drop-down menu.
- Give the log group a name, such as
SonicWall-Logs.
- In the newly created log group, create a new log stream and give it a name, such as
SonicWall-Logstream.
Create or set up IAM User and Permissions
We decided to create new IAM User that can be used in SonicWall FireWall software to send logs to AWS. To more easily manage user permissions, we created an IAM Group instead of assigning permissions directly to an IAM User. We assigned necessary permissions to the Group and then assigned the IAM User to the Group. This allows us to modify permissions for a set of users at a time. The following steps show how we accomplished that.
Create IAM group
- On the IAM console, under Groups, we selected Create New Group.
- We named the group as
SonicWall-Agentsand then attached the
CloudWatchLogsFullAccessIAM policy to it.
- After clicking Next Step, our Review screen looked like the one below. We checked the Group Name and the Policies sections to make sure they are right.
- Created the IAM user group by selecting Create Group.
Now that the IAM user group has been created successfully, we then proceeded to create the IAM User. The following steps demonstrate how we achieved that.
Create IAM User
- On the IAM console under Users, we selected Add User and provided the user name as
SonicWall-user1.
- In order to allow this user to make API calls, we checked the Programmatic access checkbox under Access type and proceeded to select Permissions.
- Under Add user to group, we checked SonicWall-Agents group which we created earlier. This allows the user to have the policies that the user group contains. (You can also directly add the required permissions to the user.) We then proceed to select Tag and then select Review.
- Clicking on Create user results in creating a new IAM User.
- We then downloaded the CSV file. Since it contains IDs for Access Key and Secret Key, we kept it in a safe, admin-only location.
Configure IAM permissions in SonicWall
Now that we have both the IAM User group and IAM user created, we then proceed to set up the SonicWall Firewall software. In this section, you can find details about how we set up the AWS account on SonicWall FireWall software so the firewall software has the necessary permissions to send logs into CloudWatch.
- We logged into the SonicWall management console, and selected Manage, then System, then Setup, then Network, and then AWS Configuration.
- We then pasted the Access Key from the CSV file into the Access Key ID text box . (We downloaded this the previous section as part of creating the IAM User.)
- We pasted the Secret Key from the same CSV file into the Secret Access Key and Confirm Key text boxes, as shown in the following screenshot. We select the Mask Key check box on SonicWall which masks the secret key and provides an additional level of security.
- Once we ensured the selected AWS Region was correct, we selected Test Connection to test the connection settings.
Enable AWS logs in your SonicWall log settings
In this section, we configure our SonicWall Firewall to send logs to the desired CloudWatch LogGroup and LogStream. To accomplish this, we followed these steps.
- On the SonicWall AWS Management Console, under Manage, we selected Log Settings and then AWS Logs.
- After ensuring the selected AWS Region is correct, we entered the Log Group and Log Stream names. (We created these earlier in the Amazon CloudWatch console.) The screenshot below shows what this step looks like.
- The Synchronization Interval filed on SonicWall FireWall allows you set the frequency duration at which you want the logs to be sent to CloudWatch. We decided to use 900 seconds, which is the maximum duration. When you perform this step, assess this variable carefully and set a frequency that gives you the right balance between performance and cost.
- We selected Accept to finish the setup.
Check syncing
To ensure the setup is working as expected, we log on to the CloudWatch console and check that the logs are syncing to the LogStream we created earlier. The following screenshot shows that the logs are getting ingested properly into CloudWatch.
Create a CloudWatch metric filter on the logs from SonicWall
Along with querying the logs using Logs Insights feature on CloudWatch, we also wanted to get notified when something specific happened so we can quickly take respective action. We decided to use the CloudWatch Metric Filter functionality that allows us to filter out a part of the log data using a Filter Pattern. This filtered message can be stored as a CloudWatch metric that can be used to create alarms.
We followed the below steps to create the Metric Filter.
- On CloudWatch Logs page, we selected the SonicWall_Log_Group log group we created earlier and selected Add Metric Filter.
- We entered the filter pattern string in the Filter Pattern textbox and selected Assign Metric, as shown in the following screenshot.
- After providing a name in the Filter Name box, a namespace name in the Metric Namespace textbox and a Metric Name in the Metric Name textbox we selected Save Filter to save the Metric Filter. This is shown in the following screenshot.
Create an alarm on the metric filter
As mentioned earlier, it is possible to create alarms on Metric Filters. This is as straight forward as creating an alarm on a regular CloudWatch metric. The following steps showcase how we created the alarm.
- On the CloudWatch LogGroup we created, under Metric Filters we selected Create Alarm, as shown in the following screenshot.
- We selected Static under Threshold type, and Greater under Whenever the ErrorCount is…. and entered 5 in the textbox and select Next.
- Because we already had an SNS topic that we wanted to use, we chose Select an existing SNS topic. If you don’t have an SNS topic created, create a new one by selecting Create new topic and following the steps and click Next.
- We provided a unique name to the alarm and selected Next. Once we reviewed the inputs in the Review screen, we created a new alarm by selecting Create alarm.
Testing the alarm
In order to ensure the alarm worked the way we wanted, we tested it with by creating some actions on our enterprise environment that would create the logs which would match the Metric filter. After we did that we went to CloudWatch Alarms section to check if the alarms are firing as expected. The following screenshot shows a historical graph of the alarm firing over a period of time.
The following screenshot shows a sample email notification triggered through CloudWatch alarm notifications.
Conclusion
This post demonstrated how we set up CloudWatch Alarms on logs ingested from SonicWall Firewall in our on-premises data center. Now our IT operations teams can be notified of specific security incidents to help them respond to such incidents quickly. As a result, our team’s Mean Time To Resolution improved considerably, allowing the team to focus on business-critical functions. To learn more about CloudWatch Logs and Metric Filters from our documentation here and here respectively.
The content and opinions in this post are those of the third-party author and AWS is not responsible for the content or accuracy of this post.
About the Author
Marcin Gornik is a Director of IT at Tommy John Inc. He has a strong networking, networking security, and system administrative background. He is passionate about IT and networking security and is excited to talk about new emerging threats. In his spare time, he is a huge advocate for clean and renewable energies and solutions. Marcin believes we are all never-ending students where there is no end to personal growth and improvement. | https://aws.amazon.com/blogs/mt/using-amazon-cloudwatch-metric-filters-and-alarms-to-monitor-logs-on-sonicwall-firewall/ | CC-MAIN-2022-05 | refinedweb | 1,714 | 53.51 |
2017 TCO Algorithm Round 1A Editorials
2017 TCO Algorithm Round 1A Editorials are now here. To make sure you get a deep insight to the TCO Algorithm Problems, our veteran members and algorithm rockstars Egor and Nickolas will be helping us with the Editorials for all the TCO Rounds!
A big thanks to Nickolas for writing the editorials for TCO17 Algorithm Round 1A. Also a big thanks to Egor for reviewing them.
You may discuss the problems in the match discussion forum.
2017 TCO Algorithm Round 1A – Division I, Level One – PingPongQueue
This was a purely implementation-oriented problem: read the statement carefully and simulate the games and the queue exactly as described. There were some corner cases, for example, if there are only two players in total they’ll always play each other, and if N = 1, after each game both players join the queue. But with careful implementation these cases didn’t require separate handling in the code.
Java reference solution: import java.util.*; public class PingPongQueue { public int[] whoPlaysNext(int[] skills, int N, int K) { int p1 = skills[0], p2 = skills[1]; Queue<Integer> q = new LinkedList<Integer>(); for (int i = 2; i < skills.length; ++i) q.add(skills[i]); int winner = -1, loser = -1; int nWins = 0; for (int i = 1; i < K; ++i) { if (Math.max(p1, p2) != winner) nWins = 0; nWins++; winner = Math.max(p1, p2); loser = Math.min(p1, p2); q.add(loser); p1 = q.remove(); if (nWins == N) { q.add(winner); p2 = q.remove(); } else { p2 = winner; } } int[] ret = {p1, p2}; Arrays.sort(ret); return ret; } }
2017 TCO Algorithm Round 1A – Division I, Level Two CheeseSlicing
This problem can be solved using classic dynamic programming: create a 3D array dp, with dp[X][Y][Z] storing the maximal area of good slices which can be obtained from piece X x Y x Z. Transitions between states correspond to cuts you do; it makes sense to only do cuts which produce a slice of thickness between S and 2*S-1. The answer will be the largest value from the array up to A x B x C piece. Java reference solution:
import java.util.*;
public class CheeseSlicing { public int totalArea(int A, int B, int C, int S) { int dp[][][] = new int[A+1][B+1][C+1]; // dp[i][j][k] stores the max area of pieces which can be obtained from i x j x k // calculate DP array upwards from S x S x S // the return will be the largest value from <= A x B x C int max = 0; for (int i = S; i <= A; i++) for (int j = S; j <= B; j++) for (int k = S; k <= C; k++) { // this piece can be viewed as one large slice int[] dim = {i, j, k}; Arrays.sort(dim); dp[i][j][k] = Math.max(dp[i][j][k], dim[1] * dim[2]); max = Math.max(max, dp[i][j][k]); // try to extend this piece in each direction by doing 1 cut // the extending slice must have the smallest dimension >=S // but <2*S (otherwise two slices can be done from it) for (int sm = S; sm < 2*S && sm <= Math.min(j, k) && i + sm <= A; sm++) dp[i + sm][j][k] = Math.max(dp[i + sm][j][k], dp[i][j][k] + j * k); for (int sm = S; sm < 2*S && sm <= Math.min(i, k) && j + sm <= B; sm++) dp[i][j + sm][k] = Math.max(dp[i][j + sm][k], dp[i][j][k] + i * k); for (int sm = S; sm < 2*S && sm <= Math.min(i, j) && k + sm <= C; sm++) dp[i][j][k + sm] = Math.max(dp[i][j][k + sm], dp[i][j][k] + i * j); } return max; } }
Alternatively, there is a short and beautiful solution which doesn’t require any iteration:
import java.util.*; public class CheeseSlicing { public int totalArea(int A, int B, int C, int S) { if (A < S || B < S || C < S) return 0; int[] dim = new int[] {A % S + S, B % S + S, C % S + S}; Arrays.sort(dim); dim[0] -= S; return (A * B * C - dim[0] * dim[1] * dim[2]) / S; } }
2017 TCO Algorithm Round 1A – Division I, Level Three PolygonRotation
One way to solve this problem is to find approximate solution using disk integration. Split the solid of revolution into narrow slices perpendicular to the Y axis. A slice at coordinate Y0 can be approximated as a conical frustum or a cylinder; to find its radius, check the coordinates at which Y = Y0 line intersects left and right sides of the polygon and pick the one which has larger absolute value. Add up the volumes of these slices, and if they are small enough, the result will be within 1E-9 of the exact answer.
Here is K.A.D.R’s tester solution which uses this technique:
#include <algorithm> #include <vector> #include <cmath> using namespace std; inline double ds(pii p1, pii p2, double sy) { if (p1.y == p2.y) return abs(max(p1.x, p2.x)); return abs(p1.x + (double)(p2.x - p1.x) / (p2.y - p1.y) * (sy - p1.y)); } double f(double sy, const vector<int>& X, const vector<int>& Y) { int n = L(X); double mx = 0.0; for(int i = 0; i < n; ++i) { if (abs(Y[i] - sy) < 1e-9) { mx = max<double>(mx, abs(X[i])); } int nx = i < n - 1 ? i + 1 : 0; if (min(Y[i], Y[nx]) > sy) continue; if (max(Y[i], Y[nx]) < sy) continue; double cur = ds(mp(X[i], Y[i]), mp(X[nx], Y[nx]), sy); mx = max(mx, cur); } return pi * mx * mx; } class PolygonRotation { public: double getVolume(vector <int> X, vector <int> Y) { double a = *min_element(all(Y)), b = *max_element(all(Y)); const int N = 1000000; double s = 0; double h = (b - a) / N; for (int i = 0; i <= N; ++i) { double y = a + h * i; s += f(y, X, Y) * ((i == 0 || i == N) ? 1 : ((i & 1) == 0) ? 2 : 4); } s *= h / 3; return s; } };
Alternatively, you could find exact answer. One way to do it was to mirror the left side of the polygon with respect of the Y axis, so that you’d have two polylines going from (0, Ymax) to (0, Ymin) in semiplane x >= 0 (one of them could belong to the Y axis). Now draw planes perpendicular to the Y axis that go through each of the vertices of these polylines, as well as through any intersection points of these two polylines. The area of the solid of revolution between any two adjacent planes would be a conical frustum, which can have its area calculated exactly. But the geometry is very tricky to get right, and the code is longer than the one that uses numerical integration approach.
Here is the reference solution used for this problem:
import java.util.*; class P { public int x,y; P(int x, int y) { this.x=x; this.y=y; } public P substr(P other) { return new P(this.x - other.x, this.y - other.y); } public int cross(P other) { return this.x * other.y - this.y * other.x; } } public class PolygonRotation { static double interX, interY; static boolean intersect(P A, P B, P C, P D) { //does line A-B intersect line C-D ? //if it does, the point of intersection is stored in global "inter" variables if (Math.min(A.x,B.x) > Math.max(C.x,D.x)) return false; if (Math.max(A.x,B.x) < Math.min(C.x,D.x)) return false; if (Math.min(A.y,B.y) > Math.max(C.y,D.y)) return false; if (Math.max(A.y,B.y) < Math.min(C.y,D.y)) return false; int den = (D.y-C.y)*(B.x-A.x) - (D.x-C.x)*(B.y-A.y); int num1 = (D.x-C.x)*(A.y-C.y) - (D.y-C.y)*(A.x-C.x); int num2 = (B.x-A.x)*(A.y-C.y) - (B.y-A.y)*(A.x-C.x); if (den == 0) return false; //lines are either parallel or overlap, but this doesn't add NEW intersection points, only old ones if (den < 0) { den *= -1; num1 *= -1; num2 *= -1; } if (num1 <= 0 || num1 >= den || num2 <= 0 || num2 >= den) return false; interX = A.x + num1 * (B.x-A.x) * 1.0 / den; interY = A.y + num1 * (B.y-A.y) * 1.0 / den; return true; } static double volume(double h, double x1, double x2) { return h * (x1*x1 + x2*x2 + x1*x2) / 3.0; } public double getVolume(int[] xpar, int[] ypar) { int N = xpar.length; int iPlus = 0, iMinus = 0; int y = ypar[0]; double x = 0.0; double vol = 0.0; // on each step we look for the next slice between two adjacent values of y // here ys are integer and correspond to vertices // iplus and iminus give the indices of previous vertex on each curve // we start with (0, Ymax) and continue until both reach (0, Ymin) do { // figure out next y which will define end of the slice: the smallest of the next ones // and which of the indices will advance (possibly both) int iPlusNext = iPlus, iMinusNext = iMinus; int yNext = Math.max(ypar[iPlus + 1], ypar[(N + iMinus - 1) % N]); if (yNext == ypar[iPlus + 1]) iPlusNext++; if (yNext == ypar[(N + iMinus - 1) % N]) iMinusNext = (N + iMinus - 1) % N; // x of the next slice is max of xs on each polyline // x on polyline can be achieved either as vertex or as intersection with edge // and there will be at most one intersection x (one of the points is always a vertex) double xNext = 0.0; // plus polyline if (yNext == ypar[iPlusNext]) xNext = Math.max(xNext, xpar[iPlusNext]); else { // find intersection of horizontal line with yNext and segment of plus polyline intersect(new P(-101, yNext), new P(101, yNext), new P(xpar[iPlus], ypar[iPlus]), new P(xpar[iPlus + 1], ypar[iPlus + 1])); xNext = Math.max(xNext, interX); } // minus polyline if (yNext == ypar[iMinusNext]) xNext = Math.max(xNext, -xpar[iMinusNext]); else { // find intersection of horizontal line with yNext and segment of minus polyline intersect(new P(-101, yNext), new P(101, yNext), new P(xpar[iMinus], ypar[iMinus]), new P(xpar[(N + iMinus - 1) % N], ypar[(N + iMinus - 1) % N])); xNext = Math.max(xNext, -interX); } // figure out whether the slice is a single conical frustum or a combination of two if (!intersect(new P(xpar[iPlus], ypar[iPlus]), new P(xpar[iPlus + 1], ypar[iPlus + 1]), new P(-xpar[iMinus], ypar[iMinus]), new P(-xpar[(N + iMinus - 1) % N], ypar[(N + iMinus - 1) % N]))) { // one conical frustum vol += volume(y - yNext, x, xNext); } else { // two vol += volume(y - interY, x, interX); vol += volume(interY - yNext, interX, xNext); } // advance iPlus = iPlusNext; iMinus = iMinusNext; y = yNext; x = xNext; } while (iPlus == 0 || iMinus == 0 || xpar[iPlus] != 0 && xpar[iMinus] != 0); return Math.PI * vol; } } | https://www.topcoder.com/blog/2017-tco-algorithm-round-1a-editorials/ | CC-MAIN-2019-09 | refinedweb | 1,828 | 69.82 |
WS2812B 8×8 LED Matrix Panel Review and Code
This post talks about how you can use the WS2812B 8×8 LED Matrix Panel with an Arduino.
WS2812B 8×8 LED Matrix Panel
The WS2812B 8×8 LED Matrix Panel is an square arrangement of 64 RGB LED’s. Each LED has its own LED driver which allows you to individually address and control each LED.
There are six pin holes where you can solder pin headers or wires to. These are the two sets for 5V and GND, a Digital In, and a Digital Out. This uses the standard WS2812B protocol to control the LED’s which only need a single data pin, 5V, and GND.
These can also be chained together to control multiple in parallel however you need to ensure that the current requirements will be met by your microcontroller.
This LED square can be used with the FastLED Arduino Library which allows you to easily control them. The LED’s are indexed numerically from the first LED (closest to the Data in port) to the last LED which is closest to the data out port.
Wiring it up to an Arduino
To wire up the WS2812B 8×8 LED Matrix Panel to an Arduino I am going to solder a 3 pin header onto the 5V, Data in, and GND pins. This will let me connect it to a breadboard and then connect it to the Arduino.
The 5V pin and GND pins are connected to the respective pins on the Arduino. The Data In (DIN) pin should ideally be connected to a resistor (of around 330 ohm) which is then connected to one of the digital pins on the Arduino. This resistor helps to reduce noise on the line and the LED panel may work without this. Here I will wire up the digital in pin to the Arduino’s digital pin three (with the noted resistor between it).
Programming the Arduino with the WS2812B 8×8 LED Matrix Panel
To program the WS2812B 8×8 LED Matrix Panel I am going to use the FastLED Arduino Library. This handles the complexity of the communication protocol and allows you to easily set the state of each LED.
This library can be added to the Arduino IDE by adding the “FastLED” library in the “Manage library” section of the Arduino IDE. Once this is added we can start using the libraries features.
To start with you need to include the libraries you want to use and set up the LED’s.
#include <FastLED.h> #define LED_PIN 3 #define NUM_LEDS 64 CRGB leds[NUM_LEDS];
Here the pin to control it from the Arduino is defined (pin 3), the number of LED’s we have in our chain (64 = 8 * 8), and we then create the CRGB LED array to control the LED’s.
void setup() { FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS); }
The setup function just adds all the LED’s to the FastLED library so it is aware of them and can be used to control them.
void loop() { for(int hue = 0; hue < 255; hue += 1) { for(int i = 0; i < NUM_LEDS; i++) { leds[i] = CHSV(hue, 128, 255); } FastLED.show(); delay(10); } }
Finally in the loop we loop the hue from 0 to 255 and set every LED to the same colour. This delays 10 milliseconds and then continues the hue loop.
This will slowly change the LED’s through a range of colours to give a pretty effect and test the LED’s.
Final Review
This WS2812B 8×8 LED Matrix Panel is a relatively cheap panel which allows you to easily program each of its LED’s. Since it works with the standard FastLED Arduino library it makes it quick to configure and write your sketch.
The LED’s are quite bright too which is very nice however you may want to dim them using the value attribute or by placing something in front of them to defuse them.
Overall this is a nice small package and I would recommend buying it for any LED needs!
Link: | https://chewett.co.uk/blog/2514/ws2812b-8x8-led-matrix-panel-review-and-code/ | CC-MAIN-2022-27 | refinedweb | 685 | 75.44 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Visual Studio 6.0 In order to understand the application development process, it is helpful to understand some of the key concepts upon which Visual Basic is built. Because Visual Basic is a Windows development language, some familiarity with the Windows environment is necessary. If you are new to Windows programming, you need to be aware of some fundamental differences between programming for Windows versus other environments.
How Windows Works: Windows, Events and Messages
A complete discussion of the inner workings of Windows would require an entire book. A deep understanding of all of the technical details isn't necessary. A simplified version of the workings of Windows involves three key concepts: windows, events and messages. Think of a window as simply a rectangular region with its own boundaries. You are probably already aware of several different types of windows: an Explorer window in Windows, a document window within your word processing program, or a dialog box that pops up to remind you of an appointment. While these are the most common examples, there are actually many other types of windows. A command button is a window. Icons, text boxes, option buttons and menu bars are all windows. The Microsoft Windows operating system manages all of these many windows by assigning each one a unique id number (window handle or hWnd). The system continually monitors each of these windows for signs of activity or events. Events can occur through user actions such as a mouse click or a key press, through programmatic control, or even as a result of another window's actions. Each time an event occurs, it causes a message to be sent to the operating system. The system processes the message and broadcasts it to the other windows. Each window can then take the appropriate action based on its own instructions for dealing with that particular message (for example, repainting itself when it has been uncovered by another window). As you might imagine, dealing with all of the possible combinations of windows, events and messages could be mind-boggling. Fortunately, Visual Basic insulates you from having to deal with all of the low-level message handling. Many of the messages are handled automatically by Visual Basic; others are exposed as Event procedures for your convenience. This allows you to quickly create powerful applications without having to deal with unnecessary details.
Understanding the Event-Driven Model
In traditional or "procedural" applications, the application itself controls which portions of code execute and in what sequence. Execution starts with the first line of code and follows a predefined path through the application, calling procedures as needed. In an event-driven application, the code doesn't follow a predetermined path ³.
Because you can't predict the sequence of events, your code must make certain assumptions about the "state of the world" when it executes. When you make assumptions (for example, that an entry field must contain a value before running a procedure to process that value), you should structure your application in such a way as to make sure that the assumption will always be valid (for example, disabling the command button that starts the procedure until the entry field contains a value). Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause the text box's Change event to occur. This would cause the code (if any) contained in the Change event to execute. If you assumed that this event would only be triggered by user interaction, you might see unexpected results. It is for this reason that it is important to understand the event-driven model and keep it in mind when designing your application.
Interactive Development
The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses an interactive approach to development, blurring the distinction between the three steps. With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to compile your application. You must then find and fix the error and begin the compile cycle again, repeating the process for each error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errors on the fly. It's almost like having an expert watching over your shoulder as you enter your code. In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. When you are ready to run and test your application, there is only a brief delay to finish compiling. If the compiler finds an error, it is highlighted in your code. You can fix the error and continue compiling without having to start over. Because of the interactive nature of Visual Basic, you'll find yourself running your application frequently as you develop it. This way you can test the effects of your code as you work rather than waiting to compile later.
Integrated Development Environment Elements
The Visual Basic integrated development environment (IDE) consists of the following elements.
Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming such as Project, Format, or Debug.
Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus depends on the part of the
environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox.
Toolbars
Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu. Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.
Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the context menu and adding controls to the resulting tab. For More Information To learn more about specific controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls." For information on how to add controls to the Toolbox, see "Adding Controls to a Project" in "Managing Projects."
Project Explorer Window
Lists the forms and modules in your current project. A project is the collection of files you use to build an application. For More Information For information on projects, see "Managing Projects."
Properties Window
Lists the property settings for the selected form or control. A property is a characteristic of an object, such as size, caption, or color. For More Information For information on properties, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."
Object Browser
Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications, see what methods and properties are available for those objects, and paste code procedures into your application.
Figure 2. Each form in your application has its own form designer window. can provide features like source code control. You add controls. graphics. see "Your First Visual Basic Application" later in this chapter. Locals. and pictures to a form to create the look you want. Add-ins.2 The Form Layout window Immediate. see "Using Wizards and Add-ins" in "Managing Projects. which allows you to support group development projects. which are available from Microsoft and third-party developers." Note You can also add features to the Visual Basic interface by using a program called an add-in. see "Debugging Your Code and Handling Errors." Code Editor Window Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application." Form Designer Serves as a window that you customize to design the interface of your application. see "Finding Out About Objects" in "Programming with Objects. They are only available when you are running your application within the IDE." For details on using add-ins to extend the Visual Basic programming environment.2) allows you to position the forms in your application using a small graphical representation of the screen. For More Information To learn more about entering code and using the code editor. For More Information To learn more about debugging and using the debug windows.For More Information For more information on using the Object Browser to view procedures. To learn more about designing an interface. see "Programming Fundamentals. ." Form Layout Window The Form Layout window (Figure 2. and Watch Windows These additional windows are provided for use in debugging your application. For More Information To learn how to add controls to an application. see "Creating a User Interface.
0 Environment Options Visual Basic provides a great deal of flexibility. allowing you to configure the working environment to best suit your individual style. Check or uncheck the SDI Development Environment check box. These include the Toolbox. Docking capabilities can be toggled on or off for a given window by selecting the appropriate check box on the Docking tab of the Options dialog box. windows can be docked to any side of the parent window. ²or² Run Visual Basic from the command line with a /sdi or /mdi parameter. they will remain on top of any other applications. as long as Visual Basic is the current application. and Immediate. to each other or to the edge of the screen. The Options dialog box is displayed. all of the IDE windows are contained within a single resizable parent window. Properties window. . Project Explorer. With the MDI option. 2. Docking Windows Many of the windows in the IDE can be docked.Visual Basic Concepts Visual Studio 6. You can choose between a single or multiple document interface. Locals. Your layout will persist between sessions of Visual Basic. or connected. With the MDI option. with SDI they can only be docked beneath the menu bar. 3. Select Options from the Tools menu. With the SDI option. available from the Options command on the Tools menu. Form Layout Window. Color Palette. Select the Advanced tab. To switch between SDI and MDI modes 1. all of the IDE windows are free to be moved anywhere on screen. The IDE will start in the selected mode the next time you start Visual Basic. and Watch windows. SDI or MDI Interface Two different styles are available for the Visual Basic IDE: single document interface (SDI) or multiple document interface (MDI). and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements.
Set properties. 3. Visual Basic Concepts Visual Studio 6. When you click the command button. 2. 2. You can use forms to add windows and dialog boxes to your application. the message "Hello. Select the window you wish to dock or undock. world!" appears in the text box. You can also use them as containers for items that are not a visible part of the application's interface.0 Hello. 4. To see how this is done. use the steps in the following procedures to create a simple application that consists of a text box and a command button. The first step in building a Visual Basic application is to create the forms that will be the basis for your application's interface. Button Control . you'll use two controls from the Toolbox. For this first application. Creating the Interface Forms are the foundation for creating the interface of an application. Write code.To dock or undock a window 1. For example. you might have a form in your application that serves as a container for graphics that you plan to display in other forms. 3. Release the mouse button. Then you draw the objects that make up the interface on the forms you create. Create the interface. Drag the window to the desired location by holding down the left mouse button. The outline of the window will be displayed as you drag. Visual Basic There are three main steps to creating an application in Visual Basic: 1.
Move the pointer onto your form. 2.3. Figure 2. .Text box Command button To draw a control using the Toolbox 1. The control appears on the form. Place the cross hair where you want the upper-left corner of the control. as shown in Figure 2.) Release the mouse button. (Dragging means holding the left mouse button down while you move an object with the mouse. Click the tool for the control you choose to draw ³ in this case. the text box. The pointer becomes a cross hair. 5. then you can move the control to another location on the form. Drag the cross hair until the control is the size you want. 4. Another simple way to add a control to a form is to double-click the button for that control in the Toolbox. This creates a default-size control located in the center of the form.3 Drawing a text box with the Toolbox 3.
²or² Use the Properties window to change the Top and Left properties. To adjust the position of locked controls . When a control is selected. you can use CTRL with the arrow keys to move the control one grid unit at a time. This will lock controls only on the selected form. ²or² Use SHIFT with the arrow keys to resize the selected control. You can also use the mouse. This is a toggle command. 3. The corner handles resize controls horizontally and vertically. while the side handles resize in only one direction. To resize a control 1. Position the mouse pointer on a sizing handle.Resizing. 2. keyboard. and menu commands to move controls. To move a control y Use the mouse to drag the control to a new location on the form. and adjust their positions. Sizing handles appear on the control. and Locking Controls Notice that small rectangular boxes called sizing handles appear at the corners of the control. Select the control you intend to resize by clicking it with the mouse. This will lock all controls on the form in their current positions so that you don't inadvertently move them once you have them in the desired location. and drag it until the control is the size you choose. If the grid is turned off. Moving. you'll use these sizing handles in the next step as you resize the control. Release the mouse button. lock and unlock control positions. the control moves one pixel at a time. To lock all control positions y From the Format menu. so you can also use it to unlock control positions. choose Lock Controls. ²or² Click the Lock Controls Toggle button on the Form Editor toolbar. controls on other forms are untouched.
click the Properties Window button on the toolbar. or position. fonts.5 The Properties window The Properties window consists of the following elements: y Object box ³ Displays the name of the object for which you can set properties. Sort tabs ³ Choose between an alphabetic listing of properties or a hierarchical view divided by logical categories. To open the Properties window. You can edit and view settings in the right column. y y To set properties from the Properties window . You now have the interface for the "Hello.5) provides an easy way to set properties for all objects on a form. world!" application. world!" application Setting Properties The next step is to set properties for the objects you've created. Figure 2.y You can "nudge" the control that has the focus by holding CTRL down and pressing the appropriate arrow key. The Properties window (Figure 2. or use the context menu for the control. ²or² You can change the control's Top and Left properties in the Property window.4 The interface for the "Hello. Click the arrow to the right of the object box to display the list of objects for the current form. Properties list ³ The left column displays all of the properties for the selected object. Figure 2. choose the Properties Window command from the View menu.4. such as those dealing with appearance. as shown in Figure 2.
In the right column. or click the Properties button on the toolbar. world!" example. set the Icon property for that form. default icon that appears when you minimize that form. select the name of a form or module. Enumerated properties have a predefined list of settings. you will probably change this icon to one that illustrates the use of the form or your application. From the View menu. Use the default settings for all other properties. To open the Code window y Double-click the form or control for which you choose to write code. You can use 32 x 32 pixel icons that were standard in 16-bit versions of Microsoft Windows and are also used in Windows 95/98 and Windows NT. you'll need to change three property settings. From the Properties list. To assign an icon to a form. world! (Empty) OK Setting the Icon Property All forms in Visual Basic have a generic. constants. You can display the list by clicking the down arrow at the right of the Settings box. . ²or² From the Project Explorer window. and choose the View Code button. Using the Code Editor window. choose Properties. The Properties window displays the settings for the selected form or control. For the "Hello. Writing Code The Code Editor window is where you write Visual Basic code for your application. as well as the 16 x 16 pixel icons used in Windows 95/98. and declarations. you can quickly view and edit any of the code in your application. Code consists of language statements. or you can cycle through the list by double-clicking a list item. However. Object Form Text box Command button Property Caption Text Caption Setting Hello. select the name of a property.1. 3. 2. type or select the new property setting.
²or² Click the Procedure View button in the lower left corner of the Code Editor window. From the Tools menu. 2. Click.6 The Code Editor window You can choose to display all procedures in the same Code window.Figure 2. select the Options dialog box. select the Options dialog box. 2. Click the arrow to the right of the list box to display a list of all objects associated with the form. The check box to the left of Procedure Separator adds or removes a separator line between procedures. On the Editor tab in the Options dialog box. Figure 2. or display a single procedure at a time. To display all procedures in the same Code window 1. clear the check box to the left of Default to Full Module View.6 shows the Code Editor window that appears when you double-click the Command button control. The box displays the name of the selected procedure ³ in this case. y . From the Tools menu. and the events for that command. ²or² Click the Full Module View button in the lower left corner of the Code Editor window. Procedure list box ³ Lists the procedures. for an object. To display one procedure at a time in the Code window 1. Choose the arrow to the right of the box to display all the procedures for the object. or events. On the Editor tab in the Options dialog box. select the check box to the left of Default to Full Module View. The Code window includes the following elements: y Object list box ³ Displays the name of the selected object.
use the procedure Command1_Click. where Text1 is the object and Text is the property. select the name of an event for the selected object.Text = "Hello. For More Information For information on creating other types of procedures.) For this example. or click the Start button on the toolbar. such as those you'll create here. world!" displayed in the text box. an underscore (_). Click the command button you've created on the form. world!" The event procedure should look like this: Private Sub Command1_Click () Text1. (The active form is the form that currently has the focus. see "Introduction to Procedures" in "Programming Fundamentals. select the name of an object in the active form. Here.property. because it's the default procedure for a command button. To create an event procedure 1. Note that a template for the event procedure is now displayed in the Code window. Command1. contains code that is executed when an event occurs (such as when a user clicks a button). if you want a command button named Command1 to invoke an event procedure when it is clicked. 2. In the Object list box. the Click procedure is already selected.Creating Event Procedures Code in a Visual Basic application is divided into smaller blocks called procedures. You can use this syntax to change property settings for any form or control in response to events that occur while your application is running. and the event name. . Text1. An event procedure for a control combines the control's actual name (specified in the Name property). choose Start from the Run menu.Text = "Hello. and you'll see "Hello. world!" End Sub You'll note here that the code is simply changing the Text property of the control named Text1 to read "Hello. 3. world!" The syntax for this example takes the form of object. For example. Type the following code between the Sub and End Sub statements: 4. An event procedure. or press F5. choose the command button. In the Procedure list box." Running the Application To run the application.
The following example illustrates how easy it can be to create a useful application in Visual Basic. in this case a ListBox object. you use a data control. To add items to the list box. so you'll need to add it: To add a control to the toolbox 1. The MSFlexGrid control isn't in the default toolbox. . a list box control. The AddItem method allows you to dynamically add items to the list box while the application is running." Creating a Project You begin creating this application by choosing New Project from the File menu. Controls. and Menus. and two command buttons. The grid displays a table of information about products retrieved from the Northwind database. Methods. 2. a list box control. Conversely. As the user selects an item by using the navigation buttons on the data control. a MSFlexGrid control. so you'll soon use many other features to manage and customize your applications. To draw the interface.property). then selecting Standard EXE in the New Project dialog box (when you first start Visual Basic. The data control provides the ability to navigate through the database recordset. Select Components from the context menu for the toolbox. the New Project dialog box is presented). synchronizing the display of records in the grid control with the position in the recordset. For More Information To learn more about methods.0) in the Controls list box and select the check box to its left. (A method is a Visual Basic function that acts on a particular object. the Clear method is used to remove all items from the list box.0 The Firstapp Sample Application Visual Basic provides you with a wealth of tools beyond the ones used in this first application. see "Understanding Properties. the name of the selected product is displayed in the data control. The Firstapp application demonstrates how a data control and a grid control can be used to display a table of information from a database. The user can also add items to a "shopping list" in the list box control by doubleclicking the current selection in the grid. Find the MSFlexGrid (Microsoft Flex Grid 6. and Events" in "Forms.method) is similar to the syntax for setting a property (object. Reviewing sample applications can be an excellent way to learn more about Visual Basic. (You can right-click within the toolbox window to display the context menu. Visual Basic creates a new project and displays a new form.) The Components dialog box will be displayed. The application consists of a data control.Visual Basic Concepts Visual Studio 6. and two command buttons. you use the AddItem method. a MSFlexGrid control.) The syntax for specifying a method (object. Visual Basic makes it easy to access database information from within your application.
Clear ' Clears the list box. set properties for the objects according to the following table. If you don't remember how. Data1_Reposition. . Use the default settings for all other properties. you can click the button to the right of the property to display a standard File Open dialog box to browse for the file. Setting Properties In the Properties window. By default.3. The icon for the MSFlexGrid control will appear in the toolbox. Double-click the form or control to display the Code window.mdb database is installed in the same directory as Visual Basic. Writing Event Code All the code for the application is contained in the Command1_Click. Use the Toolbox to draw a data control.mdb Products Data1 Clear Exit The DatabaseName property of the data control must include the actual path to the database. a list box control. the RecordSource property in the Properties window will contain a list of tables or recordsets for the selected database. List1. check out "Creating the Interface" earlier in this chapter. the Nwind. an MSFlexGrid control. you are invoking the Clear method of the list box. and then type the code for each event procedure. Once the DatabaseName property has been set. Command2_Click. Add this code to the Command1_Click event procedure to clear the list box when the user clicks the button: Private Sub Command1_Click () List1. Click the OK button. Setting the DataSource property of the MSFlexGrid control to Data1 automatically links the grid to the data control. When you select the DatabaseName property in the Properties window. and MSFlexGrid1_DblClick event procedures. End Sub In the above statement. and two command buttons on the form. Object Form Data1 Property Caption DatabaseName RecordSource MSFlexGrid1 Command1 Command2 DataSource Caption Caption Setting Products path \Nwind. The Clear method deletes the contents of the list box.
the first statement invokes the Unload event for the form. One possible name for the project is "Northwind Shopping List. As you .AddItem MSFlexGrid1. Saving a Project You finish your work on the application by choosing Save Project from the File menu. the value of the title field in the recordset of the data control. You can use this application as a basis for adding similar functionality in your own applications. Add this code to the Data1_Reposition event procedure to update the caption each time a record is selected: Private Sub Data1_Reposition () Data1. The text to be added to the list box is contained in the argument of the method.Recordset("ProductName") End Sub In the above statement. Add this code to the MSFlexGrid_DblClick event procedure to add an item to the list box when the user doubleclicks a selected row: Private Sub MSFlexGrid1_DblClick () List1.mdb. Older versions of Microsoft Windows limited you to file names of eight characters. Of course.Text End Sub In the above statement.Caption = Data1. Enhancing Your Application You have just completed your first Visual Basic application: one that performs a simple but useful function. substituting your own data instead of Nwind. The second statement calls the End function." Windows 95.Add this code to the Command2_Click event procedure to unload the form from memory and end the application: Private Sub Command2_Click () Unload Form1 End ' Ends application. which ends the application. such as saving a file. Visual Basic will prompt you separately to save the form and then the project. End Sub In the above procedure. to add additional information such as price and availability. with a three-character extension. If you needed to perform a function at shutdown. you could place that code in the form's Unload event procedure. in this case. and even to gather credit card information and transmit an order across the Internet. to make this application truly useful. Passing a value to an argument is similar to assigning a value to a property. and file names can include spaces. you might want to add functionality to save or print the contents of the list box. you are assigning the value on the right (the contents of the Title field in the Recordset of the data control) to the property on the left (the Caption property of the data control object). the equal sign isn't required. and Windows NT allow you to use file names up to 255 characters in length. you are invoking the AddItem method of the list box (List1). Windows 98. unlike the assignment statement.
all balloons are capable of these methods. or to the event of being released by rising into the air. methods. methods and events. you will find examples of doing all that and a lot more. Other controls let you access other applications and process data as if the remote application was part of your code. and events which define their interaction with the user. you customize the object to meet the requirements of your application. A balloon's properties include visible attributes such as its height. and events as its responses. they are the objects that you will work with to build your application. the visual part of the application with which the user will interact. Properties can be thought of as an object's attributes. An everyday object like a child's helium balloon also has properties. a balloon would respond to the event of being punctured by deflating itself. as well as form-specific items such as menus and dialog boxes. For instance. methods and events. and Menus The first step to creating an application with Visual Basic is to create the interface. By setting the properties of the form and writing Visual Basic code to respond to its events. and events. methods as its actions. Other properties describe its state (inflated or not inflated). This chapter introduces the basic concepts of working with forms and controls and their associated properties. Again. the settings of these properties may differ from one balloon to another. diameter and color. . Controls. Controls are objects that are contained within form objects. Visual Studio 6. Many of the standard controls are discussed. Forms and controls are the basic building blocks used to create the interface. all balloons have these properties. or attributes that aren't visible such as its age. Forms are objects that expose properties which define their appearance. methods which define their behavior. Understanding Properties. By definition. Each type of control has its own set of properties. It has an inflate method (the action of filling it with helium). Methods and Events Visual Basic forms and controls are objects which expose their own properties.continue on through the rest of the Programmer's Guide. Some of the controls you can use in your applications are best suited for entering or displaying text.0 Forms. Balloons also have predefined responses to certain external events. methods and events that make it suitable for a particular purpose. a deflate method (expelling its contents) and a rise method (if you were to let go of it). A balloon also has inherent methods or actions that it might perform.
1 Objects have properties.Color) followed by the assignment of the value (Red). While you can't actually program a balloon. and perform methods If you were able to program a balloon. you can program a Visual Basic form or control. you are in control. which denotes the distance to rise.Figure 3. then invoke the MakeNoise method with an argument of "Bang" (the type of noise to make). the code describes the balloon's behavior when a puncture event occurs: invoke the Deflate method. Properties can also be set in the Properties window while you are designing your application. respond to events.Rise 5 The syntax is similar to the property ³ the object (a noun) followed by the method (a verb). You decide which properties should be changed. The balloon might respond to an event as follows: Sub Balloon_Puncture() Balloon.Diameter = 1 End Sub In this case.Inflated = False Balloon. To set the balloon's properties: Balloon. called an argument. A balloon's methods are invoked like this: Balloon.MakeNoise "Bang" Balloon. You could change the color of the balloon from code by repeating this statement and substituting a different value.Inflated = True Note the syntax of the code ³ the object (Balloon) followed by the property (.Diameter = 10 Balloon. the Inflated property is set to False and the Diameter property is set to a new value. there is an additional item. Since the balloon is no longer inflated.Color = Red Balloon.Inflate Balloon. As the programmer. Some methods will have one or more arguments to further describe the action to be performed. the Visual Basic code might look like the following. methods invoked or events responded to in order to achieve the desired appearance and behavior. In the third example.Deflate Balloon. .Deflate Balloon.
Run time is any time you are actually running the application and interacting with the application as the user would. Left and Top properties determine the form's location in relation to the upper left-hand corner of the screen. minimized. You can learn more about each property by selecting it and pressing F1 to view the context-sensitive Help.2 Forms and controls have their own properties. You can set a form's properties at design time in the Properties window. and methods with which you can control their appearance and behavior.0 Designing a Form Form objects are the basic building blocks of a Visual Basic application. Forms have their own properties. the Icon property sets the icon that is displayed when a form is minimized. The Name property sets the name by which you will refer to the form in code. events. or at run time by writing code. Form2. Height and Width properties determine the initial size of a form. its name is set to Form1. Change some of the properties of a form in the Properties window (Figure 3. Figure 3. The MaxButton and MinButton properties determine whether the form can be maximized or minimized. Figure 3. The Caption property determines the text that is shown in the form's title bar. and write code for their events at design time. or normal state. By default. Note You work with forms and controls. By changing the BorderStyle property. when a form is first added to a project. such as "frmEntry" for an order entry form. events. The best way to familiarize yourself with the many form properties is to experiment. which is any time you're building an application in the Visual Basic environment. The WindowState property can be set to start the form in a maximized.Visual Studio 6.3). you can control the resizing behavior of the form. and methods The first step in designing a form is to set its properties. the actual windows with which a user interacts when they run the application. It's a good idea to set the Name property to something more meaningful. and so forth. Setting Form Properties Many of a form's properties affect its physical appearance. set their properties. then run the application to see their effect.3 The Properties window .
Form Events and Methods As objects. forms can perform methods and respond to events. These methods and more are discussed in "Working with Text and Graphics. see "More About Forms" in "Creating a User Interface. For example. Many of a form's methods involve text or graphics. The Activate event occurs whenever a form becomes the active form." For More Information For additional information on forms. or you can create your own "button" using an image control containing a graphic. in the Deactivate event you might save changes to a file or database. such as an icon. Circle.0 Clicking Buttons to Perform Actions The easiest way to allow the user to interact with an application is to provide a button to click. To make a form visible. Using Command Buttons .Show Invoking the Show method has the same effect as setting a form's Visible property to True. you would invoke the Show method: Form2. The Print. Line. These events are convenient for initializing or finalizing the form's behavior. the Deactivate event occurs when another form or application becomes active. This allows you to perform actions such as moving or resizing controls on a form when its dimensions have changed. either by user interaction or through code. in the Activate event you might write code to highlight the text in a particular text box. and Refresh methods are useful for printing or drawing directly onto a form's surface. The Resize event of a form is triggered whenever a form is resized." Visual Basic Concepts Visual Studio 6. You can use the command button control provided by Visual Basic.
Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. even if you change the focus to a different control other than a command button. it not only carries out the appropriate action. Change &Signal).vbp sample application. it also looks as if it's being pushed in and released. pressing ENTER chooses the button. At design time. When the user chooses the button. you specify a default command button by setting that button's Default property to True. If the command button is the default Cancel button for the form. and then choose the button by pressing the SPACEBAR or ENTER. (See "Understanding Focus" later in this chapter. Whenever the user clicks a button. the Test Buttons example from the Controls sample application contains a command button with its Caption property set to "Change Signal. You place code in the Click event procedure to perform any action you choose. Figure 3. see Button. Set the command button's Value property to True in code: y y y y y y cmdClose.) Press an access key (ALT+ the underlined letter) for a command button. the Click event procedure is invoked. There are many ways to choose a command button at run time: y y Use a mouse to click the button. you specify a default Cancel button by setting that button's Cancel property to True. In Figure 3.) Notice that 'S' is the access key for this button. denoted by an underline. Inserting an ampersand (&) in the text of the Caption property makes the character following it the access key for that button (for example. y All these actions cause Visual Basic to invoke the Click event procedure.4 Command button with a caption ." (For a working version of this example.frm in the Controls. then pressing ESC chooses the button. even if you change the focus to another control.4. Move the focus to the button by pressing the TAB key. The Test Buttons Application You use the Caption property to display text on the button to tell the user what the button does.Value = True Invoke the command button's Click event in code: cmdClose_Click If the command button is the default command button for the form. At design time.
The actual text displayed in a label is controlled by the Caption property. if you set the BorderStyle property to 1 (which you can do at design time). the caption is the only visible part of the label control. Labels contain text that can only be read. To provide this feature Text that can be edited by the user. Sizing a Label to Fit Its Contents . You can use labels to identify controls. see "Using Visual Basic's Standard Controls. the label appears with a border ³ giving it a look similar to a text box. for example to identify a field on a form or display instructions to the user Label Use this control Text box Labels and text boxes are discussed in the following sections: Using Labels to Display Text A label control displays text that the user cannot directly change. which can be set at design time in the Properties window or at run time by assigning it in code. such as text boxes and scroll bars. Use labels when you want your application to display text on a form. and text boxes when you want to allow the user to enter text. For More Information For information on additional properties of the command button. that do not have their own Caption property." Controls for Displaying and Entering Text Label and text box controls are used to display or enter text. while text boxes contain text that can be edited. By default. for example an order entry field or a password box Text that is displayed only. BackStyle. a different traffic light icon is displayed each time the button is clicked. In the example. You can also change the appearance of the label by setting the BackColor. However. the code in the command button's Click event procedure is executed. and Font properties.When a user clicks the command button. ForeColor.
as shown in Figure 3. AutoSize must be set to True.6. Figure 3.frm in the Controls. as shown in Figure 3. while retaining the same width. you'll notice that for the WordWrap example to actually work. For More Information For additional information on the label control's properties. For a working version of this example. But what if you want to enter a longer caption. see Wordwrap. If set to True. The width of the label is increased only if the width of a single word exceeds the current width of the control.5. unless you've set the Locked property to True. Text boxes should not be used to display text that you don't want the user to change. for the label's WordWrap property to take effect. The AutoSize property determines if a control should be automatically resized to fit its contents. see "Using Visual Basic's Standard Controls. both check boxes must be selected. Figure 3.5 AutoSize example The WordWrap property causes the label to grow vertically to fit its contents.Single-line label captions can be specified at design time in the Properties window. the label grows horizontally to fit its contents. .vbp.6 WordWrap example Note If you run the AutoSize example from Controls. or a caption that will change at run time? Labels have two properties that help you size the controls to fit larger or smaller captions: AutoSize and WordWrap." Working with Text Boxes Text boxes are versatile controls that can be used to get input from the user or to display text.vbp sample application. This is because.
Note The ScrollBars property should not be confused with scroll bar controls. For example. MultiLine and ScrollBars. The SelStart and SelLength properties allow you to modify the behavior to suit your purpose. A multipleline text box automatically manages word wrap as long as there is no horizontal scroll bar.7 Insertion point example . In some cases.Text = "Here are two lines" _ & vbCrLf & "in a text box" End Sub Working with Text in a Text Box You can control the insertion point and selection behavior in a text box with the SelStart. a text box displays a single line of text and does not display scroll bars. In a word processing application. the default insertion point or cursor position within the text box is to the left of any existing text.The actual text displayed in a text box is controlled by the Text property.7. If the text box loses and then regains the focus. which are available only at design time. Multiple-Line Text Boxes and Word Wrap By default. When a line of text is longer than what can be displayed on a line. only part of the text will be visible. SelLength and SelText properties. Line breaks cannot be entered in the Properties window at design time. If the SelStart property is set to a value equal to or greater than the number of characters in the text box.frm in the Controls. If the text is longer than the available space. which are not attached to text boxes and have their own set of properties. When a text box first receives the focus. the following event procedure puts two lines of text into a multiple-line text box (Text1) when the form is loaded: Sub Form_Load () Text1. the user might expect new characters to appear after any existing text. with 0 being the left-most position. Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. at run time by setting it in code. the user might expect their typing to replace any existing entry. the text box wraps the text to the next line. Automatic word wrap saves the user the trouble of inserting line breaks at the end of lines. the insertion point will be placed after the last character. or by input from the user at run time. The look and behavior of a text box can be changed by setting two properties. The SelStart property is a number that indicates the insertion point within the string of text. as shown in Figure 3. These properties are only available at run time.vbp sample application. Figure 3. see Text. the insertion point will be wherever the user last placed it. It can be set in three different ways: at design time in the Property window. For a working version of this example. this behavior can be disconcerting to the user. You can also use the constant vbCrLf to insert a carriage return/linefeed combination. The ScrollBars property is set to 0-None by default. Within a procedure. The current contents of a text box can be retrieved at run time by reading the Text property. It can be moved by the user from the keyboard or with the mouse. you create a line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and 10). In a data entry application.
the selected text will be replaced." Controls That Present Choices to Users Most applications need to present choices to their users. A small set of options from which a user can choose just one. In some cases.The SelLength property is a numeric value that sets the width of the insertion point. see "Using Visual Basic's Standard Controls. ranging from a simple yes/no option to selecting from a list containing hundreds of possibilities. To provide this feature A small set of choices from which a user can choose one or more options.8 Selection example If the user starts typing while a block of text is selected. Option buttons (use frames if additional groups are needed) Use this control Check boxes .8 shows the selection behavior. you might want to replace a text selection with new text by using a paste command. The following table summarizes these controls and their appropriate uses. The SelText property is a string of text that you can assign at run time to replace the current selection. SelText will insert its text at the current insertion point. Visual Basic includes several standard controls that are useful for presenting choices. starting from the current insertion point. For More Information For additional information on the text box control's properties. Figure 3. Setting the SelLength to a number greater than 0 causes that number of characters to be selected and highlighted. If no text is selected. Figure 3.
A scrollable list of choices from which the user can choose. a command button. You use check boxes in an application to give users true/false or yes/no options. For a working version of this example. Bold and Italic can both be checked. List box Combo box Selecting Individual Options with Check Boxes A check box indicates whether a particular condition is on or off. a user can select any number of check boxes at the same time. The application has a text box.frm in the Controls. Figure 3. For example in Figure 3.10 Check box example The following table lists the property settings for the objects in the application. Because check boxes work independently of each other. Figure 3.9 Check boxes The Check Box Application The Check Box example uses a check box to determine whether the text is displayed in regular or italic font. The user can either choose from the list or type a choice in the edit field. and two check boxes. as shown in Figure 3.10. Object Property Setting .vbp sample application. see Check. a label. A scrollable list of choices along with a text edit field.9.
Italic = False End If End Sub Grouping Options with Option Buttons Option buttons present a set of two or more choices to the user. its Value property is set to 0.Value = vbChecked Then ' If checked.Italic = True Else ' If not checked. txtDisplay.Bold = True Else ' If not checked.Form Name Caption frmCheck Check Box Example txtDisplay Some sample text chkBold &Bold chkItalic &Italic cmdClose &Close Text box Name Text First Check box Name Caption Second Check box Name Caption Command button Name Caption When you check Bold or Italic.Font.Font. Private Sub chkBold_Click () If ChkBold. txtDisplay. Events in the Check Box Application The Click event for the check box occurs as soon as you click the box. the text is converted to bold or italic by setting the Bold or Italic properties of the Font object returned by the Font property of the text box.Font. the check box's Value property is set to 1. txtDisplay. If so. txtDisplay. the check box will be unchecked when it is first displayed. This event procedure tests to see whether the check box has been selected (that is. so unless you change Value. The default Value is 0. selecting one option button immediately clears all the other buttons in . Unlike check boxes. when unchecked. if its Value = vbChecked).Font. option buttons should always work as part of a group.Bold = False End If End Sub Private Sub chkItalic_Click () If ChkItalic. however.Value = vbChecked Then ' If checked. You can use the constants vbChecked and vbUnchecked to represent the values 1 and 0.
the group. Repeat step 2 for each additional option button you wish to add to the frame. you must place some of them inside frames or picture boxes. always draw the frame or picture box first. Select the option button control from the toolbox and draw the control within the frame.12 Option button groups A user can select only one option button in the group when you draw option buttons in a frame.12 shows a form with two option button groups. Figure 3. not in a frame or picture box) constitute one group. Defining an option button group tells the user. If you want to create additional option button groups. Figure 3. in the option button group shown in Figure 3. If you try to move existing controls onto a frame. and then draw the option buttons on top of it. When you create a separate group this way. Drawing the frame first and then drawing each control on the frame allows you to move the frame and controls together. as do all the option buttons inside a picture box.11. the user can select one of three option buttons. 3.11 Selecting an option button Creating Option Button Groups All of the option buttons placed directly on a form (that is. 2." For example. All the option buttons inside any given frame constitute a separate group. . Select the frame control from the toolbox and draw the frame on the form. Figure 3. "Here is a set of choices from which you can choose one and only one. the controls will not move with the frame. To group controls in a frame 1.
vbp sample application. y y y To make a button the default in an option button group. It remains selected until a user selects a different option button or code changes it. The Options Application The form shown in Figure 3. you need to understand that all controls are children of the form on which they are drawn. The Left and Top properties of a control are relative to the parent form. Assigning its Value property to True in code: optChoice. meaning that it is unavailable.Value = True Using a shortcut key specified in the caption of a label. Selecting or Disabling Option Buttons An option button can be selected by: y y Clicking it at run time with the mouse. most controls support the read-only Parent property. set its Value property to True at design time.12 demonstrates how option buttons can be contained within a form or within a frame control. and the control's position relative to the container's Left and Top properties does not change because the control moves with the container. In fact. To understand the concept of containers.13 uses option buttons to determine the processor type and operating system for a fictional computer. Containers for Controls While controls are independent objects. When the user selects a option button in either group. For a working version of this example. To disable an option button. set its Enabled property to False. and controls cannot be moved outside the boundaries of the parent. Tabbing to the option button group and then using the arrow keys to select an option button within the group. When the program is run it will appear dimmed. the caption of the label is changed to reflect the current choices. Moving a container moves the controls as well. which returns the form on which a control is located. Figure 3. see Options. a certain parent and child relationship exists between forms and controls. Being a child affects the placement of a control on the parent form.Note If you have existing controls that you want to group in a frame. Figure 3.frm in the Controls. you can select all the controls and cut and paste them into a frame or picture control.13 Option button example .
Object Label Property Name Caption Command button Name Caption First option button Name Caption Second option button Name Caption Value Third option button Name Caption Frame Name Caption Fourth option button Name Caption Fifth option button Name Caption Value Setting lblDisplay (Empty) cmdClose &Close opt486 &486 opt586 &Pentium True opt686 P&entium Pro fraSystem &Operating System optWin95 Windows 95 optWinNT Windows NT True .The following table lists the property settings for the objects in the application.
14 Single-column list box . The user can then scroll up and down or left to right through the list. strComputer. that concatenates the two variables and updates the label's Caption property: Sub DisplayCaption() lblDisplay. Each time a new option button is selected. scroll bars automatically appear on the control. y The key to this approach is the use of these two form-level variables. although you can set up multiple columns as well. Figure 3. strSystem. only the value of the variables change from one instance to the next. called DisplayCaption. the code in its Click event updates the appropriate variable: Private Sub opt586_Click() strComputer = "Pentium" Call DisplayCaption End Sub It then calls a sub procedure." Using List Boxes and Combo Boxes List boxes and combo boxes present a list of choices to the user.Caption = "You selected a " & _ strComputer & " running " & strSystem End Sub A sub procedure is used because the procedure of updating the Caption property is essentially the same for all five option buttons. For More Information Variables and sub procedures are discussed in detail in "Programming Fundamentals.14 shows a single-column list box. This saves you from having to repeat the same code in each of the Click events. These variables contain different string values. depending on which option buttons were last selected. strComputer and strSystem. If the number of items exceeds what can be displayed in the combo box or list box. the choices are displayed vertically in a single column.Events in the Options Application The Options application responds to events as follows: y The Click events for the first three option buttons assign a corresponding description to a form-level string variable. Figure 3. By default. The Click events for the last two option buttons assign a corresponding description to a second formlevel variable.
A combo box control combines the features of a text box and a list box. Figure 3. or MDI forms (text boxes and MDI forms have a ScrollBars property to add or remove scroll bars that are attached to the control). the code would look like this: List1. The HScrollBar (horizontal) and VScrollBar (vertical) controls operate independently from other controls and have their own set of events.15 Combo box In contrast to some other controls that contain a single value. Scroll bar controls are not the same as the built-in scroll bars that are attached to text boxes.AddItem "San Francisco" List boxes and combo boxes are an effective way to present a large number of choices to the user in a limited amount of space.AddItem "New York" List1. list boxes. removing and retrieving values from their collections at run time. Examples of slider controls can be seen in the Windows 95/98 control panel. Because these controls can indicate the current position on a scale. see "Using Visual Basic's Standard Controls.AddItem "Paris" List1. and methods. to control the sound volume or to adjust the colors in a picture. To add several items to a list box named List1. This control allows the user to select either by typing text into the combo box or by selecting an item from its list. scroll bar controls can be used individually to control program input ³ for example. properties." Using Scroll Bars as Input Devices Although scroll bars are often tied to text boxes or windows. list boxes and combo boxes contain multiple values or a collection of values. for example the label's Caption property or the text box's Text property. combo boxes. They have built-in methods for adding. . Windows interface guidelines now suggest using slider controls as input devices instead of scroll bars. A slider control of this type is included in the Professional and Enterprise editions of Visual Basic.15 shows a combo box. you'll sometimes see them used as input devices. For More Information For additional information on the list box and combo box controls. Figure 3.
To provide this feature A container for other controls. The actual picture that is displayed is determined by the Picture property. the shape control.Picture = LoadPicture("VANGOGH. image controls.gif") The picture box control has an AutoSize property that. They require less system resources and consequently display somewhat faster than the picture box control. shape and line controls are sometimes referred to as "lightweight" graphical controls. and line controls are discussed in the following sections: Working With the Picture Box Control The primary use for the picture box control is to display a picture to the user. the image control. you can use the LoadPicture function to set the Picture property. causes the picture box to resize automatically to match the dimensions of its contents. when set to True. Each is best suited for a particular purpose. Displaying a simple graphical element Use this control Picture box Picture box Image control or picture box Shape or line control Picture boxes.For More Information For additional information on scroll bar controls. shape controls. Displaying a picture. see "Using Visual Basic's Standard Controls. they contain a subset of the properties. To display or replace a picture at run time." Controls That Display Pictures and Graphics Because Windows is a graphical user interface. and the line control. Note Form objects also have a Picture property that can be set to display a picture directly on the form's background. Printing or graphics methods. methods and events available in the picture box. The image. Take extra care in designing your form if you plan on . it's important to have a way to display graphical images in your application's interface. The Picture property contains the file name (and optional path) for the picture file that you wish to display. Visual Basic includes four controls that make it easy to work with graphics: the picture box control. You supply the name (and optional path) for the picture and the LoadPicture function handles the details of loading and displaying it: picMain.
using a picture box with the AutoSize enabled. The picture will resize without regard to other controls on the form, possibly causing unexpected results, such as covering up other controls. It's a good idea to test this by loading each of the pictures at design time.
Using the Picture Box as a Container
The picture box control can also be used as a container for other controls. Like the frame control, you can draw other controls on top of the picture box. The contained controls move with the picture box and their Top and Left properties will be relative to the picture box rather than the form. A common use for the picture box container is as a toolbar or status bar. You can place image controls on it to act as buttons, or add labels to display status messages. By setting the Align property to Top, Bottom, Left, or Right, the picture box will "stick" to the edge of the form. Figure 3.16 shows a picture box with its Align property set to Bottom. It contains two label controls which could be used to display status messages. Figure 3.16 Picture box used as a status bar
Other Uses for the Picture Box
The picture box control has several methods that make it useful for other purposes. Think of the picture box as a blank canvas upon which you can paint, draw or print. A single control can be used to display text, graphics or even simple animation. The Print method allows you to output text to the picture box control just as you would to a printer. Several font properties are available to control the characteristics of text output by the Print method; the Cls method can be used to erase the output. Circle, Line, Point and Pset methods may be used to draw graphics on the picture box. Properties such as DrawWidth, FillColor, and FillStyle allow you to customize the appearance of the graphics. Animation can be created using the PaintPicture method by moving images within the picture control and rapidly changing between several different images. For More Information For additional information on the picture box control, see "Using Visual Basic's Standard Controls."
Lightweight Graphical Controls
The image, shape and line controls are considered to be lightweight controls; that is, they support only a subset of the properties, methods, and events found in the picture box. Because of this, they typically require less system resources and load faster than the picture box control.
Using Image Controls Instead of Picture Boxes
The image control is similar to the picture box control but is used only for displaying pictures. It doesn't have the ability to act as a container for other controls, and it doesn't support the advanced methods of the picture box. Pictures are loaded into the image control just as they are in the picture box: at design time, set the Picture property to a file name and path; at run time, use the LoadPicture function.. For More Information For additional information on the image control, see "Using Visual Basic's Standard Controls."
Using an Image Control to Create Your Own Buttons
An image control also recognizes the Click event, so you can use this control anywhere you'd use a command button. This is a convenient way to create a button with a picture instead of a caption. Grouping several image controls together horizontally across the top of the screen ³ usually within a picture box ³ allows you to create a toolbar in your application. For instance, the Test Buttons example shows an image control that users can choose like they choose a command button. When the form is first displayed, the control displays one of three traffic icons from the Icon Library included with Visual Basic. Each time the image control is clicked, a different icon is displayed. (For a working version of this example, see Button.frm in the Controls.vbp sample application.) If you inspect the form at design time, you will see that it actually contains all three icons "stacked" on top of each other. By changing the Visible property of the top image control to False, you allow the next image (with its Visible property set to True) to appear on top. Figure 3.17 shows the image control with one of the traffic icons (Trffc10a.ico). Figure 3.17 Image control with a traffic icon
To create a border around the image control, set the BorderStyle property to 1-Fixed Single. Note Unlike command buttons, image controls do not appear pushed in when clicked. This means that unless you change the bitmap in the MouseDown event, there is no visual cue to the user that the "button" is being pushed. For More Information For information on displaying a graphic image in an image control, see "Using Visual Basic's Standard Controls."
Using Shape and Line Controls
Shape and line controls are useful for drawing graphical elements on the surface of a form. These controls don't support any events; they are strictly for decorative purposes. Several properties are provided to control the appearance of the shape control. By setting the Shape property, it can be displayed as a rectangle, square, oval, circle, rounded rectangle, or rounded square. The BorderColor and FillColor properties can be set to change the color; the BorderStyle, BorderWidth, FillStyle, and DrawMode properties control how the shape is drawn. The line control is similar to the shape control but can only be used to draw straight lines. For More Information For additional information on the shape and line controls, see "Using Visual Basic's Standard Controls."
The Images Application
The form shown in Figure 3.18 uses four image controls, a shape control, a picture box, and a command button. When the user selects a playing card symbol, the shape control highlights the symbol and a description is displayed in the picture box. For a working version of this example, see Images.frm in the Controls.vbp sample application. Figure 3.18 Image and shape control example
The following table lists the property settings for the objects in the application. Object Picture box Property Name Align First image control Name Picture Second image control Name Picture Third image control Name Picture Fourth image control Name Caption Shape control Name Shape BorderWidth Height Width Command button Name Caption Setting picStatus Bottom imgClub Spade.ico imgDiamond Diamond.ico imgHeart Heart.ico imgSpade Spade.ico shpCard 4 - Rounded Rectangle 2 735 495 cmdClose &Close
Events in the Images Application
The Images application responds to events as follows:
y
The Click event in each of the image controls sets the Left property of the shape control equal to its own Left property, moving the shape on top of the image. The Cls method of the picture box is invoked, clearing the current caption from the status bar. The Print method of the picture box is invoked, printing the new caption on the status bar.
y y
The code in the image control Click event looks like this:
Private Sub imgHeart_Click() shpCard.Left = imgClub.Left picStatus.Cls picStatus.Print "Selected: Club" shpCard.Visible = True End Sub
Note that the first line in the Click event code assigns a value (the Left property of the image control) to the Left property of the shape control using the = operator. The next two lines invoke methods, so no operator is needed. In the third line, the value ("Selected: Club") is an argument to the Print method. There is one more line of code in the application that is of interest; it is in the Form Load event.
shpCard.Visible = False
By setting the Visible property of the shape control to False, the shape control is hidden until the first image is clicked. The Visible property is set to True as the last step in the image control Click event. For More Information For additional information on properties, methods, and events see "Programming Fundamentals."."
Its properties. For more information on common dialog control. most information is stored in one or more central databases. see the Visual Basic Data Access Guide. At run time.Data Access Controls In today's business. directories and files. Each serves a unique purpose. Miscellaneous Controls Several other standard controls are included in Visual Basic. the user can rearrange columns and rows to provide different views of the data. including Microsoft Access and SQL Server. . These controls are normally used together to provide a view of drives. y y y y For More Information For additional information on data access controls. with the changes appearing in the underlying database. The DataCombo control is like a combination of the DataList control and a text box. Think of it as a pipeline between the database and the other controls on your form. methods. but with the built-in capability of displaying a list of directories in the currently selected drive. The FileListBox control also looks like a list box with a list of file names in a selected directory." For more information on working with external data. y y Note These controls are provided primarily for backward compatibility with applications created in earlier versions of Visual Basic. Visual Basic includes several data access controls for accessing most popular databases. see "Using Visual Basic's Standard Controls. When used in conjunction with an ADO Data control. File System Controls Visual Basic includes three controls for adding file handling capabilities to your application. y The DriveListBox control looks like a combo box. When used in conjunction with an ADO Data control. It provides a drop-down list of drives from which the user can select. The common dialog control provides an easier method of working with file access. and events allow you to navigate and manipulate external data from within your own application. it can be automatically filled with a list of data from a field in an external database. they have special properties and events that tie them together. The Microsoft Hierarchical FlexGrid control is a unique control for presenting multiple views of data. y The ADO Data control is used to connect to a database. The DirListBox is similar to a list box control. Think of it as a combination of a grid and a tree or outline control. The selected text in the text box portion can be edited. The DataGrid control displays data in a grid or table. it presents fully editable data from multiple fields in an external database. see "Miscellaneous Controls" later in this chapter. The DataList control is similar to the list box control.
When an object has the focus. The common dialog control adds built-in dialog boxes to your application for the selection of files. when command buttons have the focus. Occurs when an object loses focus. only the text box with the focus will display text entered by means of the keyboard. For example. see "Using Visual Basic's Standard Controls.y The timer control can be used to create an event in your application at a recurring interval. several applications can be running at any time. Using the SetFocus method in code. and printing functions. You can see when some objects have the focus. Forms and most controls support these events. but only the application with the focus will have an active title bar and can receive user input. You can give focus to an object by: y y y Selecting the object at run time. Through the OLE container control. fonts.19). On a Visual Basic form with several text boxes. Event GotFocus LostFocus Description Occurs when an object receives focus." Understanding Focus Focus is the ability to receive user input through the mouse or keyboard. or for reversing or changing conditions you set up in the object's GotFocus procedure. The OLE container control is an easy way to add capabilities like linking and embedding to your application. it can receive input from a user. Figure 3. In the Microsoft Windows interface. they appear with a highlighted border around the caption (see Figure 3. This is useful for executing code without the need for user interaction. Word and many others. The GotFocus and LostFocus events occur when an object receives or loses focus. Using an access key to select the object at run time. A LostFocus event procedure is primarily used for verification and validation updates. you can provide access to the functionality of any OLEenabled application such as Microsoft Excel. colors.19 A command button showing focus . y y For More Information For additional information on any of the standard controls.
For more information. When the application starts. Text1 has the focus. Command1. which occurs before a control loses focus. In many cases. controls that are invisible at run time. Validate Event of Controls Controls also have a Validate event. For example. because the Validate event occurs before the focus is lost.20. The Enabled property allows the object to respond to user-generated events such as keyboard and mouse events. Note A form can receive focus only if it doesn't contain any controls that can receive the focus. cannot receive focus. such as the Timer control. such as the lightweight controls. this event occurs only when the CausesValidation property of the control that is about to receive the focus is set to True. Lightweight controls include the following: y y y y y Frame control Image control Label control Line control Shape control Additionally. Text1 and Text2. cannot receive focus. and then a command button. it is more appropriate than the LostFocus event for data validation. as shown in Figure 3. . assume you create two text boxes. the tab order is the same as the order in which you created the controls. Usually. see "Validating Control Data By Restricting Focus" in "Using Visual Basic's Standard Controls That Can't Receive Focus Some controls. The Visible property determines whether an object is visible on the screen. Setting the Tab Order The tab order is the order in which a user moves from one control to another by pressing the TAB key. Pressing TAB moves the focus between controls in the order they were created.An object can receive focus only if its Enabled and Visible properties are set to True. Each form has its own tab order. However.
the second has a TabIndex of 1. the button with its Value set to True) has its TabStop property automatically set to True. set the TabIndex property. don't have a TabIndex property and are not included in the tab order. even though the control is skipped when you cycle through the controls with the TAB key. You can remove a control from the tab order by setting its TabStop property to False (0). Visual Basic automatically renumbers the tab order positions of the other controls to reflect insertions and deletions. Note An option button group has a single tab stop. The selected button (that is. Removing a Control from the Tab Order Usually. As a user presses the TAB key.20 Tab example To change the tab order for a control.Figure 3. the first control drawn has a TabIndex value of 0. Even if you set the TabIndex property to a number higher than the number of controls. The TabIndex property of a control determines where it is positioned in the tab order. and so on. while the other buttons have their TabStop property set to False. When you change a control's tab order position. these controls are skipped. For example. Visual Basic converts the value back to the number of controls minus 1. as shown in the following table. . TabIndex before it is changed Control Text1 Text2 Command1 0 1 2 1 2 0 TabIndex after it is changed The highest TabIndex setting is always one less than the number of controls in the tab order (because numbering starts at 0). pressing TAB at run time selects each control in the tab order. the TabIndex values for the other controls are automatically adjusted upward. A control whose TabStop property has been set to False still maintains its position in the actual tab order. as well as disabled and invisible controls. Note Controls that cannot get the focus. if you make Command1 first in the tab order. By default.
A menu control is an object. for example.22. which is invoked when the menu control is selected with the mouse or using the keyboard. the Click event. When you click a menu title (such as File). and Save As¬ are all found on the File menu. and others at design time or at run time. (In Windows 95 or later. if you click a text box with the right mouse button. the Exit menu item on the File menu closes the application.21. Some menu items perform an action directly. and submenu titles. the Enabled and Visible properties. menus offer a convenient and consistent way to group commands and an easy way for users to access them. These menu items should be followed by an ellipsis (¬).Menu Basics If you want your application to provide a set of commands to users. the Checked property. Menu controls contain only one event. the file-related commands New. like other objects it has properties that can be used to define its appearance and behavior. you activate context menus by clicking the right mouse button. separator bars.22. independent of the menu bar. the Save File As dialog box appears. Figure 3. For example. Other menu items display a dialog box ³ a window that requires the user to supply information needed by the application to perform the action. In Figure 3. pop-up menus are also called context menus. Menu items can include commands (such as New and Exit).21 The elements of a menu interface on a Visual Basic form The menu bar appears immediately below the title bar on the form and contains one or more menu titles. Open. For example. you should group menu items according to their function. To make your application easier to use. Figure 3. when you choose Save As¬ from the File menu. You can set the Caption property.) You should use pop-up menus to provide an efficient method for accessing common. for example. see "Creating Menus with the Menu Editor" in "Creating a User Interface. Each menu item the user sees corresponds to a menu control you define in the Menu Editor (described later in this chapter). The items displayed on the pop-up menu depend on the location of the pointer when the right mouse button is pressed. For More Information For additional information on menu controls. contextual commands. therefore.22 A pop-up menu .21 Illustrates the elements of a menu interface on an untitled form." Pop-up Menus A pop-up menu is a floating menu that is displayed over a form. a menu containing a list of menu items drops down. as shown in Figure 3. a contextual menu would appear. Figure 3. as shown in Figure 3.
to quickly change a single property.23 Figure 3. see "Creating Menus" in "Creating a User Interface. You would normally create a menu in the Menu Editor. and change and delete existing menus and menu bars. shown in Figure 3.23 The Menu Editor While most menu control properties can be set using the Menu Editor. you can add new commands to existing menus. use the PopupMenu method. choose Menu Editor. To display a pop-up menu. all menu properties are also available in the Properties window. To display the Menu Editor y From the Tools menu.Any menu that has at least one menu item can be displayed at run time as a pop-up menu. You can customize menus in a completely interactive manner that involves very little programming. see "Creating Menus" in "Creating a User Interface. you could use the Properties window. create new menus and menu bars. This opens the Menu Editor. replace existing menu commands with your own commands." Using the Menu Editor With the Menu Editor. The main advantage of the Menu Editor is its ease of use. For More Information For additional information on creating pop-up menus." Prompting the User with Dialog Boxes . however. For More Information For additional information on creating menus and using the Menu Editor.
Modeless dialog boxes are rare. a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box. y Figure 3.24 looks like this: MsgBox "Error encountered while trying to open file. Dialog boxes are a specialized type of form object that can be created in one of three ways: y y Predefined dialog boxes can be created from code using the MsgBox or InputBox functions. Managing Projects To create an application with Visual Basic. This chapter describes how to build and manage projects. The code for displaying the dialog box shown in Figure 3. You can continue to work elsewhere in the current application while the dialog box is displayed. Customized dialog boxes can be created using a standard form or by customizing an existing dialog box. Figure 3. or arguments. "Text Editor" You supply three pieces of information. a constant (numeric value) to determine the style of the dialog box.In Windows-based applications. From the Edit menu.". vbExclamation. Styles are available with various combinations of buttons and icons to make creating dialog boxes easy.24 shows an example of a predefined dialog box created using the MsgBox function. such as Print and File Open. and a title. Modeless dialog boxes let you shift the focus between the dialog box and another form without having to close the dialog box. . Use modeless dialog boxes to display frequently used commands or information." & vbCrLf & "please retry. they are usually displayed as modal dialog boxes. A modal dialog box must be closed (hidden or unloaded) before you can continue working with the rest of the application. For example. the Find dialog box in Visual Basic is an example of a modeless dialog box. A project is the collection of files you use to build an application. Because most dialog boxes require user interaction. Standard dialog boxes. to the MsgBox function: the message text. you work with projects. dialog boxes are used to prompt the user for data needed by the application to continue or to display information to the user. can be created using the common dialog control. you will usually display a dialog because a response is needed before the application can continue.24 A predefined dialog box This dialog is displayed when you invoke the MsgBox function in code.
frx). add. and File Formats. Optionally. When you have completed all the files for a project. All of the files and objects can be shared by other projects as well. . you will usually create new forms.dll files. choose the Make project. one or more files containing ActiveX controls (. Optionally. This information is updated every time you save the project. or remove editable files from a project. One file for each form (. you can convert the project into an executable file (.ocx). Visual Basic reflects your changes in the Project Explorer window." The Project Explorer As you create. Optionally. you might also reuse or modify forms that were created for previous projects. which contains a current list of the files in the project. Limitations. y y y y The project file is simply a list of all the files and objects associated with the project. for additional information related to other project types see the Component Tools Guide.cls).ocx and .bas).exe command.res). A project consists of: y y y One project file that keeps track of all the components (.frm file that contains binary properties. one file for each class module (.vbp).1 shows some of the types of files you can include in a Visual Basic project.frm). you work with a project to manage all the different files that make up the application. For information about binary data files and project files." later in this chapter. For More Information For more details about creating executables. After all of the components in a project have been assembled and the code written. These files are not editable and are automatically generated for any . References in this chapter assume a standard . Note With the Professional and Enterprise editions of Visual Basic.When you create an application. see "Making and Running an Executable File. The same is true for other modules or files that you might include in your project.exe project. Working with Projects As you develop an application. ActiveX controls and objects from other applications can also be shared between projects. as well as information on the environment options you set. a single resource file (. see "Visual Basic Specifications. you compile your project to create an executable file. The Project Explorer window in Figure 4. Optionally. one file for each standard module (. One binary data file for each form containing data for properties of controls on the form (. you can also create other types of executable files such as .exe): From the File menu. such as Picture or Icon.
cls file name extension) are similar to form modules. as well as references to the ActiveX controls and insertable objects that are used in the project. see "Creating Your Own Classes" in "Programming with Objects. Form Modules Form modules (. A project file contains the same list of files that appears in the Project Explorer window. Limitations. and external procedures. including their property settings. For More Information For information about writing code in class modules. and File Formats. and File Formats. For More Information The specific format of information stored in the .vbp file is described in "Visual Basic Specifications. event procedures. You can use class modules to create your own objects. You can open an existing project file by double-clicking its icon. They can also contain form-level declarations of constants. Limitations. and general procedures." The Structure of a Visual Basic Project The following sections describe the different types of files and objects that you can include in a project.vbp). For More Information For more about creating forms. see "Visual Basic Specifications.frm file name extension) can contain textual descriptions of the form and its controls." Standard Modules ." For information about the format and content of form files.Figure 4. by choosing the Open Project command from the File menu." Class Modules Class modules (.1 The Project Explorer window The Project File Each time you save a project. or by dragging the file and dropping it on the Project Explorer window. including code for methods and properties. Visual Basic updates the project file (. except that they have no visible user interface. see "Developing an Application in Visual Basic" and "Creating a User Interface. variables.
see "Programming Fundamentals" and "Programming with Objects. see "Creating ActiveX Components" in the Component Tools Guide. For More Information For more information on using resource files. For More Information For more information on ActiveX documents. but are used to create ActiveX controls and their associated property pages for displaying design-time properties. The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX controls. constants. Components In addition to files and modules. and "International Issues. text strings. which you can then localize instead of the entire application.dob) are similar to forms. the files containing the controls included with Visual Basic are copied to a common directory (the \Windows\System subdirectory under Windows 95 or later).res file name extension) contain bitmaps.bas file name extension) can contain public or module-level declarations of types. You can also create your own controls using the Professional or Enterprise editions of Visual Basic. A project can contain no more than one resource file. For More Information For more information on ActiveX control creation.ocx file name extension) are optional controls which can be added to the toolbox and used on forms. For More Information For information about using modules.Standard modules (. and public procedures. variables. ActiveX Controls ActiveX controls (. see "Using the ActiveX Controls" in the Component Tools Guide. For More Information For more information on using the included ActiveX controls. When you install Visual Basic. For example." ActiveX Documents ActiveX documents (." in the Component Tools Guide. The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX documents. . external procedures. see "Creating an ActiveX Control" in "Creating ActiveX Components.pag) modules are also similar to forms." Resource Files Resource files (. see "Using a Resource File" later in this chapter. Additional ActiveX controls are available from a wide variety of sources. you can keep all of the user-interface text strings and bitmaps in a resource file. if you plan to localize your application in a foreign language.ctl) and Property Page (. but are displayable in an Internet browser such as Internet Explorer. several other types of components can be added to the project. User Control and Property Page Modules User Control (. and other data that you can change without having to re-edit your code.
and Saving Projects Four commands on the File menu allow you to create. For More Information For more information about ActiveX designers. modules. prompting you to save any files that have changed. For More Information For more information on references. and text. Creating. see "ActiveX Designers" in "Programming with Objects. Open Project Closes the current project. are components you can use as building blocks to build integrated solutions. open. including the forms. You can select a type of project from the New Project dialog." Standard Controls Standard controls are supplied by Visual Basic. prompting you to save any changes. see "Programming with Components. are always included in the toolbox. such as spreadsheets. unlike ActiveX controls and insertable objects. such as a Microsoft Excel Worksheet object. which can be removed from or added to the toolbox.Insertable Objects Insertable objects. accessed from the References menu item on the Project menu.vbp) file. see "Using Other Applications' Objects" later in this chapter. ActiveX Designers ActiveX designers are tools for designing classes from which objects can be created." References You can also add references to external ActiveX components that may be used by your application. Standard controls. and ActiveX controls listed in its project (. bitmaps. which were all created by different applications. An integrated solution can contain data in different formats. You assign references by using the References dialog. . Visual Basic then creates a new project with a single new file. Additional designers may be available from other sources. Opening. and save projects. Menu command New Project Description Closes the current project. For More Information For more information on using other applications' objects. such as the command button or frame control. The design interface for forms is the default designer. Visual Basic then opens an existing project.
such as a form. Visual Basic also prompts you to save any forms or modules that have changed. can be part of more than one project. 2. Removing. and choose Open. 2. This is useful for building and testing solutions involving user-created controls or other components. Select an existing project or a new project type. Select a project or a component of a project in the Project Explorer. Removing. When more than one project is loaded. see "Adding. A single file. Select Project. To remove a project from the current project group 1. Note that changes made to a form or module in one project will be propagated amongst all projects that share that module. choose Remove Project Adding. and Saving Files Working with files within a project is similar to working with the projects themselves. and class modules. standard. To add a file to a project 1. Save Project As Updates the project file of the current project. From the File menu. the caption of the Project Explorer window will change to Project Group and the components of all open projects will be displayed. From the File menu. For More Information For more information about sharing files. . Add filetype (where filetype is the type of file).2) is displayed. saving the project file under a file name that you specify. To add an additional project to the current project group 1. The Add Project dialog box is displayed. The Add filetype dialog box (Figure 4. It is also possible to share files between projects.Save Project Updates the project file of the current project and all of its form. choose Add Project. Working with Multiple Projects In the Professional and Enterprise editions of Visual Basic. it is possible to have more than one project open at a time. and Saving Files" later in this chapter.
You can also drag and drop . To change a file without affecting other projects. If you delete a file outside of Visual Basic. Note You can drag and drop files from the Windows Explorer. Visual Basic displays an error message warning you that a file is missing. To save an individual file without saving the project 1.2. To insert a text file into your code 1. Select an existing file or a new file type. select the form or module into which you want to insert code. select the file in the Project Explorer. if you make changes to a file and save it. choose Save filename As from the File menu. Visual Basic updates this information in the project file when you save it. Figure 4. . This is useful for adding a list of constants or for adding snippets of code that you might have saved in text files. Merging Text You can also insert existing text from other files into one of your code modules. From the Project window. you are not adding a copy of the file. choose Remove filename. The file will be removed from the project but not from the disk. when you open the project. Therefore. Visual Basic cannot update the project file. your changes will affect any project that includes the file. or Network Neighborhood into the Project window to add them to a project. and choose Open. 2. you are simply including a reference to the existing file in the project. From the Project menu. however. Select the file in the Project Explorer. 3.ocx files onto the toolbox to add new controls. To remove a file from a project 1. File Manager. From the File menu.2 The Add Form dialog box When you add a file to a project. choose Save filename . Select the file in the Project Explorer. and then save the file under a new file name. 2. If you remove a file from a project. therefore.
3. All of the ActiveX controls that you selected will now appear in the toolbox. 4. Adding Controls to a Project The set of controls available in the toolbox can be customized for each project. and move the cursor to the point in the Code Editor where you want to insert code. The basic set of standard controls that always appear in the toolbox is described in "Forms. From the Project menu. Choose OK to close the Components dialog box.3 The Components dialog box . as doing so may put the module into an internally inconsistent state. as shown in Figure 4. The items listed in this dialog box include all registered ActiveX controls. insertable objects. To add a control to a project's toolbox 1. select the Controls tab. such as a Microsoft Excel Chart. From the Edit menu. In particular. select the Insertable Objects tab. Any given control must be in the toolbox before you can add it to a form in the project. and ActiveX designers. and choose Open. To view insertable objects. To view controls with . choose Components. changing this attribute may cause serious problems with the GlobalMultiUse and GlobalSingleUse classes. Figure 4. To add a control (. 3. and Menus. you should not edit attributes manually. choose Insert File. The Components dialog box is displayed. Choose the View Code button. be careful not to change settings of the attribute VB_PredeclaredId. 2. select the check box to the left of the control name. Note If you edit Visual Basic source files using a text or code editor other than Visual Basic." Adding ActiveX Controls to a Project You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.ocx file name extension) or an insertable object to the toolbox.3. In general. Select the name of the text file you want to insert. Controls.2.ocx file name extensions.
oca files are typically stored in the same directory as the ActiveX controls and are recreated as needed (file sizes and dates may change). The Components dialog box is displayed. choose the Browse button. 2. but not as controls. From the Project menu. choose References. Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project. To make another application's objects available in your code. To add objects to the toolbox. and search other directories for files with a . 2. set a reference to that application's object library. The References dialog box is displayed. When you add an ActiveX control to the list of available controls. This file stores cached type library information and other data specific to the control. Clear the check box next to each control you want to remove.oca extension. either as controls in the toolbox or as programmable objects in your code. such as those included in the Microsoft Excel object library. The control icons will be removed from the toolbox. see "Adding Controls to a Project" earlier in this chapter.To add ActiveX controls to the Components dialog box. Note Each ActiveX control is accompanied by a file with an . .4. Visual Basic automatically selects the check box. as shown in Figure 4. Removing Controls from a Project To remove a control from a project 1. choose Components.ocx file name extension. The . To add a reference to another application's object library 1. Select the check box next to each reference you want to add to your project. Using Other Applications' Objects You can also use objects from other applications. From the Project menu.
choose the Browse button. see "International Issues. Select an existing resource file (. For More Information " For information on the Object Browser. You can use any object listed in the Object Browser in your code. and other material that may change between localized versions or between revisions or specific configurations.res extension. thus reducing the time it takes your project to compile. see "Finding Out About Objects" in "Programming with Objects. 3.To add references to applications not listed in the References dialog box." ." Using a Resource File A resource file allows you to collect all of the version-specific text and bitmaps for an application in one place. screen text.4 The References dialog box If you are not using any objects in a referenced library. 2. From the Project menu. Figure 4. To add a file to a project 1. Choose OK to add the selected references to your project. and then select the application. icons. select Add File. Once you have set references to the object libraries you want. you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve. A single project can have only one resource file. This can include constant declarations.res) and choose Open. if you add a second file with a . an error occurs. The Add File dialog box is displayed. For More Information For more information on the contents of a resource file. you can find a specific object and its methods and properties in the Object Browser by choosing Object Browser from the View menu.
Project Description A user-friendly name for the project. such as creating a form. you can find more information by searching Help. Use the Project Properties dialog box. Wizards are a type of add-in that can simplify certain tasks. Property settings are saved to the project (." Using Wizards and Add-Ins Visual Basic allows you to select and manage add-ins. for example. components. Identifies the project in code. the project name and class name cannot exceed a total of 37 characters. For More Information To learn about setting environment options that affect all projects. see "Developing An Application in Visual Basic. The context ID for the specific Help topic to be called when the user selects the "?" button while the application's object library is selected in the Object Browser. Several wizards are included in Visual Basic. Displayed in the References and Object Browser dialog boxes. or Sub Main ( ). and multithreading. spaces. including those for compiling. The following table describes some of the options you can set. special source code control capabilities. or start with a nonalphabetic character. These extensions add capabilities to the Visual Basic development environment.vbp) file. Help File Project Help Context ID The name of the Help file associated with the project. . which are extensions to Visual Basic. For a public class name. Microsoft and other developers have created add-ins you can use in your applications. Option Startup Object Project Name Description The first form that Visual Basic displays at run time.). accessible through the Project Properties command on the Project menu. It can't contain periods (. When you're ready to access some of the more advanced options. Many other options are also available.Setting Project Options Visual Basic allows you to customize each project by setting a number of properties.
choose Application Wizard. When you are finished making your selections. To unload an add-in or prevent it from loading. Once installed. Using the Add-In Manager You can add or remove an add-in to your project by using the Add-In Manager.To have an add-in appear on the Add-In Manager dialog box. Highlight an add-in from the list and click the desired behaviors in Load Behavior. choose Add-In Manager. Visual Basic saves your add-in selections between editing sessions. all you need to do is add code for your own specific functionality. they will appear as selections on the Add-Ins menu. 2. Select the Application Wizard icon. Some of the wizards also appear as icons in the related dialog boxes. choose New Project. which is accessible from the Add-Ins menu. Depending upon your Load Behavior selections. the developer of the add-in must ensure that it is installed properly. Wizards are installed or removed using the Add-in Manager. Using Wizards Wizards make working with Visual Basic even easier by providing task-specific assistance. It generates the forms and the code behind the forms based on your choices. the Application Wizard can also be accessed using its icon in the New Project dialog box. choose OK. From the File menu. ²or² 1. 2. . the Application Wizard included in Visual Basic helps you to create the framework for an application by presenting a series of questions or choices. The Professional and Enterprise editions of Visual Basic include other wizards. Note Selecting an add-in may add menu items to the Visual Basic Add-Ins menu. To install an add-in 1. including a Data Form Wizard for creating forms to be used with databases. and an ActiveX Document Wizard for converting forms for use in Internet applications. To start the Application Wizard y From the Add-Ins menu. for example. 3. For example. From the Add-Ins menu. clear all Load Behavior boxes. The Add-In Manager dialog box lists the available add-ins. Visual Basic connects the selected add-ins and disconnects the cleared add-ins.
Visual Basic is an object-based programming language. Once you understand a few basic concepts. Imagine the chaos that would result if your application's code was allowed to execute in random order. the event-driven nature of Visual Basic introduces some subtle differences. Visual Basic supports a number of common programming constructs and language elements. The form that you see on screen is a representation of the properties that define its appearance and intrinsic behavior. the structure of its code closely models its physical representation on screen. By definition. As with any modern programming language. much of the material covered in this chapter will seem familiar. the need for organization or structure becomes obvious.1 A form and its related form module . where the instructions are stored and the order in which instructions are executed. Try and approach this material with an open mind.3. you will need to write the code that defines the application's behavior. 5. The structure of an application is the way in which the instructions are organized. that is. As applications become more complex. After creating the interface for your application using forms and controls. 6. Simple applications such as the classic "hello world" example have a simple structure. the structure is important to the programmer: how easily can you find specific instructions within your application? Because a Visual Basic application is based on objects. Don't worry: whether you realize it or not. you will be able to create powerful applications using Visual Basic. objects contain data and code. If you're new to programming. In addition to controlling the execution of an application. you've been dealing with objects most of your life. objects actually help to make programming easier than ever before. 7. The mere mention of objects may cause undue anxiety in many programmers. This chapter introduces the essential components of the Visual Basic language. organization isn't very important with a single line of code. Programming Fundamentals 4.frm) that contains its code. Figure 5. If you've programmed in other languages. the material in this chapter will serve as an introduction to the basic building blocks for writing code. there is a related form module (with file name extension . While most of the constructs are similar to other languages. once you understand the differences you can use them to your advantage. Once you understand the basics. For each form in an application. The Structure of a Visual Basic Application An application is really nothing more than a set of instructions directing the computer to perform a task or tasks.
Whereas a standard module contains only code. your project contains a single form module. there is a corresponding set of event procedures in the form module. A procedure that might be used in response to events in several different objects should be placed in a standard module. Forms can contain controls. In addition to event procedures. form modules can contain general procedures that are executed in response to a call from any event procedure. You can add additional form.Each form module contains event procedures ³ sections of code where you place the instructions that will execute in response to specific events. A class module (. While "Managing Projects" describes which components you can add to an application. and standard modules. a class module contains both code and data ³ you can think of it as a control without a physical representation. Code that isn't related to a specific form or control can be placed in a different type of module. rather than duplicating the code in the event procedures for each object. as needed. a standard module (. Class modules are discussed in "Programming with Objects. class. this chapter explains how to write code in the various components that make up an application.BAS). ." y How an Event-Driven Application Works A discussion of the Event-driven model. For each control on a form.CLS) is used to create objects that can be called from procedures within your application. By default.
it helps to think of your application in terms of the objects that it represents. Determining which procedures belong in which module depends somewhat on the type of application that you are creating. Vcr. it may not be as obvious that you need to design the structure of the code. is based on the objects that comprise a video cassette recorder and a television. Figure 5. The VCR application consists of two form modules. Each module contains one or more procedures that contain the code: event procedures. and optional class modules. Sub or Function procedures. and two class modules.vbp.2 The structure of the VCR project is shown in the Object Browser . The design of the sample application for this chapter. The way you structure your application can make a difference in its performance as well as in the maintainability and usability of your code. optional standard modules for shared code. The code in a Visual Basic application is organized in a hierarchical fashion. and Property procedures.Before You Start Coding Perhaps the most important (and often overlooked) part of creating an application in Visual Basic is the design phase. A typical application consists of one or more modules: a form module for each form in the application. While it's obvious that you need to design a user interface for your application. a standard module. You can use the Object Browser to examine the structure of the project (Figure 5.2). Because Visual Basic is based on objects.
or Record buttons are "pushed. cmdRecord. The event procedures for all of these objects are contained in the Vcr." the Pause and Stop buttons need to be enabled. Because they are independent code modules. and so on).3 The main form for the VCR application In many cases there are repetitive procedures that are shared by more than one object. The software VCR also contains a clock (lblTime). A group of Command buttons (cmdPlay. Rather than repeat this code in each button's Click event procedure. The classes defined in these modules have no direct references to any of the objects in the forms. . such as the tape transport mechanism or the logic for recording a television program. some of the functions of the software VCR have no visual representation. all of the modifications can be done in one place. when the Play. This and other shared procedures are contained in the standard module. Some parts of a VCR aren't visible.The main form for the VCR application (frmVCR) is a visual representation of a combination VCR and television screen (Figure 5. Rewind. function indicators (shpPlay.3).frm form module. they could easily be reused to build an audio recorder without any modifications. it's better to create a shared Sub procedure that can be called by any button. Vcr. Figure 5. and so on) mimic the buttons used to operate a VCR. code to control the direction and speed of the "tape" is contained in the clsTape module. Code to initiate the "recording" process is contained in the clsRecorder module. shpRecord.bas.cls. Likewise. These are implemented as two class modules: Recorder. a channel indicator (lblChannel). It is composed of several objects that model those found in the real world version. If these procedures need to be modified in the future. For example. and a "picture tube" (picTV).cls and Tape.
class or standard modules. or Property procedure contains pieces of code that can be executed as a unit. variable. discuss the basics of using the Code Editor. A Sub. These are discussed in the section "Procedures" later in this chapter. general procedures. and so on. If you have several forms in an application. As your applications get larger and more sophisticated. The code that you write in a form module is specific to the particular application to which the form belongs. types. you would also see descriptions of the form and its controls. type. standard. including their property settings. and formatting code. Standard Modules . y Form Modules Form modules (. Visual Basic has its own rules for organizing. constants. Like any programming language." As you learn more about objects and writing code. If you were to look at a form module in a text editor. the second Form2. class. You can place constant. Simple applications can consist of just a single form. Code Modules Code in Visual Basic is stored in modules. The following topics introduce code modules and procedures. and form module can contain: y Declarations. Each standard. it's a good idea to give them meaningful names to avoid confusion when writing or editing your code. By default. Code Writing Mechanics Before you begin. and cover basic rules for writing code. Over time. Visual Basic names the first form in a project Form1. it might also reference other forms or objects within that application. it's important to establish naming conventions. and external procedures. They can contain procedures that handle events. Eventually you might find that there is common code you want to execute in several forms. and all of the code in the application resides in that form module. and form-level declarations of variables. you can refer to the VCR sample application for examples of various different coding techniques. so you create a separate module containing a procedure that implements the common code. Some suggested naming conventions are presented in "Visual Basic Coding Conventions. Function. you can build up a library of modules containing shared procedures. There are three kinds of modules: form. you add additional forms. This separate module should be a standard module. You don't want to duplicate the code in both forms. and dynamic-link library (DLL) procedure declarations at the module level of form. and class. it's important to understand the mechanics of writing code in Visual Basic. Procedures.In addition to designing the structure of your code.FRM file name extension) are the foundation of most Visual Basic applications. editing.
Class Modules Class modules (. You can write code in class modules to create new objects.4 The Code Editor window . For More Information For information about writing code in class modules. These new objects can include your own customized properties and methods. and User Controls. external procedures. types. forms are just class modules that can have controls placed on them and can display form windows. if you're careful not to reference forms or controls by name. From the standpoint of writing code." Note The Professional and Enterprise editions of Visual Basic also include ActiveX Documents. Using the Code Editor The Visual Basic Code Editor is a window where you write most of your code. The code that you write in a standard module isn't necessarily tied to a particular application. ActiveX Designers. They can contain global (available to the whole application) or module-level declarations of variables. Figure 5. constants.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. see "Programming with Objects. Actually.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. It is like a highly specialized word processor with a number of features that make writing Visual Basic code a lot easier. these modules should be considered the same as form modules.Standard modules (. These introduce new types of modules with different file name extensions. and global procedures. The Code Editor window is shown in Figure 5. a standard module can be reused in many different applications.4.
In a form module.Because you work with Visual Basic code in modules. among others. where you place module-level variable. use the View Selection buttons in the lower left-hand corner of the editor window. or to view all of the procedures in the module with each procedure separated from the next by a line (as shown in Figure 5. The procedure list for a general section of a module contains a single selection ³ the Declarations section. Switching between sections is accomplished using the Object Listbox. and DLL declarations. You can choose to view a single procedure at a time. the list includes a general section. Code within each module is subdivided into separate sections for each object contained in the module. constant. As you add Sub or Function procedures to a module. accessed using the Procedure Listbox.4). . Each section of code can contain several different procedures. for a standard module only a general section is shown. and DblClick events. For example. those procedures are added in the Procedure Listbox below the Declarations section. For a class module. a section for the form itself. a separate Code Editor window is opened for each module you select from the Project Explorer. Standard modules don't list any event procedures. To switch between the two views. Class modules list only the event procedures for the class itself ³ Initialize and Terminate. Two different views of your code are available in the Code Editor window. The procedure list for a form module contains a separate section for each event procedure for the form or control. the procedure list for a Label control includes sections for the Change. because a standard module doesn't support events. the list includes a general section and a class section. and a section for each control contained on the form. Click.
After you enter the first argument value.Automatic Code Completion Visual Basic makes writing code much easier with features that can automatically fill in statements. Auto Quick Info can also be accessed with the CTRL+I key combination. Type in the first few letters of the property name and the name will be selected from the list. accessed through the Options command on the Tools menu. statement or function prototypes. Even if you choose to disable the Auto List Members feature. Figure 5. When you enter the name of a control in your code. the editor displays lists of appropriate choices. Options for enabling or disabling these and other code settings are available on the Editor tab of the Options dialog.6). properties. or values. This option is also helpful when you aren't sure which properties are available for a given control. the Auto List Members feature presents a drop-down list of properties available for that control (Figure 5.5 The Auto List Members feature The Auto Quick Info feature displays the syntax for statements and functions (Figure 5. the second argument appears in bold. you can still access it with the CTRL+J key combination.5). with the first argument in bold. the TAB key will complete the typing for you. When you enter the name of a valid Visual Basic statement or function the syntax is shown immediately below the current line.6 Auto Quick Info . Figure 5. As you enter code. and arguments for you.
Bookmarks Bookmarks can be used to mark lines of code in the Code Editor so that you can easily return to them later. both online and when printed." Code Basics This section presents information on code writing mechanics. Bookmarks menu item. adding comments to your code. Commands to toggle bookmarks on or off as well as to navigate existing bookmarks are available from the Edit. Using this character can make your code easier to read. including breaking and combining lines of code. The following code is broken into three lines with line-continuation characters ( _): . Breaking a Single Statement Into Multiple Lines You can break a long statement into multiple lines in the Code window using the line-continuation character (a space followed by an underscore). and following naming conventions in Visual Basic. or from the Edit toolbar For More Information For more information on key combinations to access these and other functions in the Code Editor window. see "Code Window Keyboard Shortcuts. using numbers in code.
For example: ' This is a comment beginning at the left edge of the ' screen.Data1. it's better to place each statement on a separate line. Limitations. Both are illustrated in the preceding code. Publishers" _ & "WHERE Publishers. Visual Basic represents numbers in hexadecimal with the prefix &H and in octal with &O.BackColor = _ Red In order to make your code more readable.Text = "Hello" : Red = 255 : Text1. however. Such words are remarks placed in the code for the benefit of the developer. and other programmers who might examine the code later." Adding Comments to Your Code As you read through the examples in this guide. and there is no statement terminator. Combining Statements on One Line There is usually one Visual Basic statement to a line. and File Formats. Remember that comments can't follow a line-continuation character on the same line.Text = "Hi!" ' Place friendly greeting in text ' box. Understanding Numbering Systems Most numbers in this documentation are decimal (base 10). you'll often come across the comment symbol ('). There are also some limitations as to where the line-continuation character can be used.RecordSource = _ "SELECT * FROM Titles.State = 'CA'" You can't follow a line-continuation character with a comment on the same line.PubID" _ & "AND Publishers.PubId = Titles. For More Information For more information. But occasionally it's convenient to use hexadecimal numbers (base 16) or octal numbers (base 8). This symbol tells Visual Basic to ignore the words that follow it. Text1. you can place two or more statements on a line if you use a colon (:) to separate them: Text1. see "Visual Basic Specifications. octal. Comments can follow a statement on the same line or can occupy an entire line. The following table shows the same numbers in decimal. Decimal 9 Octal &O11 Hexadecimal &H9 . Note You can add or remove comment symbols for a block of code by selecting two or more lines of code and choosing the Comment Block or Uncomment Block buttons on the Edit toolbar. and hexadecimal. However.
variables. some number systems lend themselves to certain tasks. see the Language Reference. classes. because Visual Basic assumes you mean the Loop keyword.Loop. y y A restricted keyword is a word that Visual Basic uses as part of its language. For More Information For a complete list of keywords. The names of the procedures. For example. and modules must not exceed 40 characters. you can have a control named Loop. The names of controls. Your forms and controls can have the same name as a restricted keyword. To refer to a form or control that has the same name as a restricted keyword. such as using hexadecimals to set the screen and control colors. and constants that you declare in your Visual Basic code must follow these guidelines: y y They must begin with a letter. you declare and name many elements (Sub and Function procedures. functions (such as Len and Abs). They can't contain embedded periods or type-declaration characters (special characters that specify a data type.Visible = True ' Qualified with the form ' name. ' Square brackets also ' work. variables. They can't be the same as restricted keywords. . For example. this code does not cause an error: MyForm. However.Visible = True ' Causes an error. This includes predefined statements (such as If and Loop). and so on). however. constants. you must either qualify it or surround it with square brackets: [ ].15 16 20 255 &O17 &O20 &O24 &O377 &HF &H10 &H14 &HFF You generally don't have to learn the hexadecimal or octal number system yourself because the computer can work with numbers entered in any system. They can be no longer than 255 characters. In your code you cannot refer to that control in the usual way. For example. forms. this code causes an error: Loop.Visible = True [Loop]. and operators (such as Or and Mod). Naming Conventions in Visual Basic While you are writing Visual Basic code.
uses variables for storing values. Using constants can make your code more readable by providing meaningful names instead of numbers. However. depending on what values the user provides. You can use two variables to hold the unknown values ³ let's name them ApplePrice and ApplesSold. For example.You can use square brackets in this way when referring to forms and controls. but as the name implies. depending on the result of the comparison. You can think of a variable as a placeholder in memory for an unknown value. The variables allow you to make a calculation without having to know in advance what the actual inputs are. your code would look like this: txtSales. Constants also store values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). and perform different operations on them. Note Because typing square brackets can get tedious. you might want to refrain from using restricted keywords as the name of forms and controls. For example. Visual Basic uses the Variant data type. you use variables to temporarily store values during the execution of an application. . You don't know the price of an apple or the quantity sold until the sale actually occurs. Arrays can be used to store indexed collections of related variables. compare them. but you don't need to store them in a property. but not when declaring a variable or defining a procedure with the same name as a restricted keyword. Data types control the internal storage of data in Visual Basic. Visual Basic. Constants and Data Types You often need to store values temporarily when performing calculations with Visual Basic. you might want to calculate several values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). Introduction to Variables. For more detailed information. There are a number of other available data types that allow you to optimize your code for speed and size when you don't need the flexibility that Variant provides. but you can also create your own.txt = ApplePrice * ApplesSold The expression returns a different total each time. you can use this technique if a future version of Visual Basic defines a new keyword that conflicts with an existing form or control name when you update your code to work with the new version. those values remain constant throughout the execution of an application. Square brackets can also be used to force Visual Basic to accept names provided by other type libraries that conflict with restricted keywords. Each time the program is run. By default. To calculate the total sales and display it in a Textbox named txtSales. the user supplies the values for the two variables. see: Variables In Visual Basic. imagine you are creating a program for a fruit stand to track the sales of apples. There are a number of built-in constants in Visual Basic. like most programming languages. You need to retain the values if you want to compare them.
the data type of ApplePrice is Currency. For More Information For more information on objects. see "Programming with Objects" and "Programming with Components. Form1. and so on. the value of a variable in a procedure is local to that procedure ³ that is. a form. "Data Types. Must not exceed 255 characters. Note that the equal sign in this example is an assignment operator. Data types define the type of information the variable stores. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes. and Currency. Declaring Variables To declare a variable is to tell the program about it in advance. Variables can represent many other values as well: text values." later in this chapter. Some examples of data types include String. In addition. Integer. When the procedure finishes." Data types are discussed in detail in the section. include Object. You declare a variable with the Dim statement. Must be unique within the same scope. supplying a name for the variable: Dim variablename [As type] Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. which is the range from which the variable can be referenced ³ a procedure. There are other ways to declare variables: . the data type of ApplesSold is an integer. Storing and Retrieving Data in Variables You use assignment statements to perform calculations and assign the result to a variable: ApplesSold = 10 ' The value 10 is passed to the ' variable. Examples of Visual Basic object types. even objects. not an equality operator. A variable name: y y y y Must begin with a letter. the value of the variable disappears.In this example. Variables can also contain objects from Visual Basic or other applications. the value (10) is being assigned to the variable (ApplesSold). Can't contain an embedded period or embedded type-declaration character. and TextBox. The optional As type clause in the Dim statement allows you to define the data type or object type of the variable you are declaring. you can't access a variable in one procedure from another procedure. ApplesSold = ApplesSold + 1 ' The variable is ' incremented. or classes. various numeric types. dates.
or class module. you could write a function where you don't need to declare TempVal before using it: Function SafeSqr(num) TempVal = Abs(num) SafeSqr = Sqr(TempVal) End Function Visual Basic automatically creates a variable with that name. click the Editor tab and check the Require Variable Declaration option. But because the TempVal variable was misspelled on the next-to-last line. which you can use as if you had explicitly declared it. or standard module: Option Explicit ²or² From the Tools menu. . you must manually add Option Explicit to any existing modules within a project. standard. therefore. this function will always return zero.y Declaring a variable in the Declarations section of a form. it can't determine whether you actually meant to implicitly declare a new variable or you just misspelled an existing variable name. it can lead to subtle errors in your code if you misspell a variable name. For example. suppose that this was the function you wrote: Function SafeSqr(num) TempVal = Abs(num) SafeSqr = Sqr(TemVal) End Function At first glance. For example. makes the variable available to all the procedures in the module. but not in modules already created. this looks the same. Declaring a local variable using the Static keyword preserves its value even when a procedure ends. Declaring a variable using the Public keyword makes it available throughout your application. Explicit Declaration To avoid the problem of misnaming variables. rather than within a procedure. y y Implicit Declaration You don't have to declare a variable before using it. form. To explicitly declare variables y Place this statement in the Declarations section of a class. you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable. While this is convenient. When Visual Basic encounters a new name. so it creates a new variable with that name. choose Options. This automatically inserts the Option Explicit statement in any new modules.
it's a good idea to use it with all your code. Module-level Variables are private to the module in which they appear. Scoping Variables Depending on how it is declared. however. You could then explicitly declare TempVal: Function SafeSqr(num) Dim TempVal TempVal = Abs(num) SafeSqr = Sqr(TemVal) End Function Now you'd understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled TemVal. and class modules. Understanding the Scope of Variables The scope of a variable defines which parts of your code are aware of its existence. Because the Option Explicit statement helps you catch these kinds of errors. standard. and class module for which you want Visual Basic to enforce explicit variable declarations. you need to use a variable with a broader scope. such as one whose value is available to all the procedures within the same module. only code within that procedure can access or change the value of that variable. it must be placed in the Declarations section of every form. Note The Option Explicit statement operates on a per-module basis. . it has a scope that is local to that procedure. You must manually add Option Explicit to any existing modules within a project. Scope Procedure-level Private Variables are private to the procedure in which they appear. When you declare a variable within a procedure. Sometimes. or even to all the procedures in your entire application.Had this statement been in effect for the form or standard module containing the SafeSqr function. but does not add it to existing code. a variable is scoped as either a procedure-level (local) or module-level variable. Visual Basic inserts Option Explicit in all subsequent form. Visual Basic allows you to specify the scope of a variable when you declare it. Visual Basic would have recognized TempVal and TemVal as undeclared variables and generated errors for both of them. Variables are available to all modules. Public Not applicable. You cannot declare public variables within a procedure. standard. If you select Require Variable Declaration.
You create module-level variables by declaring them with the Private keyword in the Declarations section at the top of the module. but Private is preferred because it readily contrasts with Public and makes your code easier to understand. but not to code in other modules. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures. You declare them with the Dim or Static keywords. For example. use the Public keyword to declare the variable. These are also known as local variables. For example. you can create a dozen different procedures containing a variable called intTemp. public variables are declared in the Declarations section at the top of the module. there is no difference between Private and Dim.intX to get the correct values. The values in public variables are available to all procedures in your application. Local variables are a good choice for any kind of temporary calculation. a module-level variable is available to all the procedures in that module. it's possible to differentiate between them in code by referring to both the module and variable names. For example: Public intTemp As Integer Advanced Variable Topics Using Multiple Variables with the Same Name If public variables in different modules share the same name.intX and Form1. As long as each intTemp is declared as a local variable.Variables Used Within a Procedure Procedure-level variables are recognized only in the procedure in which they're declared. For example: Dim intTemp As Integer ²or² Static intPermanent As Integer Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing. Like all module-level variables. if there is a public Integer variable intX declared in both Form1 and in Module1. you can refer to them as Module1. . Variables Used by All Modules To make a module-level variable available to other modules. For example: Private intTemp As Integer At the module level. Variables Used Within a Module By default. each procedure recognizes only its own version of intTemp.
or Form1. Module1.intX when calling the value of the form's Integer variable. Public intX As Integer ' Declare the form's intX ' variable. Sub Test() ' Set the value for the intX variable in Module2. Sub Test() ' Set the value for the intX variable in the form. ' Calls Test in Module2.Test MsgBox Module1. Module2. intX = 2 End Sub The third intX variable is declared in the form module. ' Displays Module2's intX. is declared in the first standard module. which has the same name. Again. If there are multiple procedures and variables with the same name. Notice in the third command button's Click event procedure.intX End Sub ' Calls Test in Module1. And again. ' Displays Module1's intX.Test MsgBox Module2. intX = 1 End Sub The second variable. a procedure named Test sets its value: Public intX As Integer ' Declare Module2's intX. is declared in the second standard module. Visual Basic takes the value of the more local variable. You'll see the separate references to the three public variables. Private Sub Command3_Click() Test ' Calls Test in Form1. Private Sub Command1_Click() Module1. The Test procedure sets its value: Public intX As Integer ' Declare Module1's intX.Test when calling the form's Test procedure. Sub Test() ' Set the value for the intX variable in Module1. End Sub Run the application and click each of the three command buttons. you don't need to specify Form1. intX = 3 End Sub Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.To see how this works. intX. insert two standard modules in a new project and draw three command buttons on a form. a procedure named Test sets its value. which in this case. intX. is the Form1 variable. .intX End Sub Private Sub Command2_Click() Module2. One variable. MsgBox intX ' Displays Form1's intX.
and procedures are treated as modulelevel variables in the form module. End Sub . For example. you could have a public variable named Temp and then. BackColor ' Assume there is also a control on the form called ' Text1. Me. or procedure because both are in the same scope. Within the form module. Local Variables You can also have a variable with the same name at a different scope. It is not legal to have a form property or control with the same name as a module-level variable. The module-level variable can be accessed from within the procedure by qualifying the variable with the module name.Temp to 1. within a procedure. End Sub Private Sub Command1_Click() Test End Sub In general.Temp End Sub ' Temp has a value of 2. Text1. Me.Temp has a value of 1. You must qualify the control with a reference to the form or the Me keyword to set or get its value or any of its properties. Shadowing Form Properties and Controls Due to the effect of shadowing. Text1 = "Variable" ' Variable shadows control. it is accessed in preference to) less local variables.Top = 0 ' Must qualify with Me to get ' control. References to the name Temp within the procedure would access the local variable. user-defined type. constants.Text1 = "Control" ' Must qualify with Me to get ' control. ' Form1. when variables have the same name but different scope. the more local variable always shadows (that is. declare a local variable named Temp.BackColor = 0 ' Must qualify with Me to get ' form property. constant. Public Temp As Integer Sub Test() Dim Temp As Integer Temp = 2 MsgBox Form1. controls. BackColor = 0 ' Variable shadows property. references to Temp outside the procedure would access the public variable.Top = 0 ' This causes an error! Me. Private Sub Form_Load() Temp = 1 ' Set Form1. So if you also had a procedure-level variable named Temp. form properties. it would shadow the public variable Temp within that module.Text1. local variables with the same names as controls on the form shadow the controls.Public vs. For example: Private Sub Form_Click () Dim Text1.
However. In form modules. local variables declared with Dim exist only while the procedure in which they are declared is executing. It can. types. the following function calculates a running total by adding a new value to the total of previous values stored in the static variable Accumulate: Function RunningTotal(num) Static ApplesSold ApplesSold = ApplesSold + num RunningTotal = ApplesSold End Function If ApplesSold was declared with Dim instead of Static. it is good programming practice to keep the names of your variables distinct from each other. when a procedure is finished executing. and the function would simply return the same value with which it was called. However. the procedure no longer has exclusive access to it. the previous accumulated values would not be preserved across calls to the function.Using Variables and Procedures with the Same Name The names of your private module-level and public module-level variables can also conflict with the names of your procedures. In this case. have the same name as public procedures. Usually. For example: . it must be qualified with the module name. you can preserve the value of a local variable by making the variable static. You can produce the same result by declaring ApplesSold in the Declarations section of the module. Because other procedures can access and change the value of the variable. the period of time during which they retain their value. when the variable is accessed from another module. try to use variables names that are different from names of controls on those forms. The values in module-level and public variables are preserved for the lifetime of your application. all its local variables are reinitialized. variables have a lifetime. Static Variables In addition to scope. exactly as you would with the Dim statement: Static Depth For example. the running totals might be unreliable and the code would be more difficult to maintain. shadowing can be confusing and lead to subtle bugs in your code. however. Once you change the scope of a variable this way. A variable in the module cannot have the same name as any procedures or types defined in the module. While the shadowing rules described above are not complex. however. Use the Static keyword to declare one or more variables inside a procedure. Declaring All Local Variables as Static To make all local variables in a procedure static. or variables defined in other modules. the values of its local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed. making it a module-level variable. place the Static keyword at the beginning of a procedure heading.
also provide a list of constants you can use with their objects." Symbolic or user-defined constants are declared using the Const statement. have no obvious meaning. you can't modify a constant or assign a new value to it as you can to a variable. and can be viewed in the Object Browser. or declared implicitly. Each of these elements is defined in the object library. Although a constant somewhat resembles a variable. For information on changing the priority of object libraries. For details on using the Object Browser. vbTileHorizontal. Even with prefixes. Modulename is the name of the module that defines the constant. see the "References Dialog Box. you can qualify references to constants with the following syntax: [libname. Constants from the Visual Basic and Visual Basic for applications object libraries are prefaced with "vb" ³ for instance. "Creating Your Own Constants.]constname Libname is usually the class name of the control or library. In these cases. You can place Static in front of any Sub or Function procedure heading." y In Visual Basic. and properties. you can greatly improve the readability of your code ³ and make it easier to maintain ³ by using constants. see "Programming with Objects. Constants are also defined in the object library for each ActiveX control. with a prefix indicating the object library that defines the constant. it's still possible that two object libraries may contain identical constants representing different values. methods. such as Microsoft Excel and Microsoft Project. Which constant is referenced in this case depends on which object library has the higher priority. including event procedures and those declared as Private. Creating Your Own Constants . Constname is the name of the constant.Static Function RunningTotal(num) This makes all the local variables in the procedure static regardless of whether they are declared with Static." To be absolutely sure you avoid constant name collisions. A constant is a meaningful name that takes the place of a number or string that does not change. Private. Constants Often you'll find that your code contains constant values that reappear over and over. Or you may find that the code depends on certain numbers that are difficult to remember ³ numbers that. constant names are in a mixed-case format. Other applications that provide object libraries. User-defined constants are described in the next section. in and of themselves. Dim. Visual Basic constants are listed in the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries in the Object Browser. There are two sources for constants: y Intrinsic or system-defined constants are provided by applications and controls. The prefixes are intended to prevent accidental collisions in cases where constants have identical names and represent different values.][modulename.
A Const statement can represent a mathematical or date/time quantity: Const conPi = 3. see "Understanding the Scope of Variables" earlier in this chapter. y For More Information For more information regarding scope. conMaxPlanets = 9. Public constants cannot be declared in a form or class module. but not to any code outside that module.10.A" Const conCodeName = "Enigma" You can place more than one constant declaration on a single line if you separate them with commas: Public Const conPi = 3. To create a constant available throughout the application. declare it in the Declarations section of the module. and the same rules apply: y y To create a constant that exists only within a procedure.14159265358979 Public Const conMaxPlanets As Integer = 9 Const conReleaseDate = #1/1/95# The Const statement can also be used to define string constants: Public Const conVersion = "07. however.The syntax for declaring a constant is: [Public|Private] Const constantname[As type] = expression The argument constantname is a valid symbolic name (the rules are the same as those for creating variable names). You can even define constants in terms of previously defined constants: Const conPi2 = conPi * 2 Once you define constants.14. and expression is composed of numeric or string constants and operators. _ conWorldPop = 6E+09 The expression on the right side of the equal sign ( = ) is often a number or literal string. To create a constant available to all procedures within a module. you can place them in your code to make it more readable. For example: Static SolarSystem(1 To conMaxPlanets) If numPeople > conWorldPop Then Exit Sub Scoping User-Defined Constants A Const statement has scope like a variable declaration. you can't use function calls in expression. . but it can also be an expression that results in a number or string (although that expression can't contain calls to functions). and place the Public keyword before Const. declare the constant in the Declarations section of a standard module. declare it within that procedure.
For example. just about anything in Visual Basic that involves data also involves data types. Data types apply to other things besides variables. because a name is always composed of characters. at most.Avoiding Circular References Because constants can be defined in terms of other constants. a variable to store a person's name is best represented as a string data type." Declaring Variables with Data Types Before using a non-Variant variable. see the section. Visual Basic can handle that data more efficiently if you declare a variable of that type. If a cycle occurs. Double. When you assign a value to a property. For example: ' In Module 1: Public Const conA = conB * 2 ' In Module 2: Public Const conB = conA / 2 ' Available throughout ' application. "Arrays. each of which is defined in terms of the other. You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion. that value has a data type. In fact. When you declare a variable. For More Information For more information. A cycle occurs when you have two or more public constants. the variable is given the Variant data type. For example. To avoid creating a cycle. Data Types Variables are placeholders used to store values. and Currency type. however. arguments to functions also have data types. or circular reference between two or more constants. You can also declare arrays of any of the fundamental types. You cannot run your code until you resolve the circular reference." later in this chapter. String. you can also supply a data type for it. they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's memory. respectively: . you must be careful not to set up a cycle. All variables have a data type that determines what kind of data they can store. The Variant data type is like a chameleon ³ it can represent many different data types in different situations. the following statements declare an Integer. Selecting data types to improve your application's performance is discussed in "Designing for Performance and Compatibility. Visual Basic generates an error when you attempt to run your application. a small number of modules. if you don't supply a data type. Public. By default. Dim or Static statement to declare it As type. ' Available throughout ' application. restrict all your public constants to a single module or. If you know that a variable will always store data of a particular type. you must use the Private.
or 3. it is an accurate fixed-point data type suitable for monetary calculations. the highest positive value of a Double data type is 1. declare it as a Single. declare it as an Integer or Long type.Private I As Integer Dim Amt As Double Static YourName As String Public BillsPaid As Currency A Declaration statement can combine multiple declarations. in which mmm is the mantissa and eee is the exponent (a power of 10). the variable is given the default type. Operations are faster with integers. The Byte Data Type If the variable contains binary data. Double. declare it as an array of the Byte data type. or Currency variable..57). Visual Basic may automatically convert between ANSI and Unicode when: . BillsPaid As Currency Private Test. using E in the same fashion treats the value as a Single data type. see "Introduction to Control Structures" later in this chapter.8 times 10 to the 308th power. or about 1. This may surprise you if your experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case. the variables Test and Amount are of the Variant data type. and these types consume less memory than other data types.402823E+38. They are especially useful as the counter variables in For.79769313486232D+308. (Arrays are discussed in "Arrays" later in this chapter). Double (double-precision floating point). any binary data in the variable is corrupted. Long (long integer). When String variables are converted between ANSI and Unicode formats. but can be subject to small rounding errors. Floating-point (Single and Double) numbers have much larger ranges than Currency.4 times 10 to the 38th power. Using Byte variables to store binary data preserves it during format conversions. Integer). For More Information To read more about control structures. Likewise. The highest positive value of a Single data type is 3. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. If the variable contains a fraction.Next loops. as in these statements: Private I As Integer. Numeric Data Types Visual Basic supplies several numeric data types ³ Integer. and Currency.. Amt As Double Private YourName As String. In the preceding example. Note Floating-point values can be expressed as mmmEeee or mmmDeee. Using a numeric data type generally uses less storage space than a variant. J As Integer Note If you do not supply a data type. Single (single-precision floating point). Amount. If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits to the left.
Visual Basic coerces the Byte to a signed integer first. to declare a string that is always 50 characters long. a string variable or argument is a variable-length string. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before assigning it to an integer. see "International Issues. In forms and class modules. fixed-length strings must be declared Private. So for unary minus. 4) By default. Visual Basic simply truncates the characters. For More Information For details on Unicode and ANSI conversions. the string grows or shrinks as you assign new data to it. EmpName is padded with enough trailing spaces to total 50 characters. Fixed-length strings in standard modules can be declared as Public or Private. You can also declare strings that have a fixed length. Because fixed-length strings are padded with trailing spaces. you may find the Trim and RTrim functions. Since Byte is an unsigned type with the range 0-255. use code like this: Dim EmpName As String * 50 If you assign a string of fewer than 50 characters. If you assign a string that is too long for the fixed-length string. . useful when working with them.y y y y Reading from files Writing to files Calling DLLs Calling methods and properties on objects All operators that work on integers work with the Byte data type except unary minus. which remove the spaces. you can declare it to be of type String: Private S As String You can then assign strings to this variable and manipulate it using string functions: S = "Database" S = Left(S." The String Data Type If you have a variable that will always contain a string and never a numeric value. it cannot represent a negative number. All numeric variables can be assigned to each other and to variables of the Variant type. You specify a fixed-length string with this syntax: String * size For example.
Text1. In the following example. RTrim Function and Trim Functions" in the Language Reference. Midnight is 0.23" intX = strY ' Passes the string to a numeric ' variable. It's also possible to assign a numeric value to a string variable. Exchanging Strings and Numbers You can assign a string to a numeric variable if the string represents a numeric value. The same general characteristics apply to dates in both types. strY = Cos(strY) ' Passes cosine to the ' string variable. 1899. For example. while values to the right of the decimal represent time. passing a non-numeric value in the string will cause a run-time error to occur. End Sub Visual Basic will automatically coerce the variables to the appropriate data type. If Recorder. Negative whole numbers represent dates before December 30. The Boolean Data Type If you have a variable that will contain simple true/false. . List1. Run the application. you can declare it to be of type Boolean. Private Sub Command1_Click() Dim intX As Integer Dim strY As String strY = "100. yes/no. values to the left of the decimal represent date information. You should use caution when exchanging strings and numbers. and list box on a form." in "Advanced Variant Topics. and click the command button. text box.For More Information See "Ltrim. place a command button." When other numeric data types are converted to Date. or on/off information. Dim blnRunning As Boolean ' Check to see if the tape is running. "Date/Time Values Stored in Variants. Enter the following code in the command button's Click event. blnRunning is a Boolean variable which stores a simple yes/no setting.Text = strY ' String variable prints in ' the text box. and midday is 0.5.AddItem Cos(strY) ' Adds cosine of number in ' the string to the listbox.Direction = 1 Then blnRunning = True End if The Date Data Type Date and time values can be contained both in the specific Date data type and in Variant variables. For More Information See the section. The default value of Boolean is False.
Visual Basic can resolve references to the properties and methods of objects with specific types before you run an application. allowing the reference to be resolved at run time. A variable declared as Object is one that can subsequently be assigned (using the Set statement) to refer to any actual object recognized by the application. Dim objDb As Object Set objDb = OpenDatabase("c:\Vb5\Biblio. For More Information For more information on creating and assigning objects and object variables. declare objects as they are listed in the Classes list in the Object Browser. instead of using a Variant or the generic Object. When working with other applications' objects. for example. This ensures that Visual Basic recognizes the specific type of object you're referencing. try to use specific classes (such as TextBox instead of Control or. in the preceding case.The Object Data Type Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. see "Creating Objects" later in this chapter. To convert a value to Currency. you use the CCur function: PayPerWeek = CCur(hours * hourlyPay) Conversion function Cbool Cbyte Ccur Cdate CDbl Cint CLng CSng Boolean Byte Currency Date Double Integer Long Single Converts an expression to . Database instead of Object) rather than the generic Object. This allows the application to perform faster at run time.mdb") When declaring object variables. Specific classes are listed in the Object Browser. Converting Data Types Visual Basic provides several conversion functions you can use to convert values into a specific data type.
CStr Cvar CVErr String Variant Error Note Values passed to a conversion function must be valid for the destination data type or an error occurs. Visual Basic automatically performs any necessary conversion. The Empty value is a special value different from 0. For More Information See the Language Reference for a specific conversion function.character string). see the section. if you attempt to convert a Long to an Integer. Variants can also contain three special values: Empty. y If you perform arithmetic operations or functions on a Variant. SomeValue = SomeValue . ' SomeValue contains "17" (a two' character string). see the section. The Variant Data Type A Variant variable is capable of storing all system-defined types of data. the Long must be within the valid range for the Integer data type. A Variant variable has the Empty value before it is assigned a value. You can test for the Empty value with the IsEmpty function: If IsEmpty(Z) Then Z = 0 . "Numeric Values Stored in Variants." in "Advanced Variant Topics. "Strings Stored in Variants. there are some traps you must avoid. The Empty Value Sometimes you need to know if a value has ever been assigned to a created variable. For details. For example. While you can perform operations on Variant variables without much concern for the kind of data they contain. use the & operator instead of the + operator." If you are concatenating strings. a zero-length string ("").15 ' SomeValue now contains ' the numeric value 2. For details. or the Null value. You don't have to convert between these types of data if you assign them to a Variant variable. and Error." in "Advanced Variant Topics. Null. For example: Dim SomeValue SomeValue = "17" ' Variant by default." y In addition to being able to act like the other standard data types. the Variant must contain something that is a number. SomeValue = "U" & SomeValue ' SomeValue now contains ' "U2" (a two.
Passing Null. The Error Value In a Variant. You can set a Variant variable back to Empty by assigning the keyword Empty to the Variant. Null is said to "propagate" through expressions. a zero-length string. see "Null" in the Language Reference. Null is commonly used in database applications to indicate unknown or missing data. Variables are not set to Null unless you explicitly assign Null to them. The Null Value The Variant data type can contain another special value: Null. if any part of the expression evaluates to Null. you can use it in expressions. a Variant containing Null. so if you don't use Null in your application. Assigning Null to a Variant variable doesn't cause an error. y y. the entire expression evaluates to Null. depending on the expression. a trappable error occurs.When a Variant contains the Empty value. and Null will propagate through expressions involving Variant variables (though Null does not propagate through certain functions). This allows you. Null values propagate through intrinsic functions that return Variant data types. unlike for other kinds of errors. normal application-level error handling does not occur. to take some alternative based on the error value. Error is a special value used to indicate that an error condition has occurred in a procedure. Null has some unique characteristics: y Expressions involving Null always result in Null. you don't have to write code that tests for and handles it. or Null) is assigned to a Variant variable. Because of the way it is used in databases. For More Information For information on how to use Null in expressions. . or the application itself. However. You can return Null from any Function procedure with a Variant return value. or an expression that evaluates to Null as an argument to most functions causes the function to return Null. Thus. Error values are created by converting real numbers to error values using the CVErr function. it is treated as either 0 or a zero-length string. The Empty value disappears as soon as any value (including 0.
For details on converting data types. however.For More Information For information on how to use the Error value in expressions. Most of the time." For additional information about the Variant data type. see "Debugging Your Code and Handling Errors. For More Information For information about the VarType function. For information on error handling. For example. in these cases. the value of VarType is the sum of the array and data type return values. and arrays are not physically stored in the Variant. or even to Currency: If VarType(X) = 5 Then X = CSng(X) ' Convert to Single. if you store values with decimal fractions in a Variant variable.) These internal representations correspond to the explicit data types discussed in "Data Types" earlier in this chapter. it is a variable that can freely change its type. Visual Basic always uses the Double internal representation. Visual Basic uses the most compact representation that accurately records the value. . you don't have to be concerned with what internal representation Visual Basic is using for a particular variable. see "Advanced Variant Topics Advanced Variant Topics Internal Representation of Values in Variants Variant variables maintain an internal representation of the values that they store. If you know that your application does not need the high accuracy (and slower speed) that a Double value supplies. see "CVErr Function" in the Language Reference. rather. (A Variant variable is not a variable with no type. no matter what you store in it. This representation determines how Visual Basic treats these values when performing comparisons and other operations. see "VarType Function" in the Language Reference. so any code you write that makes decisions based on the return value of the VarType function should gracefully handle return values that are not currently defined. you can use the VarType function. To read more about arrays. The actual data are stored elsewhere. With an array variable. Objects. If you want to know what value Visual Basic is using. you can speed your calculations by converting the values to Single. see "Data Types" earlier in this chapter. or a pointer to the string or array. four bytes of the Variant are used to hold either an object reference. Later operations may cause Visual Basic to change the representation it is using for a particular variable. When you assign a value to a Variant variable. For example. Note A variant always takes up 16 bytes. this array contains Double values: Private Sub Form_Click() Dim dblSample(2) As Double MsgBox VarType(dblSample) End Sub Future versions of Visual Basic may add additional Variant representations. see "Arrays" later in this chapter. strings. Visual Basic handles conversions automatically.
Visual Basic converts the representation of the number to a string automatically. you cannot perform any arithmetic operations on the value U2 even though it contains a numeric character.Numeric Values Stored in Variants When you store whole numbers in Variant variables. thousands separator.50") While these two statements would return false: IsNumeric("DM100") IsNumeric("1. Visual Basic provides several conversion functions that you can use to convert values into a specific type (see "Converting Data Types" earlier in this chapter). the reverse would be the case ³ the first two would return false and the second two true ³ if the country setting in the Windows Control Panel was set to Germany.560.50") However. Canada. The Format function . and decimal separator symbols. you use the CCur function: PayPerWeek = CCur(hours * hourlyPay) An error occurs if you attempt to perform a mathematical operation or function on a Variant that does not contain a number or something that can be interpreted as a number. For example. Likewise. Sometimes you want to use a specific representation for a number. if it is very large or has a fractional component. Visual Basic uses the most compact representation possible. it uses the Regional settings (specified in the Windows Control Panel) to interpret the thousands separator.560. Visual Basic will use a Long value or. For example. the Variant uses an Integer representation for the value. these two statements would return true: IsNumeric("$100") IsNumeric("1. you can perform calculations on the values +10 or -1. or Australia. If you assign a Variant containing a number to a string variable or property. Thus. For example. For this reason. The IsNumeric function performs this task: Do anyNumber = InputBox("Enter a number") Loop Until IsNumeric(anyNumber) MsgBox "The square root is: " & Sqr(anyNumber) When Visual Basic converts a representation that is not numeric (such as a string containing a number) to a numeric value. and currency symbol. because the entire value is not a valid number. a Double value.7E6 because they are valid numbers. To convert a value to Currency. You can also use the Format function to convert a number to a string that includes formatting such as currency. you often want to determine if a Variant variable contains a value that can be used as a number. If you want to explicitly convert a number to a string. you cannot perform any calculations on the value 1040EZ. for example. if you store a small number without a decimal fraction. however. decimal separator. If you then assign a larger number. use the CStr function. you might want a Variant variable to store a numeric value as Currency to avoid round-off errors in later calculations. if the country setting in the Windows Control Panel is set to United States.
use the & operator.automatically uses the appropriate symbols according to the Regional Settings Properties dialog box in the Windows Control Panel. regardless of the representation of the value in the variables. For More Information See "Format Function" and topics about the conversion functions in the Language Reference. it generates a Type mismatch error." . see "International Issues. however. Several functions return date/time values. 1) . the + operator adds the two values. then the + operator performs string concatenation. As mentioned earlier. For more information on Unicode. Visual Basic first attempts to convert the string into a number. the following code: Sub Form_Click () Dim X. the situation becomes more complicated. If both of the Variants contain strings. the + operator performs addition.Hour(rightnow) minutesleft = 60 . X & Y End Sub produces this result on the form: 67 13 67 67 Note Visual Basic stores strings internally as Unicode. To make sure that concatenation occurs.Minute(rightnow) Print daysleft & " days left in the year. if unsuccessful. storing and using strings in Variant variables poses few problems. daysleft = Int(DateSerial(Year(rightnow) _ + 1. If the conversion is successful. For information on writing code for applications that will be distributed in foreign markets." Strings Stored in Variants Generally. minutesleft rightnow = Now ' Now returns the current date/time. sometimes the result of the + operator can be ambiguous when used with two Variant values. X & Y X = 6 Print X + Y. If both of the Variants contain numbers. hoursleft. DateSerial returns the number of days left in the year: Private Sub Form_Click () Dim rightnow. For example. For example.rightnow) hoursleft = 24 . daysleft." Date/Time Values Stored in Variants Variant variables can also contain date/time values. But if one of the values is represented as a number and the other is represented as a string. see "International Issues. 1. Y X = "6" Y = "7" Print X + Y.
adding or subtracting fractions adds or subtracts time." Print minutesleft & " minutes left in the hour." End Sub You can also perform math on date/time values. For example. you can compare a Variant containing a date/time value with a literal date: If SomeDate > #3/6/93# Then Similarly. while subtracting 1/24 subtracts one hour. For example.Text) daysleft = DateSerial(Year(SomeDate) + _ 1. to December 31. If you do not include a date in a date/time literal. earlier or later in other countries) will be incorrect. These are all valid date/time values: SomeDate SomeDate SomeDate SomeDate = = = = #3-6-93 13:20# #March 27. Calculations on dates don't take into account the calendar revisions prior to the switch to the Gregorian calendar. 0100. The range for dates stored in Variant variables is January 1. however. see "International Issues. you can use the IsDate function to determine if a Variant contains a value that can be considered a valid date/time value. Visual Basic sets the date part of the value to December 30.Text = daysleft & " days left in the year. Visual Basic converts the text into a date and computes the days left until the end of the year: Dim SomeDate. 9999.Print hoursleft & " hours left in the day. 1. so calculations producing date values earlier than the year in which the Gregorian calendar was adopted (1752 in Britain and its colonies at that time. If the property contains text that can be considered a valid date.Text) Then SomeDate = CDate(Text1. Therefore. the following code tests the Text property of a text box with IsDate. daysleft If IsDate(Text1. 1993 1:20am# #Apr-2-93# #4 April 1993# For More Information For information on handling dates in international formats. 1) . adding 20 adds 20 days. Adding or subtracting integers adds or subtracts days. You can then use the CDate function to convert the value into a date/time value. Visual Basic accepts a wide variety of date and time formats in literals. Visual Basic sets the time part of the value to midnight (the start of the day). you can compare a date/time value with a complete date/time literal: If SomeDate > #3/6/93 1:20pm# Then If you do not include a time in a date/time literal.SomeDate Text2. You can use date/time literals in your code by enclosing them with the number sign (#)." . 1899." In the same way that you can use the IsNumeric function to determine if a Variant variable contains a value that can be considered a valid numeric value. in the same way you enclose string literals with double quotation marks ("").
"Creating Your Own Data Types. see "Date Function" in the Language Reference. all the elements in an array must have the same data type. and so on). including user-defined types (described in the section. Setting the data type of an array to Variant allows you to store objects alongside other data types in an array. numbers.Text & " is not a valid date. They are different from the control arrays you specify by setting the Index property of controls at design time. use the Private statement in the Declarations section of a module to declare the array.Else MsgBox Text1. You can declare an array of any of the fundamental data types. Objects Stored in Variants Objects can be stored in Variant variables. Arrays of variables are always contiguous. Arrays allow you to refer to a series of variables by the same name and to use a number (an index) to tell them apart. Declaring Fixed-Size Arrays There are three ways to declare a fixed-size array. the individual elements may contain different kinds of data (objects. This can be useful when you need to gracefully handle a variety of data types. you cannot load and unload elements from the middle of the array." End If For More Information For information about the various date/time functions. unlike control arrays. To create a module-level array. including objects. Of course. y y Setting Upper and Lower Bounds . depending on the scope you want the array to have: y To create a public array. when the data type is Variant. In Visual Basic there are two types of arrays: a fixed-size array which always remains the same size. strings. declared in code." in "More About Programming") and object variables (described in "Programming with Objects"). Because Visual Basic allocates space for each index number. and a dynamic array whose size can change at run-time. Arrays have both upper and lower bounds. use the Public statement in the Declarations section of a module to declare the array. you're probably familiar with the concept of arrays. Dynamic arrays are discussed in more detail in the section "Dynamic Arrays" later in this chapter. Arrays If you have programmed in other languages. use the Private statement in a procedure to declare the array. For example. avoid declaring an array larger than necessary. This helps you create smaller and simpler code in many situations. To create a local array. Note The arrays discussed in this section are arrays of variables. because you can set up loops that deal efficiently with any number of cases by using the index number. All the elements in an array have the same data type. and the elements of the array are contiguous within those bounds.
When declaring an array. these array declarations can appear in the Declarations section of a module: Dim Counters(14) As Integer Dim Sums(20) As Double ' 15 elements. To create a public array.647).147. The following code creates two arrays. provide it explicitly (as a Long data type) using the To keyword: Dim Counters(1 To 15) As Integer Dim Sums(100 To 120) As String In the preceding declarations.483. and populate it with other arrays of different data types. follow the array name by the upper bound in parentheses.147. For example. with index numbers running from 0 to 20. the index numbers of Counters range from 1 to 15. Dim countersB(5) As String For intX = 0 To 4 countersB(intX) = "hello" Next intX Dim arrX(2) As Variant ' Declare a new two-member ' array.483. ' 21 elements. It then declares a third Variant array and populates it with the integer and string arrays.648 to 2. To specify a lower bound. and the index numbers of Sums range from 100 to 120. one containing integers and the other strings. Arrays that Contain Other Arrays It's possible to create a Variant array. ' Declare and populate an integer array. The second creates an array with 21 elements. The upper bound cannot exceed the range of a Long data type (-2. Private Sub Command1_Click() Dim intX As Integer ' Declare counter variable. arrX(2) = countersB() MsgBox arrX(1)(2) ' Display a member of each . The default lower bound is 0. Dim countersA(5) As Integer For intX = 0 To 4 countersA(intX) = 5 Next intX ' Declare and populate a string array. arrX(1) = countersA() ' Populate the array with ' other arrays. with index numbers running from 0 to 14. you simply use Public in place of Dim: Public Counters(14) As Integer Public Sums(20) As Double The same declarations within a procedure use Dim: Dim Counters(14) As Integer Dim Sums(20) As Double The first declaration creates an array with 15 elements.
the following statement declares a two-dimensional 10-by-10 array within a procedure: Static MatrixA(9. to keep track of each pixel on your computer screen. This can be done using a multidimensional array to store the values. 1 To 10) As Double You can extend this to more than two dimensions.' array. you can declare arrays of multiple dimensions. For example: Dim MultiD(3. 1 To 10) As Double For I = 1 To 10 For J = 1 To 10 MatrixA(I. Be especially careful with Variant arrays. 9) As Double Either or both dimensions can be declared with explicit lower bounds: Static MatrixA(1 To 10. J) = I * 10 + J Next J Next I For More Information For information about loops. see "Loop Structures" later in this chapter. MsgBox arrX(2)(3) End Sub Multidimensional Arrays Sometimes you need to keep track of related information in an array. so use multidimensional arrays with care. 1 To 15) This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. you need to refer to its X and Y coordinates. The total number of elements is the product of these three dimensions. these statements initialize every element in MatrixA to a value based on its location in the array: Dim I As Integer. or 600. the total storage needed by the array increases dramatically. For example. . For example. 1 To 10. Using Loops to Manipulate Arrays You can efficiently process a multidimensional array by using nested For loops. Note When you start adding dimensions to an array. With Visual Basic. because they are larger than other data types. J As Integer Static MatrixA(1 To 10. For example. | https://www.scribd.com/document/77648945/Visual-Basic-Concepts | CC-MAIN-2017-39 | refinedweb | 29,999 | 60.11 |
A friend was asking if I knew a way of grabbing the output from a python function within ipython. I couldn’t see an easy way (the normal shell way of ‘>’ redirection won’t work). So the following is a quick hack on IPython’s OutputTrap:
Sample session, just defining a function that outputs something and I’m also using the ipython trick of preceding the command with a comma to make the args into strings…
In [1]: def myfunc():
...: print 'hello'
...:
...:
In [2]: run grab
In [3]: ,grab dumpfile myfunc()
and grab.py is…
import sys
from IPython import OutputTrap
def grab(fname, cmd):
dump = OutputTrap.OutputTrap('dump','','',trap_out=1,quiet_out=1)
dump.trap_all()
try:
eval(cmd, sys._getframe(1).f_globals, sys._getframe(1).f_locals)
except:
print sys.exc_info()
dump.release_all()
file(fname,'w').writelines( dump.summary() )
dump.flush_all()
… and the output of myfunc() appears in the file ‘dumpfile’ so it seems to work, but note I haven’t done much testing. | https://rcjp.wordpress.com/category/python/ | CC-MAIN-2017-26 | refinedweb | 163 | 62.78 |
Hey guys,
I have this Java code and I'm trying to convert it to MIPS. I've made an effort and I'm confused to what mistakes I've made.
If anyone knows MIPS, I'd really appreciate some guidance!
When ran in Java, I get these values:
x = 10500531
y = -1374550272
a = 256
b = -1364049997
c = -1364050253
//Bitwise.java public class BitWise { public static void main( String [] args ) { int x = 0xA039B3FF; int y = 0xFFAE1207; int a = 0; int b = 0; int c = 0; int count = 0; while( count < 8 ) { x = x >>> 1; y = y << 1; a = x & y; b = x | y; c = x ^ y; count++; } System.out.println("X = "+ x); System.out.println("y = "+ y); System.out.println("a = "+ a); System.out.println("b = "+ b); System.out.println("c = "+ c); } }
.text li $t0, 0 # count = 0 li $s1, 0xA039B3FF # x = 0xA039B3FF li $s2, 0xFFAE1207 # y = 0xFFAE1207 li $s3, 0 # a = 0 li $s4, 0 # b = 0 li $s5, 0 # c = 0 li $t1, 8 # cutoff value for counting variable loop: addi $t0, $t0, 1 # count++ xor $s5, $s1, $s2 # x xor y or $s4, $s1, $s2 # x or y and $s3, $s1, $s2 # x and y sll $s2, $s2, 1 # y = y << 1 srl $s1, $s1, 1 # x = x >>> 1 blt $t0, $t1, loop # if counting variable < 8 loop end:
Cheers,
Wootens | https://www.daniweb.com/programming/software-development/threads/350358/converting-java-code-to-mips | CC-MAIN-2017-22 | refinedweb | 224 | 76.25 |
sbi(TCCR0B, WGM02); // Yes in TCCR0B sbi(TCCR0A, WGM01); sbi(TCCR0A, WGM00);
OCR0A = 249; // For 16Mhz clock
SIGNAL(TIMER0_OVF_vect) {unsigned long m = timer0_millis; m++; timer0_millis = m; }
m = timer0_millis; // used to be m = timer0_overflow_count;
if ((TIFR0 & _BV(TOV0)) && (t < 249)) // 249 instead of 255
return ((m * 1000ul) + (unsigned int(t) * 4); // (64 / clockCyclesPerMicrosecond()) would also work in place of 4// An 8Mhz clock would use 8 since it has a resolution of 8uS
SIGNAL(TIMER0_OVF_vect){ ++timer0_millis; }
This will also break PWM on at least one pin ...
Is there a reason the interrupt service routine can't be reduced to a simple increment...
tone uses timer2 so would not be affected. But the impact on the timer0 PWMs seems a high price to pay for a savings of a small fraction of a percent of flash memory.
Well it's accuracy is closer to expected
The tone.cpp file does use Timer0 and OCR0A ...
PORTB = PORTB ^ B00100000; delayMicroseconds(25);
PORTB = PORTB ^ B00100000; delay(1);
...accuracy seems to be determined more by the accuracy of the crystal than errors in the core implimentation
Although there are defines for all the timers, the code only uses timer2.
... the faster the ISR completes, the better your program will behave as expected, practical or not.
Why would all timers be defined if only timer2 is used?
If I used timer2 for something else, would tone() be unavailable? | http://forum.arduino.cc/index.php?topic=22891.msg172958 | CC-MAIN-2015-40 | refinedweb | 231 | 68.2 |
9. Cart and Checkout¶
In django-SHOP the cart’s content is always stored inside the database. In previous versions of the software, the cart’s content was kept inside the session for anonymous users and stored in the database for logged in users. Now the cart is always stored in the database. This approach simplifies the code and saves some random access memory, but adds another minor problem:
From a technical point of view, the checkout page is the same as the cart. They can both be on separate pages, or be merged on the same page. Since what we would normally name the “Checkout Page”, is only a collection of Cascade Plugins, we won’t go into further detail here.
9.1. Expired Carts¶
Sessions expire, but then the cart’s content of anonymous customers still remains in the database. We therefore must assure that these carts will expire too, since they are of no use for anybody, except, maybe for some data-mining experts.
By invoking
./manage.py shopcustomers Customers in this shop: total=3408, anonymous=140, expired=88, active=1108, guests=2159, registered=1109, staff=5.
we gather some statistics about customers having visited of our django-SHOP site. In this example we see that 1109 customers bought as registered users, while 2159 bought as guests. There are 88 customers in the database, but they don’t have any associated session anymore, hence they can be considered as expired. Invoking
./manage.py shopcustomers --delete-expired
deletes those expired customers, and with them their expired carts. This task shall be performed by a cronjob on a daily or weekly basis.
9.2. Cart Models¶
The cart consists of two models classes
Cart and
CartItem, both inheriting from
BaseCart
and
BaseCartItem respectively. As with most models in django-SHOP, these are using the
Deferred Model Pattern, so that inheriting from a base class automatically sets the
foreign keys to the appropriate model. This gives the programmer the flexibility to add as many
fields to the cart, as the merchant requires for his special implementation.
In most use-cases, the default cart implementation will do the job. These default classes can be
found at
shop.models.defaults.cart.Cart and
shop.models.defaults.cart_item.CartItem.
To materialize the default implementation, it is enough to
import these two files into the
merchants shop project. Otherwise we create our own cart implementation inheriting from
BaseCart
and
BaseCartItem. Since the item quantity can not always be represented by natural numbers, this
field must be added to the
CartItem implementation rather than its base class. Its field type
must allow arithmetic operations, so only
IntegerField,
FloatField or
DecimalField
are allowed as quantity.
Note
Assure that the model
CartItem is imported (and materialized) before model
Product and classes derived from it.
The
Cart model uses its own manager. Since there is only one cart per customer, accessing the
cart must be performed using the
request object. We can always access the cart for the current
customer by invoking:
from shop.models.cart import CartManager cart = CartModel.objects.get_or_create_from_request(request)
Adding a product to the cart, must be performed by invoking:
from shop.models.cart import CartItemManager cart_item = CartItemManager.get_or_create( cart=cart, product=product, quantity=quantity, **extras)
This returns a new cart item object, if the given product could not be found in the current cart.
Otherwise it returns the existing cart item, increasing the quantity by the given value. For
products with variations it’s not always trivial to determine if they shall be considered as
existing cart items, or as new ones. Since django-SHOP can’t tell that difference for any kind
of product, it delegates this question. Therefore the class implementing the shop’s products shall
override their method
is_in_cart. This method is used to tell the
CartItemManager whether a
product has already been added to the cart or is new.
Whenever the method
cart.update(request) is invoked, the cart modifiers run against all items
in the cart. This updates the line totals, the subtotal, extra costs and the final sum.
9.2.1. Watch List¶
Instead of implementing a separate watch-list (some would say wish-list), django-SHOP uses a simple trick. Whenever the quantity of a cart item is zero, this item is considered to be in the watch list. Otherwise it is considered to be in the cart. The train of though is as follows: A quantity of zero, never makes sense for items in the cart. On the other side, any quantity makes sense for items in the watch-list. Therefore reducing the quantity of a cart item to zero is the same as keeping an eye on it, without actually wanting it to purchase.
9.3. Cart Views¶
Displaying the cart in django-SHOP is as simple, as adding any other page to the CMS. Change into the Django admin backend and enter into the CMS page tree. At an appropriate location in that tree add a new page. As page title use “Cart”, “Basket”, “Warenkorb”, “Cesta”,-cart” into the Id-field just below. This identifier is required by some templates which link directly onto the cart view page. If this field is not set, some links onto the cart page might not work properly.
It is suggested to check the checkbox named Soft root. This prevents that a menu item named “Cart” will appear side by side with other pages from the CMS. Instead, we prefer to render a special cart symbol located on the right of the navigation bar.
9.3.1. Cart using a Cart from section Shop. This Cart Plugin can be rendered in four different ways:
9.3.1.1. Editable Cart¶
An “Editable Cart” is rendered using the Angular JS template engine. This means that a customer may change the number of items, delete them or move them to the watch-list. Each update is reflected immediately into the cart’s subtotal, extra fields and final totals.
Using the above structure, the rendered cart will look similar to this.
Depending on the chosen template, this layout may vary.
9.3.1.2. Static Cart¶
An alternative to the editable cart is the static cart. Here the cart items are rendered by the Django template engine. Since here everything is static, the quantity can’t be changed anymore and the customer would have to proceed to the checkout without being able to change his mind. This probably only makes sense when purchasing a single product.
9.3.1.3. Cart Summary¶
This only displays the cart’s subtotal, the extra cart fields, such as V.A.T., shipping costs and the final total.
9.3.1.4. Watch List¶
A special view of the cart is the watch list. It can be used by customers to remember items they want to compare or buy sometimes later. The watch-list by default is editable, but does not allow to change the quantity. This is because the watch-list shares the same object model as the cart items. If the quantity of an item 0, then that cart item is considered to be watched. If instead the quantity is 1 ore more, the item is considered to be in the cart. It therefore is very easy to move items from the cart to the watch-list and vice versa. This concept also disallows to have an item in both the cart and the watch-list. This during online shopping, often can be a major point of confusion.
9.3.1.5. Render templates¶
The path of the templates used to render the cart views is constructed using the following rules:
- Look for a folder named according to the project’s name, ie.
settings.SHOP_APP_LABELin lower case. If no such folder can be found, then use the folder named
cart.
editable.html,
static.html,
watch.htmlor
summary.html.
These templates are written to be easily extensible by the customized templates. To override the
“editable cart” add a template with the path, say
myshop/cart/editable.html to the projects
template folder. This template then shall begin with
{% extend "shop/cart/editable.html" %}
and only override the
{% block %}...{% endblock %} interested in.
Many of these template blocks are themselves embedded inside HTML elements such as
<script id="shop/....html" type="text/ng-template">. The reason for this is that the editable
cart is rendered in the browser by AngularJS using so called directives. Hence it becomes very
straight-forward to override Angular’s script templates using Django’s internal template engine.
9.3.1.5.1. Multiple templates¶
If for some special reasons we need different cart templates, then we must add this line to the
projects
settings.py:
CMSPLUGIN_CASCADE_PLUGINS_WITH_EXTRA_RENDER_TEMPLATES = { 'ShopCartPlugin': ( (None, _("default")), # the default behavior ('myproject/cart/other-editable.html', _("extra editable")), ) }
This will add an extra select button to the cart editor. The site administrator then can choose between the default template and an extra editable cart template.
9.3.1.5.2. Proceed to Checkout¶
On the cart’s view, the merchant may decide whether to implement the checkout forms together with the cart, or to create a special checkout page onto which the customer can proceed. From a technical point of view, it doesn’t make any difference, if the cart and the checkout are combined on the same CMS page, or if they are split across two or more pages. In the latter case simply add a button at the end of each page, so that the customer can easily proceed to the next one.
On the checkout page, the customer has to fill out a few forms. These can be a contact form, shipping and billing addresses, payment and shipping methods, and many more. Which ones depend on the configuration, the legal regulations and the requirements of the shop’s implementation. In Cascade Plugins all shop specific CMS plugins are listed. They can be combined into whatever makes sense for a successful checkout.
9.3.2. Add a Cart via manually written Cart Template¶
Instead of using the CMS plugin system, the template for the cart can also be implemented manually.
Based on an existing page template, locate the element, where the cart shall be inserted. Then
use one of the existing templates in the folder
django-shop/shop/templates/shop/cart/ as a
starting point, and insert it at an appropriate location in the page template. Next, in the
project’s
settings.py, add this specialized template to the list
CMS_TEMPLATES and select
it for that page.
From a technical point of view, it does not make any difference whether we use the cart plugin or a handcrafted template. If the HTML code making up the cart has to be adopted to the merchants needs, we normally are better off and much more flexible, if we override the template code as described in section Render templates. Therefore, it is strongly discouraged to craft cart and checkout templates by hand.
9.4. Cart Modifiers¶
Cart Modifiers are simple plugins that allow the merchant to define rules in a programmatic way, how the totals of a cart are computed and how they are labeled. A typical job is to compute tax rates, adding discounts, shipping and payment costs, etc.
Instead of implementing each possible combination for all of these use cases, the django-SHOP framework offers an API, where third party applications can hooks into every computational step. One thing to note here is that Cart Modifiers are not only invoked, when the cart is complete and the customer wants to proceed to the checkout, but also for each item before being added to the cart.
This allows the programmer to vary the price of certain items, depending on the current state of the cart. It can for instance be used, to set one price for the first item, and other prices for every further items added to the cart.
Cart Modifiers are split up into three different categories: Generic, Payment and Shipping. In the
shops
settings.py they must be configured as a list or tuple such as:
SHOP_CART_MODIFIERS = ( 'shop.modifiers.defaults.DefaultCartModifier', 'shop.modifiers.taxes.CartExcludedTaxModifier', 'myshop.modifiers.PostalShippingModifier', 'shop.modifiers.defaults.PayInAdvanceModifier', 'shop_stripe.modifiers.StripePaymentModifier', )
Generic modifiers are applied always. The Shipping and Payment modifiers are applied only for the selected shipping and/or payment method. If the customer has not yet decided, how to ship or how to pay, then the corresponding modifiers are not applied.
When updating the cart, modifiers are applied in the order of the above list. Therefore it makes a difference, if taxes are applied before or after having applied the shipping costs.
Moreover, whenever in the detail view the quantity of a product is updated, then all configured
modifiers are ran for that item. This allows the
ItemModelSerializer, to even change the unit
price of a product, depending on the total content of the cart.
Cart modifiers are easy to write and they normally consist only of a few lines of code. It is the intention of django-SHOP to seed an eco-system for these kinds of plugins. Besides computing the total, cart modifiers can also be used to sum up the weight, if the merchant’s product models specifies it.
Here is an incomplete list of some useful cart modifiers:
9.4.1. Generic Cart Modifiers¶
These kinds of cart modifiers are applied unconditionally onto the cart. A typical instance is the
DefaultCartModifier, the
CartIncludeTaxModifier or the
CartExcludeTaxModifier.
9.4.1.1. DefaultCartModifier¶
The
shop.modifiers.default.DefaultCartModifier is required for almost every shopping cart.
It handles the most basic calculations, ie. multiplying the items unit prices with the chosen
quantity. Since this modifier sets the cart item’s line total, it must be listed as the first entry
in
SHOP_CART_MODIFIERS.
9.4.1.2. Payment Cart Modifier¶
From these kinds of modifiers, only that for the chosen payment method is applied. Payment Modifiers
are used to add extra costs or discounts depending on the chosen payment method. By overriding the
method
is_disabled a payment method can be disabled; useful to disable certain payments in case
the carts total is below a certain threshold.
9.4.1.3. Shipping Cart Modifier¶
From these kinds of modifiers, only that for the chosen shipping method is applied. Shipping
Modifiers are used to add extra costs or discounts depending on chosen shipping method, the number
of items in the cart and their weight. By overriding the method
is_disabled a shipping method
can be disabled; useful to disable certain payments in case the cart’s total is below a certain
threshold or the weight is too high.
9.4.1.4. How Modifiers work¶
Cart modifiers should extend the
shop.modifiers.base.BaseCartModifier class and extend one
or more of the given methods:
Note
Until version 0.2 of django-SHOP, the Cart Modifiers returned the amount and label for the extra item rows, and django-SHOP added them up. Since Version 0.3 cart modifiers must change the line subtotals and cart total themselves.
- class
shop.modifiers.base.
BaseCartModifier(identifier=None)¶
Cart Modifiers are the cart’s counterpart to backends.
It allows to implement taxes and rebates / bulk prices in an elegant and reusable manner: Every time the cart is refreshed (via it’s update() method), the cart will call all subclasses of this modifier class registered with their full path in settings.SHOP_CART_MODIFIERS.
The methods defined here are called in the following sequence: 1. pre_process_cart: Totals are not computed, the cart is “rough”: only relations and quantities are available 1a. pre_process_cart_item: Line totals are not computed, the cart and its items are “rough”: only relations and quantities are available 2. process_cart_item: Called for each cart_item in the cart. The modifier may change the amount in cart_item.line_total. 2a. add_extra_cart_item_row: It optionally adds an object of type ExtraCartRow to the current cart item. This object adds additional information displayed on each cart items line. 3. process_cart: Called once for the whole cart. Here, all fields relative to cart items are filled. Here the carts subtotal is used to computer the carts total. 3a. add_extra_cart_row: It optionally adds an object of type ExtraCartRow to the current cart. This object adds additional information displayed in the carts footer section. 4. post_process_cart: all totals are up-to-date, the cart is ready to be displayed. Any change you make here must be consistent!
Each method accepts the HTTP request object. It shall be used to let implementations determine their prices according to the session, and other request information.
arrange_watch_items(watch_items, request)¶
Arrange all items, which are being watched. Override this method to resort and regroup the returned items.
arrange_cart_items(cart_items, request)¶
Arrange all items, which are intended for the shopping cart. Override this method to resort and regroup the returned items.
pre_process_cart(cart, request)¶
This method will be called before the Cart starts being processed. It shall be used to populate the cart with initial values, but not to compute the cart’s totals.
pre_process_cart_item(cart, item, request)¶
This method will be called for each item before the Cart starts being processed. It shall be used to populate the cart item with initial values, but not to compute the item’s linetotal.
process_cart_item(cart_item, request)¶
This will be called for every line item in the Cart: Line items typically contain: product, unit_price, quantity and a dictionary with extra row information.
If configured, the starting line total for every line (unit price * quantity) is computed by the DefaultCartModifier, which typically is listed as the first modifier. Posterior modifiers can optionally change the cart items line total.
After processing all cart items with all modifiers, these line totals are summed up to form the carts subtotal, which is used by method process_cart.
post_process_cart_item(cart, item, request)¶
This will be called for every line item in the Cart, while finally processing the Cart. It may be used to collect the computed line totals for each modifier.
process_cart(cart, request)¶
This will be called once per Cart, after every line item was treated by method process_cart_item.
The subtotal for the cart is already known, but the total is still unknown. Like for the line items, the total is expected to be calculated by the first cart modifier, which typically is the DefaultCartModifier. Posterior modifiers can optionally change the total and add additional information to the cart using an object of type ExtraCartRow.
post_process_cart(cart, request)¶
This method will be called after the cart was processed in reverse order of the registered cart modifiers. The Cart object is “final” and all the fields are computed. Remember that anything changed at this point should be consistent: If updating the price you should also update all relevant totals (for example).
add_extra_cart_item_row(cart_item, request)¶
Optionally add an ExtraCartRow object to the current cart item.
This allows to add an additional row description to a cart item line. This method optionally utilizes and/or modifies the amount in cart_item.line_total. | http://django-shop.readthedocs.io/en/latest/reference/cart-checkout.html | CC-MAIN-2017-47 | refinedweb | 3,169 | 55.54 |
Bean Injection
We support the injection of various resources using
@EndpointInject or
@BeanInject. This can be used to inject
Endpoint instances which can be used for testing when used with Mock endpoints; see the Testing for an example.
ProducerTemplate instances for POJO Producing
client side proxies for POJO Producing
Using @BeanInject
For example to inject a bean named foo, you can enlist the bean in the Registry such as in a Spring XML file:
<bean id="foo" class="com.foo.MyFooBean"/>
And then in a Java
RouteBuilder class, you can inject the bean using
@BeanInject as shown below:
public class MyRouteBuilder extends RouteBuilder { @BeanInject("foo") MyFooBean foo; public void configure() throws Exception { .. } }
If you omit the name, then Camel does a lookup by type, and injects the bean if there is exactly only one bean of that type enlisted in the Registry.
@BeanInject MyFooBean foo;
Bean Injection with Quarkus or CDI
When using Camel with CDI, Spring Boot, or Quarkus, then the
@Inject, or
@Named annotations can be used to inject Camel resources as well. | https://camel.apache.org/manual/bean-injection.html | CC-MAIN-2022-05 | refinedweb | 175 | 51.21 |
Opened 10 years ago
Closed 10 years ago
#1624 closed Bug (No Bug)
_crypt_DecryptData not working in Windows 2000
Description
Please try the example from the AutoIt Help:
#include <Crypt.au3> ; This example shows how to decrypt a string Local Const $bEncrypted = Binary("0x040A0D2594CE1FFC8E4CE5BC14E8724B6B5900225EA8E45CF328" & _ "9D0D6A48E490E53FB66F39FF5CA967C5F6CD04D399AF09E18E7A91EEA32F7BBBB714DEC6865128CE3A" & _ "4F1BB826554B69B7AC96E8AAA639656F0323E34745167F4B72FF4984A1C4B81E1F66DDD9743B9C664406D76B52") MsgBox(0, "Decrypted data", BinaryToString(_Crypt_DecryptData($bEncrypted, "once", $CALG_RC2)))
Even Win2000 is very old, you did not stopped the support for this OS, as i can read on the homepage.
The script is running fine under XP,Vista and Win7.
Attachments (0)
Change History (4)
comment:1 Changed 10 years ago by brainwilli@…
comment:2 Changed 10 years ago by brainwilli@…
Found that:
"
When you try to decrypt data on a computer that is running the Microsoft Windows XP operating system, and the data was encrypted by using the RC2 algorithm on a computer that is running Microsoft Windows 2000, you may not be able to decrypt the data successfully.
To be able to decrypt the data successfully, you must make an explicit call to the CryptSetKeyParam function. The CryptSetKeyParam function is defined in the Advapi32.dll file to adjust the key length for the RC2 algorithm explicitly.
"
I have the same problem with the RC4 algo...
That is not an AutoIT bug, but perhaps someone can update the help file to inform
about this issue.
(Maybe there is an workaround to get the script running....)
comment:3 Changed 10 years ago by brainwilli@…
Sorry, no bug Please close this ticket
comment:4 Changed 10 Bug seems to be elswhere.
I encrypted a string in Windows 2000. Then the script does the job in Windows 2000.
But the 'Windows 2000 script' does not run in Vista.
Perhaps there is some difference in encrypting under Win2000 and encrypting under XP/Vista/Win7 ? | https://www.autoitscript.com/trac/autoit/ticket/1624 | CC-MAIN-2020-16 | refinedweb | 299 | 60.55 |
Subject: Re: [boost] [gsoc 2013] chrono::date
From: Anurag Kalia (anurag.kalia_at_[hidden])
Date: 2013-04-25 18:06:30
> If we were to say:
>
> typedef std::chrono::duration
> <
> std::int32_t, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>
> > days;
>
> typedef std::chrono::time_point
> <
> std::chrono::system_clock, days
> > day_point;
>
> We would have a time_point and duration with a precision suitable for counting sunrises. We could also easily create a clock that ticked once per sunrise.
>
> Now when you get 1000 ticks of this clock, you can know that 1000 days have passed. And yes, 1000 days can be converted to seconds. And when doing so you'll get 86,400,000 seconds. And if it matters that the correct answer is 86,400,001 seconds because you've crossed a leap second boundary, then you need specialized tools for that level of precision. People who need such precision rightly don't trust general purpose tools.
>
> To put this into perspective, the std::chrono::system_clock on your computer (if it is implemented on your platform) is counting seconds since New Years 1970 UTC, with a precision of seconds, or perhaps milliseconds, or maybe even microseconds (on my system it is microseconds). As I write this, my computer claims it is 1,366,849,370,271,425 microseconds past New Years 1970 UTC. And absolutely no one sends in bug reports that this number is 25,000,000 microseconds too low (). No one cares or expects the precision to be better than 0.00000001829024.
>
> The very few people who do care, refuse to use UTC. They use TAI () instead, which does not include leap seconds. And needless to say, they aren't using the POSIX getimeofday() on their laptop to get the current time (which is what std::chrono::system_clock is commonly based on). They've got atomic clocks ticking 9,192,631,770 times a second.
>
Thanks a lot. I am sorry to say that I am one of the pedants who mourn the loss of a leap second. But I realise that over a course of 5000 years, UTC and TAI would diverge by approximately an hour, which is not enough to change dates in both time standards. Moreover, over such large intervals (as you so helpfully pointed out) an error margin of 1 day really does not matter. Suddenly, chrono because a very palatable foundation for the library.
> To verify my claims about your std::chrono::system_clock, I encourage you to play with the following code. If you discover I'm wrong, I would really appreciate being corrected. I do not have in my possession all implementations of <chrono>, nor access to all platforms. So I depend upon people such as yourself to tell me what you're seeing.
>
> #include <chrono>
> #include <ctime>
> #include <iostream>
>
> int
> main()
> {
> using namespace std;
> using namespace std::chrono;
> typedef duration<int, ratio_multiply<hours::period, ratio<24> >::type> days;
> system_clock::time_point now = system_clock::now();
> system_clock::duration tp = now.time_since_epoch();
> days d = duration_cast<days>(tp);
> tp -= d;
> hours h = duration_cast<hours>(tp);
> tp -= h;
> minutes m = duration_cast<minutes>(tp);
> tp -= m;
> seconds s = duration_cast<seconds>(tp);
> tp -= s;
> std::cout << d.count() << "d " << h.count() << ':'
> << m.count() << ':' << s.count();
> std::cout << " " << tp.count() << "["
> << system_clock::duration::period::num << '/'
> << system_clock::duration::period::den << "]\n";
>
> time_t tt = system_clock::to_time_t(now);
> tm utc_tm = *gmtime(&tt);
> std::cout << utc_tm.tm_year + 1900 << '-';
> std::cout << utc_tm.tm_mon + 1 << '-';
> std::cout << utc_tm.tm_mday << ' ';
> std::cout << utc_tm.tm_hour << ':';
> std::cout << utc_tm.tm_min << ':';
> std::cout << utc_tm.tm_sec << '\n';
This example also proved invaluable. After tweaking it, I have a good idea now of how to use Julian Dates (+/- reasonable constant) to represent dates. Thank you!
PS: Since this ML is heavy traffic, is it okay for me to send such thank you emails? I really wanted to, but I am not sure how they are received.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2013/04/202904.php | CC-MAIN-2020-29 | refinedweb | 664 | 66.64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.