public interface LSParser
LSParser
provides an API for parsing XML and building the
corresponding DOM document structure. A LSParser
instance
can be obtained by invoking the
DOMImplementationLS.createLSParser()
method.
As specified in [DOM Level 3 Core] , when a document is first made available via the LSParser:
value
and
nodeValue
attributes of an Attr
node initially
return the XML 1.0
normalized value. However, if the parameters "
validate-if-schema" and "
datatype-normalization" are set to true
, depending on the attribute normalization
used, the attribute values may differ from the ones obtained by the XML
1.0 attribute normalization. If the parameters "
datatype-normalization" is set to false
, the XML 1.0 attribute normalization is
guaranteed to occur, and if the attributes list does not contain
namespace declarations, the attributes
attribute on
Element
node represents the property [attributes] defined in [XML Information Set]
.
Asynchronous LSParser
objects are expected to also
implement the events::EventTarget
interface so that event
listeners can be registered on asynchronous LSParser
objects.
Events supported by asynchronous LSParser
objects are:
LSParser
finishes to load the document. See also the
definition of the LSLoadEvent
interface. LSParser
signals progress as data is parsed. This
specification does not attempt to define exactly when progress events
should be dispatched. That is intentionally left as
implementation-dependent. Here is one example of how an application might
dispatch progress events: Once the parser starts receiving data, a
progress event is dispatched to indicate that the parsing starts. From
there on, a progress event is dispatched for every 4096 bytes of data
that is received and processed. This is only one example, though, and
implementations can choose to dispatch progress events at any time while
parsing, or not dispatch them at all. See also the definition of the
LSProgressEvent
interface. Note: All events defined in this specification use the
namespace URI "http://www.w3.org/2002/DOMLS"
.
While parsing an input source, errors are reported to the application
through the error handler (LSParser.domConfig
's "
error-handler" parameter). This specification does in no way try to define all possible
errors that can occur while parsing XML, or any other markup, but some
common error cases are defined. The types (DOMError.type
) of
errors and warnings defined by this specification are:
"check-character-normalization-failure" [error]
"doctype-not-allowed" [fatal]
true
and a doctype is encountered. "no-input-specified" [fatal]
LSInput
object. "pi-base-uri-not-preserved" [warning]
false
and the following XML file is parsed:
<!DOCTYPE root [ <!ENTITY e SYSTEM 'subdir/myentity.ent' ]> <root> &e; </root>And
subdir/myentity.ent
contains:
<one> <two/> </one> <?pi 3.14159?> <more/>
"unbound-prefix-in-entity" [warning]
true
and an unbound namespace prefix is
encountered in an entity's replacement text. Raising this warning is not
enforced since some existing parsers may not recognize unbound namespace
prefixes in the replacement text of entities. "unknown-character-denormalization" [fatal]
false
and a character is encountered for which the
processor cannot determine the normalization properties. "unsupported-encoding" [fatal]
"unsupported-media-type" [fatal]
true
and an unsupported media type is encountered. In addition to raising the defined errors and warnings, implementations are expected to raise implementation specific errors and warnings for any other error and warning cases such as IO errors (file not found, permission denied,...), XML well-formedness errors, and so on.
See also the Document Object Model (DOM) Level 3 Load and Save Specification.
| Modifier and Type | Field and Description |
|---|---|
static short |
ACTION_APPEND_AS_CHILDREN
Append the result of the parse operation as children of the context
node.
|
static short |
ACTION_INSERT_AFTER
Insert the result of the parse operation as the immediately following
sibling of the context node.
|
static short |
ACTION_INSERT_BEFORE
Insert the result of the parse operation as the immediately preceding
sibling of the context node.
|
static short |
ACTION_REPLACE
Replace the context node with the result of the parse operation.
|
static short |
ACTION_REPLACE_CHILDREN
Replace all the children of the context node with the result of the
parse operation.
|
| Modifier and Type | Method and Description |
|---|---|
void |
abort()
Abort the loading of the document that is currently being loaded by
the
LSParser . |
boolean |
getAsync()
true if the LSParser is asynchronous,
false if it is synchronous. |
boolean |
getBusy()
true if the LSParser is currently busy
loading a document, otherwise false . |
DOMConfiguration |
getDomConfig()
The
DOMConfiguration object used when parsing an input
source. |
LSParserFilter |
getFilter()
When a filter is provided, the implementation will call out to the
filter as it is constructing the DOM tree structure.
|
Document |
parse(LSInput input)
Parse an XML document from a resource identified by a
LSInput . |
Document |
parseURI(String uri)
Parse an XML document from a location identified by a URI reference [IETF RFC 2396].
|
Node |
parseWithContext(LSInput input,
Node contextArg,
short action)
Parse an XML fragment from a resource identified by a
LSInput and insert the content into an existing document
at the position specified with the context and
action arguments. |
void |
setFilter(LSParserFilter filter)
When a filter is provided, the implementation will call out to the
filter as it is constructing the DOM tree structure.
|
static final short ACTION_APPEND_AS_CHILDREN
Element
or a DocumentFragment
.static final short ACTION_REPLACE_CHILDREN
Element
, a Document
, or a
DocumentFragment
.static final short ACTION_INSERT_BEFORE
Element
or a
DocumentFragment
.static final short ACTION_INSERT_AFTER
Element
or a
DocumentFragment
.static final short ACTION_REPLACE
Element
or a
DocumentFragment
.DOMConfiguration getDomConfig()
DOMConfiguration
object used when parsing an input
source. This DOMConfiguration
is specific to the parse
operation. No parameter values from this DOMConfiguration
object are passed automatically to the DOMConfiguration
object on the Document
that is created, or used, by the
parse operation. The DOM application is responsible for passing any
needed parameter values from this DOMConfiguration
object to the DOMConfiguration
object referenced by the
Document
object.
DOMConfiguration
objects for LSParser
add or modify the following parameters:
"charset-overrides-xml-encoding"
true
LSInput
overrides
any encoding from the protocol. false
"disallow-doctype"
true
false
"ignore-unknown-character-denormalizations"
true
false
"infoset"
DOMConfiguration
for a description of
this parameter. Unlike in [DOM Level 3 Core]
, this parameter will default to true
for
LSParser
. "namespaces"
true
false
"resource-resolver"
LSResourceResolver
object, or null. If
the value of this parameter is not null when an external resource
(such as an external XML entity or an XML schema location) is
encountered, the implementation will request that the
LSResourceResolver
referenced in this parameter resolves
the resource. "supported-media-types-only"
true
false
"validate"
DOMConfiguration
for a description of this parameter.
Unlike in [DOM Level 3 Core]
, the processing of the internal subset is always accomplished, even
if this parameter is set to false
. "validate-if-schema"
DOMConfiguration
for a description of this parameter.
Unlike in [DOM Level 3 Core]
, the processing of the internal subset is always accomplished, even
if this parameter is set to false
. "well-formed"
DOMConfiguration
for a description of this parameter.
Unlike in [DOM Level 3 Core]
, this parameter cannot be set to false
. LSParserFilter getFilter()
DOMConfiguration
parameters have been applied. For
example, if "
validate" is set to true
, the validation is done before invoking the
filter.void setFilter(LSParserFilter filter)
DOMConfiguration
parameters have been applied. For
example, if "
validate" is set to true
, the validation is done before invoking the
filter.boolean getAsync()
true
if the LSParser
is asynchronous,
false
if it is synchronous.boolean getBusy()
true
if the LSParser
is currently busy
loading a document, otherwise false
.Document parse(LSInput input) throws DOMException, LSException
LSInput
.input
- The LSInput
from which the source of the
document is to be read.LSParser
is a synchronous
LSParser
, the newly created and populated
Document
is returned. If the LSParser
is
asynchronous, null
is returned since the document
object may not yet be constructed when this method returns.DOMException
- INVALID_STATE_ERR: Raised if the LSParser
's
LSParser.busy
attribute is true
.LSException
- PARSE_ERR: Raised if the LSParser
was unable to load
the XML document. DOM applications should attach a
DOMErrorHandler
using the parameter "
error-handler" if they wish to get details on the error.Document parseURI(String uri) throws DOMException, LSException
uri
- The location of the XML document to be read.LSParser
is a synchronous
LSParser
, the newly created and populated
Document
is returned, or null
if an error
occured. If the LSParser
is asynchronous,
null
is returned since the document object may not yet
be constructed when this method returns.DOMException
- INVALID_STATE_ERR: Raised if the LSParser.busy
attribute is true
.LSException
- PARSE_ERR: Raised if the LSParser
was unable to load
the XML document. DOM applications should attach a
DOMErrorHandler
using the parameter "
error-handler" if they wish to get details on the error.Node parseWithContext(LSInput input, Node contextArg, short action) throws DOMException, LSException
LSInput
and insert the content into an existing document
at the position specified with the context
and
action
arguments. When parsing the input stream, the
context node (or its parent, depending on where the result will be
inserted) is used for resolving unbound namespace prefixes. The
context node's ownerDocument
node (or the node itself if
the node of type DOCUMENT_NODE
) is used to resolve
default attributes and entity references.
Document
node and the action
is ACTION_REPLACE_CHILDREN
, then the document that is
passed as the context node will be changed such that its
xmlEncoding
, documentURI
,
xmlVersion
, inputEncoding
,
xmlStandalone
, and all other such attributes are set to
what they would be set to if the input source was parsed using
LSParser.parse()
.
LSParser
is asynchronous (LSParser.async
is
true
).
ErrorHandler
instance associated with the "
error-handler" parameter of the DOMConfiguration
.
parseWithContext
, the values of the
following configuration parameters will be ignored and their default
values will always be used instead: "
validate", "
validate-if-schema", and "
element-content-whitespace". Other parameters will be treated normally, and the parser is expected
to call the LSParserFilter
just as if a whole document
was parsed.input
- The LSInput
from which the source document
is to be read. The source document must be an XML fragment, i.e.
anything except a complete XML document (except in the case where
the context node of type DOCUMENT_NODE
, and the action
is ACTION_REPLACE_CHILDREN
), a DOCTYPE (internal
subset), entity declaration(s), notation declaration(s), or XML or
text declaration(s).contextArg
- The node that is used as the context for the data
that is being parsed. This node must be a Document
node, a DocumentFragment
node, or a node of a type
that is allowed as a child of an Element
node, e.g. it
cannot be an Attribute
node.action
- This parameter describes which action should be taken
between the new set of nodes being inserted and the existing
children of the context node. The set of possible actions is
defined in ACTION_TYPES
above.DOMException
- HIERARCHY_REQUEST_ERR: Raised if the content cannot replace, be
inserted before, after, or as a child of the context node (see also
Node.insertBefore
or Node.replaceChild
in [DOM Level 3 Core]
).
LSParser
doesn't
support this method, or if the context node is of type
Document
and the DOM implementation doesn't support
the replacement of the DocumentType
child or
Element
child.
LSParser.busy
attribute is true
.LSException
- PARSE_ERR: Raised if the LSParser
was unable to load
the XML fragment. DOM applications should attach a
DOMErrorHandler
using the parameter "
error-handler" if they wish to get details on the error.void abort()
LSParser
. If the LSParser
is currently
not busy, a call to this method does nothing. Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2015, Oracle and/or its affiliates. All rights reserved.


| Properties | index /home/surf/sfdcexport/lib/Properties.py |
Structure for reading and providing access to properties, read from a
file, throughout a project.
Properties class is a singleton-type class that will read the properties file
the first time the class is instantiated, parsing the file and populating
data members in the class for use by all future instantiations.
Author: Kevin Shuk<EMAIL_ADDRESS>Date: Sep 17, 2005
Copyright: (c) 2005, Kevin Shuk
All Rights Reserved
| Modules | ||||||
|
| Classes | ||||||||||||||||||||||||||||||
|
|
| Data | ||
| ident = '$ID: $' |


|
unity-menustack
0.1.0
A way to track unity menu navigation that doesn't suck too much
|
Base for a control capable of navigating to a different Menu within a MenuRoot More...
Public Member Functions | |
| virtual void | Navigate () |
| Triggers navigation More... | |
Protected Member Functions | |
| abstract Menu | GetNavigationLocation () |
| Provides a location to navigate to, when navigation occurs More... | |
|
protectedpure virtual |
Provides a location to navigate to, when navigation occurs
Implemented in MenuStack.Navigation.ExitMenuNavigator, MenuStack.Navigation.SceneMenuNavigator, MenuStack.Navigation.RegexMenuNavigator, MenuStack.Navigation.BackMenuNavigator, MenuStack.Navigation.DirectMenuNavigator, and MenuStack.Navigation.NextMenuNavigator.
|
virtual |
Triggers navigation
Implements MenuStack.Navigation.INavigator.
Reimplemented in MenuStack.Navigation.ExitMenuNavigator, MenuStack.Navigation.SceneMenuNavigator, and MenuStack.Navigation.BackMenuNavigator.


Welcome to Summit Gaming!
Updates
Feel free to browse around our work in progress website! Use the hyperlinks above or to the left to redirect yourself wherever you wish to go! I will be posting updates to the server here from time to time!
-NascarNick 7/31/15


Toggle navigation
FUNCY
Shop
funcy
Pricing
Where
Contact
Sign In
Only cool things!
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
PRO PLAN
$10 / month
Personal use
Unlimited projects
27/7 support
DEV PLAN
$20 / month
Personal use
Unlimited projects
27/7 support
FREE PLAN
$0 / month
Personal use
Unlimited projects
27/7 support
Contact
name
Email
Suscribe to newsletter
Subject
Payment
Shipment
Product
Other
Send!


I am Analyticals and details oriented Web & Android application developer professional with stellar communication skills. Adept at bringing all team members together to reach a common goal on time and under budget. Conceptualizing app solutions with the latest technology, design theory, and a large dose of creativity.
The Department of Computer Science & Engineering at the Uttara University provides a diverse research environment, which enables students to actively participate in the department’s life, and excel in their studies.
+8801632704577
+8801744165013
Educating ownself doesn't have to be boring to me. Sometimes, It could be science, the oceans or even horror films. I search my interests on google and become as knowledgeable as I can about my passions. I have weakness to know about ancient history.


Guess a Number
Win:
0
Losse:
0
Guess a number between 1 and 99 in seven attempts
Submit
Reset
Previous Guesses


Philadelphia Eagles to host final minutes of high school playoff game after shooting suspended play
by Paulina DedajThe Philadelphia Eagles are helping two New Jersey high school football teams play out the final 17 minutes of a playoff game that was cut short over the weekend because of a shooting that critically injured a 10-year-old boy.
The Eagles offered to host Pleasantville and Camden high school at Lincoln Financial Field on Nov. 30 to complete their playoff game, which came to a sudden stop Friday evening when gunfire erupted.
“It’s extremely unfortunate that a senselessly violent act has impacted this game, and there will certainly be a wide range of emotions along both sidelines. However, thanks to the Eagles’ generosity and community spirit, Pleasantville and Camden student-athletes and their families will have an opportunity to write their own ending to this game,” Larry White, executive director of the New Jersey State Interscholastic Athletic Association, said in a news release.

Six men have since been charged in connection to the shooting, including a 27-year-old man who was shot. A 15-year-old male was also grazed in the shooting.
The playoff game will resume play on neutral and safe grounds at 4 p.m.
CLICK HERE TO GET THE FOX NEWS APP
Players will be given a limited number of free passes, as the game will be closed to the public. It will also be live-streamed for free online.
The Associated Press contributed to this report.


Below is a list of common errors in Go. Click on any of them to find out frequent causes, fixes, and more.
template.ParseGlob()
→
"html/template: pattern matches no files:"
package: html/template
Want to contribute to this project? Submit a PR!
Created by Jon Calhoun, but you can check out the source and contribute on GitHub


Index
Prevent frequently-included CMake files from being re-parsed multiple times.
mchbuild_include_guard()


| 1 | package app.cmd; | |
| 2 | ||
| 3 | import app.MyImage; | |
| 4 | import java.awt.Color; | |
| 5 | import java.awt.Rectangle; | |
| 6 | import tools.TwoPoint; | |
| 7 | ||
| 8 | /** | |
| 9 | * | |
| 10 | * An implementation of CMD which calculates the average color and sets it onto | |
| 11 | * target. | |
| 12 | * | |
| 13 | */ | |
| 14 | public class SetAvgColor implements CMD { | |
| 15 | ||
| 16 | /** | |
| 17 | * | |
| 18 | * Calculates average color based on area's getRectangle() and sets it onto | |
| 19 | * img. | |
| 20 | * | |
| 21 | * @param img Target. | |
| 22 | * @param area Information on where to calculate new color. | |
| 23 | */ | |
| 24 | @Override | |
| 25 | public void execute(MyImage img, TwoPoint area) { | |
| 26 | int a = 0; | |
| 27 | int r = 0; | |
| 28 | int g = 0; | |
| 29 | int b = 0; | |
| 30 | Rectangle rect = area.getRectangle(); | |
| 31 |
4
1. execute : changed conditional boundary → KILLED 2. execute : Changed increment from 1 to -1 → KILLED 3. execute : Replaced integer addition with subtraction → KILLED 4. execute : negated conditional → KILLED |
for (int y = 0; y < rect.height + 1; y++) { |
| 32 |
4
1. execute : changed conditional boundary → KILLED 2. execute : Changed increment from 1 to -1 → KILLED 3. execute : Replaced integer addition with subtraction → KILLED 4. execute : negated conditional → KILLED |
for (int x = 0; x < rect.width + 1; x++) { |
| 33 | ||
| 34 |
2
1. execute : Replaced integer addition with subtraction → KILLED 2. execute : Replaced integer addition with subtraction → KILLED |
int val = img.getImg().getRGB(x + rect.x, y + rect.y); |
| 35 |
3
1. execute : Replaced bitwise AND with OR → KILLED 2. execute : Replaced Unsigned Shift Right with Shift Left → KILLED 3. execute : Replaced integer addition with subtraction → KILLED |
a += (0xff000000 & val) >>> 24; |
| 36 |
3
1. execute : Replaced bitwise AND with OR → KILLED 2. execute : Replaced Shift Right with Shift Left → KILLED 3. execute : Replaced integer addition with subtraction → KILLED |
r += (0x00ff0000 & val) >> 16; |
| 37 |
3
1. execute : Replaced bitwise AND with OR → KILLED 2. execute : Replaced Shift Right with Shift Left → KILLED 3. execute : Replaced integer addition with subtraction → KILLED |
g += (0x0000ff00 & val) >> 8; |
| 38 |
2
1. execute : Replaced bitwise AND with OR → KILLED 2. execute : Replaced integer addition with subtraction → KILLED |
b += (0x000000ff & val); |
| 39 | } | |
| 40 | ||
| 41 | } | |
| 42 | ||
| 43 |
3
1. execute : Replaced integer multiplication with division → SURVIVED 2. execute : Replaced integer addition with subtraction → KILLED 3. execute : Replaced integer addition with subtraction → KILLED |
int divider = (rect.height + 1) * (rect.width + 1); |
| 44 |
1
1. execute : Replaced integer division with multiplication → KILLED |
a /= divider; |
| 45 |
1
1. execute : Replaced integer division with multiplication → KILLED |
r /= divider; |
| 46 |
1
1. execute : Replaced integer division with multiplication → KILLED |
g /= divider; |
| 47 |
1
1. execute : Replaced integer division with multiplication → KILLED |
b /= divider; |
| 48 | ||
| 49 |
1
1. execute : removed call to app/MyImage::setColor → KILLED |
img.setColor(new Color(r, g, b, a)); |
| 50 | ||
| 51 | } | |
| 52 | ||
| 53 | } | |
Mutations | ||
| 31 |
1.1 2.2 3.3 4.4 |
|
| 32 |
1.1 2.2 3.3 4.4 |
|
| 34 |
1.1 2.2 |
|
| 35 |
1.1 2.2 3.3 |
|
| 36 |
1.1 2.2 3.3 |
|
| 37 |
1.1 2.2 3.3 |
|
| 38 |
1.1 2.2 |
|
| 43 |
1.1 2.2 3.3 |
|
| 44 |
1.1 |
|
| 45 |
1.1 |
|
| 46 |
1.1 |
|
| 47 |
1.1 |
|
| 49 |
1.1 |


{% extends "base.html" %} {% block title %}Open Radar Search Results{% endblock %} {% block content %}
No matching results found.
{% endif %}Didn't find what you wanted? Try this Google Custom Search.
{% endblock %} {% block sidebar %} {% endblock %}


Beat The Black Friday Rush & Get 3 Echo Dot Smart Speakers For Just $65
For Black Friday, Amazon will be discounting the Echo Dot to just $25, but right now you can get it even cheaper. If you're willing to buy three of them.
You can get three Echo Dot smart speakers for $64.97 or $21.65 each, if you use the promo code DOT3PACK at checkout.
The Echo Dot is going to be a really great gift to pick up for someone this holiday season. It's going to be a great stocking stuffer and great for those Secret Santa gift exchanges that you do at work and other places. Now that it's under $22 though, it's a great time to buy it.
Advertisement
Echo Dot is Amazon's cheapest smart speaker with Alexa included. This is going to allow you to ask Alexa for things like the weather, the news, and much more. You can even control your smart home products by using your voice, with the Echo Dot. That's part of what makes the Echo Dot so amazing.
Of course, this is also a smart speaker. So you can ask Alexa to play music from a variety of streaming services. Spotify, Amazon Music Unlimited, Pandora, Audible and so much more.
There are currently tens of thousands of Alexa skills available, with more being added all of the time. Alexa Skills can be used to give Alexa even more capability. Like the ability to make your kids laugh with Laugh Box, or giving you the news from CNN or Fox News, and so much more.
Advertisement
Echo Dot comes in four colors: heather gray, sandstone, charcoal and plum. Only the sandstone and plum colors have a white top, the other two have a black top. In case that is important to you. But all four are wrapped in fabric, which helps to keep it clean and also keep the music sounding great.
You can pick up this three pack of the Echo Dot smart speakers from Amazon by clicking here.
Echo Dot (3-Pack) - Amazon - $64.97
Advertisement


TABLE TENNIS (INDIVIDUAL)
Contact: Mayank Singh
+918007827505
Entry Fee: Boys Rs.100
RULES :-
1. All standard ITTF rules applicable.
2. Best of five, wherein team winning 3 matches will win the match. (3 straight singles,2
reverse singles if required)
3. A team must comprise of 5 players (3 playing+2 extra).
4. No single entry is allowed. It is only a team event.
5. Serve should be proper not hiding the ball.
6. Each player serves twice, one after the other.
7. A game may be of 3 or 5 sets.
8. Each set consists of 11 points.
9. Bat is compulsory. Balls will be provided.
TABLE TENNIS (INDIVIDUAL)
Contact Raunak Ojha
+91800781060
Entry Fee: Girls Rs.100
RULES
1) single event
2)3 sets of 11 points ruk
Table Tennis (Individual)
1. There will be best of 3 sets of 11 point rally.
2. Semis & finals will be of 5 sets of 11 point rally
TABLE TENNIS (TEAM)
Contact: Mayank Singh
+918007827505
Raunak Ojha
+918007810605
Entry Fee: Boys Rs.300
RULES
1. Team consists of 3 playing players and 2 substitute players.
2.Order of the games will be 1st, 2nd, 3rd, 1st, 2nd.
3.Best of 3 games for initial matches and best of 5 games for Semi-Final and Final will be played.
4. Games will be of 11 point rally.
TABLE TENNIS (TEAM)
Contact: Mayank Singh
+918007827505
Raunak Ojha
+918007810605
Entry Fee: Girls Rs.200
RULES
Table Tennis (Team)
1. Team consists of 3 playing players and 2 substitute players.
2.Order of the games will be 1st, 2nd, 3rd, 1st, 2nd.
3.Best of 3 games for initial matches and best of 5 games for
Semi-Final and Final will be played.


It's creation something new, that can see and use thousands of people. Junior Web Developer with code in heart. Motto 'Do not stop learning!'.
New Era of web pages, with great features!
It's not mine..
Semantic HTML markup and efficent CSS
WEB's wheelhors
Makes site Live!


What you get
Online participation in laboratory exercises
Individual support from trainers
Opportunity for scholarship for free education
Interactive platform access and real-time training
Learning resources and homework check
Examinations and assessment
Participation in practical projects
Certificates and diplomas
Assistance in getting a job


Alaina will handle input, scraping the CHSCS Moodle homepage for the h1 tag (which designates the title of the cover news)
Josh will handle the algorithm, checking the content of the page against itself on a timer
Henry will handle the output, sending the user a message via Twilio if the page has updated


The socket namespace contains the core functionality of LuaSocket.
To obtain the socket namespace, run:
-- loads the socket module local socket = require("socket")
socket.headers.canonic
The socket.headers.canonic table is used by the HTTP and SMTP modules to translate from lowercase field names back into their canonic capitalization. When a lowercase field name exists as a key in this table, the associated value is substituted in whenever the field name is sent out.
You can obtain the headers namespace if case run-time modifications are required by running:
-- loads the headers module local headers = require("headers")
socket.bind(address, port [, backlog])
This function is a shortcut that creates and returns a TCP server object bound to a local address and port, ready to accept client connections. Optionally, user can also specify the backlog argument to the listen method (defaults to 32).
Note: The server object returned will have the option "reuseaddr" set to true.
socket.connect[46](address, port [, locaddr] [, locport] [, family])
This function is a shortcut that creates and returns a TCP client object connected to a remote address at a given port. Optionally, the user can also specify the local address and port to bind (locaddr and locport), or restrict the socket family to "inet" or "inet6". Without specifying family to connect, whether a tcp or tcp6 connection is created depends on your system configuration. Two variations of connect are defined as simple helper functions that restrict the family, socket.connect4 and socket.connect6.
socket._DEBUG
This constant is set to true if the library was compiled with debug support.
socket._DATAGRAMSIZE
Default datagram size used by calls to receive and receivefrom. (Unless changed in compile time, the value is 8192.)
socket.gettime()
Returns the UNIX time in seconds. You should subtract the values returned by this function to get meaningful values.
t = socket.gettime() -- do stuff print(socket.gettime() - t .. " seconds elapsed")
socket.newtry(finalizer)
Creates and returns a clean try function that allows for cleanup before the exception is raised.
Finalizer is a function that will be called before try throws the exception.
The function returns your customized try function.
Note: This idea saved a lot of work with the implementation of protocols in LuaSocket:
foo = socket.protect(function() -- connect somewhere local c = socket.try(socket.connect("somewhere", 42)) -- create a try function that closes 'c' on error local try = socket.newtry(function() c:close() end) -- do everything reassured c will be closed try(c:send("hello there?\r\n")) local answer = try(c:receive()) ... try(c:send("good bye\r\n")) c:close() end)
socket.protect(func)
Converts a function that throws exceptions into a safe function. This function only catches exceptions thrown by the try and newtry functions. It does not catch normal Lua errors.
Func is a function that calls try (or assert, or error) to throw exceptions.
Returns an equivalent function that instead of throwing exceptions in case of a failed try call, returns nil followed by an error message.
socket.select(recvt, sendt [, timeout])
Waits for a number of sockets to change status.
Recvt is an array with the sockets to test for characters available for reading. Sockets in the sendt array are watched to see if it is OK to immediately write on them. Timeout is the maximum amount of time (in seconds) to wait for a change in status. A nil, negative or omitted timeout value allows the function to block indefinitely. Recvt and sendt can also be empty tables or nil. Non-socket values (or values with non-numeric indices) in the arrays will be silently ignored.
The function returns a list with the sockets ready for reading, a list with the sockets ready for writing and an error message. The error message is "timeout" if a timeout condition was met, "select failed" if the call to select failed, and nil otherwise. The returned tables are doubly keyed both by integers and also by the sockets themselves, to simplify the test if a specific socket has changed status.
Note: select can monitor a limited number of sockets, as defined by the constant socket._SETSIZE. This number may be as high as 1024 or as low as 64 by default, depending on the system. It is usually possible to change this at compile time. Invoking select with a larger number of sockets will raise an error.
Important note: a known bug in WinSock causes select to fail on non-blocking TCP sockets. The function may return a socket as writable even though the socket is not ready for sending.
Another important note: calling select with a server socket in the receive parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever.
Yet another note: If you close a socket and pass it to select, it will be ignored.
Using select with non-socket objects: Any object that implements getfd and dirty can be used with select, allowing objects from other libraries to be used within a socket.select driven loop.
socket._SETSIZE
The maximum number of sockets that the select function can handle.
socket.sink(mode, socket)
Creates an LTN12 sink from a stream socket object.
Mode defines the behavior of the sink. The following options are available:
Socket is the stream socket object used to send the data.
The function returns a sink with the appropriate behavior.
socket.skip(d [, ret1, ret2 ... retN])
Drops a number of arguments and returns the remaining.
D is the number of arguments to drop. Ret1 to retN are the arguments.
The function returns retd+1 to retN.
Note: This function is useful to avoid creation of dummy variables:
-- get the status code and separator from SMTP server reply local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
socket.sleep(time)
Freezes the program execution during a given amount of time.
Time is the number of seconds to sleep for. If time is negative, the function returns immediately.
socket.source(mode, socket [, length])
Creates an LTN12 source from a stream socket object.
Mode defines the behavior of the source. The following options are available:
Socket is the stream socket object used to receive the data.
The function returns a source with the appropriate behavior.
socket._SOCKETINVALID
The OS value for an invalid socket.
socket.try(ret1 [, ret2 ... retN])
Throws an exception in case ret1 is falsy, using ret2 as the error message. The exception is supposed to be caught by a protected function only.
Ret1 to retN can be arbitrary arguments, but are usually the return values of a function call nested with try.
The function returns ret1 to retN if ret1 is not nil or false. Otherwise, it calls error passing ret2 wrapped in a table with metatable used by protect to distinguish exceptions from runtime errors.
-- connects or throws an exception with the appropriate error message c = socket.try(socket.connect("localhost", 80))
socket._VERSION
This constant has a string describing the current LuaSocket version.


My 3.5 gram shroom trip.
This would be my 5th time dosing up on shrooms, and the highest dose yet. Prior to this I did 2.6 grams.  I still have not experienced significant visual effects, but everything in my vision always sort of dances around, looking very amusing.
There were 4 of us. Myself, my good friend J, his girlfriend K and her friend M. K and M would be dosing for their first times, luckily we were smart about this and only gave them a half eighth each. A little background. First of all, J and K have only been together for a short while, actually not even considering themselves together yet.
I learned a lot about myself and these other 3 people that night. We all ate our shrooms in peanut butter sandwiches, and washed them down with orange juice, at about 11:00 pm. at 11:45 or so we left the house, to go for a walk in the nearby woods, on a little dirt trail that leads around to a city park we could hang out at. By this time we were all definitely coming up, and we found ourselves confused and scared in these woods, but finally made our way to the park. Its not a long walk, probably 5-10 minutes. We got to the park, and I bought myself a dr. pepper and we got on the swings for a while. The dr pepper felt awesome to drink.
I'm going to guess we hung out at the park for an hour. But now that I think about it, that would mean about an hour and a half would be lost, so I don't know. By this time my eyes are wide open, things are beginning to morph a little bit in my vision, and we all have a good case of the giggles. I thought that I had reached the peak, but I was wrong. We saw some cars driving into the parking lot, so we left quickly, back into the woods.
We went in a new direction up onto a hill, where we found a wood platform thing for exersising, I guess for doing situps at an incline or something. Anways I was the first to lay down on this thing. The sky was beautiful. The stars seemed to be shining and twinkling brighter and more beautifully than I could ever imagine, and the half moon was an awesome complement to them. I layed there on that thing for at least another hour. I didn't want to go. It was so beautiful. I stared up to the stars and was, in my head, not visually, sort of transported to another world, revolving around that star, looking back at our sun.
I really began thinking about myself and my life. Unlike how I always thought shrooms would make me think, I was actually really positive. For once I was really happy with myself and my life, and I became very confident and lost all fear of anything.  What are they gonna do?' I felt so grateful to be here looking at the sky at this time.   I could have stayed there all night, but my friends were ready to head back, so on we went.
This, I feel, was the peak, and I couldn't be happier about it. There wasn't a place in the world I'd rather be then right there, on that sit up thing, looking at the sky.
During the walk home, we all sort of concluded that the peak had ended. M is still being herself. More and more I realize who she is, and more and more I do not like her. She really gave us all a bad vibe.
We got back to my house at about 3 am apparently. We went to my room to smoke some weed. Once I got inside I realized my trip was still going strong. Things leaned in a really negative direction from this point on. We talked for a while, but I began to get really quiet and just thought a lot. At one point I looked up and saw these other 3 people as what they really are: just animals. Suddenly they all became very alien looking and I couldn't understand why these 3 other animals had gathered in my room with me to make sounds with our mouths. I had to look away, for some reason looking at these alien creatures disgusted me, even though visually they looked completely normal. I snapped myself out of this quickly, but it sort of made me wonder why I had never seen people that way before. It was like I was seeing a human being for the first time. Very weird and sort of disturbing.
We smoked out of my bong. J decided to pack a huge bud, probably about a gram, into the bowl. It was overflowing, and we all were cracking up. He hit the bong like you would hit a giant pipe, he kept puffing it quickly to get the large ammount of pot in the bowl cherried. He got about half of the bowl down, with the chamber of the bong filled with tons of thick white smoke, then passed it to K to clear. She took as big a hit as she could, but only got probably less than 1/3 of the smoke.
She then started coughing really really bad, for about 10 minutes. None of us were expecting this and J felt very bad. She was starting to freak out. She said she needed air, so she went outside, and then didn't come back. This put some extreme stress on all of us. It was 4 in the morning, we were all on mushrooms, and this girl had ran off into the night.  We went outside to smoke a cigarette, and look for her, as casually as possible.
J found her on the ground out by her car. He picked her up and carried her inside. We got her some water and made her comfortable but she continued to hyperventilate for a good ammount of time. A lot of stress had been lifted. J and I were very sure she was fine, just freaking out, but she insisted she needed to breath like that or she was going to die. Finally we got into a conversation and she joined it, and after a minute or so she realized she had stopped hyperventilating, and sort of laughed that she really thought she was about to die from lack of oxygen.
After this, the night quickly winded down. We were all glad the ordeal had come to an end. Its funny how on mushrooms, simple situations seem so complex. Every little word or facial expression or anything can mean anything. J and I were discussing this, how shrooms make communication so difficult. Its funny. I remember at one point he asked me to roll him a cigarette, and I paused for a minute then said alright.  I guess I said 'alright' in a tone that sounded like 'yeah fine whatever', so he was bummed about that, and I was trying to figure out what I said wrong.  And that was that, even though my mind continued to analize what had just happened for a while afterwards.
I began to feel really bad. I remember at one point my mindset went all negative, everything in my vision seemed to melt away, and I couldn't respond to anyone asking questions.  I felt like everything I had come to believe about myself and my life, particulary during the peak when I was watching the stars, was all wrong. I felt insecure and wanted to cry. Luckily I reminded myself how rediculous the situation was. J forgot about it before I did, and the night went on. I just kept over-analizing everything I said, and everything anyone else said. We didn't get to sleep till 7 am, except M who fell asleep earlier.
The comedown was very introspective.  K insisted that J had saved her life. I could see a definite new thing going on between them. In my shroomed state of mind I was very happy for them, I could tell that this would be a very strong foundation for a relationship, and that things were (now) going very well for them. I feel like I stepped over some mental boundaries and really learned something about myself.
Its really funny how beautiful life is. There is so much good to be found, but these people that control us. They don't want us to have fun.  Stuff that has been here long before any government was. The mushroom is a teacher. Its such a beautiful part of life. Why aren't we allowed to appreciate life anymore? These days life isn't enough. Money, beauty, money, popularity, and money make everything in today's world. People don't understand that you never own anything.  Everything belongs to mother earth. I understand that you need money to live. I just wish it didn't have to be that way. These are the things the mushrooms showed me last night, under the clear starry sky.
Take a minute at night before you go to bed, and go outside and look at the stars. Maybe they will remind you too how beautiful life is.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Postfix is Wietse
Venema's attempt to provide an alternative to the widely-used
Sendmail program. Sendmail is responsible for most of the e-mail
delivered on the Internet. With an estimated 100 million users, that's billions
of messages daily. A stunning number.
Postfix attempts to be fast, easy to administer, and secure, while at
the same time being sendmail compatible enough to not upset existing users.


This part of the book contains four
chapters of introductory material. Chapter
1, introduces the concepts of data structures and
algorithms and presents reasons for using them. It also
presents a few topics in software engineering that are
applied throughout the rest of the book. Chapter
2, presents a number of topics on pointers. Pointers
appear a great deal in this book, so this chapter serves as
a refresher on the subject. Chapter
3, presents recursion, a popular technique used with
many data structures and algorithms. Chapter
4, describes how to analyze algorithms. The techniques
in this chapter are used to analyze algorithms throughout
the book.


PERLXSTUT
Section: Perl Programmers Reference Guide (1)Updated: 2009-04-22
Index Return to Main Contents
NAME
perlXStut - Tutorial for writing XSUBsDESCRIPTION
This tutorial will educate the reader on the steps involved in creating a Perl extension. The reader is assumed to have access to perlguts, perlapi and perlxs.This tutorial starts with very simple examples and becomes more complex, with each new example adding new features. Certain concepts may not be completely explained until later in the tutorial in order to slowly ease the reader into building extensions.
This tutorial was written from a Unix point of view. Where I know them to be otherwise different for other platforms (e.g. Win32), I will list them. If you find something that was missed, please let me know.
SPECIAL NOTES
make
This tutorial assumes that the make program that Perl is configured to use is called "make". Instead of running ``make'' in the examples that follow, you may have to substitute whatever make program Perl has been configured to use. Running perl -V:make should tell you what it is.Version caveat
When writing a Perl extension for general consumption, one should expect that the extension will be used with versions of Perl different from the version available on your machine. Since you are reading this document, the version of Perl on your machine is probably 5.005 or later, but the users of your extension may have more ancient versions.To understand what kinds of incompatibilities one may expect, and in the rare case that the version of Perl on your machine is older than this document, see the section on ``Troubleshooting these Examples'' for more information.
If your extension uses some features of Perl which are not available on older releases of Perl, your users would appreciate an early meaningful warning. You would probably put this information into the README file, but nowadays installation of extensions may be performed automatically, guided by CPAN.pm module or other tools.
In MakeMaker-based installations, Makefile.PL provides the earliest opportunity to perform version checks. One can put something like this in Makefile.PL for this purpose:
eval { require 5.007 } or die <<EOD; ############ ### This module uses frobnication framework which is not available before ### version 5.007 of Perl. Upgrade your Perl before installing Kara::Mba. ############ EOD
Dynamic Loading versus Static Loading
It is commonly thought that if a system does not have the capability to dynamically load a library, you cannot build XSUBs. This is incorrect. You can build them, but you must link the XSUBs subroutines with the rest of Perl, creating a new executable. This situation is similar to Perl 4.This tutorial can still be used on such a system. The XSUB build mechanism will check the system and build a dynamically-loadable library if possible, or else a static library and then, optionally, a new statically-linked executable with that static library linked in.
Should you wish to build a statically-linked executable on a system which can dynamically load libraries, you may, in all the following examples, where the command ""make"`` with no arguments is executed, run the command ''"make perl"" instead.
If you have generated such a statically-linked executable by choice, then instead of saying ""make test"``, you should say ''"make test_static"``. On systems that cannot build dynamically-loadable libraries at all, simply saying ''"make test"" is sufficient.
TUTORIAL
Now let's go on with the show!EXAMPLE 1
Our first extension will be very simple. When we call the routine in the extension, it will print out a well-known message and return.Run ""h2xs -A -n Mytest"". This creates a directory named Mytest, possibly under ext/ if that directory exists in the current working directory. Several files will be created under the Mytest dir, including MANIFEST, Makefile.PL, lib/Mytest.pm, Mytest.xs, t/Mytest.t, and Changes.
The MANIFEST file contains the names of all the files just created in the Mytest directory.
The file Makefile.PL should look something like this:
use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( NAME => 'Mytest', VERSION_FROM => 'Mytest.pm', # finds $VERSION LIBS => [''], # e.g., '-lm' DEFINE => '', # e.g., '-DHAVE_SOMETHING' INC => '', # e.g., '-I/usr/include/other' );
The file Mytest.pm should start with something like this:
package Mytest; use 5.008008; use strict; use warnings; require Exporter; our @ISA = qw(Exporter); our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.01'; require XSLoader; XSLoader::load('Mytest', $VERSION); # Preloaded methods go here. 1; __END__ # Below is the stub of documentation for your module. You better edit it!
The rest of the .pm file contains sample code for providing documentation for the extension.
Finally, the Mytest.xs file should look something like this:
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" MODULE = Mytest PACKAGE = Mytest
Let's edit the .xs file by adding this to the end of the file:
void hello() CODE: printf("Hello, world!\n");
It is okay for the lines starting at the ``CODE:'' line to not be indented. However, for readability purposes, it is suggested that you indent CODE: one level and the lines following one more level.
Now we'll run ""perl Makefile.PL"". This will create a real Makefile, which make needs. Its output looks something like:
% perl Makefile.PL Checking if your kit is complete... Looks good Writing Makefile for Mytest %
Now, running make will produce output that looks something like this (some long lines have been shortened for clarity and some extraneous lines have been deleted):
% make cp lib/Mytest.pm blib/lib/Mytest.pm perl xsubpp -typemap typemap Mytest.xs > Mytest.xsc && mv Mytest.xsc Mytest.c Please specify prototyping behavior for Mytest.xs (see perlxs manual) cc -c Mytest.c Running Mkbootstrap for Mytest () chmod 644 Mytest.bs rm -f blib/arch/auto/Mytest/Mytest.so cc -shared -L/usr/local/lib Mytest.o -o blib/arch/auto/Mytest/Mytest.so \ \ chmod 755 blib/arch/auto/Mytest/Mytest.so cp Mytest.bs blib/arch/auto/Mytest/Mytest.bs chmod 644 blib/arch/auto/Mytest/Mytest.bs Manifying blib/man3/Mytest.3pm %
You can safely ignore the line about ``prototyping behavior'' - it is explained in ``The PROTOTYPES: Keyword'' in perlxs.
If you are on a Win32 system, and the build process fails with linker errors for functions in the C library, check if your Perl is configured to use PerlCRT (running perl -V:libc should show you if this is the case). If Perl is configured to use PerlCRT, you have to make sure PerlCRT.lib is copied to the same location that msvcrt.lib lives in, so that the compiler can find it on its own. msvcrt.lib is usually found in the Visual C compiler's lib directory (e.g. C:/DevStudio/VC/lib).
Perl has its own special way of easily writing test scripts, but for this example only, we'll create our own test script. Create a file called hello that looks like this:
#! /opt/perl5/bin/perl use ExtUtils::testlib; use Mytest; Mytest::hello();
Now we make the script executable ("chmod +x hello"), run the script and we should see the following output:
% ./hello Hello, world! %
EXAMPLE 2
Now let's add to our extension a subroutine that will take a single numeric argument as input and return 0 if the number is even or 1 if the number is odd.Add the following to the end of Mytest.xs:
int is_even(input) int input CODE: RETVAL = (input % 2 == 0); OUTPUT: RETVAL
There does not need to be whitespace at the start of the ""int input"`` line, but it is useful for improving readability. Placing a semi-colon at the end of that line is also optional. Any amount and kind of whitespace may be placed between the ''"int"`` and ''"input"".
Now re-run make to rebuild our new shared library.
Now perform the same steps as before, generating a Makefile from the Makefile.PL file, and running make.
In order to test that our extension works, we now need to look at the file Mytest.t. This file is set up to imitate the same kind of testing structure that Perl itself has. Within the test script, you perform a number of tests to confirm the behavior of the extension, printing ``ok'' when the test is correct, ``not ok'' when it is not.
use Test::More tests => 4; BEGIN { use_ok('Mytest') }; ######################### # Insert your test code below, the Test::More module is use()ed here so read # its man page ( perldoc Test::More ) for help writing this test script. is(&Mytest::is_even(0), 1); is(&Mytest::is_even(1), 0); is(&Mytest::is_even(2), 1);
We will be calling the test script through the command ""make test"". You should see output that looks something like this:
%make test PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/Mytest....ok All tests successful. Files=1, Tests=4, 0 wallclock secs ( 0.03 cusr + 0.00 csys = 0.03 CPU) %
What has gone on?
The program h2xs is the starting point for creating extensions. In later examples we'll see how we can use h2xs to read header files and generate templates to connect to C routines.h2xs creates a number of files in the extension directory. The file Makefile.PL is a perl script which will generate a true Makefile to build the extension. We'll take a closer look at it later.
The .pm and .xs files contain the meat of the extension. The .xs file holds the C routines that make up the extension. The .pm file contains routines that tell Perl how to load your extension.
Generating the Makefile and running "make" created a directory called blib (which stands for ``build library'') in the current working directory. This directory will contain the shared library that we will build. Once we have tested it, we can install it into its final location.
Invoking the test script via ""make test"" did something very important. It invoked perl with all those "-I" arguments so that it could find the various files that are part of the extension. It is very important that while you are still testing extensions that you use ""make test"``. If you try to run the test script all by itself, you will get a fatal error. Another reason it is important to use ''"make test"`` to run your test script is that if you are testing an upgrade to an already-existing version, using ''"make test"" ensures that you will test your new extension, not the already-existing version.
When Perl sees a "use extension;", it searches for a file with the same name as the "use"'d extension that has a .pm suffix. If that file cannot be found, Perl dies with a fatal error. The default search path is contained in the @INC array.
In our case, Mytest.pm tells perl that it will need the Exporter and Dynamic Loader extensions. It then sets the @ISA and @EXPORT arrays and the $VERSION scalar; finally it tells perl to bootstrap the module. Perl will call its dynamic loader routine (if there is one) and load the shared library.
The two arrays @ISA and @EXPORT are very important. The @ISA array contains a list of other packages in which to search for methods (or subroutines) that do not exist in the current package. This is usually only important for object-oriented extensions (which we will talk about much later), and so usually doesn't need to be modified.
The @EXPORT array tells Perl which of the extension's variables and subroutines should be placed into the calling package's namespace. Because you don't know if the user has already used your variable and subroutine names, it's vitally important to carefully select what to export. Do not export method or variable names by default without a good reason.
As a general rule, if the module is trying to be object-oriented then don't export anything. If it's just a collection of functions and variables, then you can export them via another array, called @EXPORT_OK. This array does not automatically place its subroutine and variable names into the namespace unless the user specifically requests that this be done.
See perlmod for more information.
The $VERSION variable is used to ensure that the .pm file and the shared library are ``in sync'' with each other. Any time you make changes to the .pm or .xs files, you should increment the value of this variable.
Writing good test scripts
The importance of writing good test scripts cannot be over-emphasized. You should closely follow the ``ok/not ok'' style that Perl itself uses, so that it is very easy and unambiguous to determine the outcome of each test case. When you find and fix a bug, make sure you add a test case for it.By running ""make test"``, you ensure that your Mytest.t script runs and uses the correct version of your extension. If you have many test cases, save your test files in the ''t`` directory and use the suffix ''.t``. When you run ''"make test"", all of these test files will be executed.
EXAMPLE 3
Our third extension will take one argument as its input, round off that value, and set the argument to the rounded value.Add the following to the end of Mytest.xs:
void round(arg) double arg CODE: if (arg > 0.0) { arg = floor(arg + 0.5); } else if (arg < 0.0) { arg = ceil(arg - 0.5); } else { arg = 0.0; } OUTPUT: arg
Edit the Makefile.PL file so that the corresponding line looks like this:
'LIBS' => ['-lm'], # e.g., '-lm'
Generate the Makefile and run make. Change the test number in Mytest.t to ``9'' and add the following tests:
$i = -1.5; &Mytest::round($i); is( $i, -2.0 ); $i = -1.1; &Mytest::round($i); is( $i, -1.0 ); $i = 0.0; &Mytest::round($i); is( $i, 0.0 ); $i = 0.5; &Mytest::round($i); is( $i, 1.0 ); $i = 1.2; &Mytest::round($i); is( $i, 1.0 );
Running ""make test"" should now print out that all nine tests are okay.
Notice that in these new test cases, the argument passed to round was a scalar variable. You might be wondering if you can round a constant or literal. To see what happens, temporarily add the following line to Mytest.t:
&Mytest::round(3);
Run ""make test"" and notice that Perl dies with a fatal error. Perl won't let you change the value of constants!
What's new here?
- *
- We've made some changes to Makefile.PL. In this case, we've specified an extra library to be linked into the extension's shared library, the math library libm in this case. We'll talk later about how to write XSUBs that can call every routine in a library.
- *
- The value of the function is not being passed back as the function's return value, but by changing the value of the variable that was passed into the function. You might have guessed that when you saw that the return value of round is of type ``void''.
Input and Output Parameters
You specify the parameters that will be passed into the XSUB on the line(s) after you declare the function's return value and name. Each input parameter line starts with optional whitespace, and may have an optional terminating semicolon.The list of output parameters occurs at the very end of the function, just after the OUTPUT: directive. The use of RETVAL tells Perl that you wish to send this value back as the return value of the XSUB function. In Example 3, we wanted the ``return value'' placed in the original variable which we passed in, so we listed it (and not RETVAL) in the OUTPUT: section.
The XSUBPP Program
The xsubpp program takes the XS code in the .xs file and translates it into C code, placing it in a file whose suffix is .c. The C code created makes heavy use of the C functions within Perl.The TYPEMAP file
The xsubpp program uses rules to convert from Perl's data types (scalar, array, etc.) to C's data types (int, char, etc.). These rules are stored in the typemap file ($PERLLIB/ExtUtils/typemap). This file is split into three parts.The first section maps various C data types to a name, which corresponds somewhat with the various Perl types. The second section contains C code which xsubpp uses to handle input parameters. The third section contains C code which xsubpp uses to handle output parameters.
Let's take a look at a portion of the .c file created for our extension. The file name is Mytest.c:
XS(XS_Mytest_round) { dXSARGS; if (items != 1) Perl_croak(aTHX_ "Usage: Mytest::round(arg)"); PERL_UNUSED_VAR(cv); /* -W */ { double arg = (double)SvNV(ST(0)); /* XXXXX */ if (arg > 0.0) { arg = floor(arg + 0.5); } else if (arg < 0.0) { arg = ceil(arg - 0.5); } else { arg = 0.0; } sv_setnv(ST(0), (double)arg); /* XXXXX */ SvSETMAGIC(ST(0)); } XSRETURN_EMPTY; }
Notice the two lines commented with ``XXXXX''. If you check the first section of the typemap file, you'll see that doubles are of type T_DOUBLE. In the INPUT section, an argument that is T_DOUBLE is assigned to the variable arg by calling the routine SvNV on something, then casting it to double, then assigned to the variable arg. Similarly, in the OUTPUT section, once arg has its final value, it is passed to the sv_setnv function to be passed back to the calling subroutine. These two functions are explained in perlguts; we'll talk more later about what that ``ST(0)'' means in the section on the argument stack.
Warning about Output Arguments
In general, it's not a good idea to write extensions that modify their input parameters, as in Example 3. Instead, you should probably return multiple values in an array and let the caller handle them (we'll do this in a later example). However, in order to better accommodate calling pre-existing C routines, which often do modify their input parameters, this behavior is tolerated.EXAMPLE 4
In this example, we'll now begin to write XSUBs that will interact with pre-defined C libraries. To begin with, we will build a small library of our own, then let h2xs write our .pm and .xs files for us.Create a new directory called Mytest2 at the same level as the directory Mytest. In the Mytest2 directory, create another directory called mylib, and cd into that directory.
Here we'll create some files that will generate a test library. These will include a C source file and a header file. We'll also create a Makefile.PL in this directory. Then we'll make sure that running make at the Mytest2 level will automatically run this Makefile.PL file and the resulting Makefile.
In the mylib directory, create a file mylib.h that looks like this:
#define TESTVAL 4 extern double foo(int, long, const char*);
Also create a file mylib.c that looks like this:
#include <stdlib.h> #include "./mylib.h" double foo(int a, long b, const char *c) { return (a + b + atof(c) + TESTVAL); }
And finally create a file Makefile.PL that looks like this:
use ExtUtils::MakeMaker; $Verbose = 1; WriteMakefile( NAME => 'Mytest2::mylib', SKIP => [qw(all static static_lib dynamic dynamic_lib)], clean => {'FILES' => 'libmylib$(LIB_EXT)'}, ); sub MY::top_targets { ' all :: static pure_all :: static static :: libmylib$(LIB_EXT) libmylib$(LIB_EXT): $(O_FILES) $(AR) cr libmylib$(LIB_EXT) $(O_FILES) $(RANLIB) libmylib$(LIB_EXT) '; }
Make sure you use a tab and not spaces on the lines beginning with ``$(AR)'' and ``$(RANLIB)''. Make will not function properly if you use spaces. It has also been reported that the ``cr'' argument to $(AR) is unnecessary on Win32 systems.
We will now create the main top-level Mytest2 files. Change to the directory above Mytest2 and run the following command:
% h2xs -O -n Mytest2 ./Mytest2/mylib/mylib.h
This will print out a warning about overwriting Mytest2, but that's okay. Our files are stored in Mytest2/mylib, and will be untouched.
The normal Makefile.PL that h2xs generates doesn't know about the mylib directory. We need to tell it that there is a subdirectory and that we will be generating a library in it. Let's add the argument MYEXTLIB to the WriteMakefile call so that it looks like this:
WriteMakefile( 'NAME' => 'Mytest2', 'VERSION_FROM' => 'Mytest2.pm', # finds $VERSION 'LIBS' => [''], # e.g., '-lm' 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' 'INC' => '', # e.g., '-I/usr/include/other' 'MYEXTLIB' => 'mylib/libmylib$(LIB_EXT)', );
and then at the end add a subroutine (which will override the pre-existing subroutine). Remember to use a tab character to indent the line beginning with ``cd''!
sub MY::postamble { ' $(MYEXTLIB): mylib/Makefile cd mylib && $(MAKE) $(PASSTHRU) '; }
Let's also fix the MANIFEST file so that it accurately reflects the contents of our extension. The single line that says ``mylib'' should be replaced by the following three lines:
mylib/Makefile.PL mylib/mylib.c mylib/mylib.h
To keep our namespace nice and unpolluted, edit the .pm file and change the variable @EXPORT to @EXPORT_OK. Finally, in the .xs file, edit the #include line to read:
#include "mylib/mylib.h"
And also add the following function definition to the end of the .xs file:
double foo(a,b,c) int a long b const char * c OUTPUT: RETVAL
Now we also need to create a typemap file because the default Perl doesn't currently support the const char * type. Create a file called typemap in the Mytest2 directory and place the following in it:
const char * T_PV
Now run perl on the top-level Makefile.PL. Notice that it also created a Makefile in the mylib directory. Run make and watch that it does cd into the mylib directory and run make in there as well.
Now edit the Mytest2.t script and change the number of tests to ``4'', and add the following lines to the end of the script:
is( &Mytest2::foo(1, 2, "Hello, world!"), 7 ); is( &Mytest2::foo(1, 2, "0.0"), 7 ); ok( abs(&Mytest2::foo(0, 0, "-3.4") - 0.6) <= 0.01 );
(When dealing with floating-point comparisons, it is best to not check for equality, but rather that the difference between the expected and actual result is below a certain amount (called epsilon) which is 0.01 in this case)
Run ""make test"" and all should be well. There are some warnings on missing tests for the Mytest2::mylib extension, but you can ignore them.
What has happened here?
Unlike previous examples, we've now run h2xs on a real include file. This has caused some extra goodies to appear in both the .pm and .xs files.- *
- In the .xs file, there's now a #include directive with the absolute path to the mylib.h header file. We changed this to a relative path so that we could move the extension directory if we wanted to.
- *
- There's now some new C code that's been added to the .xs file. The purpose of the "constant" routine is to make the values that are #define'd in the header file accessible by the Perl script (by calling either "TESTVAL" or &Mytest2::TESTVAL). There's also some XS code to allow calls to the "constant" routine.
- *
- The .pm file originally exported the name "TESTVAL" in the @EXPORT array. This could lead to name clashes. A good rule of thumb is that if the #define is only going to be used by the C routines themselves, and not by the user, they should be removed from the @EXPORT array. Alternately, if you don't mind using the ``fully qualified name'' of a variable, you could move most or all of the items from the @EXPORT array into the @EXPORT_OK array.
- *
- If our include file had contained #include directives, these would not have been processed by h2xs. There is no good solution to this right now.
- *
- We've also told Perl about the library that we built in the mylib subdirectory. That required only the addition of the "MYEXTLIB" variable to the WriteMakefile call and the replacement of the postamble subroutine to cd into the subdirectory and run make. The Makefile.PL for the library is a bit more complicated, but not excessively so. Again we replaced the postamble subroutine to insert our own code. This code simply specified that the library to be created here was a static archive library (as opposed to a dynamically loadable library) and provided the commands to build it.
Anatomy of .xs file
The .xs file of ``EXAMPLE 4'' contained some new elements. To understand the meaning of these elements, pay attention to the line which reads
MODULE = Mytest2 PACKAGE = Mytest2
Anything before this line is plain C code which describes which headers to include, and defines some convenience functions. No translations are performed on this part, apart from having embedded POD documentation skipped over (see perlpod) it goes into the generated output C file as is.
Anything after this line is the description of XSUB functions. These descriptions are translated by xsubpp into C code which implements these functions using Perl calling conventions, and which makes these functions visible from Perl interpreter.
Pay a special attention to the function "constant". This name appears twice in the generated .xs file: once in the first part, as a static C function, then another time in the second part, when an XSUB interface to this static C function is defined.
This is quite typical for .xs files: usually the .xs file provides an interface to an existing C function. Then this C function is defined somewhere (either in an external library, or in the first part of .xs file), and a Perl interface to this function (i.e. ``Perl glue'') is described in the second part of .xs file. The situation in ``EXAMPLE 1'', ``EXAMPLE 2'', and ``EXAMPLE 3'', when all the work is done inside the ``Perl glue'', is somewhat of an exception rather than the rule.
Getting the fat out of XSUBs
In ``EXAMPLE 4'' the second part of .xs file contained the following description of an XSUB:
double foo(a,b,c) int a long b const char * c OUTPUT: RETVAL
Note that in contrast with ``EXAMPLE 1'', ``EXAMPLE 2'' and ``EXAMPLE 3'', this description does not contain the actual code for what is done is done during a call to Perl function foo(). To understand what is going on here, one can add a CODE section to this XSUB:
double foo(a,b,c) int a long b const char * c CODE: RETVAL = foo(a,b,c); OUTPUT: RETVAL
However, these two XSUBs provide almost identical generated C code: xsubpp compiler is smart enough to figure out the "CODE:" section from the first two lines of the description of XSUB. What about "OUTPUT:" section? In fact, that is absolutely the same! The "OUTPUT:" section can be removed as well, as far as "CODE:" section or "PPCODE:" section is not specified: xsubpp can see that it needs to generate a function call section, and will autogenerate the OUTPUT section too. Thus one can shortcut the XSUB to become:
double foo(a,b,c) int a long b const char * c
Can we do the same with an XSUB
int is_even(input) int input CODE: RETVAL = (input % 2 == 0); OUTPUT: RETVAL
of ``EXAMPLE 2''? To do this, one needs to define a C function "int is_even(int input)". As we saw in ``Anatomy of .xs file'', a proper place for this definition is in the first part of .xs file. In fact a C function
int is_even(int arg) { return (arg % 2 == 0); }
is probably overkill for this. Something as simple as a "#define" will do too:
#define is_even(arg) ((arg) % 2 == 0)
After having this in the first part of .xs file, the ``Perl glue'' part becomes as simple as
int is_even(input) int input
This technique of separation of the glue part from the workhorse part has obvious tradeoffs: if you want to change a Perl interface, you need to change two places in your code. However, it removes a lot of clutter, and makes the workhorse part independent from idiosyncrasies of Perl calling convention. (In fact, there is nothing Perl-specific in the above description, a different version of xsubpp might have translated this to TCL glue or Python glue as well.)
More about XSUB arguments
With the completion of Example 4, we now have an easy way to simulate some real-life libraries whose interfaces may not be the cleanest in the world. We shall now continue with a discussion of the arguments passed to the xsubpp compiler.When you specify arguments to routines in the .xs file, you are really passing three pieces of information for each argument listed. The first piece is the order of that argument relative to the others (first, second, etc). The second is the type of argument, and consists of the type declaration of the argument (e.g., int, char*, etc). The third piece is the calling convention for the argument in the call to the library function.
While Perl passes arguments to functions by reference, C passes arguments by value; to implement a C function which modifies data of one of the ``arguments'', the actual argument of this C function would be a pointer to the data. Thus two C functions with declarations
int string_length(char *s); int upper_case_char(char *cp);
may have completely different semantics: the first one may inspect an array of chars pointed by s, and the second one may immediately dereference "cp" and manipulate *cp only (using the return value as, say, a success indicator). From Perl one would use these functions in a completely different manner.
One conveys this info to xsubpp by replacing "*" before the argument by "&". "&" means that the argument should be passed to a library function by its address. The above two function may be XSUB-ified as
int string_length(s) char * s int upper_case_char(cp) char &cp
For example, consider:
int foo(a,b) char &a char * b
The first Perl argument to this function would be treated as a char and assigned to the variable a, and its address would be passed into the function foo. The second Perl argument would be treated as a string pointer and assigned to the variable b. The value of b would be passed into the function foo. The actual call to the function foo that xsubpp generates would look like this:
foo(&a, b);
xsubpp will parse the following function argument lists identically:
char &a char&a char & a
However, to help ease understanding, it is suggested that you place a ``&'' next to the variable name and away from the variable type), and place a ``*'' near the variable type, but away from the variable name (as in the call to foo above). By doing so, it is easy to understand exactly what will be passed to the C function --- it will be whatever is in the ``last column''.
You should take great pains to try to pass the function the type of variable it wants, when possible. It will save you a lot of trouble in the long run.
The Argument Stack
If we look at any of the C code generated by any of the examples except example 1, you will notice a number of references to ST(n), where n is usually 0. ``ST'' is actually a macro that points to the n'th argument on the argument stack. ST(0) is thus the first argument on the stack and therefore the first argument passed to the XSUB, ST(1) is the second argument, and so on.When you list the arguments to the XSUB in the .xs file, that tells xsubpp which argument corresponds to which of the argument stack (i.e., the first one listed is the first argument, and so on). You invite disaster if you do not list them in the same order as the function expects them.
The actual values on the argument stack are pointers to the values passed in. When an argument is listed as being an OUTPUT value, its corresponding value on the stack (i.e., ST(0) if it was the first argument) is changed. You can verify this by looking at the C code generated for Example 3. The code for the round() XSUB routine contains lines that look like this:
double arg = (double)SvNV(ST(0)); /* Round the contents of the variable arg */ sv_setnv(ST(0), (double)arg);
The arg variable is initially set by taking the value from ST(0), then is stored back into ST(0) at the end of the routine.
XSUBs are also allowed to return lists, not just scalars. This must be done by manipulating stack values ST(0), ST(1), etc, in a subtly different way. See perlxs for details.
XSUBs are also allowed to avoid automatic conversion of Perl function arguments to C function arguments. See perlxs for details. Some people prefer manual conversion by inspecting ST(i) even in the cases when automatic conversion will do, arguing that this makes the logic of an XSUB call clearer.
While experts may argue about these idioms, a novice to Perl guts may prefer a way which is as little Perl-guts-specific as possible, meaning automatic conversion and automatic call generation, as in ``Getting the fat out of XSUBs''. This approach has the additional benefit of protecting the XSUB writer from future changes to the Perl API.
Extending your Extension
Sometimes you might want to provide some extra methods or subroutines to assist in making the interface between Perl and your extension simpler or easier to understand. These routines should live in the .pm file. Whether they are automatically loaded when the extension itself is loaded or only loaded when called depends on where in the .pm file the subroutine definition is placed. You can also consult AutoLoader for an alternate way to store and load your extra subroutines.Documenting your Extension
There is absolutely no excuse for not documenting your extension. Documentation belongs in the .pm file. This file will be fed to pod2man, and the embedded documentation will be converted to the manpage format, then placed in the blib directory. It will be copied to Perl's manpage directory when the extension is installed.You may intersperse documentation and Perl code within the .pm file. In fact, if you want to use method autoloading, you must do this, as the comment inside the .pm file explains.
See perlpod for more information about the pod format.
 You will either need to have write permission into the directories where Perl is installed, or ask your system administrator to run the make for you.Alternately, you can specify the exact directory to place the extension's files by placing a ``PREFIX=/destination/directory'' after the make install. (or in between the make and install if you have a brain-dead version of make). This can be very useful if you are building an extension that will eventually be distributed to multiple systems. You can then just archive the files in the destination directory and distribute them to your destination systems.
EXAMPLE 5
In this example, we'll do some more work with the argument stack. The previous examples have all returned only a single value. We'll now create an extension that returns an array.This extension is very Unix-oriented (struct statfs and the statfs system call). If you are not running on a Unix system, you can substitute for statfs any other function that returns multiple values, you can hard-code values to be returned to the caller (although this will be a bit harder to test the error case), or you can simply not do this example. If you change the XSUB, be sure to fix the test cases to match the changes.
Return to the Mytest directory and add the following code to the end of Mytest.xs:
void statfs(path) char * path INIT: int i; struct statfs buf; PPCODE: i = statfs(path, &buf); if (i == 0) { XPUSHs(sv_2mortal(newSVnv(buf.f_bavail))); XPUSHs(sv_2mortal(newSVnv(buf.f_bfree))); XPUSHs(sv_2mortal(newSVnv(buf.f_blocks))); XPUSHs(sv_2mortal(newSVnv(buf.f_bsize))); XPUSHs(sv_2mortal(newSVnv(buf.f_ffree))); XPUSHs(sv_2mortal(newSVnv(buf.f_files))); XPUSHs(sv_2mortal(newSVnv(buf.f_type))); } else { XPUSHs(sv_2mortal(newSVnv(errno))); }
You'll also need to add the following code to the top of the .xs file, just after the include of ``XSUB.h'':
#include <sys/vfs.h>
Also add the following code segment to Mytest.t while incrementing the ``9'' tests to ``11'':
@a = &Mytest::statfs("/blech"); ok( scalar(@a) == 1 && $a[0] == 2 ); @a = &Mytest::statfs("/"); is( scalar(@a), 7 );
New Things in this Example
This example added quite a few new concepts. We'll take them one at a time.- *
- The INIT: directive contains code that will be placed immediately after the argument stack is decoded. C does not allow variable declarations at arbitrary locations inside a function, so this is usually the best way to declare local variables needed by the XSUB. (Alternatively, one could put the whole "PPCODE:" section into braces, and put these declarations on top.)
- *
-
This routine also returns a different number of arguments depending on the
success or failure of the call to statfs. If there is an error, the error
number is returned as a single-element array. If the call is successful,
then a 9-element array is returned. Since only one argument is passed into
this function, we need room on the stack to hold the 9 values which may be
returned.
We do this by using the PPCODE: directive, rather than the CODE: directive. This tells xsubpp that we will be managing the return values that will be put on the argument stack by ourselves.
- *
-
When we want to place values to be returned to the caller onto the stack,
we use the series of macros that begin with ``XPUSH''. There are five
different versions, for placing integers, unsigned integers, doubles,
strings, and Perl scalars on the stack. In our example, we placed a
Perl scalar onto the stack. (In fact this is the only macro which
can be used to return multiple values.)
The XPUSH* macros will automatically extend the return stack to prevent it from being overrun. You push values onto the stack in the order you want them seen by the calling program.
- *
- The values pushed onto the return stack of the XSUB are actually mortal SV's. They are made mortal so that once the values are copied by the calling program, the SV's that held the returned values can be deallocated. If they were not mortal, then they would continue to exist after the XSUB routine returned, but would not be accessible. This is a memory leak.
- *
-
If we were interested in performance, not in code compactness, in the success
branch we would not use "XPUSHs" macros, but "PUSHs" macros, and would
pre-extend the stack before pushing the return values:
EXTEND(SP, 7);
The tradeoff is that one needs to calculate the number of return values in advance (though overextending the stack will not typically hurt anything but memory consumption).
Similarly, in the failure branch we could use "PUSHs" without extending the stack: the Perl function reference comes to an XSUB on the stack, thus the stack is always large enough to take one return value.
EXAMPLE 6
In this example, we will accept a reference to an array as an input parameter, and return a reference to an array of hashes. This will demonstrate manipulation of complex Perl data types from an XSUB.This extension is somewhat contrived. It is based on the code in the previous example. It calls the statfs function multiple times, accepting a reference to an array of filenames as input, and returning a reference to an array of hashes containing the data for each of the filesystems.
Return to the Mytest directory and add the following code to the end of Mytest.xs:
SV * multi_statfs(paths) SV * paths INIT: AV * results; I32 numpaths = 0; int i, n; struct statfs buf; if ((!SvROK(paths)) || (SvTYPE(SvRV(paths)) != SVt_PVAV) || ((numpaths = av_len((AV *)SvRV(paths))) < 0)) { XSRETURN_UNDEF; } results = (AV *)sv_2mortal((SV *)newAV()); CODE: for (n = 0; n <= numpaths; n++) { HV * rh; STRLEN l; char * fn = SvPV(*av_fetch((AV *)SvRV(paths), n, 0), l); i = statfs(fn, &buf); if (i != 0) { av_push(results, newSVnv(errno)); continue; } rh = (HV *)sv_2mortal((SV *)newHV()); hv_store(rh, "f_bavail", 8, newSVnv(buf.f_bavail), 0); hv_store(rh, "f_bfree", 7, newSVnv(buf.f_bfree), 0); hv_store(rh, "f_blocks", 8, newSVnv(buf.f_blocks), 0); hv_store(rh, "f_bsize", 7, newSVnv(buf.f_bsize), 0); hv_store(rh, "f_ffree", 7, newSVnv(buf.f_ffree), 0); hv_store(rh, "f_files", 7, newSVnv(buf.f_files), 0); hv_store(rh, "f_type", 6, newSVnv(buf.f_type), 0); av_push(results, newRV((SV *)rh)); } RETVAL = newRV((SV *)results); OUTPUT: RETVAL
And add the following code to Mytest.t, while incrementing the ``11'' tests to ``13'':
$results = Mytest::multi_statfs([ '/', '/blech' ]); ok( ref $results->[0]) ); ok( ! ref $results->[1] );
New Things in this Example
There are a number of new concepts introduced here, described below:- *
- This function does not use a typemap. Instead, we declare it as accepting one SV* (scalar) parameter, and returning an SV* value, and we take care of populating these scalars within the code. Because we are only returning one value, we don't need a "PPCODE:" directive - instead, we use "CODE:" and "OUTPUT:" directives.
- *
- When dealing with references, it is important to handle them with caution. The "INIT:" block first checks that "SvROK" returns true, which indicates that paths is a valid reference. It then verifies that the object referenced by paths is an array, using "SvRV" to dereference paths, and "SvTYPE" to discover its type. As an added test, it checks that the array referenced by paths is non-empty, using the "av_len" function (which returns -1 if the array is empty). The XSRETURN_UNDEF macro is used to abort the XSUB and return the undefined value whenever all three of these conditions are not met.
- *
-
We manipulate several arrays in this XSUB. Note that an array is represented
internally by an AV* pointer. The functions and macros for manipulating
arrays are similar to the functions in Perl: "av_len" returns the highest
index in an AV*, much like $#array; "av_fetch" fetches a single scalar value
from an array, given its index; "av_push" pushes a scalar value onto the
end of the array, automatically extending the array as necessary.
Specifically, we read pathnames one at a time from the input array, and store the results in an output array (results) in the same order. If statfs fails, the element pushed onto the return array is the value of errno after the failure. If statfs succeeds, though, the value pushed onto the return array is a reference to a hash containing some of the information in the statfs structure.
As with the return stack, it would be possible (and a small performance win) to pre-extend the return array before pushing data into it, since we know how many elements we will return:
av_extend(results, numpaths);
- *
- We are performing only one hash operation in this function, which is storing a new scalar under a key using "hv_store". A hash is represented by an HV* pointer. Like arrays, the functions for manipulating hashes from an XSUB mirror the functionality available from Perl. See perlguts and perlapi for details.
- *
- To create a reference, we use the "newRV" function. Note that you can cast an AV* or an HV* to type SV* in this case (and many others). This allows you to take references to arrays, hashes and scalars with the same function. Conversely, the "SvRV" function always returns an SV*, which may need to be cast to the appropriate type if it is something other than a scalar (check with "SvTYPE").
- *
- At this point, xsubpp is doing very little work - the differences between Mytest.xs and Mytest.c are minimal.
EXAMPLE 7 (Coming Soon)
XPUSH args AND set RETVAL AND assign return value to arrayEXAMPLE 8 (Coming Soon)
Setting $!EXAMPLE 9 Passing open files to XSes
You would think passing files to an XS is difficult, with all the typeglobs and stuff. Well, it isn't.Suppose that for some strange reason we need a wrapper around the standard C library function "fputs()". This is all we need:
#define PERLIO_NOT_STDIO 0 #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include <stdio.h> int fputs(s, stream) char * s FILE * stream
The real work is done in the standard typemap.
But you loose all the fine stuff done by the perlio layers. This calls the stdio function "fputs()", which knows nothing about them.
The standard typemap offers three variants of PerlIO *: "InputStream" (T_IN), "InOutStream" (T_INOUT) and "OutputStream" (T_OUT). A bare "PerlIO *" is considered a T_INOUT. If it matters in your code (see below for why it might) #define or typedef one of the specific names and use that as the argument or result type in your XS file.
The standard typemap does not contain PerlIO * before perl 5.7, but it has the three stream variants. Using a PerlIO * directly is not backwards compatible unless you provide your own typemap.
For streams coming from perl the main difference is that "OutputStream" will get the output PerlIO * - which may make a difference on a socket. Like in our example...
For streams being handed to perl a new file handle is created (i.e. a reference to a new glob) and associated with the PerlIO * provided. If the read/write state of the PerlIO * is not correct then you may get errors or warnings from when the file handle is used. So if you opened the PerlIO * as ``w'' it should really be an "OutputStream" if open as ``r'' it should be an "InputStream".
 We'll use the perlio "PerlIO_puts()" function as an example.
In the C part of the XS file (above the first MODULE line) you have
#define OutputStream PerlIO * or typedef PerlIO * OutputStream;
And this is the XS code:
int perlioputs(s, stream) char * s OutputStream stream CODE: RETVAL = PerlIO_puts(stream, s); OUTPUT: RETVAL
We have to use a "CODE" section because "PerlIO_puts()" has the arguments reversed compared to "fputs()", and we want to keep the arguments the same.
Wanting to explore this thoroughly, we want to use the stdio "fputs()" on a PerlIO *. This means we have to ask the perlio system for a stdio "FILE *":
int perliofputs(s, stream) char * s OutputStream stream PREINIT: FILE *fp = PerlIO_findFILE(stream); CODE: if (fp != (FILE*) 0) { RETVAL = fputs(s, fp); } else { RETVAL = -1; } OUTPUT: RETVAL
Note: "PerlIO_findFILE()" will search the layers for a stdio layer. If it can't find one, it will call "PerlIO_exportFILE()" to generate a new stdio "FILE". Please only call "PerlIO_exportFILE()" if you want a new "FILE". It will generate one on each call and push a new stdio layer. So don't call it repeatedly on the same file. "PerlIO()"_findFILE will retrieve the stdio layer once it has been generated by "PerlIO_exportFILE()".
This applies to the perlio system only. For versions before 5.7, "PerlIO_exportFILE()" is equivalent to "PerlIO_findFILE()".
Troubleshooting these Examples
As mentioned at the top of this document, if you are having problems with these example extensions, you might see if any of these help you.- *
-
In versions of 5.002 prior to the gamma version, the test script in Example
1 will not function properly. You need to change the ``use lib'' line to
read:
use lib './blib';
- *
-
In versions of 5.002 prior to version 5.002b1h, the test.pl file was not
automatically created by h2xs. This means that you cannot say ``make test''
to run the test script. You will need to add the following line before the
``use extension'' statement:
use lib './blib';
- *
-
In versions 5.000 and 5.001, instead of using the above line, you will need
to use the following line:
BEGIN { unshift(@INC, "./blib") }
- *
- This document assumes that the executable named ``perl'' is Perl version 5. Some systems may have installed Perl version 5 as ``perl5''.
See also
For more information, consult perlguts, perlapi, perlxs, perlmod, and perlpod.Author
Jeff Okamoto<EMAIL_ADDRESS>and assisted by Dean Roehrich, Ilya Zakharevich, Andreas Koenig, and Tim Bunce.
PerlIO material contributed by Lupe Christoph, with some clarification by Nick Ing-Simmons.
Changes for h2xs as of Perl 5.8.x by Renee Baecker
Last Changed
2007/10/11
Index
- NAME
- DESCRIPTION
- SPECIAL NOTES
- TUTORIAL
-
- EXAMPLE 1
- EXAMPLE 2
- What has gone on?
- Writing good test scripts
- EXAMPLE 3
- What's new here?
- Input and Output Parameters
- The XSUBPP Program
- The TYPEMAP file
- Warning about Output Arguments
- EXAMPLE 4
- What has happened here?
- Anatomy of .xs file
- Getting the fat out of XSUBs
- More about XSUB arguments
- The Argument Stack
- Extending your Extension
- Documenting your Extension
- Installing your Extension
- EXAMPLE 5
- New Things in this Example
- EXAMPLE 6
- New Things in this Example
- EXAMPLE 7 (Coming Soon)
- EXAMPLE 8 (Coming Soon)
- EXAMPLE 9 Passing open files to XSes
- Troubleshooting these Examples
- See also
- Author
This document was created by man2html, using the manual pages.
Time: 05:29:09 GMT, December 24, 2015


Before Change
else:
raise ValueError("unknown solver: {}".format(self.solver))
if self.solver != "osqp":
warnings.warn(("solver={!r} is deprecated and will be removed in future versions, "
"please use solver="osqp".".format(self.solver)),
category=DeprecationWarning, stacklevel=2)
if self.timeit is not None:
import timeit
def _inner():
After Change
max_iter = self.max_iter
if max_iter is not None:
max_iter = int(max_iter)
if self.solver == "ecos":
solver = EcosSolver(max_iter=max_iter, verbose=self.verbose)
elif self.solver == "osqp":
solver = OsqpSolver(max_iter=max_iter, verbose=self.verbose)


Add New Schedule
Doctor Name
Available Days
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Available Time
Amount of Patient
Select a Room
1
2
3
4
5
6
7
8
9
10
or
Reset


Lets get in touch. Please send us a message:
Lekki-Lagos, NG
Phone:<PHONE_NUMBER>8
Email: decagondev@gmail.com