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 |
|---|---|---|---|---|---|
If you use Visual Studio 2010 at all, stop what you are doing and install the Productivity Power Tools. It is extraordinarily easy to do so ( go to Tools->Extension Manager…, and search for “Productivity Power Tools” ):
There are a number of fantastic features in the Power Tool deliverable, but the one I want to point out is the new Solution Navigator. ( There have been a number of posts about these capabilities today, but I simply couldn’t help myself on this. I had to write about it! :) )
Solution Navigator: A Solution Explorer Replace
After you install the power tool and open your favorite solution, notice the new Solution Navigator tool window. The Solution Navigator gives a number of new features that you will quickly find invaluable. There are a number of little capabilities that you will find valuable, such as the ability to collapse all nodes in the navigator with one click of a button:
But this is just the start. You can also filter the Navigator by typing in a search string in the search toolbox as seen below:
In the example above, you’ll notice that I typed in “Main” in the search box, which highlights the “Main” method found in the Program class located in the Program.cs file in the OrderProcessor project. This exemplifies yet another fantastic addition, which is the ability to drill down into individual files to see the types found in those files. Nice!
You can do the same thing with Assembly references as well, which allows you to drill down into the assembly, getting at contained namespaces and types:
Another great touch is the ability to root the navigator to any arbitrary node. You do this by clicking the icon to the right of the node you want to root, or select the node and hit Ctrl-Right Arrow:
And here’s a shot of the Project node I selected above rooted in the navigator.
The great thing about this of course, is that it removes some of the noise in the UI when you are working in one particular area of your source base.
You’ll also notice the “All, Open, Unsaved, Edited” words below the solution. Below I’m showing you what happens to the navigator when I’ve got a three documents opened in the document well and want to filter the navigator so that I can quickly see what projects those files belong to:
I just can’t say enough how great this new capability is.
It has simply made my day! :)
Cameron | http://blogs.msdn.com/b/camerons/archive/2010/07/20/productivity-power-tools-a-must-have.aspx | CC-MAIN-2014-10 | refinedweb | 426 | 53.55 |
Action that converts TODO comments to GitHub issues on push.
This action will convert your
# TODOcomments to GitHub issues when a new commit is pushed.
The new issue will contain a link to the line in the file containing the TODO, together with a code snippet and any defined labels. The action performs a
GETrequest to retrieve GitHub's
languages.ymlfile file to apply highlighting to the snippet.
It will also close an issue when a
# TODOis removed in a pushed commit. A comment will be posted with the ref of the commit that it was closed by.
The
# TODOcomment is commonly used in Python, but this can be customised to whatever you want.
Create a workflow file in your .github/workflows directory as follows:
Latest version is
v2.4.1.
name: "Workflow" on: ["push"] jobs: build: runs-on: "ubuntu-latest" steps: - uses: "actions/[email protected]" - name: "TODO to Issue" uses: "alstr/[email protected]" id: "todo" with: TOKEN: ${{ secrets.GITHUB_TOKEN }}
If you use the action in a new repo, you should initialise the repo with an empty commit.
| Input | Default value | Description | |----------|---------------|-------------| |
REPO|
"${{ github.repository }}"| The path to the repository where the action will be used, e.g. 'alstr/my-repo' (automatically set) | |
BEFORE|
"${{ github.event.before }}"| The SHA of the last pushed commit (automatically set) | |
SHA|
"${{ github.sha }}"| The SHA of the latest commit (automatically set) | |
TOKEN|
"${{ secrets.GITHUB_TOKEN }}"| The GitHub access token to allow us to retrieve, create and update issues (automatically set) | |
LABEL|
"# TODO"| The label that will be used to identify TODO comments | |
COMMENT_MARKER|
"#"| The marker used to signify a line comment in your code | |
CLOSE_ISSUES|
true| Optional input that specifies whether to attempt to close an issue when a TODO is removed | |
AUTO_P|
true| For multiline TODOs, format each line as a new paragraph when creating the issue |
def hello_world(): # TODO Come up with a more imaginative greeting print('Hello world!')
This will create an issue called "Come up with a more imaginative greeting".
The action expects a colon and/or space to follow the
TODOlabel (so
TODO:or just
TODO).
Should the title be longer than 80 characters, it will be truncated for the issue title.
The full title will be included in the issue body and a
todolabel will be attached to the issue.
A reference hash is added to the end of the issue body. This is to help prevent duplication of TODOs.
def hello_world(): # TODO Come up with a more imaginative greeting # Everyone uses hello world and it's boring. print('Hello world!')
You can create a multiline todo by continuing below the initial TODO declaration with a comment.
The extra line(s) will be posted in the body of the issue.
The
COMMENT_MARKERinput must be set to the correct syntax (e.g.
#for Python).
Each line in the multiline TODO will be formatted as a paragraph in the issue body. To disable this, set
AUTO_Pto
false.
def hello_world(): # TODO(alstr) Come up with a more imaginative greeting
As per the Google Style Guide, you can provide an identifier after the TODO label. This will be included in the issue title for searchability.
Don't include parentheses within the identifier itself.
def hello_world(): # TODO Come up with a more imaginative greeting # Everyone uses hello world and it's boring. # labels: enhancement, help wanted print('Hello world!')
You can specify the labels to add to your issue in the TODO body.
The labels should be on their own line below the initial TODO declaration.
Include the
labels:prefix, then a list of comma-separated label titles. If any of the labels do not already exist, they will be created.
The
todolabel is automatically added to issues to help the action efficiently retrieve them in the future.
def hello_world(): # TODO Come up with a more imaginative greeting # Everyone uses hello world and it's boring. # assignees: alstr, bouteillerAlan, hbjydev print('Hello world!')
Similar to labels, you can define assignees as a comma-separated list.
If the assignee is not valid, it will be dropped from the issue creation request.
def hello_world(): # TODO Come up with a more imaginative greeting # Everyone uses hello world and it's boring. # milestone: 1 print('Hello world!')
You can set the issue milestone by specifying the milestone ID. Only a single milestone can be specified.
If the milestone does not already exist, it will be dropped from the issue creation request.
def hello_world(): print('Hello world!')
Removing the
# TODOcomment will close the issue on push.
This is still an experimental feature. By default it is enabled, but if you want to disable it, you can set
CLOSE_ISSUESto
falseas described in Inputs.
def hello_world(): # TODO Come up with a more imaginative greeting, like "Greetings world!" print('Hello world!')
Should you change the
# TODOtext, this will currently create a new issue, so bear that in mind.
This may be updated in future.
This action will convert your# TODOcomments to GitHub issues when a new commit is pushed.
As the TODOs are found by analysing the difference between the new commit and the previous one, this means that if this action is implemented during development any existing TODOs will not be detected. For them to be detected, you would have to remove them, commit, put them back and commit again.
The action was developed for the GitHub Hackathon and is still in an early stage. Whilst every effort is made to ensure it works, it comes with no guarantee.
It may not yet work for events other than
pushor those with a complex workflow syntax .
If you do encounter any problems, please file an issue. PRs are welcome and appreciated!
Thanks to Jacob Tomlinson for his handy overview of GitHub Actions.
Thanks to GitHub's linguist repo for the
languages.ymlfile used by the app to determine the correct highlighting to apply to code snippets. | https://xscode.com/alstr/todo-to-issue-action | CC-MAIN-2021-10 | refinedweb | 974 | 57.37 |
This restaurant is closedFind similar restaurants
Own this business? Learn more about offering online ordering to your diners.
Gloria's Cafe
Monday lentil soup
Tuesday vegetable soup
Wednesday green plantains soup
Thursday tortilla soup
Friday beef rib soup
Saturday beef tripe soup
Sunday hen stew soup
carne asada, chicharron, huevo, aguacate, frijoles, chorizo typical platter grilled beef, pork skin, sausage, egg, avocado, beans
carne, chicharron, huevo, arroz, frijoles y maduros small typical platter beef, fried pork skin, egg, rice, beans and sweet plantains
carne molida, chicharron, huevo, maduros, frijoles, aguacate y arroz country platter ground beef, pork skin, egg, sweet plantains, beans, avocado and rice
papa, arroz y frijoles top flank in creole sauce, potato, rice and beans
maduros, arroz frijoles top flank grilled sweet plantains, rice and beans
maduros, papa, arroz y frijoles tongue in sauce sweet plantains, potato, rice and beans
maduros, arroz y frijoles top round steak with onions sweet plantains, rice and beans
arroz, frijoles y huevo frito top round steak with fried egg rice and beans
frijoles, maduros y arroz grilled top round steak beans, sweet plantains and rice
arroz, frijoles y ensalada grilled pork chop rice, beans and salad
ensalada, arroz, frijoles y maduros breaded pork loin salad, sweet plantains, rice and beans
arroz, frijoles, maduros y ensalada grilled pork loin rice, beans, sweet plantains and salad
arroz, frijoles, maduros y ensalada breaded steak rice, beans, sweet plantains and salad
carne de res, chicharron, chorizo, carne de cerdo, patacon, yuca y arepa beef platter beef steak, pork skin, sausage, pork steak, green plantain, cassava and corn cake
papa criolla, ensalada y chimichurri skirt steak small yellow potatoes, salad and chimichurri sauce
papa frita, chicken with rice French fries
arroz, frijoles y ensalada grilled chicken breast, rice, beans and salad
arroz, frijoles, maduros y ensalada chicken breast in creole sauce, rice, beans, sweet plantains and salad
arroz, frijoles y ensalada, breaded chicken breast, rice, beans and salad
arroz, frijoles, maduros y ensalada, grilled chicken breast with onion, rice, beans, sweet plantains and salad
tostones y ensalada, rice with seafood green plantain and salad
steamed red snapper
fried red snapper
fried red tilapia
steamed red tilapia
seafood casserole
shrimp with garlic sauce
shrimp with hot sauce
breaded shrimp
breaded tilapia filet
beef patties
sausage with corn cake
fried pork skin with corn cake
boiled corn in milk guava paste.
chips and salsa
oatmeal
sweet corn cake
chicken pie
green plantain
fried sweet plantain
French fries
white rice
red beans
order of avocado
order of salad
avocado salad
champagne, apple, orange, grape, pineapple, pony malta
domestic beer
import beer
three, milks flan
figs with cheese
ice cream cake
chicken or beef, served with red beans, pico de gallo and sour cream.
beef or chicken sauteed with onions, beans and cheese inside. Also comes with pico de gallo, sour cream, red beans, and rice.
soft or crispy corn tortilla. Beef, chicken, or chorizo. Served with pico de gallo, red beans, and rice.
chicken, cheese, and roasted salsa, wrapped in a flour tortilla and fried to perfection. Drizzled with chipotle mayonnaise and barbeque sauce. Served with pico de gallo, sour cream, and rice and beans.
lightly breaded or grilled. Served with rice and red beans or tostones and salad
fried pork skin, carne asada, sweet plantains and served with an egg, rice, and red beans
served with rice, red beans and a choice of tostones or sweet plantains
chicken, beef, and shrimp
ask your server for details.
ask your server for details.
ask your server for details.
served with the meat special, soup of the day, rice, salad and sweet plantains.
brown sugar water
shakes and smoothies
custard flan
Menu for Gloria. | https://www.allmenus.com/fl/orlando/34300-glorias-cafe/menu/ | CC-MAIN-2018-30 | refinedweb | 613 | 53.89 |
In this tutorial, you’ll learn how to use Python to delete a file or directory (folder). You’ll learn how to do this using the
os library and the
shutil library to do this. You’ll learn how to do delete a single file, how to delete all files in a directory, and how to delete an entire directory in Python. You’ll also learn how to handle errors, so that if a file or a directory doesn’t exist, that you program will continue to run successfully without crashing.
After reading this guide, you’ll have learned how to use Python to delete files and folders using the
os library, the
pathlib library, and the
shutil library. Why learn three different libraries? Each library comes with specific pros and specific cons – learning how to use these libraries to meet your specific needs can have tremendous benefits on how well your code runs.
You’ll also learn how to make sure your code runs safely, meaning that your code will first check if a file or a directory exist before deleting it. This means that your program won’t crash if it encounters files or folders that don’t exist, allowing your program to continue running.
The Quick Answer: Use os.unlink or shutil.rmtree
Use Python to Delete a File Using os
Deleting a single file using Python is incredibly easy, using the
os.remove() function. The
os library makes it easy to work with, well, your operating system. Because deleting a file is a common function, the library comes with the
.remove() function built in.
What you need to do is simply pass the path of the file into the function, and Python will delete the filter.
Be careful: there is no confirmation prompt to this, so be sure that this is actually what you want to be doing!
# Delete a single file using os import os file_path = "" # Check if the file exists if os.path.exists(file_path): os.remove(file_path)
Let’s explore what we’ve done here:
- We declared our file path, including an extension. If you’re using Windows and don’t want to escape your backslashes, be sure to make the string a raw string by prepending a letter
rto it.
- We run a conditional expression that uses the
os.path.exists()function to check whether a file exists or not.
- If the file exists, we use the
remove()function to pass in the file we want to delete
In the next section, you’ll learn how to use Python to delete all files in a directory using
os.
Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!
Use Python to Delete all Files in a Directory Using os
In order to delete all the files in a folder with Python, but keep the folder itself, we can loop over each file in that folder and delete it using the method we described above.
In order to do this, we’ll use the helpful
glob module which I’ve described in depth here. What the
glob library helps us do is get the paths to all files in a directory.
Let’s see how we can use the
os and
glob libraries to delete all
.csv files in a given directory. We’ll begin by importing the required libraries:
import os import glob
glob is not a preinstalled library. Because of this, you may need to install it. This can be done by using either
pip or
conda in the terminal, such as below:
pip install glob
Let’s see how we can delete all files in a directory using Python:
# Delete all files in a folder using os import glob import os directory = '/Users/nikpi/Desktop/Important Folder/*' files = glob.glob(directory) for file in files: if os.path.exists(file): os.remove(file)
Let’s take a look at what we’ve done here:
- We use
globto generate a list of files in the directory specified. We use the
*wildcard operator to ensure that all files in the directory are gathered.
- We then loop over each file in that list, check if it exists, and if it exists, we remove it.
In the next section, you’ll learn how to use the
os library to delete files conditionally, when used with
glob.
Delete Files Conditionally with Python
When working with different files in your operating system, you may want to delete files conditionally. For example, you may want to use Python to delete all files with a certain word in the filename or files that have a certain filetype.
For this, we can use the
glob library to find all files in a folder, especially using a condition. To learn more about the
glob library and how to use it to find all files in a directory using Python, you can check out my in-depth tutorial here.
Now that you’re ready to go, let’s see how we can use the two libraries to find all the files matching a condition and delete them.
# Delete all .csv files in a folder using glob and os import os import glob file_path = '*.csv' files = glob.glob(file_path) for file in files: os.remove(file)
Let’s explore what we’ve done here:
- We imported the two libraries,
osand
glob
- We then assigned our file path including our condition to the variable
file_path
- This variable was passed into the
glob()function, which returns a list of all the files matching that condition
- We then iterate over the list, deleting every file in the list using the
os.remove()function
This is a really helpful way to clear up a directory after processing files.
This approach is quite helpful to handle errors. If no files match the condition, then the list is empty and the for loop doesn’t occur.
In the next section, you’ll learn how to use the object-oriented
pathlib library to delete a file using Python.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Use Pathlib to Delete a File using Python
The
pathlib library uses an object-oriented approach to handling files and file paths. Because of this, we can use the library to access attributes of Path objects or apply methods onto the objects. One of these methods is the
.unlink() method, which is used to delete files.
Let’s see how we can use the pathlib library to delete a file:
# Delete a file using Pathlib import pathlib path_string = "/Users/nikpi/Desktop/Important Folder/datagy.txt" path = pathlib.Path(path_string) path.unlink(missing_ok=True)
You may notice that we passed in an argument into the
.unlink() method. By passing in
missing_ok = True, we tell pathlib to not throw an error if the file doesn’t exist. This is similar to using the
os library to first check if the file exists, but it does save us one line of code.
In the next section, we’ll move on to learning how to use Python to delete entire directories.
Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!
Use Python to Delete Directories Using os
Interestingly, both the
os and
pathlib libraries do not have functions or methods that allow you to delete non-empty directories. Because of this, we need to first delete all files in a directory to be able to delete the directory itself.
In order to delete a directory using the
os library, we’ll use the
.rmdir() function. If we try to delete a directory that has files in it, Python will throw an
Directory not empty error.
In order to avoid this, we first need to delete the files in the folder.
Instead of using the
glob library in this example, let’s try using a different function. We’ll loop over the files in the folder using the
listdir() function. Let’s give this a shot:
# Delete a directory using os import os path = '/Users/nikpi/Desktop/Important Folder/' files = os.listdir(path) for file in files: file_path = os.path.join(path, file) os.unlink(file_path) os.rmdir(path)
Let’s take a look at what we’ve done here:
- We loaded our path variable and used the
os.listdir()function to generate a list of all the files in the folder
- We looped over each file, by first creating a full path to the file using the
os.path.join()function and the deleting the file
- Once all files were deleted, we used the
os.rmdir()function to delete the directory
Keep in mind, that if the folder contains another folder, then this code will fail. In those cases, read on to see how to use the
shutil library to delete a folder that contains files and other folders.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Use Pathlib to Delete Directories in Python
Similar to the
os library,
pathlib can only delete directories if they are empty. Because of this, in order to delete our folder, we must first delete every file in the folder.
Let’s see how we can do this using the
pathlib library:
# Delete a directory using pathlib import pathlib path_string = '/Users/nikpi/Desktop/Important Folder/' path = pathlib.Path(path_string) for file in path.iterdir(): file.unlink() path.rmdir()
We follow a similar path here as we did with the
os library: we looped over each file in the directory and deleted it. Following that, we deleted the directory itself.
In the next section, you’ll learn how to use
shutil to delete directories, even if they have files in them.
Want to learn how to use the Python
zip() function to iterate over two lists? This tutorial teaches you exactly what the
zip() function does and shows you some creative ways to use the function.
Delete Directories Using Shutil in Python
With the two methods above, directories could only be deleted when they didn’t contain any files or folders. Using
shutil, however, we can delete directories using Python even if they are non-empty.
Let’s see how we can use
shutil to delete directories using Python:
# Delete directories in Python using shutil import shutil path = '/Users/nikpi/Desktop/Important Folder' shutil.rmtree(path, ignore_errors=True)
We simply need to pass in the path of a directory into the
shutil.rmtree() function to be able to delete an entire directory, even if it includes files. By using the
ignore_errors=True, we make the execution safer, by preventing the program from crashing if the directory doesn’t exist.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Conclusion
In this post, you learned how to use Python to delete a file or a directory. You learned how to do this using the
os library, the
shutil library, and the
pathlib library. You also learned how to delete all files in a directory using a Python for loop.
To learn more about the
pathlib library, check out the official documentation here. | https://datagy.io/python-delete-file-or-directory/ | CC-MAIN-2022-27 | refinedweb | 1,959 | 71.04 |
Data.
- Update: The examples in this post were updated for the latest Keras API. The datagen.next() function was removed.
- Update Oct/2016: Updated examples for Keras 1.1.0, TensorFlow 0.10.0 and scikit-learn v0.18.
- Update Jan/2017: Updated examples for Keras 1.2.0 and TensorFlow 0.12.1.
- Update Mar/2017: Updated example for Keras 2.0.2, TensorFlow 1.0.1 and Theano 0.9.0.
Keras Image Augmentation API
Like the rest of Keras, the image augmentation API is simple and powerful.
Keras provides the ImageDataGenerator class that defines the configuration for image data preparation and augmentation. This includes capabilities such as:
- Sample-wise standardization.
- Feature-wise standardization.
- ZCA whitening.
- Random rotation, shifts, shear and flips.
- Dimension reordering.
- Save augmented images to disk.
An augmented image generator can be created as follows:
Rather than performing the operations on your entire image dataset in memory, the API is designed to be iterated by the deep learning model fitting process, creating augmented image data for you just-in-time. This reduces your memory overhead, but adds some additional time cost during model training.
After you have created and configured your ImageDataGenerator, you must fit it on your data. This will calculate any statistics required to actually perform the transforms to your image data. You can do this by calling the fit() function on the data generator and pass it your training dataset.
The data generator itself is in fact an iterator, returning batches of image samples when requested. We can configure the batch size and prepare the data generator and get batches of images by calling the flow() function.
Finally we can make use of the data generator. Instead of calling the fit() function on our model, we must call the fit_generator() function and pass in the data generator and the desired length of an epoch as well as the total number of epochs on which to train.
You can learn more about the Keras image data generator API in the Keras.
Point of Comparison for Image Augmentation
Now that you know how the image augmentation API in Keras works, let’s look at some examples.
We will use the MNIST handwritten digit recognition task in these examples. To begin with, let’s take a look at the first 9 images in the training dataset.
Running this example provides the following image that we can use as a point of comparison with the image preparation and augmentation in the examples below.
Example MNIST images
Feature Standardization
It is also possible to standardize pixel values across the entire dataset. This is called feature standardization and mirrors the type of standardization often performed for each column in a tabular dataset.
You can perform feature standardization by setting the featurewise_center and featurewise_std_normalization arguments on the ImageDataGenerator class. These are in fact set to True by default and creating an instance of ImageDataGenerator with no arguments will have the same effect.
Running this example you can see that the effect is different, seemingly darkening and lightening different digits.
Standardized Feature MNIST Images
ZCA Whitening
A whitening transform of an image is a linear algebra operation that reduces the redundancy in the matrix of pixel images.
Less redundancy in the image is intended to better highlight the structures and features in the image to the learning algorithm.
Typically, image whitening is performed using the Principal Component Analysis (PCA) technique. More recently, an alternative called ZCA (learn more in Appendix A of this tech report) shows better results and results in transformed images that keeps all of the original dimensions and unlike PCA, resulting transformed images still look like their originals.
You can perform a ZCA whitening transform by setting the zca_whitening argument to True.
Running the example, you can see the same general structure in the images and how the outline of each digit has been highlighted.
ZCA Whitening MNIST Images
Random Rotations
Sometimes images in your sample data may have varying and different rotations in the scene.
You can train your model to better handle rotations of images by artificially and randomly rotating images from your dataset during training.
The example below creates random rotations of the MNIST digits up to 90 degrees by setting the rotation_range argument.
Running the example, you can see that images have been rotated left and right up to a limit of 90 degrees. This is not helpful on this problem because the MNIST digits have a normalized orientation, but this transform might be of help when learning from photographs where the objects may have different orientations.
Random Rotations of MNIST Images
Random Shifts
Objects in your images may not be centered in the frame. They may be off-center in a variety of different ways.
You can train your deep learning network to expect and currently handle off-center objects by artificially creating shifted versions of your training data. Keras supports separate horizontal and vertical random shifting of training data by the width_shift_range and height_shift_range arguments.
Running this example creates shifted versions of the digits. Again, this is not required for MNIST as the handwritten digits are already centered, but you can see how this might be useful on more complex problem domains.
Random Shifted MNIST Images
Random Flips
Another augmentation to your image data that can improve performance on large and complex problems is to create random flips of images in your training data.
Keras supports random flipping along both the vertical and horizontal axes using the vertical_flip and horizontal_flip arguments.
Running this example you can see flipped digits. Flipping digits is not useful as they will always have the correct left and right orientation, but this may be useful for problems with photographs of objects in a scene that can have a varied orientation.
Randomly Flipped MNIST Images
Saving Augmented Images to File
The data preparation and augmentation is performed just in time by Keras.
This is efficient in terms of memory, but you may require the exact images used during training. For example, perhaps you would like to use them with a different software package later or only generate them once and use them on multiple different deep learning models or configurations.
Keras allows you to save the images generated during training. The directory, filename prefix and image file type can be specified to the flow() function before training. Then, during training, the generated images will be written to file.
The example below demonstrates this and writes 9 images to a “images” subdirectory with the prefix “aug” and the file type of PNG.
Running the example you can see that images are only written when they are generated.
Augmented MNIST Images Saved To File
Tips For Augmenting Image Data with Keras
Image data is unique in that you can review the data and transformed copies of the data and quickly get an idea of how the model may be perceive it by your model.
Below are some times for getting the most from image data preparation and augmentation for deep learning.
- Review Dataset. Take some time to review your dataset in great detail. Look at the images. Take note of image preparation and augmentations that might benefit the training process of your model, such as the need to handle different shifts, rotations or flips of objects in the scene.
- Review Augmentations. Review sample images after the augmentation has been performed. It is one thing to intellectually know what image transforms you are using, it is a very different thing to look at examples. Review images both with individual augmentations you are using as well as the full set of augmentations you plan to use. You may see ways to simplify or further enhance your model training process.
- Evaluate a Suite of Transforms. Try more than one image data preparation and augmentation scheme. Often you can be surprised by results of a data preparation scheme you did not think would be beneficial.
Summary
In this post you discovered image data preparation and augmentation.
You discovered a range of techniques that you can use easily in Python with Keras for deep learning models. You learned about:
- The ImageDataGenerator API in Keras for generating transformed images just in time.
- Sample-wise and Feature wise pixel standardization.
- The ZCA whitening transform.
- Random rotations, shifts and flips of images.
- How to save transformed images to file for later reuse.
Do you have any questions about image data augmentation or.
Interesting tutorial.
I’m working through the step to standardize images across the dataset and run into the following error:
AttributeError Traceback (most recent call last)
in ()
18 datagen.flow(X_train, y_train, batch_size=9)
19 # retrieve one batch of images
—> 20 X_batch, y_batch = datagen.next()
21 # create a grid of 3×3 images
22 for i in range(0, 9):
AttributeError: ‘ImageDataGenerator’ object has no attribute ‘next’
I have checked the Keras documentation and see no mention of a next attribute.
Perhaps I’m missing something.
Thanks for the great tutorials!
Yep, the API has changed. See:
I will update all of the examples ASAP.
UPDATE: I have updated all examples in this post to use the new API. Let me know if you have any problems at all.
Works like a charm! Thanks
Glad to hear it Andy.
for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
File “/usr/local/lib/python2.7/dist-packages/keras/preprocessing/image.py”, line 475, in next
x = self.image_data_generator.random_transform(x.astype(‘float32’))
File “/usr/local/lib/python2.7/dist-packages/keras/preprocessing/image.py”, line 346, in random_transform
fill_mode=self.fill_mode, cval=self.cval)
File “/usr/local/lib/python2.7/dist-packages/keras/preprocessing/image.py”, line 109, in apply_transform
x = np.stack(channel_images, axis=0)
AttributeError: ‘module’ object has no attribute ‘stack’
how to solve this error …?
I have not seen an error like that before. Perhaps there is a problem with your environment?
Consider re-installing Theano and/or Keras.
i solved this error by updating numpy version ….previously it 1.8.0..now 1.11.1..it means it should be more than 1.9.0
Great, glad to here it narayan.
Now i have question that how to decide value for this parameter So that i can get good testing accuracy ..i have training dataset with 110 category with 32000 images ..
featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=0.,
width_shift_range=0.,
height_shift_range=0.,
shear_range=0.,
zoom_range=0.,
channel_shift_range=0.,
fill_mode=’nearest’,
cval=0.,
horizontal_flip=False,
vertical_flip=False,
rescale=None,
dim_ordering=K.image_dim_ordering()
Waiting for your positive reply…
My advice is to try a suite of different configurations and see what works best on your problem.
Thanks a lot.
all worked fine except the last code to save images to file, I got the following exception
Walids-MacBook-Pro:DataAugmentation walidahmed$ python augment_save_to_file.py
Using TensorFlow backend.
Traceback (most recent call last):
File “augment_save_to_file.py”, line 20, in
for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9, save_to_dir=’images’, save_prefix=’aug’, save_format=’png’):
File “/usr/local/lib/python2.7/site-packages/keras/preprocessing/image.py”, line 490, in next
img = array_to_img(batch_x[i], self.dim_ordering, scale=True)
File “/usr/local/lib/python2.7/site-packages/keras/preprocessing/image.py”, line 140, in array_to_img
raise Exception(‘Unsupported channel number: ‘, x.shape[2])
Exception: (‘Unsupported channel number: ‘, 28)
Any advice?
thanks again
Double check your version of Keras is 1.1.0 and TensorFlow is 0.10.
Hello Jason,
Thanks a lot for your tutorial. It is helping me in many ways.
I had question on mask image or target Y for training image X
Can i also transform Y along with X. Helps in the case of training for segmentation
I managed to do it.
datagen = ImageDataGenerator(shear_range=0.02,dim_ordering=K._image_dim_ordering,rotation_range=5,width_shift_range=0.05, height_shift_range=0.05,zoom_range=0.3,fill_mode=’constant’, cval=0)
for samples in range(0,100):
seed = rd.randint(low=10,high=100000)
for imags_batch in datagen.flow(imgs_train,batch_size=batch_size,save_to_dir=’augmented’,save_prefix=’aug’,seed=seed,save_format=’tif’):
print(‘-‘)
break
for imgs_mask_batch in datagen.flow(imgs_mask_train, batch_size=batch_size, save_to_dir=’augmented’,seed=seed, save_prefix=’mask_aug’,save_format=’tif’):
print(‘|’)
break
print((samples+1)*batch_size)
This is great stuff but I wonder if you could provide an example like this with an RGB image with three channels? I am getting some really buggy results personally with this ImageGenerator.
Great suggestion, thanks Addie.
I wonder what
channel_shift_rangeis about. The doc says “shift range for each channels”, but what does this actually mean? Is it adding a random value to each channel or doing something else?
I have not used this one yet, sorry Lucas.
You could try experimenting with it or dive into the source to see what it’s all about.
Hi,
Thanks for the post. I’ve one question i.e., we do feature standardization in the training set, so while testing, we need those standardized values to apply on testing images ?
Yes Indra, any transforms like standardization performed on the data prior to modeling will also need to be performed on new data when testing or making predictions.
In the case of standardization, we need to keep track of means and standard deviations.
Thanks again Jason. Why do we subplot 330+1+i? Thanks
This is matplotlab syntax.
The 33 creates a grid of 3×3 images. The number after that (1-9) indicates the position in that grid to place the next image (left to right, top to bottom ordering).
I hope that helps.
How do I save the augmented images into a directory with a class label prefix or even better into a subdirectory of class name?
Great question Vineeth,
You can specify any directory and filename prefix you like in the call to flow()
can we augment data of a particular class. I mean images of a class which are less, to deal with the class imbalance problem.
Great idea.
Yes, but you may need to prepare the data for each class separately.
Hi Jason,
Thanks for your post!
I have a question: Does this apply to image data with RGBXYZ for each pixel?
Each of my input image is of six channels including RGB and XYZ (world coordinate), which was acquired from an organized point cloud by PCL(Point Cloud Library). I am wondering whether there is a correct way to do data augmentation for my images.
I think ImageDataGenerator might be correct only for RGB images? Because when you shift/rotate/flip the RGB image, it means camera movement indeed, and the XYZ coordinates should be changed as well.
Thanks.
Hi Lebron, I believe this specific API is intended for 3d pixel data. You might be able to devise your own similar domain-specific transforms for you own data.
Thanks Jason!
To confirm, do you mean image with RGB only by “3d pixel data”? And if I have more channels, I have to do all the augmentation by myself, rather than using Keras API?
Yes, I believe that to be the case, but I could be wrong.
When I use zoom_range of 0.2 and inspect the output images, it seems to zoom h and v axes independently. However I want to have a small amount of zoom variation while preserving the aspect ratio of the images.
Also, when I specify a rotation_range, the rotated images have aliasing artefacts. Is there any way to specify rotations with antialiasing?
I’m not sure off hand.
Do you think these concerns will affect the skill of the model?
Thanks Jason,
Aspect ratio of the image is important in a facial recognition setting. Antialiasing of rotated images I’m not so sure about, but as they are small images (244 x 244) it doesn’t make sense to degrade them further.
I can modify my own copy of the Keras code to maintain the aspect ratio of the zoom and should be able to substitute PIL’s rotation function, which does antialiasing, for the one used in Keras.
Keep up the good work, your writing has really helped me get up to speed with Keras quickly
Very nice Brian.
Let me know how you go.
Hi Brian.
The transformations in ImageGenerator are applied using [scipy.ndimage.interpolation.affine_transform](), with “order” (the order of spline used for interpolation) set to zero.
Change this to one for linear interpolation or higher for higher orders.
Hi Jason,
Thank you for your post! Very clear!
I am trying to use ImageDataGenerator now. But if I want to apply feature standardization to unseen data in the future, I need to save the ImageDataGenerator to disk, right? Any suggestion to do it? Thanks a lot.
That is correct, or you can standardize manually and just save the coefficients used.
Hi Jason
I using Keras 2.x ‘tf’ seeting.
Why I can’t using
X_batch, y_batch = datagen.flow(train, train, batch_size=32)
For example :
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 28, 28,1)
X_test = X_test.reshape(X_test.shape[0], 28, 28,1)
# convert from int to float
X_train = X_train.astype(‘float32’)
X_test = X_test.astype(‘float32’)
# define data preparation
datagen = ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True)
# fit parameters from data
datagen.fit(X_train)
# configure batch size and retrieve one batch of images
X_batch, y_batch = datagen.flow(X_train, y_train, batch_size=9)
Can you tell me why?
Thanks!
What error do you get exactly?
Hi, Hason
The error message is :
too many values to unpack (expected 2)
I’m sorry I have not seen this error before, I do not have any good suggestions.
Hi Jason,
I have training data of the shape (2000,4,100,100) which means 2000 samples of the size 100×100 with 4 channels and dtype= uint8, stored as ‘.npy’ file. Can I use Image Augmentation technique on such data?
You may, try it and see. | http://machinelearningmastery.com/image-augmentation-deep-learning-keras/ | CC-MAIN-2017-26 | refinedweb | 2,998 | 57.98 |
#cd /usr/pkgsrc/mail/clamav #bmake install clean <SNIP> Note that as of version 0.80, clamav.conf has been replaced by clamd.conf. Be sure to update your configuration to reflect this.
=> Registering installation for clamav-0.90.1 clamav-0.90.1 requires installed package curl-7.16.1 clamav-0.90.1 requires installed package gmp-4.2.1 ===> Cleaning for clamav-0.90.1
# pkg_info cdrecord-2.00.3nb2 Software for creating ISO9660 images and writing CDs/CD-RWs dfuibe_installer-1.1.6 DFUI BSD Installer backend dfuife_curses-1.5 DFUI curses frontend digest-20050731 Message digest wrapper utility gettext-lib-0.14.5 Internationalized Message Handling Library (libintl) libaura-3.1 Collection of useful C functions libdfui-4.2 LIBrary for DragonFly User Interfaces libinstaller-5.1 Library of support functions for the BSD Installer applicati libidn-0.6.11 Internationalized Domain Names command line tool curl-7.16.1 Client that groks URLs gmp-4.2.1 Library for arbitrary precision arithmetic libtool-base-1.5.22nb4 Generic shared library support script (the script itself) m4-1.4.8 GNU version of UNIX m4 macro language processor libmilter-8.13.8 Mail filter support library for sendmail clamav-0.90.1 Anti-virus toolkit
# less mk.conf #=xorg WRKOBJDIR=/usr/obj/pkgsrc ACCEPTABLE_LICENSES+=sendmail-license . endif ~ ~
# pkg_delete clamav-0.90.1 =========================================================================== The following users are no longer being used by clamav-0.90.1, and they can be removed if no other software is using them: <SNIP> /var/clamav
# pwd /usr/pkgsrc/mail/clamav # bmake clean ===> Cleaning for clamav-0.90.1
# bmake show-options Any of the following general options may be selected: clamav-experimental curl Enable curl support. milter
These options are enabled by default: curl
These options are currently enabled: curl
You can select which build options to use by setting PKG_DEFAULT_OPTIONS or PKG_OPTIONS.clamav.
# bmake PKG_OPTIONS.clamav="curl milter" install clean <SNIP> => Required installed package libmilter>=8.13.1: libmilter-8.13.8 found <SNIP> checking whether setpgrp takes no argument... no checking for sendmail... /usr/sbin/sendmail checking for __gmpz_init in -lgmp... yes checking for curl >= 7.10.0... pkg-config: not found 7.16.1 checking for mi_stop in -lmilter... no checking for library containing strlcpy... no checking for mi_stop in -lmilter... no configure: error: Cannot find libmilter *** Error code 1
Stop. bmake: stopped in /usr/pkgsrc/mail/clamav WARNING: *** Please consider adding USE_LANGUAGES+=c++ to the package Makefile. WARNING: *** Please consider adding USE_LANGUAGES+=fortran to the package Makefile. *** Error code 1
Stop. bmake: stopped in /usr/pkgsrc/mail/clamav
Notice both the curl and libmilter versions are higher then requested though for curl it's looking for ">= 7.10.0".
Further more if I fix The USE_LANGUAGES errors by adding them to the mk.conf (apparently they need to be added somewhere in the Makefile, no idea where though...) it start starts to complain about USE_LANGUAGES+=c
Can some pkgsrc guru please look into this? Clamav with libmilter is either seriously broke or I somehow need to get an older version of libmilter installed. If it's the later please do provide me with instructions. | https://www.dragonflybsd.org/mailarchive/users/2007-04/msg00005.html | CC-MAIN-2017-22 | refinedweb | 528 | 54.18 |
Create custom emoji for individual projects
ProblemProblem
#48907 will implement custom emoji for the group scope. This does however not yet make it possible to have custom emoji in for example personal projects. Sometimes these projects can also grow large and thus they will eventually get a need for some more community features like custom emoji.
Puttin the ability to add/remove custom emoji in your personal namespace (meaning your personal settings that no one else can access) is out of the question. Custom emoji should make it possible for more than one person to add them in order to let the community thrive. See for more information #13931 (comment 86312705)
Note: This will need #48907 to be implemented first!
ScopeScope
- Implement #48907 in the scope of a single project (Not personal namespace).
- Any project member can add custom emoji (meaning that this option should be made accessible to any project member)
- members can only delete their own emoji
- Maintainers can delete any custom emoji
- project transfers will not bring emoji along (future improvement) | https://gitlab.com/gitlab-org/gitlab-ce/issues/48911 | CC-MAIN-2019-30 | refinedweb | 174 | 58.01 |
Solution
It worked like this...
1) Change the MIME type to "application/x-javascript"
2) Now HTTP 405 Resource not allowed Error in IIS error would come so, Home Directory > Configuration and From the "Mappings" tab, select the "Add" button.Click the "Browse..." button, choose "Dynamic Link Libraries *.dll" from the "Files of Type" dropdown, and select c:\WINDOWS\System32\inetsrv\asp.dll. and add "JSON" "GET,POST" verb.
IIS would now work and read the json and treeloader would work.
Regards
Thanks xerifa
Thank you so much for posting your solution. I also struck this problem and spent hours tring to get it to work on IIS. I knew it was IIS related because the same files worked fine on Apache.
For ExtJS Admin: I think this fix really needs to be added to the Installation Guidelines as there are a lot of people who will want to use the Tree menu on IIS web servers and this requires additional configuration to support JSON.
Extra note: Google (and the internal forum search) was useless in finding this post - I only found it by using Windows Live Search...
API Search || Ext 3: docs-demo-upgrade guide || User Extension Repository
Frequently Asked Questions: FAQs
Tutorial: Grid (php/mysql/json) , Application Design and Structure || Extensions: MetaGrid, MessageWindow
IIS7 configuration to support JSON
IIS7 configuration to support JSON:Using IIS manager: clock on IIS server (the main node on the left - where you see the machine name)
- Add ‘json’ MIME Type
File name extension: .json
- Double click on ‘MIME Types’ icon
- Click ‘Add…’ link (under Actions section on the right side)
- In ‘Add MIMI Type’ window type:
MIME type: application/x-javascript
- Click OK, You should see the .json MIME Type added to the list of the MIME Types list.
Request path: *.json
- Double click on ‘Handler Mappings’ icon
- Click on ‘Add Script Map…’ link (under Actions section on the right side)
- In ‘Add Script Map’ window type:
IIS6 configuration to support JSON:
Using IIS manager
Extension: .json
- Add ‘json’ MIME Type
- On the main IIS server right click and select ‘Properties’
- From ‘Properties’ window in ‘MIME Types’ section click on ‘MIME Types’ button.
- From ‘MIME Types’ window click on ‘New…’ button
- In ‘MIME Type’ window type:
MIME type: application/x-javascript
2. Add Application Extension for ‘json’ MIME Type- On the ‘Default Web Site’ (or the site where you want to enable json for) right click and select ‘Properties’.
- Click OK, You should see the .json MIME Type added to the list of the MIME Types.
- Click OK to the ‘MIME Types’ window
- Click OK to ‘Properties’ window
- From ‘Properties window’ select ‘Home Directory’ tab if not selected.
- Click on ‘Configuration…’ button.
- From ‘Application Configuration’ window select ‘Mappings’ tab if not selected.
- From ‘Mapping’ tab click ‘Add…’ button.
- In ‘Add\Edit Application Extension Mapping’ window type:Executable: C:\WINDOWS\system32\inetsrv\asp.dll
Extension: .json
Select ‘All verbs’ on ‘Verbs’ radio button selection.
Check ‘Script engine’ and ‘Verify that file exist’ check boxes then click OK, You should see the .json extension added to the list of Application extensions.
- Click ‘OK’ to ‘Application Configuration’ window this will open ‘Inheritance Overrides’ window click ‘OK’ then click ‘OK’ on the Properties window.Important Note:
Make sure you have Active Server Pages Allowed in the Web Service Extensions section of your IIS configuration.
IIS6:
IIS6 Manager -> (local computer) -> Web Service Extensions -> Active Server Pages
Then click ‘Allow’ button.
IIS7:
1. from IIS7 manager click on the computer name item on the left
2. click on “ISAPI and CGI Restrictions” icon (in IIS section)
3. the “ISAPI and CGI Restrictions” window will show then make sure the ‘Restriction’ for ‘Active Server Pages’ is ‘Allowed’
IIS 5.1 Disabled OK button
I hope I can save someone a few minutes of searching by this little helpful tip on adding the mime type to IIS 5.1.
I was could not get the OK button to become enabled, then I found a this . Bassically if you enter all the information and then click on the file name or just click on the file name at any point and the OK button will be enabled.
anyone using visual studio's built-in development server as an environment?
i use visual web developer 2005 express edition - just wondering if these kinda issues will be resolved if i use the non-free 2008 version
If you're using the asp.net development server, you may need to add a custom HttpHandler for the .json files in the examples.
Here is an example of an HttpHandler class which you would place in the App_Code folder. After adding the httphandler class to the App_Code folder, an entry for the handler is required in the web.config file.
C#
Code:
using System; using System.Web; public class JSONHandler: IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.Write(System.IO.File.ReadAllText(context.Request.PhysicalPath)); } public bool IsReusable { get { return false; } } }
Code:
Imports Microsoft.VisualBasic Public Class JSONHandler Implements IHttpHandler Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable Get Return False End Get End Property Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest context.Response.Write(System.IO.File.ReadAllText(context.Request.PhysicalPath)) End Sub End Class
Code:
<httpHandlers> <add verb="*" path="*.json" validate="false" type="JSONHandler" /> </httpHandlers>
json and IIS7 layout_browser.js
hello,
i add the json type mime in my iis7, but it was not working
the funny thing , that i was abble to read the tree-data.json file via http//.../tree-data.json
i discover under firebug that the call to this file was in "POST" mode, & i was getting :
II7 7.0 Detailled error 405.0 Method Not Allowed
I add in the layout-browser.js line 58 : "requestMethod : "GET"
loader: new Ext.tree.TreeLoader({
dataUrl:'tree-data.json',
requestMethod : "GET"
}),
By that way the tree-data.json is read and the data are displayed in the tree panel
Is this "POST" method is normal when calling a static file??
I am just discovering EXT , and congratulations for this very usefull product, .. but a beat difficult to enter in.
RegardsPhilippe
If on IIS 7, what would you do for step 2? the asp.net dll does not exist in that directory. | https://www.sencha.com/forum/showthread.php?33266-Some-Problem-with-JSON&p=229858&viewfull=1 | CC-MAIN-2015-22 | refinedweb | 1,050 | 56.15 |
Unit testing C# in .NET Core using dotnet test and xUnit
This tutorial takes you through an interactive experience building a sample solution step-by-step to learn unit testing concepts. If you prefer to follow the tutorial using a pre-built solution, view or download the sample code before you begin. For download instructions, see Samples and Tutorials.
Creating the source project
Open a shell window. Create a directory called unit-testing-using-dotnet-test to hold the solution.
Inside this new directory, run
dotnet new sln to create a new solution. Having a solution
makes it easier to manage both the class library and the unit test project.
Inside the solution directory, create a PrimeService directory. The directory and file structure thus far should be as follows:
/unit-testing-using-dotnet-test unit-testing-using-dotnet-test.sln /PrimeService
Make PrimeService the current directory and run
dotnet new classlib to create the source project. Rename Class1.cs to PrimeService.cs. To use test-driven development (TDD), you first-dotnet-test directory.
Run the dotnet sln command to add the class library project to the solution:
dotnet sln add .\PrimeService\PrimeService.csproj
Creating the test project
Next, create the PrimeService.Tests directory. The following outline shows the directory structure:
/unit-testing-using-dotnet-test unit-testing-using-dotnet-test.sln /PrimeService Source Files PrimeService.csproj /PrimeService.Tests
Make the PrimeService.Tests directory the current directory and create a new project using
dotnet new xunit. This command creates a test project that uses xUnit as the test library. The generated template configures the test runner in the PrimeServiceTests.csproj file similar to the following code:
<ItemGroup> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" /> <PackageReference Include="xunit" Version="2.2.0" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" /> </ItemGroup>
The test project requires other packages to create and run unit tests.
dotnet new in the previous step added xUnit and the xUnit runner. shows the final solution layout:
/unit-testing-using-dotnet-test unit-testing-using-dotnet-test.sln /PrimeService Source Files PrimeService.csproj /PrimeService.Tests Test Source Files PrimeServiceTests.csproj
To add the test project to the solution, run the dotnet sln command in the unit-testing-using-dotnet-test directory:
dotnet sln add .\PrimeService.Tests\PrimeService.Tests.csproj
Creating the first test
The TDD approach calls for writing one failing test, making it pass, then repeating the process. Remove UnitTest1.cs from the PrimeService.Tests directory and create a new C# file named PrimeService_IsPrimeShould.cs. Add the following code:
using Xunit; using Prime indicates a test method that is run by the test runner. From the PrimeService.Tests folder, execute
dotnet test to build the tests and the class library and then run the tests. The x. Replace the existing
IsPrime method implementation with the following code:
public bool IsPrime(int candidate) { if (candidate == 1) { return false; } throw new NotImplementedException("Please create a test first"); }
In the PrimeService.Tests those cases as new tests with the
[Fact] attribute, but that quickly becomes tedious. There are other xUnit attributes that enable you to write a suite of similar tests:
[Theory]represents a suite of tests that execute the same code but have different input arguments.
[InlineData]attribute specifies values for those inputs.
Instead of creating new tests, apply these two attributes,
[Theory] and
[InlineData], to create a single theory in the PrimeService_IsPrimeShould.cs file. The theory is a method that tests several values less than two, again, and two of these tests should fail. To make all of the tests pass, change the
if clause at the beginning of the
IsPrime method in the PrimeService.cs file:
if (candidate < 2)
Continue to iterate by adding more tests, more theories, and more code in the main library. You have the finished version of the tests and the complete implementation of the library. | https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test | CC-MAIN-2019-04 | refinedweb | 646 | 50.33 |
Atmega328 has one 16 bit timer which is more powerful comparing to 8 bit timers. 16 bit timer is called Timer/Counter1. Counter1 has twice more bits than 8 bit Counter0, so you get more counts leading to longer duration and more precise timings.
16 bit timer has pretty same functionality as Timer0 plus more specific ones. We won’t be discussing Normal, CTC, fast PWM and correct phase PWM modes as these are equivalent to Timer0. But lets focus on fresh things. There we have a new module called Input Capture Unit along with Input Capture Flag (ICF1) interrupt and new waveform generating mode called Phase and Frequency Correct PWM.
Dealing with 16 bit registers
Working with 16 bit timer means dealing with 16 bit registers:
- TCNT1: [TCNT1H and TCNT1L] – Timer/Counter1;
- OCR1A: [OCR1AH and OCR1AL] – Output Compare Register 1 A;
- OCR1B: [OCR1BH and OCR1BL] – Output Compare Register 1 B;
- ICR1: [ICR1H and ICR1L] – Input Capture Register 1
As AVR is 8 bit microcontroller it has an 8 bit bus structure. So whole 16 bit number cant be stored at once. When programming in C you can usually write 16 bit number in simple manner like this:
OCR1A=0x2564;
Compiler will sort this out automatically. But if you need to write separate bytes of 16 register then you need to write high byte first and then low:
OCR1AH=0x25; OCR1AL=0x64;
This is because 16 bit registers share one special TEMP register allowing to write 16 bit value at once, but using two clock cycles. If you need to read 16 bit register first has to be low byte and then high.
Power of Input Capture unit
Input capture functionality is special feature of 16 timer. It gives a new way of using timer. It is using external signal on ICP1 pin (or comparator output) to save current counter value to Input Capture Register ICR1 and generate interrupt (ICF1) of event.
In this very simplified diagram you can see how it works. What this is is good for? Actually this functionality is used a lot when you need to measure signal frequency, duty cycle. Schema is simple – save ICR1 at least two register values when calling interrupts and then calculate what ever you want. Be sure to save Input Capture Register Value before another event occurs as it will overwrite current value.
Input capture may be triggered by rising or falling edge and even noise canceler may be used to make sure signal is real. Ok, its time for example. Lets measure the duty cycle of signal fed in to ICP1 pin.
So we are going to capture three time-stamps needed to calculate duty cycle. One pair for measuring signal at level “1” and second pair of times-tamps to measure signal period. Seams easy. But there are some hidden stones. First one – what if signal frequency is to big. In this case we cannot do much in software level – just external frequency dividers would help. Second problem is when signal is too slow and one full timer count-up may not be enough. Here we can find a solution by introducing software counter to keep timer overflow counts. So we are going to deal with two interrupts that may overlap. Lets see how it goes:
#include <avr/io.h> #include <avr/interrupt.h> //Counts overflovs volatile uint16_t T1Ovs1, T1Ovs2; //Variables holding three timestamps volatile uint16_t Capt1, Capt2, Capt3; //capture Flag volatile uint8_t Flag; //Initialize timer void InitTimer1(void) { //Set Initial Timer value TCNT1=0; //First capture on rising edge TCCR1B|=(1<<ICES1); //Enable input capture and overflow interrupts TIMSK1|=(1<<ICIE1)|(1<<TOIE1); } void StartTimer1(void) { //Start timer without prescaller TCCR1B|=(1<<CS10); //Enable global interrutps sei(); } //capture ISR ISR(TIMER1_CAPT_vect) { if (Flag==0) { //save captured timestamp Capt1=ICR1; //change capture on falling edge TCCR1B&=~(1<<ICES1); //reset overflows T1Ovs2=0; } if (Flag==1) { Capt2=ICR1; //change capture on rising edge TCCR1B|=(1<<ICES1); //save first overflow counter T1Ovs1=T1Ovs2; } if (Flag==2) { Capt3=ICR1; //stop input capture and overflow interrupts TIMSK1&=~((1<<ICIE1)|(1<<TOIE1)); } //increment Flag Flag++; } //Overflow ISR ISR(TIMER1_OVF_vect) { //increment overflow counter T1Ovs2++; } int main(void) { //dutycycle result holder volatile uint8_t DutyCycle; InitTimer1(); StartTimer1(); while(1) { //calculate duty cycle if all timestamps captured if (Flag==3) { DutyCycle=(uint8_t)((((uint32_t)(Capt2-Capt1)+((uint32_t)T1Ovs1*0x10000L))*100L) /((uint32_t)(Capt3-Capt1)+((uint32_t)T1Ovs2*0x10000L))); //send Duty Cycle value to LCD or USART //clear flag Flag=0; //clear overflow counters; T1Ovs1=0; T1Ovs2=0; //clear interrupt flags to avoid any pending interrupts TIFR1=(1<<ICF1)|(1<<TOV1); //enable input capture and overflow interrupts TIMSK1|=(1<<ICIE1)|(1<<TOIE1); } } }
You can see in example that measuring of DutyCycle practically doesn’t depend on frequency – well at some range. If running an MCU at 16 MHz then measured waveform period can range from about 1µs or less up to several seconds considering that 16 bit interrupt counter can have max 65536 values. I don’t say that this algorithm is effective or good for any reasons. If you actually know the range of PWM frequency you can do way better approach. This example is just to represent how input capture mode works.
Phase and frequency correct PWM
This may sound a little scary but this mode is really easy to understand. We talked a bit about Phase correct PWM for Timer0. The main difference between phase correct and phase and frequency correct PWM is where the compare values and top values are updated. In phase correct mode these values were updated when counter reaches TOP value. In phase and frequency correct mode TOP values and compare values are updated when counter reaches BOTTOM. This way wave form gets symmetrical in all periods. In this mode TOP value can be defined in two ways by ICR1 register, which is free in this mode, or OCR1A. Usually it is better to use ICR1 register – then you have free OCR1A register to generate waveforms. But if you need to change PWM frequency pretty fast then use OCR1A because it is double buffered. Lowest TOP value can be 3 while highest 0xFFFF. Lets make simple example of phase and frequency correct mode. We will generate 500Hz PWM – non inverted on OC1A and inverted on OC1B pins.
#include <avr/io.h> void InitPort(void) { //Init PB1/OC1A and PB2/OC1B pins as output DDRB|=(1<<PB1)|(1<<PB2); } void InitTimer1(void) { //Set Initial Timer value TCNT1=0; //set non inverted PWM on OC1A pin //and inverted on OC1B TCCR1A|=(1<<COM1A1)|(1<<COM1B1)|(1<<COM1B0); //set top value to ICR1 ICR1=0x00FF; //set corrcet phase and frequency PWM mode TCCR1B|=(1<<WGM13); //set compare values OCR1A=0x0064; OCR1B=0x0096; } void StartTimer1(void) { //Start timer with prescaller 64 TCCR1B|=(1<<CS11)|(1<<CS10); } int main(void) { InitPort(); InitTimer1(); StartTimer1(); while(1) { //do nothing } }
This is it with 16-bit timer. Its only a fraction of what timer can do. I bet you can run other modes by your own now. So keep practicing. Codes to download are here[25KB].
You can’t disable interrupts within an ISR. The final RETI instruction will set the global I bit.
Would you like me to act as a reviewer for your material? I’d be happy to help. I truly appreciate your efforts with the tutorials.
Pingback: Electronics-Lab.com Blog » Blog Archive » Programming 16 bit timer on Atmega328
Yep – somehow I missed that. Anyway I was thinking of doing DutyCycle calculations inside ISR(TIMER1_CAPT_vect)interrupt – so disabling and enabling wouldn’t be an issue.
Reviewing would be great. Even a contributing – one person job leads to more errors.
Corrected the code. Instead disabling interrupts I stooped timer until Duty cycle is calculated. Then timer is started again.
I don’t think that will work. You are stopping the Timer1 clock but this does not stop CLKio, so the IC edge detectors will still operate and generate interrupts. The conventional approach is to disable the IC interrupt instead (ICIE1).
(my last comment disappeared?)
Disabling the Timer1 clock is not the same as disabling the interrupt. The Input Capture edge detectors operate from CLKio, which keeps going. The conventional approach is to enable/disable the Input Capture Interrupt.
(my last comment disappeared?) – Could be captcha problem. Somehow it was disabled automatically as some other comments.
Thank you for finding this error. It really keeps interrupting and capturing timestamps of stopped timer what leads to wrong calculations. Just disabled TIMER1_CAPT interrupts to avoid this.
Just curious. Are you finding these tutorials useful and clear enough? Feel free to add suggestions where to pay more attention to: explanations, technical details, code examples.
Personally, I don’t need your tutorials, but if someone else is going to the considerable effort to write them then I’m happy to lend my experience to the process. I’m fortunate in having been into embedded software as a career for many years, and have already fallen into all the usual pit-falls!
Incidentally, in your corrected code, you can remove the redundant Timer clock disables/enables (apart from the initial one), but just before you re-enable the interrupt you should clear the ICF1 flag by writing to TIFR1. This is because you will probably have an ‘old’ interrupt pending that you want to ignore.
These pit-falls is probably most important part when learning. Your experience is invaluable here. I hope you will keep an eye in future.
Regarding corrections. I left Timer running but disabled the capture and overflow interrupts. After calculus done cleared interrupt flags in case any presence of them and re-enabled interrupts. This should work. I understand that program layout isn’t the best but this intended to be only to show how input capture works.
You shouldn’t use a read-modify-write for the timer interrupt flags register (for exactly the same reason as with PIN registers). You may clear flags that you didn’t intend to, and although it won’t affect this example, it’s not good to leave a ‘trap’ set like this.
Sorry to be pedantic on things like this, but if people try to use this code for their own experiments, they will have problems if they try to extend the functionality at all.
Don’t be sorry. This is very important to do it right at the very beginning. This is what a tutorial is for. Gladly I’m also pulling some bad habits out.
Fixed. Thanks.
The duty cycle calculation really doesn’t need 64-bit integers. That one line causes the code to grow from ~500 bytes to ~5500 bytes!!! And I don’t think it will work since the casts are performed too late, which will therefore overflow the 16-bit multiply that will be implemented. Also, the overflows should be multiplied by 0x10000 instead of 0xFFFF.
It’s still not pretty, but this works and saves about 4.5kB of program space:
DutyCycle = (uint8_t)((((uint32_t)(Capt2 – Capt1) PLUS ((uint32_t)T1Ovs1 * 0x10000L)) * 100L) / ((uint32_t)(Capt3 – Capt1) PLUS ((uint32_t)T1Ovs2 * 0x10000L)));
I’ve used PLUS since they seem to get removed when posting.
Note: it is vital that the subtraction is performed in unsigned 16-bit math then cast to 32-bit – this then gives the right answer even when Capt1 is larger than Capt2.
I’m wandering why I casted to 64 bit values while keeping 32 bits in mind? Probably did this absently.
Tested your code with simulator -works OK. Thanks.
The Read-Modify-Write has crept back in on TIFR1 😉
Thanks. Copied wrong part 🙂
Pingback: AVR Timers for dummies | Scrapbook
am using this program to detect frequency and through GSM we are sending that frequency as message to mobile..but this program is not working for us.pls help us.
Hi
My name is Uema.
I’ve live in Okinawa in Japan.
May I indroduce Your Code My Home Page.
Your Input capture code very well.
Thank You.
(I can little speak Endlish. Easy Word Please! )
thanks capture was helpfully.
from iran | https://embedds.com/programming-16-bit-timer-on-atmega328/ | CC-MAIN-2019-09 | refinedweb | 2,006 | 64.3 |
std::clock
Returns the approximate processor time used by the process since the beginning of an implementation-defined era related to the program's execution. To convert result value to seconds divide it by CLOCKS_PER_SEC.
Only the difference between two values returned by different calls to std::clock is meaningful, as the beginning of the std::clock era does not have to coincide with the start of the program. std::clock time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system. For example, if the CPU is shared by other processes, std::clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, std::clock time may advance faster than wall clock.
[edit] Parameters
(none)
[edit] Return value
Processor time used by the program so far or (clock_t)(-1) if that information is unavailable.
[edit] Exceptions
(none)
[edit] Notes
On POSIX-compatible systems,
clock_gettime with clock id CLOCK_PROCESS_CPUTIME_ID offers better resolution.
The value returned by
clock() may wrap around on some implementations. For example, on a machine with 32-bit std::clock_t, it wraps after 2147 seconds or 36 minutes.
[edit] Example
This example demonstrates the difference between clock() time and real time
#include <iostream> #include <iomanip> #include <chrono> #include <ctime> #include <thread> // the function f() does some time-consuming work void f() { volatile double d = 0; for(int n=0; n<10000; ++n) for(int m=0; m<10000; ++m) d += d*n*m; } int main() { std::clock_t c_start = std::clock(); auto t_start = std::chrono::high_resolution_clock::now(); std::thread t1(f); std::thread t2(f); // f() is called on two threads t1.join(); t2.join(); std::clock_t c_end = std::clock(); auto t_end = std::chrono::high_resolution_clock::now(); std::cout << std::fixed << std::setprecision(2) << "CPU time used: " << 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC << " ms\n" << "Wall clock time passed: " << std::chrono::duration<double, std::milli>(t_end-t_start).count() << " ms\n"; }
Output:
CPU time used: 1590.00 ms Wall clock time passed: 808.23 ms | http://en.cppreference.com/w/cpp/chrono/c/clock | CC-MAIN-2015-32 | refinedweb | 351 | 51.38 |
I have an loop Angular JS:
angular.forEach($scope.message, function (item) {
return (item.id_user == input.id_user) ? true : false;
});
item
angular.forEach($scope.message, function (item, $index) {});
Sorry for all the vitriol of the community. You're very close to your solution but are a bit confused by documentation. It's okay, let me help clarify!
In the documentation for angular.forEach you will see the following statement:
Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.
And then the following example:
var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']);
Essentially, the code is like this:
angular.forEach('name of list/array you want to loop through', 'callback function to be called for each element of the list')
The important part that you're missing is that the 'callback...' mentioned above can be handed 3 variables which you can then use in your callback. Your callback will be called for each element in the list. Here is some explanation of those 3 variables:
Value: The value of the i-th element/property in the list/array/object
Key: i - the index belonging to the current item in the array
Object: the the object itself (or array/list itself)
Here is an example i put together for you where I use the Key to create a new string showing the index of each letter in $scope.message. Hope this helped! | https://codedump.io/share/EwDnor5jW0RY/1/how-to-get-index-of-array-element-in-loop | CC-MAIN-2017-04 | refinedweb | 305 | 56.76 |
Download presentation
Presentation is loading. Please wait.
Published byAyla Quincy Modified about 1 year ago
1
1 Threads (Extra Lecture) Developing MultiThreaded Application (Part III) Overview Waiting for Synchronized Data. Creating Thread Groups. Daemon Threads. Using Threads with Swing GUI Components: Things to Note. Preview: Sorting Algorithms (Part I).
2
2 Threads (Extra Lecture) Waiting for Synchronized Data We note that each method which may potentially cause a race condition (i.e. may be called by different threads before completion) should be declared synchronized. We also note that there are cases when synchronization is not enough; we must call some methods of the Thread class to help the situation. We exemplify: The classic example is the “producer/consumer” problem within which a producer and a consumer share data. When a thread arrives at a synchronized method and finds that it has arrived too early, the thread should wait (call the wait() method of Thread). Note that either the producer or the consumer thread might arrive too early. When a thread finished processing synchronized data, the thread calls notify()/notifyAll() to tell other threads to stop waiting. Using wait() and notify()/notifyAll() methods producer/consumer problems can be implemented properly. When a thread calls wait() inside a synchronized method/block, another method is allowed to access the code. What happens when an exception is thrown while a synchronized method is being executed?
3
3 Threads (Extra Lecture) Example 1: Waiting for Synchronized Data class Q { int n; boolean valueSet=false; synchronized int get () { if(!valueSet) try{wait();}catch(InterruptedException e){ } System.out.println("Got:"+n); valueSet=false; notify(); return n; } synchronized void put (int n) { if(valueSet) try{wait();}catch(InterruptedException e){} this.n=n; valueSet=true; System.out.println("Put:"+n); notify(); } } class Producer implements Runnable{ Q q; Thread th=new Thread(this, "Producer"); Producer(Q q){ this.q=q; th.start(); } public void run(){ int i=0; while(true){ q.put(i++); } Producer consumer
4
4 Threads (Extra Lecture) Example 1: Waiting for Synchronized Data (Cont’d) class Consumer implements Runnable{ Q q; Thread th=new Thread(this, "Consumer"); Consumer(Q q){ this.q=q; th.start(); } public void run(){ while(true){ q.get(); } public class PCproblem{ public static void main(String[] s){ Q q=new Q(); new Producer(q); new Consumer(q); System.out.println(“press Conrl-C to stop."); }
5
5 Threads (Extra Lecture) Thread Groups Guidelines for using thread groups: 1- Use the ThreadGroup constructor to construct a thread group: Construct a thread group using the ThreadGroup constructor: ThreadGroup g = new ThreadGroup("timer thread group"); This creates a thread group g named”thread group”. The name is a string and must be unique. 2- Place a thread in a thread group using the Thread constructor: Thread t = new Thread(g, new ThreadClass(), "This thread"); The statement new ThreadClass() creates a runnable instance for the ThreadClass. You can addd a thread group under another thread group to form a tree in which every thread group except the initial one has a parent. 3- To find out how many threads in a group are currently running, use the activeCount( ) method: System.out.println("The number of “ + “ runnable threads in the group + g.activeCount() ); 4- Each thread belongs to a thread group.By default, a newly created thread becomes a member of the current thread group that spawned it. To find which group a thread belongs to, use the getThreadGroup() method. Note:You have to start the each thread individually. There is no start() method in ThredGroup!!!
6
6 Threads (Extra Lecture) Creating a Thread Group Within your Java program, there may be times when you have multiple threads working on a similar task. In such cases, you may find it convenient to group threads by type, which then allows you to manipulate the group as a single entity. For example, suppose you have a number of animation threads that you need to pause based on user input. You can group these threads into a single-thread group and then suspend all with one function call. Class ThreadGroup has methods for creating and manipulating thread groups. This class provides the constructors: public ThreadGroup(String groupName) Constructs a ThreadGroup with name groupName. public ThreadGroup(ThreadGroup parent, String child) Constructs a child ThreadGroup of parent called child The second constructor above shows that a thread group can be the parent thread group to a child thread group. The following example demonstrate the use of some methods of the ThreadGroup class.
7
7 Threads (Extra Lecture) Thread Groups: A Pictorial View
8
8 Threads (Extra Lecture) Example 2: Printing All Progams’ Threads This program prints all active threads. It uses the getThreadGroup() method of java.lang.Thread and getParent() method of java.lang.ThreadGroup to walk up to the top level thread group; then using enumerate to list all the threads in the main thread group and its children (which covers all thread groups). public class AllThreads { public static void main(String[] args) { ThreadGroup top = Thread.currentThread().getThreadGroup(); while(true) { if (top.getParent() != null) top = top.getParent(); else break; } Thread[] theThreads = new Thread[top.activeCount()]; top.enumerate(theThreads); for (int i = 0; i < theThreads.length; i++) { System.out.println(theThreads[i]); } } }
9
9 Threads (Extra Lecture) Daemon Threads A daemon thread is a thread that runs for the benefit of other threads. A typical example of a daemon thread in Java is the garbage collector. Daemon threads run in the background (I.e., when processor time is available that would otherwise go to waste). Unlike other threads, if daemon threads are the only threads that are running, the program will exit because the daemons have no other threads to serve. Non-daemon threads are conventional user threads. Depending on your program’s purpose, there may be times when you need to create your own daemon threads. In such cases you use the method call myThread.setDaemon(true) to designate myThread as daemon. If a thread is to be a daemon, it must be set as such before its start() method is called or an IllegalThreadStateException is thrown.
10
10 Threads (Extra Lecture) Using Threads with Swing GUI Components Having demonstrated the use of the synchronized keyword and the wait(), notify() methods, we are now ready to comment on threads and swing components. Note that event-handling code executes in a single thread, the event-dispatching thread. This ensures that each event handler will finish executing before the next one executes. For instance, while the actionPerformed() method is executing, the program's GUI is frozen -- it won't repaint, respond to mouse clicks or respond to any other event. This suggests that the code in event handlers should execute very quickly otherwise your program's perceived performance will be poor. What happens in a program in which one event handler calls an infinite method? Most methods in the Java Swing API are not thread-safe and, therefore, care should be taken when using these methods. For this reason Swing components can be accessed by only one thread at a time, generally, the event-dispatching thread. However, a few operations are guaranteed to be thread-safe.
11
11 Threads (Extra Lecture) Using Threads with Swing GUI Components (Cont’d) Therefore, if your program creates threads to perform tasks that affect the GUI, or if it manipulates the already-visible GUI in response to anything different from the standard events, then things can go wrong. To access to a GUI from outside event-handling or painting code, you can use the invokeLater() or invokeAndWait() methods of the SwingUtilities class. An applet program that construct its GUI in the init() method is said to be doing it in “the right way”. This is because existing browsers don't paint an applet until after its init() and start() methods have been called. Likewise an application program that creates its GUI in the main() method (creates the GUI, adds components to it and show() s it only) is said to be doing GUI in “the right way”. A program that creates and refers to its GUI the right way, might not need to worry about safety issues due to threads. We’ll exemplify these issues in the lab.
Similar presentations
© 2017 SlidePlayer.com Inc. | http://slideplayer.com/slide/3801468/ | CC-MAIN-2017-09 | refinedweb | 1,376 | 64 |
On 04/24/2012 12:32 AM, Greg Ewing wrote: > Dag Sverre Seljebotn wrote: > >> I'm excited about Julia because it's basically what I'd *like* to >> program in. My current mode of development for much stuff is Jinja2 or >> Tempita used for generating C code; Julia would be a real step forward. > > It looks interesting, but I have a few reservations about > it as it stands: > > * No modules, just one big global namespace. This makes it > unsuitable for large projects, IMO. As far as I know it seems like namespaces are on their TODO-list. But of course, that also means it's undecided. > * Multiple dispatch... I have mixed feelings about it. When > methods belong to classes, the class serves as a namespace, > and as we all know, namespaces are a honking great idea. > Putting methods outside of classes throws away one kind of > namespace. Well, there's still the namespace of the argument type. I think it is really a syntactic rewrite of obj->foo(bar) to foo(obj, bar) If Julia gets namespace support then the version ("method") of "foo" to use is determined by the namespace of obj and bar. And in Python there's all sorts of problems with who wins the battle over __add__ and __radd__ and so on (though it's a rather minor point and not something that by itself merits a new language IMO...). > * One-based indexing? Yuck. I suppose it's what Fortran and > Matlab users are familiar with, but it's not the best > technical decision, IMO. > > On the plus side, it does seem to have a very nice and > unobtrusive type system. > >> the next natural step is to implement Python in Julia, with CPython >> C-API compatability. Which would be great. > > That would indeed be an interesting thing to explore. Dag | https://mail.python.org/pipermail/cython-devel/2012-April/002377.html | CC-MAIN-2016-40 | refinedweb | 304 | 71.34 |
better code for try and catch
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
posted
Mar 05, 2005 08:13:00
0
I have the following code using the try { } and catch { } statements:
//method to allow the contents of accNo to change to store a different String value, if required public void setAccNo (String accountNo) { //ensure accountNo contains only numbers up to a maximum of 8 digits; and convert to one if true String inputAccountNo = accountNo; int i = -1; try { i = Integer.parseInt(accountNo); System.out.println("The value of i = "+i); //ensure accountNo contains no more than 8 digits; assuming 8 digits is the size used for account number int num = 9999; if (i > num) { System.out.println("Account Number: "+inputAccountNo + " is NOT valid as greater than num"); }//end if }//end try catch (NumberFormatException e) { System.out.println("Account number: "+inputAccountNo +" Invalid. Must contain numbers only and be no more than 8 digits"); //cannot continue without a valid account number so program stops if System.exit ()put in //don't wish to execute the program so left System.exit( ) out completely inputAccountNo = "Invalid Account Number"; }//end catch System.out.println("inputAccountNo: = "+inputAccountNo); this.accountNo = inputAccountNo; }//end method setAccNo
Could someone tell me if I have implemented this the best way? Expecially with the if statement in the try { }
Thanking you in advance!
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
Mar 05, 2005 08:32:00
0
At a quick glance it looks like a great start. The try-catch around a parseInt is a very simple and reliable way to validate a number.
Where is your input coming from? If it's a console app you might let the user try again, maybe in a loop that runs until it gets a good account number.
acctNumber = ""; while !validateAcctNumber(acctNumber) display "enter account number" acctNumber = readConsole() end use the acctNumber
That particluar loop would show an error message before the user enters the first time. I'll let you figure out how to avoid that.
The "num = 9999" bit could be moved up to a constant. It's common to see something like this - all caps is a convention for constants.
public static final int ACCT_NUM_MAX = 9999;
It's easier to find in the future and other methods could include the value in prompts or instructions, eg "Enter an account number between 1 and " + ACCT_NUMBER_MAX.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
posted
Mar 05, 2005 09:20:00
0
Many thanks for your reply post
The input is coming from a TestFile at the moment so I have no need to implement a While loop as only one account number to validate. (Thanks for mentioning it though).
I particuly liked the constant value; never thought of that.
Thanks again!
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
posted
Mar 05, 2005 09:40:00
0
Just another quick question:
Why would you declare a constant public static final ACCT_NUMBER_MAX?
I understand that static means ACCT_NUMBER_MAX would be that amount throughout the program and final means it can't be changed. So why both?
M Beck
Ranch Hand
Joined: Jan 14, 2005
Posts: 323
posted
Mar 05, 2005 10:44:00
0
because the very phrase ACCT_NUMBER_MAX tells you something useful when you're reading the code - namely, "this means the highest account number possible" - which just plain the number itself wouldn't tell you.
also, you might be using ACCT_NUMBER_MAX in a lot of places in the code. then, if it should ever happen that you want to change it, you just need to change the definition of ACCT_NUMBER_MAX in one place, instead of chasing down each instance of the number itself and hope you catch them all.
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
posted
Mar 05, 2005 11:23:00
0
M Beck, thank you for your response.
Unfortunately, I don't think my response was very clear.
I'm happy about declaring a constant.
What I'm a little vague with is declaring a constant both:
static AND final?
My understanding is static ensures the same value is used throughout.
My understanding is final ensures the value can't be changed.
So why declare a constant both i.e. static AND final?
Steven Bell
Ranch Hand
Joined: Dec 29, 2004
Posts: 1071
posted
Mar 05, 2005 11:42:00
0
static only means that there is one reference per Class as instead of one reference per Instance. It does not stop you from changing the object that the reference points to. final stops you fram changing what the reference points to, but it does not stop you from modifying the contents of the reference.
example:
public static String static1 = "Hello"; public static final String staticFinal1 = "Goodbye"; public static final char[] staticFinalArray = {'A', 'B', 'C'}; static1 = staticFinal1;//legal static1 now = "Goodbye" staticFinal1 = static1;//comiple error staticFinalArray[1] = 'D';//legal, staticFinalArray now contains A, D, C
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
I like...
posted
Mar 05, 2005 11:42:00
0
As M Beck discusses, the reason for the final is so it does not get changed in any code. Attempts to do so will result in a compile time error. As for the static, the static doesn't mean so much that it is used "throughout the program" (that would be a loose interpretation). It ultimately means that only a single instance of that variable is created in memory.
Lets say I an object MyThing, and we want to define a constant MAX_VALUE in MyThing. So I do the following:
public class MyThing { public final int MAX_VALUE = 6789; }
If my program creates 1000 instances of MyThing, there will be 1000 separate int's created in memory, all holding the same value (and since they are final, none can be changed). Each will have a single reference pointer to it (the MAX_VALUE of each of the 1000 MyThing instances). This seems like a waste of memory since they are all holding the same value. If however, I change that to a static attribute:
public class MyThing { public static final int MAX_VALUE = 6789; }
Now, whether I create 1, 1000, or 1 million instances of MyThing, only one int is stored in memory. Therefore I am saving memory space (and I
believe
improving performance slightly, but I'm not sure on that.)
The other advantage of a static attribute, is I do not need to instantiate an instance of the object in order to access its value. So if somewhere else in my program I need to know the MAX_VALUE for MyThing, I can write MyThing.MAX_VALUE as in:
if (value < MyThing.MAX_VALUE) //ok since MAX_VALUE is static
instead of having to go thorough the expensive process of creating an instance of the object first:
MyThing thing = new MyThing(); if (value < thing.MAX_VALUE) //this would be necessary if MAX_VALUE was not static
So in the above case, since we are declaring something as final, such that it will not change, and we therefore know each instance will have the same value, why not make it static to save memory, and make it available without needing to instantiate an object?
There are times where you will make an attribute static without making it final. Let's say I have an object for which I know a specific attribute will be the same for each instance of the object, but it may change (and thus is not final). For example, if I have a BankAccount class with an "interestRate" attribute. I want all instances of my BankAccount object to have the same interest rate, but that rate changes daily. If I create a non-static attribute:
public class BankAccount { private double interestRate = 1.5; public void setInterstRate(double interestRate) { this.interestRate = interestRate; }
When the interest rate changes, I have to change the interestRate attribute for all instances of BankAccount. If there are thousands of instance, it becomes a very expensive process and lowers performance. (Not to mention I'm using a several thousand times more memory then I need to be since they all hold the same value).
However, if I make interestRate static:
public class BankAccount { private static double interestRate = 1.5; public static void setInterstRate(double theInterestRate) { interestRate = theInterestRate; } }
Now I can change the interest rate for all accounts, whether 1, 1000, or 1 million, in a single call:
BankAccount.setInterstRate(someClass.getTodaysPrimeRate + 0.5);
It is much less expensive, and thus better performance, to call a method one time then to call it 10 thousand, or 1 million times.
I hope that helps you to understand static and final and why we would make the constant both static and final in your code; and when you would make something only static.
[ March 05, 2005: Message edited by: Mark Vedder ]
Maureen Charlton
Ranch Hand
Joined: Oct 04, 2004
Posts: 218
posted
Mar 05, 2005 11:51:00
0
Steven Bell and Mark Vedder,
What can I say:
Excellent replys.
Extreemly clear. Thank you very much!
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
I like...
posted
Mar 05, 2005 12:02:00
0
By the way, the book
Head First
Java
does a great job of explaining these type of concepts. Check it out at the
publisher's site (Oreilly)
. Note, the 2nd edtion just came out, and if you do a search at Amazon by title or author, only the 1st edition is shown. You need to search by ISBN (0-596-00920-8) to get the second edition to come up.
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18671
posted
Mar 05, 2005 12:19:00
0
Note that
Bookpool
has no trouble locating the
correct edition
.
"I'm not back." - Bill Harding,
Twister
Mark Vedder
Ranch Hand
Joined: Dec 17, 2003
Posts: 624
I like...
posted
Mar 05, 2005 12:47:00
0
Jim,
Thanks for the link. I had not run across or heard of Bookpool before. I see their prices are a little better then Amazon's. I'll be taking a look at them in the future. I'm sure others will appreciate it as well.
-Mark
I agree. Here's the link:
subject: better code for try and catch
Similar Threads
Can't figure out why variable isn't recognized
Database file reader
Exceptions
Validation: check to see whether it is all integers
Sequential of 2 accounts file processing concurrently to update balance
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/398836/java/java/code-catch | CC-MAIN-2015-32 | refinedweb | 1,811 | 59.84 |
I am doing a simple exercise which asks me to implement a standalone 'map' function on a list using foldRight. And the solution I came up with is this:
def mapFun[T,U](xs: List[T], f: T => U): List[U] = {
(xs foldRight List[U]())((x, y) => f(x) :: y)
}
val sl = List(1,2,3)
//now try to square every item
mapFun(sl, x => x * x) //**missing parameter type**
mapFun(sl, (x:Int) => x * x) //ok, gives List(1,4,9)
As is denoted above an explicit 'Int' type must be specified for the code to compile. However it seems to me that the compiler should be able to infer the type of 'x' since 'sl' is of type 'List[Int]' which means T is 'Int' and then the 'x*x' expression's type U should also be 'Int'.
I guess it may have something to do with the variance or contra-variance kind of stuff or something where sub typing is mixed with generic typing..
My scala compiler version is 2.11 bundle (dynamics).
Supplement to the standard answer: From Functional Programming in Scala Chapter 3:
This is an unfortunate restriction of the Scala compiler; other functional languages like Haskell and OCaml provide complete inference, meaning type annotations are almost never required
Scala's type inference doesn't flow inside a parameter list, only between parameter lists. This will work:
def mapFun[T,U](xs: List[T])(f: T => U): List[U] = {
(xs foldRight List[U]())((x, y) => f(x) :: y)
}
val sl = List(1,2,3)
println(mapFun(sl)(x => x * x)) | http://jakzaprogramowac.pl/pytanie/59774,a-compiling-error-about-scala-type-inference | CC-MAIN-2017-43 | refinedweb | 265 | 51.21 |
Here is the code:
Code :
import java.util.Scanner; public class Problem2 { public static void main (String []args){ // Scanner Scanner scan = new Scanner(System.in); // Declorations double kilograms = 1; System.out.println("Kilograms\tPounds"); // For loop for (int i = 1; i <= 199; i += 2) { System.out.println(i + " " + i * 2.2); } } }
The answers give me two columns, but the problem is sometimes there are 10 zeros after the decimal so for the third answer it is 6.6000000000 etc. I just want to use one character after the decimal and I don't know how. I have tried the printf and using %d,f etc but that didn't work :/ | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/5587-how-format-printingthethread.html | CC-MAIN-2015-48 | refinedweb | 110 | 67.96 |
Central repository for user extensions?
Is there a place I can find all this great user extensions other than hunting for them in the forums and finding out which of the posts contains the latest version?
Not that I've seen. The only thing I know of summarizing them is at
API Search || Ext 3: docs-demo-upgrade guide || User Extension Repository
Frequently Asked Questions: FAQs
Tutorial: Grid (php/mysql/json) , Application Design and Structure || Extensions: MetaGrid, MessageWindow
I think, that Ext team should create separate svn repo for Ext.ux and strongly recommend to use it. To me has already bothered to try to discover updates in forum =(-= miu-miu =-
Linux, Perl, GNU, Open Source, Ajax, Ubuntu 9.04
- suggestion about "hunting" extensions on forum is to maintain it full list in wiki. But not as raw list, but make it browsable by namespace,like:
====main extensions page===
Ext.ux.panel -> link to Ext.ux.panel namespace list
Ext.ux.Store -> link to Ext.ux.Store namespace list
.....
Ext.ux.BadChosenUxName - link to particular extension page, with bad chosen name, coz generally each extension should include itself in some higher-level namespace (with some exceptions of course)
====main extensions page===
====Ext.ux.panel page ===
Ext.ux.panel.GMappanel -> link to Ext.ux.panel.GMappanel extension page
Ext.ux.panel.Youtubepanel -> link to Ext.ux.panel.Youtubepanel extension page
====Ext.ux.panel page ===
etc..
Think such method will not imply additional efforts for authors (they'll just maintain wiki page, not forum post) and also greatly structurized Ext.ux.* namespace
P.S. Such approach solves problem only in half, but it better then nothing. Of coz, right approach is to create sane JS archive network (there is openjsan.org but its dead project), but JS community is divided into framework clans (i can say even "tribes") and no one is interested in it.
I second having a Ext.ux repository, git or svn!
I think this would be something both devs and users here could appreciate
Any good free hostings of SVN or git repos?
It would be best if we could use a well-know provider in this area that is free. | https://www.sencha.com/forum/showthread.php?39743-Central-repository-for-user-extensions | CC-MAIN-2016-18 | refinedweb | 363 | 59.4 |
Turbolinks for Flask.
Project description
Turbolinks for Flask.
Turbolinks
Turbolinks makes following links in your web application faster. For more information, visit the original rails repo: turbolinks.js.
Installation
To install Flask-Turbolinks, simply:
$ pip install Flask-Turbolinks
Or alternatively if you don’t have pip:
$ easy_install Flask-Turbolinks
Usage
To enable turbolinks, you need to put turbolinks.js in the <head> of your html templates.
The backend flask app should be wrapped with turbolinks:
from flask import Flask from flask_turbolinks import turbolinks app = Flask(__name__) # you app should has a secret key for session app.secret_key = 'secret' turbolinks(app)
And everything works now, no more configuration.
Note
You can install the javascript code with component:
$ component install lepture/flask-turbolinks
You can also grab the code from turbolinks.js on GitHub. It is written in CoffeeScript, you can compile it with:
coffee -c turbolinks.js.coffee
Demo
There is a demo in the example directory, start a server and open the url with Chrome. View the requests with developer tools of Chrome.
Changelog
We keep the changelog on GitHub releases.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/Flask-Turbolinks/ | CC-MAIN-2019-04 | refinedweb | 204 | 67.96 |
This challenge was two parts, the first part was overflowing the buffer of size, and the second part was overwriting the return address with the address of winrar. Since there was no alsr and we are given the binary, the address can be hard coded.
The size needed to prime fill the stack up to the return address was
24 , so we sent 24 A's and the return address
Exploit
from pwn import * import time context(arch='amd64', os='linux') context.log_level = True binary = ELF('jumpy') competition = True if competition: conn = remote("wcscctf.org", 8484) else: conn = remote('localhost', 1234) def getInput(): print conn.recvline() def sendPayload(): #no aslr winAddress = p64(0x400636) filler = 'a'*24 payload = filler + winAddress #test the payload in gdb to see if it overwrote registers with open('payload', 'w') as f: f.write(payload) conn.sendline(payload) time.sleep(1) print conn.recvline() + conn.recvline() if __name__ == "__main__": getInput() sendPayload() | https://paxson.io/200-wcscctf-jumpy/ | CC-MAIN-2021-49 | refinedweb | 155 | 54.42 |
Action Method Return Type
In the previous section, you learned about parameter binding with Web API action method. Here, you will learn about the return types of action methods which in turn will be embedded in the Web API response sent to the client.
The Web API action method can have following return types.
- Void
- Primitive type or Complex type
- HttpResponseMessage
- IHttpActionResult
Void
It's not necessary that all action methods must return something. It can have void return type.
For example, consider the following Delete action method that just deletes the student from the data source and returns nothing.
public class StudentController : ApiController { public void Delete(int id) { DeleteStudentFromDB(id); } }
As you can see above Delete action method returns void. It will send 204 "No Content" status code as a response when you send HTTP DELETE request as shown below.
Primitive or Complex Type
An action method can return primitive or other custom complex types as other normal methods.
Consider the following Get action methods.
public class Student { public int Id { get; set; } public string Name { get; set; } } public class StudentController : ApiController { public int GetId(string name) { int id = GetStudentId(name); return id; } public Student GetStudent(int id) { var student = GetStudentFromDB(id); return student; } }
As you can see above, GetId action method returns an integer and GetStudent action method returns a Student type.
An HTTP GET request
will return following response in Fiddler.
An HTTP GET request
will return following response in Fiddler.
HttpResponseMessage
Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API request/response pipeline.
Visit Web API HTTP Message Life Cycle Poster for more details.
As you can see in the above figure, the Web API controller returns HttpResponseMessage object. You can also create and return an object of HttpResponseMessage directly from an action method.
The advantage of sending HttpResponseMessage from an action method is that you can configure a response your way. You can set the status code, content or error message (if any) as per your requirement.
public HttpResponseMessage Get(int id) { Student stud = GetStudentFromDB(id); if (stud == null) { return Request.CreateResponse(HttpStatusCode.NotFound, id); } return Request.CreateResponse(HttpStatusCode.OK, stud); }
In the above action method, if there is no student with specified id in the DB then it will return HTTP 404 Not Found status code, otherwise it will return 200 OK status with student data.
For example, an http GET request
will get following response considering student with id=100 does not exists in the DB.
The same way, an HTTP GET request
will get following response considering student with id=1 exists in the database .
IHttpActionResult
The IHttpActionResult was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.
You can create your own class that implements IHttpActionResult or use various methods of
ApiController class that returns an object that implement the IHttpActionResult.
public IHttpActionResult Get(int id) { Student stud = GetStudentFromDB(id); if (stud == null) { return NotFound(); } return Ok(stud); }
In the above example, if student with specified id does not exists in the database then it will return response with the status code 404 otherwise it sends student data with status code 200 as a response. As you can see, we don't have to write much code because NotFound() and Ok() method does it all for us.
The following table lists all the methods of ApiController class that returns an object of a class that implements IHttpActionResult interface.
Visit MSDN to know all the members of ApiController.
Create Custom Result Type
You can create your own custom class as a result type that implements IHttpActionResult interface.
The following example demonstrates implementing IHttpActionResult class.
public class TextResult : IHttpActionResult { string _value; HttpRequestMessage _request; public TextResult(string value, HttpRequestMessage request) { _value = value; _request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage() { Content = new StringContent(_value), RequestMessage = _request }; return Task.FromResult(response); } }
Now, you can return TextResult object from the action method as shown below.
public IHttpActionResult GetName(int id) { string name = GetStudentName(id); if (String.IsNullOrEmpty(name)) { return NotFound(); } return new TextResult(name, Request); } | https://www.tutorialsteacher.com/webapi/action-method-return-type-in-web-api | CC-MAIN-2022-21 | refinedweb | 711 | 53.41 |
I installed the Developer runtime, which incidentally is LinkID=150227 for Mac. In any case, I got my Converter recognized as a .NET type; however I couldn't get passed the AG_E_PARSER_BAD_TYPE error when loading the converter reference in XAML. I initially thought there may be some namespace issue, but I can see the Converter is reflecting it's correct namespace, and the XML namespace seems to match too. I tried importing my converted in App.py before the XAML is loaded to see if that would put it in scope, but that didn't work either. I'm not sure what to try next? Anyone have any ideas? On Jan 20, 2010, at 3:12 AM, Jimmy Schementi wrote: >> I took a simple converter and ported it to IronPython, however >> I'm getting the ever helpful SystemError 2255. > > Do you have the Silverlight "Developer" runtime? The "Consumer" runtime give you only error codes, while the developer runtime gives you actual exception messages. Here's the developer runtime: > > >> I can manually import my converter class via the REPL, and do a dir on it too. >> Which leads me to believe there's another issue I'm unaware of. >> Perhaps it's not supported? Has anyone else tried implementing a >> converter in IronPython yet? > > IValueConverter is an interface that allows you to make custom data conversions that happen during data binding in XAML:. However, IronPython doesn't directly support data binding in Silverlight, since Python classes are not 1-to-1 with CLR classes. The XAML required to hook up a converter (Converter={StaticResource FormatConverter}) won't be able to find a FormatConverter class defined in IronPython either, since the name is auto-generated. So, you'll be able to interact with your Python classes from the REPL, but they will fail to be used in XAML (if you use the developer runtime you'll probably see an error in the XAML parser ... which unfortunately also gives cryptic error msgs =P) > > There are two ways to wire this up: > > (1) Use clrtype.py to control the CLR type, properties, etc, that the IronPython class generates. Lukáš Čenovský recently showed that you can do data-binding with this in Silverlight: > > (2) Have anything your XAML needs to reference as a C# stub (defining all things requiring static references, including properties and methods), which your Python class inherits from and defines the actual behavior. > > I suggest #1 as it's a more elegant solution, but #2 will work as a good safety net if you encounter something that doesn't work in #1. > > ~Jimmy | https://mail.python.org/pipermail/ironpython-users/2010-January/012009.html | CC-MAIN-2018-26 | refinedweb | 431 | 61.97 |
Use the WMI Connection Manager dialog box to specify a Microsoft Windows Management Instrumentation (WMI) connection to a server.
To learn more about the WMI connection manager, see WMI Connection Manager.
Provide a unique name for the connection manager.
Describe the connection manager. As a best practice, describe the connection manager in terms of its purpose, to make packages self-documenting and easier to maintain.
Provide the name of the server to which you want to make the WMI connection.
Specify the WMI namespace.
Select to use Windows Authentication. If you use Windows Authentication, you do not need to provide a user name or password for the connection.
If you do not use Windows Authentication, you must provide a user name for the connection.
If you do not use Windows Authentication, you must provide the password for the connection.
Test the connection manager settings. | http://technet.microsoft.com/en-us/library/ms177278.aspx | crawl-003 | refinedweb | 144 | 50.94 |
This example shows how to log data from three analog sensors to an SD card or to a USB Flash memory stick using the Bridge library. The memory is not connected to the microcontroller, but the AR9331, which is why Bridge must be used.
Prepare your memory by creating an empty folder in the root directory named "arduino". When OpenWrt-Yun finds this folder on an attached storage device, it creates a link to the memory to the "/mnt/sd" path.
You can remove the Flash memory while Linux and the sketch are running but be careful not to remove it while data is writing to the card.
There is no circuit for this example.
image developed using Fritzing. For more circuit examples, see the Fritzing project page
Include the FileIO header, for communicating with the SD card.
#include <FileIO.h>
in
setup(), initialize Bridge, Serial communication, and FileSystem (for communicating with the OpenWrt-Yun file system). Wait for an active serial connection before starting the remainder of the sketch.
In
loop(), create a string that starts with a timestamp to organize the data to be logged. You'll create the
getTimeStamp() function below.
Read the data from the sensors and append them to the string, separating the values with a comma :
Open the file you'll be writing the data to using a
File object and
FileSystem.open(). With the modifier
FILE_APPEND, you can write information to the end of the file. If the file doesn't already exist, it will be created. In this case, you'll be creating and writing to a file at the root directory of the SD card named "datalog.txt".
If the file opens successfully, write the string to it, close the file, and print the information to the Serial monitor.
If there is a problem opening the file, send an error to the Serial monitor :
Last, you'll write the function
getTimeStamp() to retrieve the time the information was read. It will be returning a string. First, create a string to hold the current time. You'll also create an instance of Process called "time". start the process and call the "date" application. "date" is a command line utility that returns the current date and the time. Using
time.addParameter(), you'll specify the parameters D and T, which will return the date (mm/dd/yy), and the current time (hh:mm:ss). Run the process and read the result into the string.
The complete sketch is below :
Last revision 2016/05/25 by SM | https://www.arduino.cc/en/Tutorial/YunDatalogger | CC-MAIN-2018-39 | refinedweb | 423 | 64.2 |
C++ newbie here. Anything wrong or complicated with this code? The main question I have is whether I can use v1 and v2 inside while (val <= v2)?
#include <iostream>
int main ()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
int sum = 0, val = v1;
while (val <= v2)
{
sum += val;
++ val;
}
std::cout << "The sum of " << v1 << " through " << v2 << " inclusive is " << sum << std::endl;
return 0;
}
Yes, you can, they're local variables in
main() so they're in scope until
main() returns (i. e. the whole lifetime of the program).
Of course you can. The statement inside the
while-loop needs to evaluate to a boolean expression, i.e.
true or
false. And as you can state that either it is true that
val <= v2 or not, this is perfectly fine. | http://m.dlxedu.com/m/askdetail/3/7a5fdd30fbcf482c982e5265343e1594.html | CC-MAIN-2018-30 | refinedweb | 139 | 90.7 |
Hi
Firstly I am new to the group and I am not a programmer, more of a
technical user. I am trying to create an active x control that will
eventually be used in several applications. I have a problem the basic
control function itself. Below is my code for the basic construction of
the gdll. I have made a container program for it using Axwindow and I
want to call the display with a method $Control->CallMethod("display");
Where display is my function from the dll. However I cannot get the
display window to show in my container. The only way it will Is if I put
a call to the display function inside the dll. Then the window shows as
soon as the AXcontrol is made.
I suspect something is wrong with my dll program. Please see below. Any
help or pointers would be appreciated.
Thanks in advance
Mike McMahon
package Mike;
use strict;
use Win32;
require Win32::GUI;
my $Width = 200;
my $Height = 200;
my $Left = 5;
my $Top = 30;
my $main;
#display(); unhash this line and the window will show in my container.
sub display {
my $Class_02 = new Win32::GUI::Class(
-name => "sub_class",
-color => 5,);
$main = Win32::GUI::DialogBox->new(
-name => "Main",
-text => "test",
-width => $Width,
-height => $Height,
-top => $Top,
-left => $Left,
-helpbutton => 0,
-dialogui => 1,
-topmost =>1,
-class => $Class_02,
-popstyle => 0xC00000,
-pushstyle => 0x40000000,
-interactive => 1,
-onMouseRightDown => \&MouseRightDw,);
return ($main->Show());
}
=pod
=begin PerlCtrl
%TypeLib = (
PackageName => 'Mike',
# DO NOT edit the next 3 lines.
TypeLibGUID => '{E91B25C6-2B15-11D2-B466-0800365DA902}',
ControlGUID => '{E91B25C7-2B15-11D2-B466-0800365DA902}',
DispInterfaceIID=> '{E91B25C8-2B15-11D2-B466-0800365DA902}',
ControlName => 'Gui Control',
ControlVer => 1,
ProgID => 'Mike.Gui',
DefaultMethod => '',
Methods => {
'display' => {
RetType => VT_BSTR,,
TotalParams => 0,
NumOptionalParams => 0,
ParamList =>[ ]
},
}, # end of 'Methods'
Properties => {
}
, # end of 'Properties'
); # end of %TypeLib
=end PerlCtrl
=cut | http://sourceforge.net/p/perl-win32-gui/mailman/message/10123576/ | CC-MAIN-2014-41 | refinedweb | 297 | 61.36 |
We have seen how to use
import statements to
import various modules and to use them in our programs. Python itself comes with several built-in modules, but the Python community has more to offer.
It’s the modules that make Python so powerful!
Third party modules add so much more functionality to Python. Now we would learn how to install these modules so that we can use those in our programs.
The simplest way to install these modules is by using . To update pip itself, you can use
pip install --upgrade pip
To find other useful commands for pip, use
pip help . This will give you a list of useful commands and arguments you can use, such as
uninstall ,
list or
search . , and
easy_install is deprecated.
Note: On some systems where both Python 2 & Python 3
Should install all the modules listed on the file.
If you need to know which packages you have installed (along with their versions) you can use the list command:
pip list
This will come in handy when installing packages with prerequisites such as torch or tensorflow. | https://forum.freecodecamp.org/t/how-to-use-python-pip-install-a-programming-tutorial/19164 | CC-MAIN-2021-10 | refinedweb | 183 | 80.11 |
The Translate object provides a way to move an Item without changing its x or y properties. More...
This element was introduced in Qt 4.7.
The Translate object provides independent control over position in addition to the Item's x and y properties.
The following example moves the Y axis of the Rectangle elements while still allowing the Row element to lay the items out as if they had not been transformed:
import QtQuick 1.0 Row { Rectangle { width: 100; height: 100 color: "blue" transform: Translate { y: 20 } } Rectangle { width: 100; height: 100 color: "red" transform: Translate { y: -20 } } }
The translation along the X axis.
The translation along the Y axis. | http://doc.qt.nokia.com/main-snapshot/qml-translate.html | crawl-003 | refinedweb | 112 | 61.46 |
(For more resources on Flash and Games, see here.)
Overview of Pulse library components
The Pulse package includes two components Pulse.swc and PulseUI.swc.The Pulse.swc offers the API required for you to build a multiplayer game. While PulseUI offers the game screen management, both aid in the rapid development of your game. The Pulse.swc is required in order to communicate with the server and with other clients. The usage of PulseUI, on the other hand, is optional. It is recommended to use the PulseUI since it allows you to focus only on the game implementation and leaves the standard feature set of a multiplayer game to be taken care of by the PulseUI package. Once you have the implementation of your game done and working well, you can then replace the PulseUI package with something of your own that is more suited to your game.
The following is a block diagram that shows the dependencies among different components:
The Pulse API design
The interaction of the game client with the server and other clients happens primarily via two classes that expose the Pulse features:
- GameClient
- GameClientCallback
The GameClient is primarily used to send request to the server while creating a room, joining a room, or sending a message to other players such as chat or game state updates during game play.
The GameClientCallback is an AS3 interface class for which one of the classes within the GameClient must implement. All notifications from the server are processed by the Pulse layer and corresponding notifications are called on the implementation of the callback class—for example, when a create room request was successful or when a chat message was received, etc.
Creating the Hello World sample
Let us now explore the Hello World sample that is included in the Pulse package. The Hello World sample and the rest of the samples rely heavily on the game screen management framework package, PulseUI, which is also included in the Pulse package along with the source code. In this article, we will focus on the code contained in the Hello World sample and how the sample makes use of the PulseUI.
In order to explore the Hello World sample, we first need to create a project in Flash Builder—all the required source files already exists in the sample folders. The Hello World sample does the following: create a room or join an existing game room, then add, remove, or modify a game state—the changes done on one client instance are then reflected on all other clients that are in the same room.
Think it is too much for a Hello World sample? It is not! These are just the basic functionalities for any multiplayer game. Moreover, we don't need to write the code for every bit of functionality because we heavily rely on Pulse SDK to do all the dirty work.
Setting up the project
Fire up the Flash Builder 4 IDE and let us start by creating an ActionScript project called Hello World:
- From the main menu, navigate to File | New | ActionScript Project. You will see the following screenshot. Enter a project name HelloWorld or any other name of your choice.
- Since we already have the entire source required for Hello World from the Pulse package, click on Next to specify that the source folder is already on the disk. This will bring up the following screen where we choose the Hello World src folder as shown. Note that the screenshot shows that Pulse was installed under F:\Gamantra. This path may be different on your computer.
- Once we have chosen the source folder, we still need to choose the main source folder and main application file. Unfortunately, in order to do this, we need to navigate a bug in Flash Builder 4. You need to click on the Back button and then again on the Next button, bringing us back to where we were.
- We now click on the Browse button, as shown in the screenshot, and choose the [source path] src and click on OK.
- Next we choose the main application file—this determines the main class file that the execution will start with.
- We need to tell the Flash Builder to use the Pulse libraries for this project. In the Flash world, the library files come with an extension .swc, which stands for shockwave component. Once you make it available to your project, you can start using the classes and functions that are exposed from within the library. In order to do so, choose the Library Path tab view and click on the Add SWC… button; navigate to the lib folder within the Pulse installation folder and choose Pulse.swc and once again do the same procedure for PulseUI.swc. Click on the Finish button.
As a final step, before attempting to run the sample, we also need to set the stage size to 800 (width) by 600 (height). The PulseUI requires the stage size to be exactly this size. We may also set the background color of our choice as shown in the following screenshot:
After this step, Flash Builder 4 should be able to crunch all the code in folders and report no problems. This will also create the swf files under the project folder within the workspace ready for you to take it for a spin.
At this point, you may also use the debugger to step through the code. But make sure the Pulse server is running so that you may login and explore all the screens.
The Hello World specification
The Hello World client will be able to create a new HelloGameState and share it with other players, and any player may change the x and y and have that change reflected in every player's screen. Here is the final screen that we will end up with:
The screenshot is that of the game screen. The circles are a visual representation of the game states, the position of the circle comes from the corresponding game states x and y values and so does the color from the color property. We will have two buttons: one to add new game states and another to remove them. To add a new circle (a game state), we click on the Add button. To remove an existing game state, we click on any of the circles and click on the Remove button. The selected circle appears to be raised like the one on the far right-hand side of the screenshot. We may also modify an existing game state by moving the circles by clicking and dragging them to a different position—doing that on one client, we can observe the change in every other player's screen as well.
The schema file
For any Pulse-based game development, we first start out with an XML-formatted schema file. Let's now explore the schema file for the Hello World sample.
The game developer must create a schema file that specifies all the needed game states, avatars, and game room objects. After you have created the schema file, we then use a Pulse modeler tool to create the class files based on the schema to be used within the game.
So first let's examine the schema file for the Hello World project:
<ObjectSchema>
<import>
<client import="pulse.gsrc.client.*" />
</import>
<class name="HelloGameState" parent="GameState" classId="601" >
<public>
<property index="0" name="x" count="1" type="int"/>
<property index="1" name="y" count="1" type="int"/>
<property index="2" name="color" count="1" type="int"/>
</public>
</class>
</ObjectSchema>
Navigate to the project folder where you have created the project and create a file called GameSchema.xml with the above content.
We will not go through the details of the XML file in greater detail since it is out of the scope of this article. For the Hello World sample, we will define a game state object that we can use to share game states among all the players within a game room. We will name the class as HelloGameState, but you are welcome to call it by any name or something that makes sense to your game. You may also define as many game state classes as you like. For the HelloGameState in the schema file, each game state instance will define three properties, namely, x, y, and color.
Code generator
In order to create the AS3 class files from the schema file, you need to run the batch file called PulseCodeGen.bat found in the $\bin folder. It takes the following three parameters:
- Path to schema file
- Namespace
- Output directory
In order to make our life easier, let us create a batch file that will call the PulseCodeGen and pass all the required parameters. The reason for creating the batch file is that you have to code generate every time you modify the schema file. As you progress through your game implementation, it is normal to add a new class or modify an existing one.
The convenience batch file may look like what's shown next. Let's call it .init.bat and save it in the same root folder for the sample along with the schema file.
@ECHO OFF
IF EXIST .\src\hw\gsrc\client del .\src\hw\gsrc\client\*.as
CALL "%GAMANTRA%"\bin\PulseCodeGen.bat .\GameSchema.xml hw.gsrc
.\src\hw\gsrc
IF NOT %ERRORLEVEL% == 0 GOTO ERROR
ECHO Success!
GOTO END
:ERROR
ECHO oops!
:END
pause
The schema file parameter to the Pulse code generator is specified as .\GameSchema.xml because the schema file and the batch file are in the same folder. The second parameter is the package name for the generated classes—in this example, it is specified to be hw.gsrc. You specify the directory that the generated classes will be saved to as the last parameter. Note that the code generator appends client to both the package and directory into which it will be saved. It is also important to match the package name and directory structure as required by the AS3 compiler.
Upon running the code gen successfully, there is one AS3 class generated for each class in the schema file and two additional supporting class files. One is a factory class called GNetClientObjectFactory, which is responsible for creating new instances of generated classes, and the other is GNetMetaDataMgr, which aids in serializing and de-serializing the transmitting data over the network. The data carried is what resides in the instances of generated classes. You don't need to deal with these two extra classes first hand; it is mostly used by the underlying Pulse runtime system.
As for the generated classes for what is defined in the schema file, the name of the class would be identical to what is specified in the schema file plus the suffix Client. In this example, there would be a class generated with the name HelloGameStateClient.as.
Go ahead and try running the batch file called init.bat under $\samples\HelloWorld.
Project directory structure
The Hello World that is part of the Pulse package is organized into the following directory structure:
- hw
- gsrc
- client
- rsrc
- ui
The package hw being the root package contains the main class HelloWorld.as, and the gsrc as you see contains the generated class. The rsrc folder contains the skin files, which we will discuss in more detail later in this article. The skin files in Pulse consist of three PNG files that provide all the basic buttons and background for the game. You can simply replace these PNG files with your own set, provided the individual elements with the file are of the exact dimensions and are placed at the exact same positions.
(For more resources on Flash and Games, see here.)
Introduction to PulseUI
Before we start exploring the code within Hello World, let's briefly check out the PulseUI framework. It contains numerous classes that implement the screen management for a multiplayer game. For us to leverage the PulseUI framework, we simply need to subclass and override the classes defined in the framework.
The bare minimum classes to subclass from PulseUI are:
- PulseGame
- Skinner
- NewGameScreen
- GameScreen
Screen management in PulseUI
The following figure shows you the various screens that are managed and the arrowhead shows how different screens could be navigated:
The PulseUI starts off with the login screen as one would expect for any multiplayer game. Upon successful login, we enter the lobby screen, where the player can browse through all the available rooms and join one of them. From the lobby screen, the player may also visit the registration screen or the top ten screen. The registration screen allows players to quickly register, which then provides them with a login username, password, and an avatar name. The top ten screen shows off the top ten players as well as the player's own ranking.
The PulseGame class
This class is where all the action starts for our multiplayer games. The game code must subclass the PulseGame class in order to leverage the initial set of required boot strapping. It also makes sense for our subclass to be the main class for the project, although it does not have to be.
PulseGame instantiates and holds a pointer to the GameClient to publish any action from the game client to the server. It also implements the GameClientCallback interface that implements the logic when the notifications from the server are received.
Let us now look at the methods that must be overridden. Starting with the constructor of the subclass (MyGame), you should instantiate your subclass of the skinner. The first thing that the constructor of PulseGame does is to create and init the login screen, as it will most probably be displayed right after the splash screen has done its thing.
It is important to have the static protected property defined in PulseGame s_instance set to our subclass instance of PulseGame as shown below:
public function MyGame() {
s_instance = this;
new MySkinner();
super();
}
Note that we also want to call the super class's (PulseGame) constructor only after we are done with our initialization.
The reason is that PulseGame is a singleton, and there are numerous places within the framework that require access to this singleton. The previous code makes sure that the instance of our subclass is returned in all cases.
The following figure shows the methods calls stack. Important to note here is that all the methods are protected, meaning that we can customize default behavior of the class at any step on the way.
In order to provide our own customized login screen, we simply override the initLoginScreen. If we wanted something fancy during the splash, we could override the splash method. On the other hand, if we simply wanted to provide a different sprite for the splash instead of the default, we would override the getSplash method.
We could also entirely skip the splash screen by overriding the splash method and calling onSplashDone, as shown below:
protected override function splash():void {
onSplashDone();
}
If the splash method is completely overridden, it is the subclass's responsibility to call the onSplashDone method after the splash screen has done its thing. The default behavior of onSplashDone is simply to call the start method.
The start method then initiates the following series of method calls. First it instantiates the GameClient, the main API class of Pulse, which enables all communication with the server. This method must be overridden if the game defines a schema, which is true in most cases. The login screen is then initialized so that it can create any sprites that are needed for display, and finally makes a call to display the login screen to the player.
In the case of advanced implementation of a game, the showLogin method may be overridden to read parameters passed from the HTML embedded code into the Flash game swf. In some cases, the game may not show the login screen, but retrieve the username and session from the fl ash parameters and directly invoke the server login.
Upon the server's response to the login request, the Pulse SDK serves up a GameLoginEvent defined in the Pulse layer. The login event callback, onLogin method, is called. The login event passed in may be examined to determine if the login was successful or returned an error.
The following is the default implementation that you may find in PulseGame:
protected function onLogin(event:GameLoginEvent):void {
if ( event.isSuccess() ) {
init(); // init the game client screen
m_timer.addEventListener(TimerEvent.TIMER,
processMsg);
m_timer.start();
}
else {
var loginError:int = event.getErrorCode();
if ( loginError == GameErrors.ERR_LOGIN_FAIL ) {
// try again
}
else {
// Server un-available!!
}
}
}
We see that if the login was successful, we can continue with the initialization for the rest of the game screens. This happens in the init method. The init method first draws the outline, which serves the background for the entire game and never changes; other game screens are laid on top of the outline. The init method after drawing the outline then initializes all the other screens. The following is how the init method looks in the PulseGame class:
protected function init():void {
// Show the outline
drawOutline();
// init other screens
initLobbyScreen();
initGameScreen();
initNewGameScreen();
initHiScoreScreen();
initRegisterScreen();
postInit();
}
Each of the init methods may be overridden to create our versions of the screen. For example, a custom lobby screen may be created by overriding the initLobbyScreen.
The outline, in addition to drawing the background, also shows the player's own avatar representation. We may provide our own implementation of the outline by simply overriding the initOutline method.
The final step of the init method is the postInit, which the subclass may override to perform any additional tasks or drawing required for the game. The default implementation of the postInit requests the server to take the player to the lobby.
Exploring the Hello World sample
In the following sections, we will explore parts of the Hello World sample, specifically dealing with the initial start-up phase.
HelloGame.as
The main class called HelloGame inherits from PulseGame, which is defined in PulseUI. In the constructor of the class, we initialize the Skinner instance that provides buttons and background for the game sample.
public function HelloGame() {
s_instance = this;
initSkinner();
super();
}
protected function initSkinner():void {
new HelloSkinner();
}
Since the Pulse server is capable of serving multiple games, we need to override the getGameId method and provide a string that must be unique among all the games hosted by the server.
public override function getGameId():String {
return "HelloWorld";
}
In order to connect to the server for sending and receiving messages, we need to create the Pulse level class instance called GameClient. To instantiate the network communication client, it also needs the instance of the generated factory class.
protected override function initNetClient():void {
var factory:GNetClientObjectFactory;
factory = new GNetClientObjectFactory();
m_netClient = new GameClient(factory, this);
}
In the Hello World example, we will modify only two screens—one screen where a new room is created and another the game screen. We will leave all the other screens such as lobby, high scores, and register as they are.
protected override function initNewGameScreen():void {
m_newGameScreen = new NewGameRoomScreen();
m_newGameScreen.init();
}
protected override function initGameScreen():void {
m_gameScreen = new HelloGameScreen();
m_gameScreen.init();
}
Whenever a new game state arrives, an existing one is removed or modified, the corresponding methods on the PulseGame are invoked. Remember that this HelloGame class inherits from PulseGame, so we can simply override these methods and pass it to the game screen for update.
public override function
onNewGameState(gameState:GameStateClient):void {
(m_gameScreen as HelloGameScreen).onAddGS(gameState);
}
public override function
onUpdateGameState(gameState:GameStateClient):void {
(m_gameScreen as HelloGameScreen).onUpdateGS(gameState);
}
public override function
onRemoveGameState(gameState:GameStateClient):void {
(m_gameScreen as HelloGameScreen).onRemoveGS(gameState);
}
That's it for the main class! The reason why it seems so simple to write games based on PulseUI is that all the game mechanics are handled by PulseUI framework. What we are doing is simply modifying the default behavior.
The login screen
The login screen is the first screen to be shown for any multiplayer game.
It offers two buttons, one being the Guest button for which the player need not type any username or password. In this case, the player will be logged in as a guest. If the player does have a username and password, the player needs to click on the OK button after filling in the fields.
The login class allows one to customize the login screen, so the server IP does not show up in the login screen. After creating the login screen, we may simply call the showIP method and pass false. The best place to call the method is by overriding the initLoginScreen in your subclass of PulseGame class.
protected override function initLoginScreen():void {
super.initLoginScreen();
m_login.setIP("127.0.0.1");
m_login.showIP(false);
}
We also need to remember to set the IP of the Pulse server. During the development phase, you may want to show the IP field, but during deployment, you may want to hide it and set the IP value programmatically.
The login method takes in the IP of the server and port. By default the IP is the localhost, but could be any IP on the Internet. The Pulse server always listens to port 2021, so the client must pass the same value. For the enterprise edition of Pulse, this port may be configured.
public function login(ip:String="127.0.0.1",
port:int=2021,
username:String=null,
password:String=null,
sessionId:int=0)
The user name and password may be passed from user input or could be null in case the player wishes to log in as a guest.
The session ID in most cases can be passed a value of zero. The session ID is provided for advanced game portal implementation where a user gets assigned a session ID from the web portal implementation. From then on, the player may jump from one page to another, containing different games. In this case, for providing the user name and the session ID, the user need not log in every time a new game is attempted to be played.
The screen class
This is the base class for all the screen classes. It defines the bare minimum methods such as init, show, and hide. Each subclass then overrides these methods for their specific sprite management.
public class Screen extends Sprite
{
protected var m_showing:Boolean;
public function Screen() {
}
public function init():void {
}
public function show():void {
if ( m_showing ) {
trace("Already showing!");
return;
}
m_showing = true;
}
public function hide():void {
if ( !m_showing ) {
trace("Already hidden!");
return;
}
m_showing = false;
}
public function isShowing():Boolean {
return m_showing;
}
For each screen, the init method is called once, where the subclass may initialize any sprites it needs, ready to be displayed. The show and hide methods can be called several times during the life of the game. The show method is called when the screen is to be displayed and hide to remove it from display. All screen-swapping is done by the showScreen method in PulseGame. If there is any custom screen class (for example, a credits screen) other than those subclassed from the PulseUI framework, it is recommended that it is inherited from the screen class so as to leverage the existing screen management code.
(For more resources on Flash and Games, see here.)
The skinner class
The skinner class provides a simplistic way to change the UI specific to your game. It is meant to provide a quick way to an alternative set of UI theme. The skinner class provides the art asset for all the UI in the game except for the art required for the game itself. It provides the background and buttons sprites for the general UI. The skinner is designed to take in three PNG files, namely online.png, ui.png, and frame.png.
Outline.png provides the art that is behind everything, which means the outline is drawn first and everything else is laid on top of it. From start to finish, the outline does not change and is always seen if nothing draws to cover it.
Frame is a small section to hold various UI elements in login and new game screen. Both outline and frame are simply copied from the file and displayed as they are onto the screen.
UI.png supplies all the required buttons for all the screens except for those required specifically for the game. Once the file content is copied into memory, it cuts it up into various pieces. The position and size of each UI element is hardcoded, which means that when you want to provide your own UI, the elements must be in the same position and size as the original.
If you needed something more sophisticated, you would need to replace the skinner with your own implementation as well as with various parts of PulseUI code where this is accessed.
The outline class
As you saw in the walk-through of the PulseGame object, the outline object is the first one to be painted onto the screen.
Let us now dissect the outline class in detail. The following screenshot shows the lobby screen that lays on top of the outline. The outline class draws the following:
- Background
- Top-left avatar
- Friends bar
- Chat history
- Chat input
All the other UI elements are laid by the lobby screen, which we will discuss shortly. Also note that the outline class is not a subclass of screen object, although it could be. The reason it does not have to be is because the outline is always present in the background as opposed to other screens, which they may show and hide many times over.
Player registration
A player may register and create an avatar right within the game. A guest player may register via the RegisterScreen. The basic information for a player to register is:
- Username
- Avatar name
All functionality to register a guest is already provided by the PulseUI framework. Similar to the HiScore screen, you may customize the font and color by overriding the getFormat method.
Exploring the game server deployment
Let us explore in detail some of the functionality of the game server.
Registration and login
As simple as it may sound, the login is a complicated beast. From a user experience stand point, login must be simple no matter what happens behind the scenes.
In order for new users to get into your game, there are the three essential steps:
- Authentication
Registration is the process where new users create their account name and set their password usually through a website. Although it is a common practice to implement this functionality as a web-based application, players are often allowed to register within the game. This has the advantage of players not having to go to another screen, typing in the URL, and so on. Casual players just don't have the patience.
When a new user successfully creates an account, the backend web server creates the database entry with the user name, password, and other collected information. This database is called the authentication database or Auth DB for short.
The authentication DB is then used to authenticate users during the time when players are attempting to log in to the game.
Other important information that the authentication database may store is the user's place of residence, e-mail, date of birth, etc. This data often comes from the user entry during the registration process. The other kinds of information that could be automatically collected are data such as date and time of registration, the IP from where the person is registering, etc. These data are valuable to collect in order establish trends as the game progresses in its deployment stages.
Further, the authentication DB could also keep track of the login activity. Every time a player logs in or out, a DB log is recorded along with other information such as the IP. This kind of data is helpful in discovering the user trends of your community. For example, this data can help you find out the last players activity in the week and be designated as the server update period, or if the user activity was high at certain periods of a week or day, it would allow yourself to be more cautious about server stability during these times.
The login
A login may be as simple as the client logging into the game server. It opens a network connection to the server to send the username and password. The server then verifies the username and password, and allows or denies the client to log in. This may be true during the development of the game, but when the game is deployed publicly and when a large number of people are on the game cluster, the login process soon gets complicated during a public deployment.
The client first contacts the balancer, which keeps track of all the load statistics of all the processes within the game cluster. The balancer first determines if the client is the latest release that is compatible with the server. If so, then the login process continues further.
The balancer then determines the least loaded session server. The determination of least load is a combination of the number of client connections the server is maintaining and the CPU usage of the machine.
The balancer then sends the session server's IP and port to the client for it to connect. The client then proceeds to connect to the assigned session server, which then must authenticate the username and password. There are two common schemes during the login process that the authentication could be implemented.
In the early authentication scheme, the authentication is verified before the connection to the session server is established. If the authentication passes, the login server will inform the appropriate session server to expect a login from the client. The session server will receive the username, and for additional security, a session key is also passed. This session key is also sent to the client, so when the client connects to the session server, the client sends the username and the session key for the session server to validate the connection. Notice that this scheme further splits the responsibility to another process, the login server.
In lazy authentication, the session server is responsible for initiating the authentication and either accept or deny the request. The lazy authentication is much simpler than the early authentication mechanism.
Dealing with multiple logins
The one common issue that must be dealt with in a public deployment is the issue of multiple logins. There are two options that could be implemented when a duplicate login is detected:
- Disallow the second login.
- Disconnect the first login.
Even though the first option seems simpler, it is not commonly adopted. There are two reasons why the second option is more practical and preferred. One technical reason is that sometimes there is a chance that there is a stale server session after a client crash, so the second login forces a cleanup of these stale sessions. If such a problem is present in a deployment, it should be fixed by the developer. But a more legitimate reason for opting for option two is the user behavior—a player may leave the computer without logging out of the game and may then choose to log in to the game from another place. When the player attempts to log in, the first loggedin client will be disconnected and the player can play from the other computer. A similar situation may arise even within the same computer when the user opens another browser window or tab and initiates a fresh login.
Guest logins
Guest logins are great for new players to try out without having to go through the extensive registration process. It provides an opportunity for them to explore your game very quickly.
Guests are special; they are let into the game without a login. But ultimately, and depending on the game, you would want them to register, especially for a multiplayer game. What sets multiplayer games apart from single player games is that the players are part of a community, which means that identity becomes an important aspect to players.
Players who log in as guests are restricted players in many ways; for one thing, they are seen as guests to other players, meaning they don't have a unique identity. Most often their data is not saved to the database, meaning that their high score or experience are not kept track by the server. These restrictions encourages a guest player to sign up and be an active member of your community while giving them an opportunity to experience your online game.
Summary
In this article, we got our feet wet exploring the Hello World sample. We learned how to set up the project in Flash Builder 4 and the project directory structure. We also learned how to create a game schema and how we can set up the code generator. Now we also have a handle on all the screens required for the game and how PulseUI manages it for us. Finally, we have made the first contact with the server and logged in the client.
Further resources on this subject:
- Flash 10 Multiplayer Game: Introduction to Lobby and Room Management [Article]
- Flash 10 Multiplayer Game: The Lobby and New Game Screen Implementation [Article]
- Flex 101 with Flash Builder 4: Part 1 [Article]
- Working with Drupal Audio in Flash (part 1) [Article]
- Flash Video Encoding, Skinning and Components in Wordpress [Article]
- Joomla! with Flash: Flashy Templates, Headers, Banners, and Tickers: Part 1 [Article] | https://www.packtpub.com/books/content/flash-10-multiplayer-game-game-interface-design | CC-MAIN-2015-11 | refinedweb | 5,604 | 60.55 |
Add Tags.
Once you've started sending tagged data, you'll see it in the Sentry web UI: the filters within the sidebar on the Project page, summarized within an event, and on the tags page for an aggregated event.
We’ll automatically index all tags for an event, as well as the frequency and the last time the Sentry SDK has seen a value. We also keep track of the number of distinct tags and can assist you in determining hotspots for various issues.
To set a tag:
using Sentry; SentrySdk.ConfigureScope(scope => { scope.SetTag("page.locale", "de-at"); });
Important: Some tags are automatically set by Sentry. We strongly recommend against overwriting those tags, and instead using your own nomenclature for names. | https://docs.sentry.io/platforms/dotnet/guides/entityframework/enriching-error-data/additional-data/adding-tags/ | CC-MAIN-2020-40 | refinedweb | 123 | 52.19 |
Sylvain Wallez wrote:
> Gianugo Rabellino wrote:
>
>> Christ :-/
>
>
>
> AFAIK, even for selection you may encounter problems as the prefix is
> used, but the actual namespace URI is ignored.
>
> There may be a workaround for the binding, however: the
> o.a.c.util.jxpath.DOMFactory class tries to guess the namespace URI when
> asked to create a prefixed element by crawling up the DOM tree up to
> finding an "xmlns:" namespace declaration attribute for that prefix.
>
> So if you add that declaration on the root element of the document you
> bind to, prefixed elements should be correctly namespaced.
Will give it a try, thanks. It would work much better than what I'm
using now (a hacky transformer that gets prefix->namespace mappings
from external files and plugs them "on the fly" when it gets a null
or empty nsURI for a qualified start/endElement). Actually, however,
my problem was in SAX parsing to a SourcePropWritingTransfomer,
where I got a DOM Namespace error. Will see if your workaround fixex
that.
Thanks so much,
--
Gianugo Rabellino
Pro-netics s.r.l. -
Orixo, the XML business alliance -
(Blogging at:) | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200402.mbox/%3C40313E3E.5020207@apache.org%3E | CC-MAIN-2014-52 | refinedweb | 185 | 62.27 |
I have tried to round the float point number to a whole number in 2 different ways:
I am trying to round up on the cans of paint. I have tried by using cans = (int)(surface + 0.5)/300; I still get the answer 0 cans even though the initial value of the surface variable is .61. I then tried cans = (int)(surface * 10)/300; which gave me 6 cans. Is there a round function with C that works like the round function in a sql statement?
Please see my code to help you understand what I am doing.
#include <stdio.h>
int main()
{
float width; /* integer to hold the width value */
float length; /* integer to hold the length value */
float area; /* integer to hold the area value */
float yard; /* integer to hold the yard value */
float height; /* integer to hold the height value */
float surface; /* integer to hold the surface value */
int cans; /* integer to hold the cans of paint value */
printf("Please enter the width of the room:\n"); /* ask for the width */
scanf("%f", &width); /* intake the width */
printf("Please enter the length of the room:\n"); /* ask for the length */
scanf("%f", &length); /* intake the length */
printf("Please enter the height of the walls\n"); /* ask for the height */
scanf("%f", &height); /* intake the height */
area = width + length; /* variable of area w + l gives the value */
yard = area /3; /* variable of yard is w + l /3 the value */
surface = (height + width + length) *4; /* variable of surface is h + w + l *4 walls = the value */
cans = (int)(surface * 10)/300; /* variable of cans is h + w + l *4/300sq.ft= the value */
printf("You will need %f square feet of carpet\n", area); /* output the area to screen */
printf("You will need %f square yards of carpet\n", yard); /* output the yards to screen */
printf("The walls are %f square feet\n", surface); /* output the surface to screen */
printf("You will need %d cans of paint\n", cans); /* output the cans to screen */
scanf("Enter anything:\n",&cans); /* a pause to be commented out */
return 0;
} | http://cboard.cprogramming.com/c-programming/32926-rounding-floating-point-sharp.html | CC-MAIN-2014-15 | refinedweb | 349 | 56.36 |
tag:blogger.com,1999:blog-178900832017-07-30T03:54:24.475-04:00Tech BlechProblems wrestled to the ground. Reviews of tech I've used. Varioso for programmers.Pat Palmer 10 is trying to high-jack my laptop before I'm ready for it. Help?I've been using Windows 8.1 (Pro) with the StartIsBack menu add-on, and I've been happy with it. Theoretically, I'm looking forwards to upgrading to Windows 10--but I have to wait to upgrade the laptop I use for my job until Drexel University's VPN promises to work with Windows 10. We've been severely warned not to upgrade to Windows 10 just yet.<br /><br /.<br /><br /. <br /><br /.<br /><br />In the meantime, since I know sooner or later I will fail to stop the upgrade and it will happen without my permission, I've ordered more RAM for this old laptop. At least, that way, maybe the upgrade won't fail just because the hardware is old. Maybe. <br /><br />It's stuff like this that makes even Microsoft fans like me, well, sometimes we just have to hate Microsoft. And this is one of those times.Pat Palmer and SendSpace: useful and reliable file servicesThere are so many ways to move files around, and to back files up, that it can make one's head spin. I work across several different computers in various locations. I've ended up relying heavily on both the <a href="" target="_blank">Dropbox</a> and <a href="" target="_blank">Sendspace</a> file services. Both are free for a limited file size and bandwidth, and both are worth paying for if you need to transfer or backup a lot of files. I've now been a paying customer of both services for a couple of years, and I've found them both to be reliable and easy to use. That said, they are not identical. Dropbox is useful for backups and sharing regularly-used files across my many different work computers. Sendspace is useful for transfering very large files among computers, either mine or belonging to other people.<br /><br />Dropbox will store your files "in the cloud" (that is, on a server, or servers, somewhere on the internet). You access the files via a special "Dropbox" folder on your computer, which is created by the Dropbox installer. Dropbox will automatically copy any files you deposit in its folder up to its servers. Then, you'll be able to reach those same files on any other computer where you've also installed Dropbox using the same logon account. To get started on a given computer, you just download and install the Dropbox client, run it and logon to your Dropbox account in the client. The client program manages your Dropbox folder. It is very smart about syncronizing local and server files, and it gives a good visual indication of when the syncronizing is done.<br /><br />Sendpace will allow you to transfer very large files. I generally zip, or compress, one or more files into a single huge file before uploading to the sendspace server. Sendspace is drop-dead simple to use. You don't need any coaching from me--just go to the site and follow instructions. When a file is too huge to move around by any other means, Sendspace can nearly always move a file between any two computers as long as they both have access to the internet. Sendspace's free service offers the sender a link to delete the file from its servers, but if the sender doesn't bother, the file will be deleted automatically after two weeks.<br /><br />Paying for Sendspace will increase the maximum allowed file size from huge to humungous. It will also allow you to keep files up on their servers indefinitely (as long as your account is paid up).<br /><br />To send a file to someone else, you do have to give Sendspace their email address; Sendspace then emails the person a link which they can use to download the file. As far as I can tell, Sendspace does not mine the emails and never spams any user or recipient of files. That the service has remained spam-free is unusual these days, and that makes it one of my favorite internet companies right now, and one of the few I can recommend whole-heartedly.<br /><br />Good services deserve good publicity; hence this blog entry. Give them a try! It won't cost you anything to try them out. However, I don't recommend that you send any sensitive data using these (or any other "cloud-based") services. There is never any guarantee that a third party company won't look inside your data. Thankfully, though, the kinds of files I'm sending around are not likely to be desirable to anyone but me or my immediate co-workers, and they don't contain anyone's private information.Pat Palmer</a></td></tr><tr><td class="tr-caption" style="text-align: center;">With SSI's;">Healthy page example.</td></tr></tbody></table>Yesterday, I received a trouble report about a Linux shared-host website which resides on GoDaddy servers. To my horror, the site now looked like the page shown on the right, instead of the page shown below it. It was pretty clear that server-side includes (SSI's) had stopped working, and since I had not updated the site in a couple of weeks and all had been working well up until yesterday, it was also clearly because of something that GoDaddy had done to the server. If nothing else, their server logbook ought to show what had been done, and so a developer like myself should be able to figure out how to adapt. Bad enough that no advance notice had been given.<br /><br />I immediately put in a call to GoDaddy technical support to find out what had happened and get some help figuring out how to get the site back to its former state of health. After navigating numerous computerized phone menus and waiting on hold for about 15 minutes, I finally reached a human being, who immediately put me on hold and then disconnected the call. This person did not call me back, so after a few more minutes, I put in a second call to GoDaddy support. Same drill: after about 15 minutes, I got a person, who didn't know anything and put me on hold while he "contacted the server group". After another 15 minutes, he returned to announce that I would have to fix the problem myself, as it was a scripting problem. OK, I enquired, how shall I fix the problem? My code hasn't changed. And in the meantime, I had verified by extensive web searching that GoDaddy's forums had no help page showing how server-side includes ought to work. Further, there were many entries in GoDaddy's forums within the past two weeks by <a href="" target="_blank">other customers</a> whose server-side includes had also stopped working. "Sorry", the tech support guy said, "it's a scripting problem and we don't touch your code. You'll have to fix it."<br /><br />I was now waffling between disbelief and rage. After spending another hour trying every wild suggestion, and everything I've ever encounted to get server-side includes working on Linux, I "patched" the problem for the short term by eliminating the SSI's altogether in the important pages of the website, so that my site once again had graphics and styling.<br /><br />Returning the next day, fresh and rested, I was able to get server-side includes working again by making this small change:<br /><pre></pre><br /> Bad directive: <!–#include virtual=”./shared/insert.txt” –><br /><br /> Good directive: <!–#include file=”./shared/insert.txt” –><br /><br />Really? One word change fixed this? And GoDaddy tech support is too stupid to tell this to customers? Needless to say, I don't trust GoDaddy. I fully expect now that the pages will stop working at any moment due to some unknown change in their server configuration.<br /><br />And, I will never, ever again use GoDaddy for any service. What arrogance these large corporations are capable of developing towards their own customer base. I'm still aghast. They could have kept my business so easily. Stay away from GoDaddy. The word "evil" comes to mind.<br /><br />I will be moving all business from GoDaddy as soon as can be arranged.<br /><br />Pat Palmer tracks clicks on its search links even if browser cookies disabled<table cellpadding="0" cellspacing="0" class="tr-caption-container" style="float: right; height: 262px; margin-left: 1em; text-align: right; width: 510px;"><tbody><tr><td style="text-align: center;"><a href="" imageanchor="1" style="clear: left; margin-bottom: 1em; margin-left: auto; margin-right: auto;"><img border="0" height="222" src="" width="400" /></a></td></tr><tr><td class="tr-caption" style="text-align: center;"><span style="color: red;"><b>Notice the status (lower left) while mousing in a Google search. The address shown in the status bar is a total lie.</b></span></td></tr></tbody></table><br />The two links below go to the same place. I got the first link by selecting "Copy Link Location" over a search result from <i>Bing</i>, and the the second link by selecting "Copy Link Location" over a search result from <i>Google</i>. <br /> <br /><br />When you click a <i>Google</i> Search result, it takes you first to <i>Google's</i> web service (the longer link below), where <i>Google</i> records what you clicked (and who knows what else about you) before forwarding to the page you actually wanted.<br /><br />I recommend that everyone switch away from Google search, since there are now good alternatives.<br /><br /><cite><b><a class="moz-txt-link-freetext" href=""></a><br /> <br /><a class="moz-txt-link-freetext" href=""></a></b></cite><br /><div class="separator" style="clear: both; text-align: center;"></div><br />I first noticed this a few months ago while trying to fix up old broken links on some websites, and I only noticed it because the<i> Google </i>web service slowed down during peek hours in the middle of the daytime. <i>Google</i> has coaxed the browser to show the false, shorter link in the status bar below the browser when you mouse over the longer link (using Javascript, I presume). It's only a matter of time until they figure out how to make "Copy Link Location" lie to us as well, after which only packet sniffing would be able to catch them in the act.<br /><br />I really don't understand why the tech community is not raising hell over this--it is yet another invasion into our privacy. Even running a browser in private browsing mode would not save us from this kind of rigging--which, my guess is, could be why Google did this. And also to more accurately charge their ad customers for click-throughs. Either way, I don't like it. Google's "Don't Be Evil" slogan is beginning to look a little ironic, and I've switched to Bing for the majority of my web searches.<cite><b> </b></cite>Pat Palmer update kills web application via namespace collisionIn my work at the <a href="" target="_blank">Academy of Natural Sciences of Drexel University</a>, I administer a database server and web server for the <a href="" target="_blank">Phycology Section</a> (on which runs a bunch of REST web services on .NET 3.5) <a href="" target="_blank"></a>. Today after downloading a number of Windows updates on the web server, one of the web services (here's <a href="" target="_blank">an example</a>) was broken. The updates I had downloaded are shown here:<br /><a href="" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="140" src="" width="400" /></a> After investigating, I noticed a long, messy compile error that had not existed before, on a page in the cache which I had not created. I stared at the error and the page until I began to understand that perhaps there was a name collision on the word "Site". I had long used a master page called Site.master, so I changed it to Site1.master and repeatedly recompiled until all pages dependent on this master page had been changed to use the new name--after which the problem disappeared.<br /><br />So answer me this. How come an update to something in .NET 4 breaks a web service running on .NET 3.5? And furthermore, how could anyone at Microsoft be dumb enough to suddenly purloin a common name such as "Site"? Probably many programmers around the world are cursing and going through the same discovery process as I write this. Bad Microsoft! Bad! Bad!Pat Palmer Files on NTFS File SystemMaintaining a web server on Microsoft Windows Server 2008 has mostly been straightforward and not very time-consuming. But recently I was confronted with a small but extremely annoying hassle, having to do with 3 files within the web server's area that could not be read, could not be deleted, and could not even be included within a .zip file. It was this last issue that first got my attention; I had been accustomed to .zip up the entire <i>wwwroot</i> area from time to time to ship it off-disk as a backup. This began to fail.<br /><br />I knew right away that I had introduced the problem while attempting to administer permissions on Pmwiki, a third-party application written in PHP that was never intended to run on a Microsoft web server. Permissions for the upload folder kept reverting so that uploading attachments to the wiki failed, and it was while wrestling with this periodically recurring conundrum that I shot myself in the foot by somehow removing my ownership of those three files. To get around this boondoggle, I had made an entire new upload folder (from a backup), and just renamed the old "stuck" upload folder.<br /><br />Then, the next time I tried my handy .zip-it-all-up backup trick, I got an error. The error, of course, happened right at the end of a long .zip process, and the entire archive failed to be created. I now had no off-disk backup happening, all due to these three "stuck" files, which I could see in the folder, but which I could neither read, delete, nor could I change permission on them. How anyone could deal with such problems without Google, I cannot imagine. Thank the universe for search engines.<br /><br />Within minutes of beginning my search, I found <a href="" target="_blank">this support page</a> on Microsoft's site. At the very bottom, I found what I needed, which was the "if all else fails" strategy, which Microsoft called "Combinations of Causes" (that gave me a chuckle). This strategy required me to use a utility called "subinacl.exe" which the support page cited as being part of the Resource Kit.<br /><br />Googling some more, I soon found that the Resource Kit was a very expensive (as in $300) book with tools on a disk in the back. I wasn't going to buy it. Then it occurred to me just to search for "subinacl.exe", and thankfully, I found that Microsoft had made it available as a download. So I downloaded it. But idiot that I am, I failed to note where it had installed itself (somewhere obscure, I promise you). Had to uninstall it, and then reinstall, this time noting down the install location, which for those of you going through the same thing, I will state here was <i>C:\Program Files\Windows Resource Kits\Tools\</i>.<br /><br />So then I took a deep breath, constructed the command line that I needed in Notepad, then opened a command window, browsed to the obscure install folder shown above, and carefully pasted my unwieldy command into the window, then (holding my breath), I hit return. A frightening amount of techno babble appeared as the command executed. After a few tries, I got it to succeed, though it still gave warnings. I had to do this four different times, once for each file and then for the containing folder. The model command line is:<br /><br /><br /><b>subinacl /onlyfile "\\?\c:\<var>path_to_problem_file</var>" /setowner=<var>domain</var>\<var>administrator</var> /grant=<var>domain</var>\<var>administrator</var>=F</b><br /><br />View this joyful output here:<br /><img alt="command window" src="" /><br /><br />Altogether, the failures of Pmwiki and Microsoft file permissions have indeed cost me hours of hassle over the five years while I have managed the server. This latest offense was just the crowning jewel. Managing file uploads on IIS is a challenge at any time, as the web server really is leery of anyone writing into a file zone that it serves. But this doggy PHP open source piece of software (Pmwiki) that was tested only on Linux is, in retrospect, hardly worth the effort. I haven't tried installing other wiki software yet (no time for the learning curve!) but surely I hope there might be another one that works better than this when running on a Windows server.<br /><br />Microsoft's support page did do the trick. The problem shouldn't be possible anyway. The big Administrator account should always be able to delete a file--what were they thinking?--but at least they provided the necessary utility to dig myself out of the pit. Still, I'm not exactly feeling kindly towards Microsoft at this moment. Or towards Pmwiki.Pat Palmer - The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine.I support a .NET application which reads a version table in its background database, which is Microsoft Access. If the version is wrong, the application refuses to run. Recently, one of the application users upgraded to a 64-bit machine, and the application began reporting that the backend database was "the wrong version", even though it was in fact the same database that had worked fine on a 32-bit machine. After some debugging, I unearthed the following error message (which was being swallowed): <b>ERROR - The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine</b>. <br /><br />Thanks to Google and other bloggers, I learned that Visual Studio 2010 Professional compiles, by default, with an option called "Any CPU". But after recompiling the application with the "x86" option (which is an alternative to "Any CPU"), the application began to work on either a 32-bit or 64-bit CPU. Huh? <br /><br />Apparently, with the "Any CPU" option, .NET ran the application as 64-bit (because it happened to reside on a 64-bit machine at the time) and a mismatch occurred when it tried to read from the 32-bit Access database. By forcing the compiler to be "x86", I forced the program to run as a 32-bit process even though it resides on a 64-bit machine, and no mismatch occurred. <br /><br />I did notice that the application starts a bit more slowly than it did on a 32-bit machine, but once running, it warms up and runs just fine.<br /><br />Those compiler options are very poorly named. And now when Office upgrades, someday, to 64-bits, I'll probably have to recompile again. Thanks, Microsoft. <br /><br /><br />Pat Palmer to write to the disk (make a writable folder) in ASP.NETTo do file uploads, some administration is always necessary on the server side. ASP.NET tries very hard to prevent users from writing anywhere on the server, so we have to take special steps if file upload is required. In particular, the IIS7 server will not let you both Execute and Write into the same folder. For the record, here are the steps for IIS7 on Windows Server 2008 (assuming you are system administrator on the server):<br /><br />* the user creates an uploads folder and sends its file spec to the administrator<br />* the administrator opens the Internet Information Services (IIS) Manager, browses to that folder, and right clicks over it to change file permissions as follows for the NETWORK SERVICE account:<br />** remove Read and Execute permission<br />** add Write permission<br /><br />Both permissions should be changed in one step, and that <i>should</i> be all that is necessary. But test the write and subsequent read carefully; if either does not work, delete the folder, create a new one, and start all over again.<br /><br />If you are using a hosting service, there should be some special procedure to get the permissions changed. In my experience, changing the permissions for this purpose has spotty success and can lead to a drawn-out hassle. I suppose it's worth it to have a reasonably secure server.Pat Palmer 2010 fails to compile program created earlier in VS.NET 2008Trying to recompile a program in Visual Studio 2010, which was originally created using Visual Studio 2008 (which is still on my PC), I got this baffling message:<br /><br /><span style="font-style: italic;">Error 9.</span><br /><br />These suggestions were too bizarre even to consider, and so I Googled. Right away, I found <a href="">this nice blog entry</a> which helped me out, and just in case it were to go away, I'm duplicating the helpful information it contains below. So, courtesy of the "dukelupus" blog, everything after this paragraph is copied verbatim from that blog. <br /><br />Changing the registry key will not help nor will adding C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\ to the path. I did not try other solutions...I used FileMon to check what Visual Studio is looking for – and it appears that it will always look for that file at C:\WINDOWS\Microsoft.NET\Framework\v3.5\, which does not contain sgen.exe.<br /><br />Just copy sgen.exe from C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\ to C:\WINDOWS\Microsoft.NET\Framework\v3.5\ and everything will now compile just fine. Here, to make your life easier, copy command:<br /><br /><span style="font-weight: bold;">copy /y “C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe” “C:\WINDOWS\Microsoft.NET\Framework\v3.5\”</span><br /><br />Good luck!Pat Palmer Server Management Studio and the "Saving changes is not permitted" error.Sometimes after a new install of Microsoft SQL Server Management Studio, you may get a default setting that prevents the user from changing the design of tables in the visual designer mode, which can be extremely frustrating, as it is not easy to figure out how to turn the checking off that is preventing table redesign. The error message will be announced in an annoying popup whose text is uncopyable: <br /><br /><i>"Saving changes is not permitted. The changes you have made require the folloing tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created."</i><br /><br />Here's how to solve this in Microsoft SQL Server Management Studio 2008: <br /><br />1) Go into the Tools...Options... menu <br /><br />2) In the popup, on the left, expand "Designers" by clicking on the plus <br /><br />3) In the "Table Options" shown to the right, MAKE SURE that "Prevent saving changes that require table re-creation" is NOT checked. <br /><br />I've lost a few hours of my life to this nuisance. Hope this will help someone else out of the conundrum.Pat Palmer workaround (Access to SQL Server) for 64-bit Windows 7I've been avoiding 64-bit Windows due to various incompatibility rumors, but this case takes the cake, as it is entirely Microsoft's fault. My work place uses a variety of shared Access databases, located on a network drive, that connect via ODBC System DSN's to a SQL Server 2008.<br /><br />Even though all DSN's appeared to be configured correctly on my colleague's brand new (64-bit) Windows 7 machine, and the ODBC connections passed their test, the actual database declined to connect to the server. Thanks to various discussion groups, we finally figured out that the graphical user interface accessible from the Administrative Tools applet in Control Panel actually brings up a 64-bit ODBC application, whereas we (for backwards compatibility) needed the strangely hidden 32-bit System DSN window. To run it, we had to browse to this path:<br /><br />C:\Windows\SysWOW64\odbcad32.exe<br /><br />Clicking on <b>odbcad32.exe</b> runs the 32-bit version of the ODBC connection setter upper. There, we re-created all the System DSN's, and finally the Access databases were happy.<br /><br /><img administration="" alt="ODBC" console"="" data="" source="" src="" width="400px" /><br /><br />By default, the Windows GUI is presenting a 64-bit ODBC connection setter upper (which I believe is in the C:\Windows\system32 path somewhere. Going manually to the first path and running the application, then adding the ODBC connections, makes it work.<br /><br />In the meantime, 3 days of work were lost to this problem.Pat Palmer Stallman's speech "A Digital Society", Apr 20, 2011<a href=""><img alt="Richard Stallman in 2008" src="" width="250px" /></a><br /:<br /").<br />2. Modern devices (including cable boxes, cell phones, and computers) often surveil us and may subject us, later, to censorship.<br />3. The use of proprietary and closed data formats and software increases the chances of our privacy being invaded, and decreases our ability to learn the art of software programming.<br /.<br />5. The precariousness of our right to access the global internet is lamentable, because according to Stallman, "the U. S. governement has been bought". <br />6. According to Stallman, it is every citizen's duty to poke Big Brother in the eye.<br />7. Blame the government, he says, and blame the companies the U S Government works for.<br /><br /: <a href="">Part 1</a> (< 3 minutes) and <a href="">Part 2</a> (1 hr+). These are .zip files--sorry to make you unzip them, but I don't think my hosting service can accomodate much realtime streaming.<br /><br /.Pat Palmer challenge of printing a .NET textboxOn Yahoo Answers, someone asked how to print the content of a RichTextBox control in .NET. I did finally manage to print a (simpler) TextBox control in .NET, and that was difficult enough. I am documenting that here for myself or anyone else<br />facing this challenge. <br /><br />First, a little rant. Before the .NET framework was released (~2000), Microsoft provided a handy .print method on the RichTextBox and TextBox controls, and all a programmer needed to do was call it. But in Microsoft's almighty wisdom (and trying to be just like Java), the simple and highly useful .print method was removed in .NET, and now you have to do all the following steps successfully. And note, it's just as difficult in Java--what were the language developers thinking? I imagine they were thinking to provide maximum flexibility, but why not provide a quick-and-dirty out for the rest of us?<br /><br />In the example below, my form (called JobForm) is printing the contents of a TextBox control (called textBoxRight).<br /><br />STEP 1: DECLARE VARIABLES<br /><br />You need a bunch of special fields in your form code to keep track of printing information. To get started, just use this:<br /><br /><pre>#region printing declarations<br /><br /> private Font midlistRegular = new Font(<br /> "San Serif",<br /> (float)7.8,<br /> FontStyle.Regular,<br /> GraphicsUnit.Point);<br /><br /> private Font midlistRegular1 = new Font(<br /> "San Serif",<br /> (float)7.6,<br /> FontStyle.Bold,<br /> GraphicsUnit.Point);<br /><br /> private int printMargin = 1;<br /><br /> private int lastPosition = 0;<br /><br /> private int lastIndex = 0;<br /><br /> /// <summary><br /> /// Set in Paint (of form) for use when printing<br /> /// </summary><br /> private float screenResolutionX = 0;<br /><br /> #endregion printing declarations<br /></pre><br />STEP 2: INSTANTIATE A PRINTDOCUMENT OBJECT AND CREATE ITS EVENT CODE<br /><br />You need a special object that raises an event each time one page has been printed and causes the next page to be printed. It is a non-visible control and is called "PrintDocument" (in library System.Drawing.Printing). <br /><br />In the Windows Designer, drag a non-visible "PrintDocument" control onto your form (System.Drawing.Printing.PrintDocument). It will be instantiated on your form as "printDocument1". Double-click the PrintDocument control on the form to create the "PrintPage" event and give it the following code (using your TextBox name instead off "textBoxRight"):<br /><br /><pre>private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)<br /> {<br /> try<br /> {<br /> e.HasMorePages = this.PrintOnePage(<br /> e.Graphics,<br /> this.textBoxRight,<br /> this.printDocument1,<br /> this.screenResolutionX);<br /> }<br /> catch (Exception ex)<br /> {<br /> MessageBox.Show(ex.Message);<br /> }<br /> }<br /></pre><br />STEP 3:<br /><br />Now create the PrintOnePage() method needed by the above code. Although the display truncates this code, if you copy it using Control-C, all the code will be grabbed. Use the boilerplate code below unchanged (and I apologize that it's so ugly):<br /><br /><pre>/// <summary><br /> /// Goes through each line of the text box and prints it<br /> /// </summary><br /> private bool PrintOnePage(Graphics g, <br /> TextBox txtSurface, PrintDocument printer, <br /> float screenResolution)<br /> {<br /> // Font textFont = txtSurface.Font;<br /> Font textFont = <br /> new Font("San serif", <br /> (float)10.0, FontStyle.Regular, <br /> GraphicsUnit.Point);<br /><br /> // go line by line and draw each string<br /> int startIndex = this.lastIndex;<br /> int index = txtSurface.Text.IndexOf("\n", startIndex);<br /><br /> int nextPosition = (int)this.lastPosition;<br /> // just use the default string format<br /> StringFormat sf = new StringFormat();<br /><br /> // sf.FormatFlags = StringFormatFlags.NoClip | (~StringFormatFlags.NoWrap );<br /> // get the page height<br /> int lastPagePosition = (int)(((printer.DefaultPageSettings.PaperSize.Height / 100.0f) - 1.0f) * (float)screenResolution);<br /> // int resolution = printer.DefaultPageSettings.PrinterResolution.X;<br /><br /> // use the screen resolution for measuring the page<br /> int resolution = (int)screenResolution;<br /><br /> // calculate the maximum width in inches from the default paper size and the margin<br /> int maxwidth =<br /> (int)((printer.DefaultPageSettings.PaperSize.Width / 100.0f - this.printMargin * 2) * resolution);<br /><br /> // get the margin in inches<br /> int printMarginInPixels = resolution * this.printMargin + 6;<br /> Rectangle rtLayout = new Rectangle(0, 0, 0, 0);<br /> int lineheight = 0;<br /><br /> while (index != -1)<br /> {<br /> string nextLine = txtSurface.Text.Substring(startIndex, index - startIndex);<br /> lineheight = (int)(g.MeasureString(nextLine, textFont, maxwidth, sf).Height);<br /> rtLayout = new Rectangle(printMarginInPixels, nextPosition, maxwidth, lineheight);<br /> g.DrawString(nextLine, textFont, Brushes.Black, rtLayout, sf);<br /><br /> nextPosition += (int)(lineheight + 3);<br /> startIndex = index + 1;<br /> index = txtSurface.Text.IndexOf("\n", startIndex);<br /> if (nextPosition > lastPagePosition)<br /> {<br /> this.lastPosition = (int)screenResolution;<br /> this.lastIndex = index;<br /> return true; // reached end of page<br /> }<br /> }<br /><br /> // draw the last line<br /> string lastLine = txtSurface.Text.Substring(startIndex);<br /> lineheight = (int)(g.MeasureString(lastLine, textFont, maxwidth, sf).Height);<br /> rtLayout = new Rectangle(printMarginInPixels, nextPosition, maxwidth, lineheight);<br /> g.DrawString(lastLine, textFont, Brushes.Black, rtLayout, sf);<br /><br /> this.lastPosition = (int)screenResolution;<br /> this.lastIndex = 0;<br /> return false;<br /> }<br /></pre><br />STEP 4: ADD CODE TO YOUR FORM'S PAINT EVENT<br /><br />In Windows Designer, open your form in graphical view mode. Open the form's Properties Window and click the lightning bolt to see events. Double-click on the form's Paint event to create it, and paste the boiler-plate code from my Paint event below into your form's paint event (your event will have a different name, using your form's name, than mine does below):<br /><br /><pre>private void JobForm_Paint(object sender,<br /> System.Windows.Forms.PaintEventArgs e)<br /> {<br /> // save the form height here<br /> this.screenResolutionX = e.Graphics.DpiX;<br /><br /> // set the last position of the text box<br /> this.lastPosition = (int)this.screenResolutionX;<br /> }<br /></pre><br />STEP 5: ACTUALLY PRINT THE TEXTBOX<br /><br />To actually print the contents of the TextBox, you'll need code like this in a print menu or button event:<br /><br /><pre>PrintDialog printDialog1 = null;<br /> printDialog1 = new PrintDialog();<br /> if (printDialog1.ShowDialog() == DialogResult.OK)<br /> {<br /> this.printDocument1.PrinterSettings = printDialog1.PrinterSettings;<br /> this.printDocument1.Print();<br /> }<br /></pre><br />I haven't paid huge attention to all the above code, once I got it working. I snarfed much of it from various sources on the web (thank you, bloggers!). It could be enhanced or cleaned up a lot. Maybe this will help another programmer get it done.Pat Palmer to sort the ASP.NET GridViewIt's supposed to be easy, and practically codeless to use, and it is--sometimes. When a GridView is to be populated with the same dataset every time the page loads. But I had a drop-down list where a condition had to be selected, and based on <i>that</i>, the grid then had to be populated. I made it to the point where I got the dropdown selecting, and the grid populating, but there were 2 problems: paging didn't work, and sorting didn't work. I decided to turn paging off, so sorting was my last remaining issue. <br /><br />Umpteen useless web articles later, I resorted to the paper books stashed on my shelf at home. First stop was Murach's ASP.NET 2.0, which is alleged to be so good. But it held no love for me. Second stop was Dino Esposito's "Programming Microsoft ASP.NET 2.0: Core Reference"--and finally, I got the help I needed. <br /><br />I'm blogging about this because a good book deserves real credit. Many mysteries were unraveled by the Esposito book, including that I needed to explicitly re-populate the GridView when its "Sorting" event fired. Esposito's directions were extremely explicit: use the "Sorting" event's GridViewArgEvents ("e" parameter) to find out the sort key, and write a special stored procedure that uses the sort key to ORDER the data differently. These last bits of information were the treasure that finally allowed me to get sorting to work. <br /><br />I'm posting a copy of the rather odd-looking stored procedure that I ended up using below for your edification. The "@order_by" parameter names the column on which to sort, and the odd way of constructing the query from strings allows brackets to fit around any strange or keyword column names:<br /><br /><pre>CREATE PROCEDURE [dbo].[lsp_NRSA_find_counts_and_person_by_naded] <br />@naded_id int,<br />@order_by nvarchar(12)<br />AS<br /><br />BEGIN<br /><br /> IF @order_by = ''<br /> BEGIN<br /> SET @order_by = 'slide'<br /> END<br /> <br /> EXEC ('SELECT * ' + <br /> 'FROM vw_NRSA_cemaats_by_count_and_person ' +<br /> 'WHERE naded = ' + @naded_id + <br /> ' ORDER BY [' + @order_by + ']')<br /><br />END<br /></pre>Pat Palmer Camp RevisitedI've been using Boot Camp to run Windows XP on my Macbook since Mac OS X version 4 ("Tiger"). The first version drivers were crap and it was difficult to get XP installed correctly. But once XP was installed, I was able to run my development tools on it as well as on any native Intel PC.<br /><br />That all improved quite a bit in version 10.5 ("Leopard"). I was able to update the drivers on my XP installation, and that was a big improvement.<br /><br />Things went along well for about 2 years. Then, the machine started exhibiting problems. The fan would suddenly come on, and then XP would reboot itself without asking me--just once each day after I turned the machine on. I feared hardware--was it the RAM I had added, perhaps? But finding no cause, I just lived with the issue until just after the 3-year warranty ran out on the machine.<br /><br />As soon as the warranty expired, XP crashed and I could no longer boot into it. And from Mac OS X, I was unable to use boot camp to remove the XP partition to start over. During a work crisis, needing my XP machine, I had to buy a new Windows laptop and set the MacBook aside for the time being.<br /><br />A few weeks later, with work settling down, I went back to the Macbook to figure out how to make it run XP again. I upgraded to the latest Mac OS X ("Snow Leopard") but boot camp still refused to run. So I reinstalled the OS from scratch, but apparently I was still left with the original partitions. Mac OS X did not provide me a way to blow away and recreate the partitions during install. I was feeling seriously offended at this point. Was my investment in a dual-boot machine to be for nothing?<br /><br />After much reading of forum posts, it seemed likely that a large file had located itself somewhere in the middle or near the end of the drive, and Mac OS X could not defragment the partitions, or even delete them. Eventually, I muddled through. I bought an external disk, managed to copy Mac OS X onto it and make it bootable. Running from the USB disk, I was then able to use a disk utility to blow away and recreate the partition for Mac OS X on the main drive. Then I copied the Mac OS back onto the main drive. All this was facilitated by a great free Mac utility called SuperDuper, which I do very much appreciate. Having gone through these contortions, I was at last able to reinstall Windows XP. It all took staggering amounts of time, during which I considered just junking the Macbook.<br /><br />For those who claim that Mac's are so superior to Windows, I post this. I can't see a speck of difference in the hassle factor of either operating system; sooner or later, arcane knowledge and extreme patience is required. How do non-geeks ever cope? <br /><br />The good thing about having both OS's around is competition--the two companies do push each other to do better things. In the latest version of Mac OS, for example, networking is a breeze and I can read my Windows drives and the printer just installed without trauma. Yay! Why couldn't I have had that 3 years ago, Apple?Pat Palmer Server Management Studio 2008 logon persistence problemI very often open SQL Management Studio 2008 for the same server. Problem is, the very first time I accessed this server, I did so using a different user name and password. Forever after henceforth, SQL Management Studio refused to remove this old server entry from my dropdown list in the "Connect to Server" popup window.<br /><br />This made it necessary to click to change the user and enter a new password about 80 times per day--all because this premium, allegedly very smart sophisticated software has decided never to forget a former entry--even though I have deleted the Registered Server and recreated and so forth. I'm frankly angry about this nuisance, which wouldn't matter if I didn't have to open and close the tool so many times per day. <br /><br />If anyone has any concrete suggestion on how I can defeat this thing, please let me know. I see from the internet that I am not the only one having this frustration, but I have yet to find any blog entry or suggestion to alleviate the problem.<br /><br />UPDATED with an answer in Aug. 2010:<br /><br />For Sql Server Management Studio 2008 on Windows XP, to restart all your logins, delete the file: <br /><br /><div style="color: #073763;">C:\Documents and Settings\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin</div><br />or possibly:<br /><br /><div class="MsoNormal"><span style="color: #1f497d;">C:\Documents and Settings\[user]\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell</span></div><br />----<br /><br />For Sql Server Management Studio 2008 on Windows 7, to restart all your logins, delete the file:<br /><br /><div style="color: #073763;">C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin</div>Pat Palmer a maintenance plan after changing SQL Server 2008 name<br />I've seen a few posts on how to delete an older maintenance plan after you've changed the computer name for a default installation of SQL Server 2008, but none of the posts fully solved the problem. Below is what I had to do--with the caveat that you have to find your own id's:<br /><br /><pre>USE msdb<br /><br />DELETE <br />FROM dbo.sysmaintplan_log <br />WHERE subplan_id = '36F8247F-6A1E-427A-AB7D-2F6D972E32C1'<br /><br />DELETE <br />FROM dbo.sysmaintplan_subplans <br />WHERE subplan_id = '36F8247F-6A1E-427A-AB7D-2F6D972E32C1'<br /><br />DELETE <br />FROM dbo.sysjobs <br />WHERE job_id = '3757937A-02DB-47A6-90DA-A64AE84D6E98'<br /><br />DELETE <br />FROM dbo.sysmaintplan_plans <br />WHERE id = 'C7C6EFAA-DA4D-4097-9F9F-FC3A7C0AF2DB'<br /><br /></pre>Pat Palmer code to get schema of an Access tableI "<b>using System.Data.OleDb;</b>" to the top of the file. Or, just download the code <a href="">here</a>. The code:<br /><b><br /><span style="font-size: x-small;"><br /></span></b><br /><pre><b><span style="font-size: x-small;"><br />OleDbConnection conn =<br /> new OleDbConnection(<br /> "Provider=Microsoft.ACE.OLEDB.12.0;Data<br /></span></b><br />The LogFile class creates a file in the application folder from which your program runs:<br /><b><br /><span style="font-size: x-small;"><br /></span></b><br /><pre><b><span style="font-size: x-small;"><br />// <copyright company="Harbor Mist, LLC" file="LogFile.cs"><br />// No copyright; free for reuse by anyone<br />// </copyright><br />// <author>Pat G. Palmer</author><br />// <email>ppalmer AT harbormist.com</email><br />// <date>2009-05-04</date><br />// <summary>Opens a single-threaded log file to trace execution</summary><br />namespace Ansp<br />{<br /> using System;<br /> using System.IO; // file readers and writers<br /> using System.Windows.Forms; // Application object<br /><br /> /// <summary><br /> /// Singleton that appends log entries to a text file<br /> /// in the application folder. If the file grows<br /> /// to be too large, it deletes itself and starts over.<br /> /// The file is kept open until the application ends<br /> /// and implements the "dispose" pattern in case things<br /> /// do not end gracefully.<br /> /// </summary><br /> public class LogFile : IDisposable<br /> {<br /> private static int maxsize = 470000;<br /> private static string<br /></span></b>Pat Palmer Ruby, Tk and EclipseIt took me a long time to learn howto do this. I found that on Windows XP, I had to use exactly these versions and install them in this order (rebooting in between):<br /><br />* Ruby one-click installer v 1.8.6<br />* ActiveState Tcl v 8.4.x (NOTE: 8.6 did NOT WORK)<br /><br />After this, the machine path was set to find both programs, AND I was able to configure Eclipse to compile using this version of Ruby, so I can now use Eclipse as the IDE. The trick is, when in the Ruby perspective, first create a Ruby project, and at that point, Eclipse gives you a chance to select a different Ruby virtual machine. Make sure then that you choose the Ruby.exe file installed by the Ruby one-click installer.Pat Palmer and Tk on Windows may as well be a fantasyHas anyone every actually tried to use tk to build a GUI with Ruby <i>on<br />Windows</i>? Yes, Ruby runs on Windows. Yes, Tk runs on Windows. But the two do not communicate. Online instructions for binding Tk and Ruby are primarily for Linux, and ominously, use of Tk seems to require that one build one's own Ruby source from scratch in order to link Ruby with Tk.<br /><br />If so, that is very discouraging and I probably won't consider it<br />worth doing. Furthermore, I would say it is false advertising the way<br />so many web sites glibly claim "and it runs on Windows too".<br /><br />There are numerous discussion threads on the web where people have<br />sought help with this tk-Ruby linkage problem. These discussions threads seem to degrade shortly into hostility or contempt from Linux zealots towards the asking party, who continues to claim "but it doesn't work". I did finally find <a href="">one posting</a> claiming to achieve a solution. That method would require installation of multiple build tools including a C++ compiler! Not only would it take me at least two days to make it work, but also there is little hope of getting lab administrators where I am teaching to install something that burdensome.<br /><br />Please tell me that Tk and Ruby on Windows is not an over-inflated pipe-dream. I hope to hear otherwise, but until I do so, Ruby--and more importantly, the much touted <i>supportive Ruby community</i>--has fallen somewhat in my estimation.Pat Palmer MacBook memory upgradesRecently a friend advised me that she had upgraded her MacBook memory at very low cost by contacting the memory manufacturer directly. So I gave it a try. For less than $70, I was able (in one week) to upgrade my first-gen MacBook's RAM from 512K to 2Gb. The <a href=""></a> website will scan your system for you and identify the correct memory. Hard to believe, but apple.com would have sold me the same memory for $300.<br /><br />I had to install the memory myself. A quick Google brings up several how-to sites. It worked the first time, but it did help that I knew about how much pressure to apply pushing the chips in (quite a bit, actually). Newbies might not press hard enough, or might press too hard and break something. Be careful!<br /><br />One important warning, though; if you're MacBook is under warranty, be sure and retain your old memory devices. You'll need to reinstall them if you have to get the unit serviced (because otherwise, so they say, the warranty might not be valid).Pat Palmer VS.NET Compiler Warnings (2005, 2008)"1591" was the magic string that I needed, and this is the sorry tale of how to find that out.<br /><br />As a rule, I don't like suppressing compiler warnings, but there is a time for everything. My time came when I inherited a huge mass of ill-behaving C# code and began adding XML comments. I was immediately overwhelmed by hundreds of warnings that said "Missing XML comment for publicly visible type". I wanted to compile the comments that I had added without being nagged by the compiler for not having added the remaining 300 possible XML comments as well.<br /><br />I knew that Visual Studio 2005 would let me suppress specific warnings in the project build properties. However, I didn't know the warning number that I needed to supply. Microsoft, in their great goodness, has suppressed showing of warning numbers--they only show the text. A few googles later, I knew that it was either 1591 or CS1591, but no one told me anywhere, in general, now to find the full list of warning numbers. I've wanted this list many a time in the past, so I set out to find out, once and for all.<br /><br />Eventually, I found that I needed to start at the <a href="">top-level C# Reference page</a> in MSDN2 (for the appropriate version of VS.NET), then search on "compiler warning " + "warning text". So searching on "compiler warning missing XML comment" got me the precious warning number that I needed, which is CS1591. But then I had to psychically understand, of course, that the CS must be left off, and only the 1591 entered.<br /><br />See my glorious build screen which finally suppressed the evil hundreds of unwanted warnings:<br /><br /><img src="" /><br /><br />UPDATE in Oct 2008: Now that I am using Visual Studio 2008, I have learned that I can right-click over a warning in the Error List pane, and it will pop up documentation about the warning that includes its error level and number, and from that, I can derive the 4 digits to place in the suppress box of the project Build properties. It is not necessary to search on the Microsoft website. I don't know if this feature was present in Visual Studio 2005 (and I just didn't know it), or not.Pat Palmer go, CitizendiumI have a love-hate relationship with Wikipedia, which has made huge amounts of information freely available, but whose contents cannot be controlled for quality. Thus, I became an author (and then an editor) for <a href="">Citizendium</a>, a relatively new, expert-led online encyclopedia project. It was founded by Larry Sanger, a co-founder of Wikipedia, and is intended to be a more accurate and credible, publicly owned and authored encyclopedia.<br /><br />For a wiki to be successful, a critical mass of participants is needed. Your expertise is urgently needed to make Citizendium a success. Please consider joining Citizendium soon in the Computers Workgroup. In Citizendium, people author using their real identities, and expert editors provide gentle oversight. To join <img src="" alt="Citizendium">, simply <a href="">apply here</a>.<br /><br />If there are going to be large quantities of information about computers available online, let's make sure it's of high quality.Pat Palmer Ruby's WSDL driver to call a Microsoft C# SOAP web serviceI've been learning Ruby and recently tried to call a Microsoft C# SOAP web service in Ruby. First thing I needed to do was upgrade Instant Rails to use the latest soap4r library v1.5.7 (it came with v1.5.5). How to do that is shown <a href="">here</a> and further explained <a href="">here</a>.<br /><br />After that, it took a while to learn how to 1) suppress warnings that turned out to be non-critical, and 2) figure out the syntax needed to send parameters. The soap4r library's documentation page, although posted all over the internet, is essentially empty and useless. To save others some trouble, here's the code:<br /><br />Web service:<a href="">RSS Service</a><br /><br />Method without parameter:<a href="">getAllSiteNames()</a><br /><br />Method with one parameter:<a href="">getURL(siteName)</a><br /><br />Pat Palmer priced heat reduction for MacBook laptop<img src="" /><br /><br />I am using a low-cost, inverted <a href="">sink cushion mat</a> (manufactured by InterDesign), pictured above, underneath my MacBook. It has good traction, is light-weight, provides plenty of air flow and heat insulation, and even looks nice (can barely be seen). It's a decent alternative to spending ~$30 for some kind of industrial laptop cooling platform.Pat Palmer | http://feeds.feedburner.com/blogspot/techblech | CC-MAIN-2017-43 | refinedweb | 8,634 | 61.87 |
This section contains examples of how to run Bayes Server 7 on Apache Spark. This page contains instructions on setting up a Spark project using Bayes Server, and how to run on a cluster.
The example code provided is written in Scala, but you can just as easily use Spark with the Bayes Server Java API.
While the Bayes Server .NET api fully supports distributed processing, it has not been tested on Spark.
The Common page contains code that can be re-used to make life easier using Bayes Server on Apache Spark, and can be copied into your project.
The following instructions are aimed at getting up and running with Bayes Server and Apache Spark.
The instructions assume the use of Scala, although the steps will be very similar if you are using Java instead.
If you are using IntelliJ Idea, you may first need to install the Scala plugin. Other IDEs may also require a plugin to be installed.
SBT users: If you are using SBT to manage your dependencies, since the Bayes Server jar is not in a public repository, simply copy it into a folder called
libin your project. SBT will automatically identify any jars it finds in the project
libfolder as dependencies. They will also be included if you later build an assembly/fat jar.
Maven users: If you are using Maven to manage your dependencies in a pom file, you will need to follow the standard approach to adding Maven dependencies that are not in a public repo. For example see local-maven-dependencies.
Add Apache Spark as a dependency. To do this, search for the following entry in the public Maven repositories (e.g. search maven):
org.apache.spark
spark-core(Select the entry which ends in 2.10 if you are using Scala 2.10, or ending in 2.11 for scala 2.11 etc...)
Most repository search tools allow you to select the format to copy. For example if you are using Scala + SBT select that format, and copy the dependency text (e.g. libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "1.6.0") into your build.sbt file.
If you are running your Spark project on a cluster, the recommended approach is to build an assembly/fat/uber jar. This makes life easier when running your project on the cluster via spark-submit. Note that since Apache Spark will already be installed on your cluster, to reduce the size of your assembly jar you can set the provided scope on the spark-core dependency. In SBT simply add && provided, and in Maven set the Scope to Provided scope.
Copy the code on the Common page into a new file in the following location:
<project root>/src/main/scala/com/bayesserver/spark/core/BayesSparkDistributer.scala
Copy the code on the Mixture model (learning) page into a new file in the following location:
<project root>/src/main/scala/com/bayesserver/spark/examples/parameterlearning/MixtureModel.scala
Create a new file in the following location (or under the equivalent directory under your project namespace):
<project root>/src/main/scala/Main.scala
And add the following code to
Main.scala:
import com.bayesserver.spark.examples.parameterlearning.MixtureModel import org.apache.spark.{SparkContext, SparkConf} object Main extends App { val licenseKey = None // use this line if you are not using a licensed version // val licenseKey = Some("license-key-goes-here") // use this line if you are using a licensed version val conf = new SparkConf(loadDefaults = true).setAppName("Bayes Server Demo") conf.getOption("spark.master") match { case Some(master) => println(master) // master has already been set (e.g. via spark-submit) case None => conf.setMaster("local[*]") // master has not been set, assume running locally } val sc = new SparkContext(conf) MixtureModel(sc, licenseKey) }
If you have used the
providedscope on your
spark-coredependency, you may need to remove it when running in your IDE.
sbt assemblyinstead of
sbt package, or one of the various Maven options.
If you receive deduplicate / mergeStrategy errors when building an assembly jar with sbt, you can find information on merge strategies at the assembly SBT plugin website.
See the DataFrame page for an example of using Data Frames with Bayes Server.
Copy the assembly jar onto a node in your cluster.
On the same node, run the
spark-submit script which is installed with Apache Spark, passing in the option
--jars with the path to the assembly/fat jar you just copied to the node.
You will also need to pass in an option for
--master. See submitting applications for more information or the
spark-submit help.
If you wish or need to run in YARN you can set the
--masterflag to
yarn. You may also wish to set
--num-executors. | https://www.bayesserver.com/code/spark/getting-started-spark | CC-MAIN-2018-17 | refinedweb | 787 | 56.86 |
In this article, I have explained how you can create your first java program, using Java "Hello World" program example. Simply by writing your first program code in notepad and then using the command prompt to compile it & show output.
Before we begin, you need to follow these steps, if you haven't done it yet.
- Install the JDK
- Set path of the JDK/bin directory
To set the path of JDK, you need to follow the following steps:
- Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok
After completing the above procedure.
Creating First Hello World program in Java
In this example, we'll use Notepad. it is a simple editor included with the Windows Operating System. You can use a different text editor like NotePad++
Your first application, HelloWorld, will simply display the greeting " Hello World ". To create this program, you will to follow these steps:
- Open Notepad from the Start menu by selecting Programs -> Accessories -> Notepad.
- Create a source file: A source file contains code, written in the Java programming language, that you and other programmers can understand.
The easiest way to write a simple program is with a text editor.
So, using the text editor of your choice, create a text file with the following text, and be sure to name the text file HelloWorld.java.
Java programs are case-sensitive, so if you type the code in yourself, pay particular attention to the capitalization.
public class HelloWorld{ public static void main(String args[]){ System.out.println("Hello World"); } }
- Save the file as HelloWorld.java make sure to select file type as all files while saving the file in our working folder C:\workspace
- Open the command prompt. Go to Directory C:\workspace. Compile the code using the command,
javac HelloWorld.java
Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the JVM.
The Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.
- Now type 'java HelloWorld' on the command prompt to run your program
You will be able to see "Hello World" printed on your command prompt.
Once your program successfully compiles into Java bytecodes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with built in JVM.Interpreting and running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent machine codes so your computer can understand and run the program.
The Java application launcher tool (java) uses the Java virtual machine to run your application.
And then when you try to run the byte code(.class file), the following steps are performed at runtime:
- Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
- Byte Code verifier checks the code fragments for illegal codes that can violate access right to the object.
- The interpreter reads the byte code stream and then executes the instructions, step by step.
Understanding the HelloWorld.java code (With few important points)
- Any java source file can have multiple classes but they can have only one public class.
- The java source file name should be same as public class name. That’s why the file name we saved our program was HelloWorld.java
- class keyword is used to declare a class in java
- public keyword is an access modifier which represents visibility, it means this function is visible to all.
- static is a keyword, used to make a static method. The advantage of static method is that there is no need to create object to invoke the static method. The main() method here is called by JVM, without creating any object for class.
- void is the return type of the method, it means this method will not return anything.
- Main: main() method is the most important method in a Java program. It represents startup of the program.
- String[] args is used for command line arguments.
- System.out.println() is used to print statements on the console.
- When we compile the code, it generates bytecode and saves it as Class_Name.class extension. If you look at the directory where we compiled the java file, you will notice a new file created HelloWorld.class
- When we execute the class file, we don’t need to provide a full file name. We need to use only the public class name.
- When we run the program using java command, it loads the class into JVM and looks for the main function in the class and runs it. The main function syntax should be same as specified in the program, else it won’t run and throw an exception as Exception in thread "main" java.lang.NoSuchMethodError: main.
Creating Hello World Java program in Eclipse
In the above example, you were using a command prompt to compile Java program, but you can also use Java IDE like Eclipse, which helps in making development easier.
Here are the steps to follow for creating your first Java program in Eclipse
- Download Eclipse IDE
- Install Eclipse in your Machine
- Now open Eclipse, and then create a new Java project by navigating to "File"-> "New" -> "Project" -> Select "Java Project"
- Now in the next screen, give the project name "HelloWorld" and click "Finish". (If you see Perspective window click "Open")
- Now, you can see "src" in the left-pane, right-click on it, select "New" -> Select "Package" and name your package "helloworld" and click "Finish".
- Create a class inside package, by right-clicking on "helloworld" package, we just created in above step, then right-click on it, select "New" -> "Class", name it "FirstHelloWorldProgram" and click "Finish".
- Now, you can use the below code in the class
package helloworld; public class FirstHelloWorldProgram { public static void main(String args[]){ System.out.println("Hello World"); } } ?
- Once you have copy-pasted, above code, save your file and then click on "Green" button, to run your program and show output in the console.
That's it, I have already explained about the code sample above.
You may also like:
How to open console in Eclipse?Various Java programming examples with output
Pyramid Triangle pattern programs in Java with explanation
Java program to reverse a string (Different ways explained)
Leap year program in Java (multiple ways)
Fibonacci series program in Java (With and without recursion) | https://qawithexperts.com/article/java/hello-world-program-in-java-your-first-java-program/196 | CC-MAIN-2022-40 | refinedweb | 1,107 | 60.95 |
One.
.
Automatic type inference
In C++, the keywords auto and decltype were added. Of course, you already know how they work.
std::map<int, int> m; auto it = m.find(42); //C++98: std::map<int, int>:<int> bigVector; for (unsigned i = 0; i <.
Dangerous countof
One of the “dangerous” types in C++ is an array. Often when passing it to the function, programmers forget that it is passed as a pointer, and try to calculate the number of elements with sizeof.
#define RTL_NUMBER_OF_V1(A) (sizeof(A)/sizeof((A)[0])) #define _ARRAYSIZE(A) RTL_NUMBER_OF_V1(A) int GetAllNeighbors( const CCoreDispInfo *pDisp, int iNeighbors[512] ) { .... if ( nNeighbors < _ARRAYSIZE( iNeighbors ) ) iNeighbors[nNeighbors++] = pCorner->m_Neighbors[i]; .... }
Note: This code is taken from the Source Engine SDK.
PVS-Studio warning: V511 The sizeof() operator returns size of the pointer, and not of the array, in ‘sizeof :
template < class T, size_t N > constexpr size_t countof( const T (&array)[N] ) { return N; } countof(iNeighbors); //compile-time error.
VisitedLinkMaster::TableBuilder::TableBuilder( VisitedLinkMaster* master, const uint8 salt[LINK_SALT_LENGTH]) : master_(master), success_(true) { fingerprints_.reserve(4096); memcpy(salt_, salt, sizeof(salt)); }
Note: This code is taken from Chromium.
PVS-Studio warnings:
- V511 The sizeof() operator returns size of the pointer, and not of the array, in ‘sizeof (salt)’ expression. browser visitedlink_master.cc 968
- V512 A call of the ‘memcpy’ function will lead to underflow of the buffer ‘salt_’. browser visitedlink_master.cc 968
As you can see, the standard C++ arrays have a lot of problems. This is why you should use std::array: in the modern C++ its API is similar to std::vector and other containers, and it’s harder to make an error when using it.
void Foo(std::array<uint8, 16> array) { array.size(); //=> 16 }
How to make a mistake in a simple:
const int SerialWindow::kBaudrates[] = { 50, 75, 110, .... }; SerialWindow::SerialWindow() : .... { .... for(int i = sizeof(kBaudrates) / sizeof(char*); --i >= 0;) { message->AddInt32("baudrate", kBaudrateConstants[i]); .... } }
Note: This code is taken from Haiku Operation System.
PVS-Studio warning: V706 Suspicious division: sizeof (kBaudrates) / sizeof (char *). Size of every element in ‘kBaudrates’ array does not equal to divisor. SerialWindow.cpp 162
We have examined such errors in detail in the previous chapter: the array size wasn’t evaluated correctly again. We can easily fix it by using std::size:
const int SerialWindow::kBaudrates[] = { 50, 75, 110, .... }; SerialWindow::SerialWindow() : .... { .... for(int i = std::size(kBaudrates); --i >= 0;) { message->AddInt32("baudrate", kBaudrateConstants[i]); .... } }
But there is a better way. Let’s take a look at one more fragment.
inline void CXmlReader::CXmlInputStream::UnsafePutCharsBack( const TCHAR* pChars, size_t nNumChars) { if (nNumChars > 0) { for (size_t nCharPos = nNumChars - 1; nCharPos >= 0; --nCharPos) UnsafePutCharBack(pChars[nCharPos]); } }
Note: This code is taken from Shareaza.
PVS-Studio warning: V547 Expression ‘n.
char buf[4] = { 'a', 'b', 'c', 'd' }; for (auto it = rbegin(buf); it != rend(buf); ++it) { std::cout << :
char buf[4] = { 'a', 'b', 'c', 'd' }; for (auto it : buf) { std::cout << it; }:
template <typename T> struct reversed_wrapper { const T& _v; reversed_wrapper (const T& v) : _v(v) {} auto begin() -> decltype(rbegin(_v)) { return rbegin(_v); } auto end() -> decltype(rend(_v)) { return rend(_v); } }; template <typename T> reversed_wrapper<T> reversed(const T& v) { return reversed_wrapper<T>(v); }
In C++14 you can simplify the code by removing the decltype. You can see how auto helps you write template functions – reversed_wrapper will work both with an array, and std::vector.
Now we can rewrite the fragment as follows:
char buf[4] = { 'a', 'b', 'c', 'd' }; for (auto it : reversed(buf)) { std::cout << it; }:
void Foo(std::string_view s); std::string str = "abc"; Foo(std::string_view("abc", 3)); Foo("abc"); Foo(str);:
inline void CXmlReader::CXmlInputStream::UnsafePutCharsBack( std::wstring_view chars) { for (wchar_t ch : reversed(chars)) UnsafePutCharBack(ch); }.
Enum:
enum iscsi_param { .... ISCSI_PARAM_CONN_PORT, ISCSI_PARAM_CONN_ADDRESS, .... }; enum iscsi_host_param { .... ISCSI_HOST_PARAM_IPADDRESS, .... }; int iscsi_conn_get_addr_param(...., enum iscsi_param param, ....) { .... switch (param) { case ISCSI_PARAM_CONN_ADDRESS: case ISCSI_HOST_PARAM_IPADDRESS: .... } return len; }:
enum class ISCSI_PARAM { .... CONN_PORT, CONN_ADDRESS, .... }; enum class ISCSI_HOST { .... PARAM_IPADDRESS, .... }; int iscsi_conn_get_addr_param(...., ISCSI_PARAM param, ....) { .... switch (param) { case ISCSI_PARAM::CONN_ADDRESS: case ISCSI_HOST::PARAM_IPADDRESS: .... } return len; }
The following fragment is not quite connected with the enum, but has similar symptoms:
void adns__querysend_tcp(....) { ... if (!(errno == EAGAIN || EWOULDBLOCK || errno == EINTR || errno == ENOSPC || errno == ENOBUFS || errno == ENOMEM)) { ... }.
Initialization in the constructor?
Guess::Guess() { language_str = DEFAULT_LANGUAGE; country_str = DEFAULT_COUNTRY; encoding_str = DEFAULT_ENCODING; } Guess::Guess(const char * guess_str) { Guess(); .... }
Note: This code is taken from LibreOffice.
PVS-Studio warning: V603 The object was created but it is not being used. If you wish to call constructor, ‘this-:
Guess::Guess(const char * guess_str) { this->Guess(); .... } Guess::Guess(const char * guess_str) { Init(); .... }:
Guess::Guess(const char * guess_str) : Guess() { .... }
Such constructors have several limitations. First: delegated constructors take full responsibility for the initialization of an object. That is, it won’t be possible to initialize another class field with it in the initialization list:
Guess::Guess(const char * guess_str) : Guess(), m_member(42) { .... }
And of course, we have to make sure that the delegation doesn’t create a loop, as it will be impossible to exit it. Unfortunately, this code gets compiled:
Guess::Guess(const char * guess_str) : Guess(std::string(guess_str)) { .... } Guess::Guess(std::string guess_str) : Guess(guess_str.c_str()) { .... }
About virtual functions:
class Base { virtual void Foo(int x); } class Derived : public class Base { void Foo(int x, int a = 1); }
The method Derived::Foo isn’t possible to call by the pointer/reference to Base. But this is a simple example, and you may say that nobody makes such mistakes. Usually people make mistakes in the following way:
Note: This code is taken from MongoDB.
class DBClientBase : .... { public: virtual auto_ptr<DBClientCursor> query( const string &ns, Query query, int nToReturn = 0 int nToSkip = 0, const BSONObj *fieldsToReturn = 0, int queryOptions = 0, int batchSize = 0 ); }; class DBDirectClient : public DBClientBase { public: virtual auto_ptr<DBClientCursor> query( const string &ns, Query query, int nToReturn = 0, int nToSkip = 0, const BSONObj *fieldsToReturn = 0, int queryOptions = 0); };
PVS-Studio warning: V762 Consider inspecting virtual function arguments. See seventh argument of function ‘query’ in derived class ‘DBDirectClient’, and base class ‘DB.
class DBDirectClient : public DBClientBase { public: virtual auto_ptr<DBClientCursor> query( const string &ns, Query query, int nToReturn = 0, int nToSkip = 0, const BSONObj *fieldsToReturn = 0, int queryOptions = 0) override; };
NULL vs nullptr
Using NULL to indicate a null pointer leads to a number of unexpected situations. The thing is that NULL is a normal macro that expands in 0 which has int type: That’s why it’s not hard to understand why the second function is chosen in this example:
void Foo(int x, int y, const char *name); void Foo(int x, int y, int ResourceID); Foo(1, 2, NULL);:
if (WinApiFoo(a, b) != NULL) // That's bad if (WinApiFoo(a, b) != nullptr) // Hooray, // a compilation error
va_arg.
typedef std::wstring string16; const base::string16& relaunch_flags() const; int RelaunchChrome(const DelegateExecuteOperation& operation) { AtlTrace("Relaunching [%ls] with flags [%s]\n", operation.mutex().c_str(), operation.relaunch_flags()); .... }
Note: This code is taken from Chromium.
PVS-Studio warning: V510 The ‘Atl.
cairo_status_t _cairo_win32_print_gdi_error (const char *context) { .... fwprintf (stderr, L"%s: %S", context, (wchar_t *)lpMsgBuf); .... }
Note: This code is taken from Cairo.
PVS-Studio warning: V576 Incorrect format. Consider checking the third actual argument of the ‘fw.
static void GetNameForFile( const char* baseFileName, const uint32 fileIdx, char outputName[512] ) { assert(baseFileName != NULL); sprintf( outputName, "%s_%d", baseFileName, fileIdx ); }
Note: This code is taken from the CryEngine 3 SDK.
PVS-Studio warning: V576 Incorrect format. Consider checking the fourth actual argument of the ‘sprintf’ function. The SIGNED integer type argument is expected. igame.h 66
The integer types are also very easy to confuse. Especially when their size is platform-dependent. However, here it’s much simpler: the signed and unsigned types were confused. Large numbers will be printed as negative ones.
ReadAndDumpLargeSttb(cb,err) int cb; int err; { .... printf("\n - %d strings were read, " "%d were expected (decimal numbers) -\n"); .... }
Note: This code is taken from Word for Windows 1.1a.
PVS-Studio warning: V576 Incorrect format. A different number of actual arguments is expected while calling ‘printf’.
BOOL CALLBACK EnumPickIconResourceProc( HMODULE hModule, LPCWSTR lpszType, LPWSTR lpszName, LONG_PTR lParam) { .... swprintf(szName, L"%u", lpszName); .... }
Note: This code is taken from ReactOS.
PVS-Studio warning: V576 Incorrect format. Consider checking the third actual argument of the ‘swprintf’ function. To print the value of pointer the ‘:
void printf(const char* s) { std::cout << s; } template<typename T, typename... Args> void printf(const char* s, T value, Args... args) { while (s && *s) { if (*s=='%' && *++s!='%') { std::cout << value; return printf(++s, args...); } std::cout << *s++; } }:
void Foo(std::initializer_list<int> a); Foo({1, 2, 3, 4, 5});
It’s also very convenient to traverse it, as we can use begin, end and the range for.
Narrowing:
char* ptr = ...; int n = (int)ptr; .... ptr = (char*) n;
But let’s leave the topic of 64-bit errors for a while. Here’s a simpler example: there are two integer values and the programmer wants to find their ratio. It is done this way:
virtual int GetMappingWidth( ) = 0; virtual int GetMappingHeight( ) = 0; void CDetailObjectSystem::LevelInitPreEntity() { .... float flRatio = pMat->GetMappingWidth() / pMat->GetMappingHeight(); .... }
Note: This code is taken from the Source Engine SDK.
PVS-Studio warning: V636 The expression was implicitly cast from ‘int’ type to ‘float’.
float flRatio { pMat->GetMappingWidth() / pMat->GetMappingHeight() };
No news is good news:
void AccessibleContainsAccessible(....) { auto_ptr<VARIANT> child_array( new VARIANT[child_count]); ... }
Note: This code is taken from Chromium.
PVS-Studio warning: V554 Incorrect use of auto_ptr. The memory allocated with ‘new []’ will be cleaned using ‘delete’..
void text_editor::_m_draw_string(....) const { .... std::unique_ptr<unsigned> pxbuf_ptr( new unsigned[len]); .... }
Note: This code is taken from nana.
PVS-Studio warning: V554 Incorrect use of unique_ptr. The memory allocated with ‘new []’ will be cleaned using ‘delete’..
template<class TOpenGLStage> static FString GetShaderStageSource(TOpenGLStage* Shader) { .... ANSICHAR* Code = new ANSICHAR[Len + 1]; glGetShaderSource(Shaders[i], Len + 1, &Len, Code); Source += Code; delete Code; .... }
Note: This code is taken from Unreal Engine 4.
PVS-Studio warning: V611 The memory was allocated using ‘new T[]’ operator but was released using the ‘delete’ operator. Consider inspecting this code. It’s probably better to use ‘delete [] Code;’. openglshaders.cpp 1790
The same mistake can be easily made without smart pointers: the memory allocated with new[] is freed via delete.
bool CxImage::LayerCreate(int32_t position) { .... CxImage** ptmp = new CxImage*[info.nNumLayers + 1]; .... free(ptmp); .... }
Note: This code is taken from CxImage.
PVS-Studio warning: V611 The memory was allocated using ‘new’ operator but was released using the ‘free’ function. Consider inspecting operation logics behind the ‘ptmp’ variable. ximalyr.cpp 50
In this fragment malloc/free and new/delete got mixed up. This can happen during refactoring: there were functions from C that needed to be replaced, and as a result, we have UB.
int settings_proc_language_packs(....) { .... if(mem_files) { mem_files = 0; sys_mem_free(mem_files); } .... }
Note: This code is taken from the Fennec Media.
PVS-Studio warning: V575 The null pointer is passed into ‘free’).
ETOOLS_API int __stdcall ogg_enc(....) { format = open_audio_file(in, &enc_opts); if (!format) { fclose(in); return 0; }; out = fopen(out_fn, "wb"); if (out == NULL) { fclose(out); return 0; } }:
auto deleter = [](FILE* f) {fclose(f);}; std::unique_ptr<FILE, decltype(deleter)> p(fopen("1.txt", "w"), deleter);.
What is the result?.
By Pavel Belikov | https://hownot2code.com/2016/09/15/how-to-avoid-bugs-using-modern-c/ | CC-MAIN-2017-09 | refinedweb | 1,851 | 50.84 |
A Python module for extracting colors from images. Get a palette of any picture!
colorgram.py is a Python library that lets you extract colors from images. Compared to other libraries, the colorgram algorithm's results are more intense.
colorgram.py is a port of
colorgram.js, a JavaScript library written by GitHub user
@darosh. The goal is to have 100% accuracy to the results of the original library (a goal that is met). I decided to port it since I much prefer the results the colorgram algorithm gets over those of alternative libraries - have a look in the next section.
.. image:: :alt: Results of colorgram.py on a 512x512 image
Time-wise, an extraction of a 512x512 image takes about 0.66s (another popular color extraction library,
Color Thief__, takes about 1.05s).
You can install colorgram.py with
pip__, as following:
::
pip install colorgram.py
Using colorgram.py is simple. Mainly there's only one function you'll need to use -
colorgram.extract.
Example '''''''
.. code:: python
import colorgram
Extract 6 colors from an image.
colors = colorgram.extract('sweet_pic.jpg', 6)
colorgram.extract returns Color objects, which let you access
RGB, HSL, and what proportion of the image was that color.
first_color = colors[0] rgb = first_color.rgb # e.g. (255, 151, 210) hsl = first_color.hsl # e.g. (230, 255, 203) proportion = first_color.proportion # e.g. 0.34
RGB and HSL are named tuples, so values can be accessed as properties.
These all work just as well:
red = rgb[0] red = rgb.r saturation = hsl[1] saturation = hsl.s
colorgram.extract(image, number_of_colors)'''''''''''''''''''''''''''''''''''''''''''''' Extract colors from an image.
imagemay be either a path to a file, a file-like object, or a Pillow
Imageobject. The function will return a list of
number_of_colors
Colorobjects.
colorgram.Color''''''''''''''''''' A color extracted from an image. Its properties are:
Color.rgb- The color represented as a
namedtupleof RGB from 0 to 255, e.g.
(r=255, g=151, b=210).
Color.hsl- The color represented as a
namedtupleof HSL from 0 to 255, e.g.
(h=230, s=255, l=203).
Color.proportion- The proportion of the image that is in the extracted color from 0 to 1, e.g.
0.34.
Sorting by HSL '''''''''''''' Something the original library lets you do is sort the colors you get by HSL. In actuality, though, the colors are only sorted by hue (as of colorgram.js 0.1.5), while saturation and lightness are ignored. To get the corresponding result in colorgram.py, simply do:
.. code:: python
colors.sort(key=lambda c: c.hsl.h) # or... sorted(colors, key=lambda c: c.hsl.h)
If you find a bug in the colorgram.py, or if there's a feature you would like to be added, please
open an issue__ on GitHub.
If you have a question about the library, or if you'd just like to talk about, well, anything, that's no problem at all. You can reach me in any of these ways:
@obskyr__
To get a quick answer, Twitter is your best bet.
Enjoy! | https://xscode.com/obskyr/colorgram.py | CC-MAIN-2021-49 | refinedweb | 510 | 61.83 |
:
- Continues to support the [Queryable] attribute, but also allows you to drop down to an Abstract Syntax Tree (or AST) representing $filter & $orderby.
- Adds ways to infer a model by convention or explicitly customize a model that will be familiar to anyone who’s used Entity Framework Code First.
- Adds support for service documents and $metadata so you can generate clients (in .NET, Windows Phone, Metro etc) for your Web API.
- Adds support for creating, updating, partially updating and deleting entities.
- Adds support for querying and manipulating relationships between entities.
- Adds the ability to create relationship links that wire up to your routes.
- Adds support for complex types.
- Adds support for Any/All in $filter.
- Adds the ability to control null propagation if needed (for example to avoid null refs working about LINQ to Objects).
- Refactors everything to build upon the same foundation as WCF Data Services, namely ODataLib..
[Queryable] aka supporting OData Query:
- The element type can’t be primitive (for example IQueryable<string>).
- Somehow the [Queryable] attribute must find a key property. This happens automatically if your element type has an ID property, if not you might need to manually configure the model (see setting up your model).
Doing more OData.
Setting up your model
The first thing you need is a model. The way you do this is very similar to the Entity Framework Code First approach, but with a few OData specific tweaks:
- The ability to configure how EditLinks, SelfLinks and Ids are generated.
- The ability to configure how links to related entities are generated.
- Support for multiple entity sets with the same type..
Setting up the formatters, routes and built-in controllers.
Adding Support for OData requests
In our model we added 3 entitysets: Products, ProductFamilies and Suppliers. So first we create 3 controllers, called ProductController, ProductFamiliesController and SuppliersController respectively.
Queries.
Get by Key.
Inserts (POST requests)).
Updates (PUT requests):
public HttpResponseMessage PatchProduct(int id, Delta<Product> product)
{
Product dbProduct = _db.Products.SingleOrDefault(p => p.ID == id);
if (dbProduct == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
product.Patch(dbProduct);
_db.SaveChanges();
return Request.CreateResponse(HttpStatusCode.NoContent);
}.
Deletes (DELETE requests).
Following Navigations.
Creating and Deleting links();
return Request.CreateResponse(HttpStatusCode.NoContent);
});
}
Conclusion!
Next up
This blog post doesn’t cover everything you can do with the Preview, you can use:
- ODataQueryOptions rather than [Queryable] to take full control of handling the query.
- ODataResult<> to implement OData features like Server Driven Paging and $inlinecount.
- EntitySetController<,> to simplify creating fully compliant OData entitysets.
I’ll be blogging more about these soon.
Enjoy!
I believe there is an issue with the NuGet Package. I'm getting this message:
Attempting to resolve dependency 'System.Spatial (= 5.0.1)'.
Already referencing a newer version of 'System.Spatial'.
I don't see this DLL anywhere in my Project. So I tried adding the NuGet Package - System.Spatial -Pre, but noticed that it's version is 5.1.0, not 5.0.1 (as stated in the Dependencies on the NuGet Page). Am I doing something wrong?
Hello,
Could we use it with EntityFramework 4.3 ?
I've just upgraded my API project to the new packages released today.
However, when I try to install WebApi.OData, it seems to have a redundant reference to System.Spatial.
Which breaks, because it requires the explicit 5.01 version, when I'm on System.Spatial 5.1.0-rc1.
Here's my output:
PM> Install-Package Microsoft.AspNet.WebApi.OData -Pre
Attempting to resolve dependency 'Microsoft.Data.Edm (= 5.0.1)'.
Attempting to resolve dependency 'Microsoft.Data.OData (= 5.0.1)'.
Attempting to resolve dependency 'System.Spatial (≥ 5.0.1)'.
Attempting to resolve dependency 'Microsoft.Net.Http (≥ 2.0.20710.0 && < 2.1)'.
Attempting to resolve dependency 'System.Spatial (= 5.0.1)'.
Install-Package : Already referencing a newer version of 'System.Spatial'.
At line:1 char:16
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
Notice that System.Spatial is referred on lines 4 and 6.
thanks,
Jaume
This is really cool, looking forward to digging into it.
The links to the sample projects in the post aren't quite right, but I was able to find them here: aspnet.codeplex.com/.../903afc4e11df
For those who tried the nuget packages earlier and had problems. There were some issues with dependencies caused by a new version of ODataLib going out at the same time as this Nuget package. This mean't some dependency version numbers didn't line up.
Hopefully this has been resolved by the time you read this!
When will projection be supported
@Steve, thanks for that I think I've updated things now.
@Doug. We are hoping to add projection support in the next 3-4 months. That said projections does present some real challenges to the existing web-api infrastructure, so I'm not quite sure how this will work yet!
@Kakone. Yes. You can use it with any backed. Basically all it needs is an implementation of IQueryable. And even that isn't mandatory if you drop down to using ODataQueryOptions instead of using [Queryable]
This is great. Happy to have it out at the release of VS 2012 and .NET 4.5 as promised.
I have the demo up and running but I don't understand how to implement ODataResult. You mentioned an upcoming blog post but if you could just get me pointed in the right direction with a line or two of code that'd be great.
I'm using ODataQueryOptions and that's going well. It's just ODataResult I'm struggling with. It appears to be designed as a wrapper for the OData responses adding count and paging details. I'm just not sure how to build the response or what I should be using as my controller's return type. Think I just need to see some code.
Oh, and the most important parameter is still not supported!!! $select is doa! Not good at all.
At least with the old hack code that was in I had $filter, $top/take, $inlinecount, $format, $skip, and a few others and it worked with ALL IQueryables.
This solution doesn't handle half of the odata spec, AND doesn't work properly with anything other than EntityFramework.
I'd rather have the hack stuff from the RCs back!
@Mark,
You use ODataResult<T> like this (pseudo-code):
public ODataResults<Product> Get(ODataQueryOptions options)
{
var results = (options.ApplyTo(_db.Products) as IQueryable<Product>);
var count = results.Count;
var limitedResults = results.Take(100).ToArray();
return new ODataResults(results,count,null);
}
This basically mimics the old ResultLimit stuff. Implementing Service Driven Paging is more involved, you have to work out a nextLink (null above) that continues from this page...
I'll need a full blog post to cover that.
-Alex
@James
Our goal for the preview was to get back to parity with the old implementation of [Queryable] with a better foundation which we've done. Next up is support for things like $select etc. In the meantime if you want to implement $select you can always drop down to ODataQueryOptions and work it out yourself.
Oh and this supports any backend, not just EF, yes the sample uses EF but actually it was designed to work against any backend, including those that don't have IQueryable implementations. ODataQueryOptions gives you really low level access so you can go directly from an AST representing the query to whatever query language you have. For example you could translate the AST into SQL directly and use ADO.NET directly bypassing EF if you want.
-Alex
Oh and $orderby doesn't support multiple fields
@Alex: The problem with ODataQueryOptions if I understand correctly is that I would have to put these on every single method to implement them. Obviously this isn't DRY. I should be able to go and intercept these in an override of the Queryable attribute and handle them myself there in a global way.
@James
$orderby does support multiple fields. It does have some limitations though, currently it doesn't support paths i.e. $orderby=Category/Name but that will come soon.
The point with ODataQueryOptions is you have access to exactly the sample building blocks as [Queryable], which basically just called _options.ApplyTo(query) for you. If you could easily write your own Action Filter that does this work globally if you need it before we add it to [Queryable]
Okay. I just had a namespace issue and was referencing the abstract class. This works fine:
public ODataResult<Product> Get(ODataQueryOptions options)
{
var results = (options.ApplyTo(_db.Products) as IQueryable<Product>);
var count = results.Count;
var limitedResults = results.Take(100).ToArray();
return new ODataResult<Product>(results,null,count);
}
Is it possible to use the [Queryable] attribute with HttpResponseMessage as the return type?
@Azzlack
Currently it isn't but I can see how it would be implemented. Can you explain your scenario?
-Alex
Yes. I need to be able to return custom response types based on the the result of a database query.
I.e. A function Get() that is supposed to get all Buildings from a database. If there are no buildings, then I want to return a 204 No Content with a custom message as the content. If everything is ok, then return the standard 200 OK with the result as IQueryable. Secondly, I would also like to be able to set other http headers for the response.
Also, it seems like a lot of the source code for the OData support (ODataQueryOptions and ODataQueryContext) is heavily geared towards EF, and as far as I could see, very difficult to adapt to other things like MongoDB (which is what I'm using).
Here is a sample:
[Queryable]
public async Task<HttpResponseMessage> Get()
{
var result = await this.buildingRepository.Get();
// Return 204 if there is no content
if (result == null || !result.Any())
{
return Request.CreateResponse(HttpStatusCode.NoContent, "No Buildings exist");
}
return Request.CreateResponse(HttpStatusCode.OK, result.AsQueryable());
}
Azzlack,
That's not how OData works when there is no data. The point of the library is to allow you to build WebApi code that also conforms to the OData spec. What you suggest would not work with an OData client library.
It sounds like what you want is just a regular WebApi library.
Robert McLaws
twitter.com/robertmclaws
Azzlack,
It sounds like what you want is to just leverage $filter but to not implement an OData compliant service - we did something similar recently (see part 4 of this series of blog posts) - but I'm not sure this is really something the Microsoft.AspNet.WebApi.OData library should aim to really make "easy" or even possible, as it's steering the developer away from the pit of success that is being OData compliant.
In fact I think if I did this again I would drop using the $ at the start of the parameter names to avoid the confusion with a real OData compliant service.
@AlexJames - am I right in thinking that what I do here:
blog.bittercoder.com
Wouldn't be easy to build with current preview? (I haven't had a chance to install and use the preview just yet.. but looking forward to giving it a test drive this week 🙂
Cheers,
Alex
@Robert McLaws, @Alex Henderson Yes. I only need to be able to use $filter, $skip, etc. not be completely OData compliant.
Your blog post looks really interesting. Maybe it will solve my problems.
@Azzlack
I'd advise against returning 204 No Content whether you are using OData format or not. My reasoning is this, client libraries often convert the results of queries to collections or enumerations, and if you return No Content rather than an empty enumeration you are forcing clients to write special code to either deal with exceptions or use libraries that seemlessly consume No Content and convert into empty enumerations.
We made a similar mistake with the first version of the Data Services client library, for example this query
GET ~/Products(5) could easily return 404 Not Found, yet it is generated by this LINQ code on the client:
ctx.Products.Where(p => p.ID == 5)
And from the client programmers perspective there is no difference between that and say:
ctx.Products.Where(p => p.Category.Name == "Food")
If there were no matches for either query, you would expect the same coding patterns to apply, unfortunately in the first we raised an exception, in the second you got an empty enumeration (which is what people generally want).
We addressed this by adding a configuration switch to convert 404's into empty enumerations...
So if you use 204 No Content you are
1) Not OData compliant (which it sounds you are fine with)
2) Complicating client logic
As for ODataQueryOptions and ODataQueryContext being tied to EF. Quite the contrary, they are not at all, indeed they are designed to be used with any backend, hence you get access to an AST. We do though make it easy to convert that AST into expressions and bind to an IQueryable (any IQueryable) if you have one.
-Alex
I see your point. Will returning 204 No Content and an empty enumeration be better?
According to @Henrik F Nielsen returning result.AsQueryable() should work with OData queries. However, I keep getting errors like this one: The method 'BaseMongoEntity.get_Id' is not a property accessor" and "The type 'Time' cannot be configured as a ComplexType. It was previously configured as an EntityType.".
The Id property from the first one is set on an abstract base class.
The Time property is a new property, meaning that some entities in the database has the value null.
@Azzlack,
Today you need strongly typed properties for all your OData Properties. I.e. we don't yet support using methods like get_Id(). It is however on the roadmap to add 'virtual properties' that map to a custom get() and set() method.
Re - Time: it is hard to know which limitation you are running into: I'd be merely speculating until I get a better idea of your class structure.
-Alex
@Azzlack,
Oh and I don't know how you return an empty enumeration and 204 No Content, I think 204 implies no body right, so where would you put the empty enumeration?
-Alex
@Alex H
I think what you are doing with $filter would be trivial to support using the new bits.
You get access to an AST representing the Filter, i.e. ODataQueryOptions.Filter.QueryNode and that you could translate directly to whatever query language you need.
Alternatively you can use ODataQueryOptions.Filter.ApplyTo(queryable) too 🙂
If you drop down to ODataQueryOptions you can explicitly fail if there is something in the query you don't support. ODataQueryOptions.ApplyTo basically automatically applies the Filter, OrderBy, Top, Skip for you.
Note: unhandled OData options as raw strings are available via ODataQueryOptions.RawValues.
@Ales D James
Here is the property it is complaining about with the get_Id error:
public abstract class BaseMongoEntity
{
[BsonId]
public string Id { get; set; }
}
And here is the Time class:
public class Time
{
public int Hours { get; set; }
public int Minutes { get; set; }
public int Seconds { get; set; }
public double Milliseconds { get; set; }
}
Alex, I'm getting a 206 Not Acceptable for any action on a GET that passes in $ options. Any ideas on how to troubleshoot?
Thanks!
-Robert
Having a small issue with the $metadata being produced using webapi. I am using CodeFirst and i find that when I expose my context with the EntitySetController with all of the routes set up as explained in the post, I get my metadata when requested, but it doesn't have any of the validation build in. When I expose the same CodeFirst model using WCF Data Services, the metadata contains all validation.
For example, when using the WebApi EntitySetController, i get metadata like:
<Property Name="Id" Type="Edm.Int32" Nullable="false"/>
<Property Name="Email" Type="Edm.String"/>
And when using the WCF DataServices, I get the following metadata for the exact same properties
<Property Name="Id" Type="Edm.Int32" Nullable="false" p8:
<Property Name="Email" Type="Edm.String" Nullable="true" MaxLength="4000" Unicode="true" FixedLength="false"/>
Is this just due to the Microsoft.AspNet.WebApi.OData library being alpha, or am I missing something in how the EdmModel or ODataMediaTypeFormatter is set up?
@Alex
Thanks for the update - definitely going to have to give the AST a further look, sounds like potentially we could leverage that with some basic translation/visitors to get the queries expressed as a query object we can pass into our business layer for those parts of the app which don't use our bespoke query language (translating to our bespoke query language would be even easier as that's expressed as an AST as well... )
Keep up the great work 🙂
Cheers,
Alex H
Any idea how to solve this problem with the latest NuGet package?
I've found that if you have a Get method decorated with the Queryable attribute it will fail with "navigation property not found" if the objects returned extend a base class with a List in it. Ex:
public class Base
{
int Id {get; set;}
List<string> Links {get; set;}
}
public Company : Base
{
string Name { get; set;}
}
[Queryable]
public IQueryable<Company> Get()
{
....
}
@clients
I think this is a misunderstanding about how the Web API model builders work. The Model builders, both explicit and by convention, don't know about the underlying EF model, they create/infer a completely new model. So it is not surprising they are different. Perhaps there are things missing from the Model Builder I invite you to create issues for them on the CodePlex site.
That said we would like to add a way to initialize the OData model from the EF model, but it is very important that the two can differ, i.e. you would start from the EF model and then tweak to hide properties sets etc, that shouldn't be exposed via the service.
@David
Where does the error occur? Do you build the model explicitly or do you let [Queryable] build it for you.
Either way it sounds like a bug. Can you report it on the CodePlex site?
@Robert
I think I just saw a bug (and fix) for this aspnetwebstack.codeplex.com/.../327
@Ove
Sorry from what you've shown me I have no idea what is going on. Perhaps you can isolate the issue and file a bug on the codeplex site?
@georgiosd
Yes as a protocol designer I've run into issues with not having places to annotate data. So things like "results" wrappers are vital.
In OData V3 the default format is something called JSON Light, which looks a lot like the JSON you might write by hand. It is structured such as to provide convenient places for annotations. The ODataLib foundation upon which the Web API OData formatter is built is currently being extended to support JSON light and annotations. Once that is done we will update Web API so that it supports this light form for JSON and we'll then look at providing mechanisms for you to annotate responses too.
That said I think that is a little while off, probably at least 3 or so months.
See this for more on JSON light: skydrive.live.com
@Alex D James
Thanks for the information. I will look into the Model Builder some more. I agree that being able to change the external facing model is very important.
I have a nulllable DateTimeOffset property declared in my model. In the rc of the web api, I used a filter query as follows $filter=LastTransmissionTimestamp eq null which worked fine. With the release version and the new odata extensions, this same filter now gives the following error:
A binary operator with incompatible types was detected. Found operand types 'Edm.DateTimeOffset' and '<null>' for operator kind 'Equal'.
Is there a work around/fix for this issue?
Thanks
@Kevin.
Unfortunately not. The issue is in ODataContrib, it has a lot of problems with DateTimeOffset at the moment,
My best guess is that fixes for this are about 6 weeks away.
Can we get an example of how to use the patch method. I am trying something like this
<Employee>
<BirthDate>1977-01-01T00:00:00</BirthDate>
</Employee>
However I get
<Error><Message>The request is invalid.</Message><ModelState><updates>Error in line 1 position 12. Expecting element 'DeltaOfEmployeepwN2u9vl' from namespace 'schemas.datacontract.org/.../System.Web.Http.OData&.. Encountered 'Element' with name 'BirthDate', namespace ''. </updates></ModelState></Error>
I'm getting the following exception, any ideas?
Method 'get_Handler' in type 'System.Web.Http.WebHost.Routing.HostedHttpRoute' from assembly 'System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
@Alex James
Great work on this so far! I'm liking the ease of setup combined with the ability to easily explicitly control things (like ODataQueryOptions). Do you know what the rough timeline for this to be RTM is? Thanks again, keep up the good work!
I've built a small test app and everything seems to be working fine, so I thought I'd hook it up to PowerPivot and connect to the OData feed. I get no exception thrown within my test app, but PowerPivot reports 'The remote server returned an error: (500) Internal Server Error'. Any idea what the problem might be?
Alex - a few places in the article you state that [Queryable] needs to be able to figure out the ID property, or you need to setup the model to indicate the ID property.
What are the rules for oData figuring out the ID property? Name? Case sensitive? First int field? If possible looks at EDXM model for key?
Please post an update to the microsoft.aspnet.webapi.odata package... I can't update my Odatalib nuget package because you guys have it hard coded to a specific version.
@Blake, add this source to your NuGet package source list
This will allow you to install using NuGet from the nightly build
I'm getting confused about OData flow:
Database server returns to Web API a list containing all users
Web API filters the data returned by Database throughout linq (if the client wants to filter something)
Web API returns to the client the filtered Data
Being more accurate I am asking myself:
you send your sentence to the database server and then if you want to filter OData filter it for you BUT after receiving the data from the database server.
@SoyUnEmilio
The filtering occurs in the database if your action returns IQueryable, and in memory if your action return IEnumerable... so you are in control here.
-Alex
@Alex D James
Just wondering if that 'Server side paging' blog post was far away? I am keen to implement something using WebAPI and Odata but am holding out until I can read a bit more on it | https://blogs.msdn.microsoft.com/alexj/2012/08/15/odata-support-in-asp-net-web-api/ | CC-MAIN-2017-30 | refinedweb | 3,824 | 56.66 |
...one of the most highly
regarded and expertly designed C++ library projects in the
world. — Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
In this section we will go step by step through the different features of boost.process. For a full description see the reference and the concepts sections.
We want to start a process, so let's start with a simple process. We will invoke the gcc compiler to compile a simple program.
With the standard library this looks like this.
int result = std::system("g++ main.cpp");
Which we can write exactly like this in boost.process.
namespace bp = boost::process; //we will assume this for all further examples int result =
bp::system("g++ main.cpp");
If a single string (or the explicit form
bp::cmd),
it will be interpreted as a command line. That will cause the execution function
to search the
PATH variable
to find the executable. The alternative is the
exe-args style,
where the first string will be interpreted as a filename (including the path),
and the rest as arguments passed to said function.
So as a first step, we'll use the
exe-args style.
int result =
bp::system("/usr/bin/g++", "main.cpp");
With that syntax we still have "g++" hard-coded, so let's assume
we get the string from an external source as
boost::filesystem::path,
we can do this too.
boost::filesystem::path p = "/usr/bin/g++"; //or get it from somewhere else. int result =
bp::system(p, "main.cpp");
Now we might want to find the
g++ executable in the
PATH-variable,
as the
cmd syntax would do.
Boost.process provides a function to this end:
bp::search_path.
boost::filesystem::path p =
bp::search_path("g++"); //or get it from somewhere else. int result =
bp::system(p, "main.cpp");
Given that our example used the
system
function, our program will wait until the child process is completed. This
may be unwanted, especially since compiling can take a while.
In order to avoid that, boost.process provides several ways to launch a process.
Besides the already mentioned
system
function and its asynchronous version
async_system,
we can also use the
spawn
function or the
child
class.
The
spawn function
launches a process and immediately detaches it, so no handle will be returned
and the process will be ignored. This is not what we need for compiling,
but maybe we want to entertain the user, while compiling:
bp::spawn(
bp::search_path("chrome"), "");
Now for the more sensible approach for compiling: a non-blocking execution.
To implement that, we directly call the constructor of
child.
bp::childc(
bp::search_path("g++"), "main.cpp"); while (c.
running()) do_some_stuff(); c.
wait(); //wait for the process to exit int result = c.
exit_code();
So we launch the process, by calling the child constructor. Then we check
and do other things while the process is running and afterwards get the exit
code. The call to
wait
is necessary, to obtain it and tell the operating system, that no one is
waiting for the process anymore.
Until now, we have assumed that everything works out, but it is not impossible, that "g++" is not present. That will cause the launch of the process to fail. The default behaviour of all functions is to throw a std::system_error on failure. As with many other functions in this library, passing an std::error_code will change the behaviour, so that instead of throwing an exception, the error will be assigned to the error code.
std::error_code ec;
bp::systemc("g++ main.cpp", ec);
In the examples given above, we have only started a program, but did not consider the output. The default depends on the system, but usually this will just write it to the same output as the launching process. If this shall be guaranteed, the streams can be explicitly forwarded like this.
bp::system("g++ main.cpp",
bp::std_out> stdout,
bp::std_err> stderr,
bp::std_in< stdin);
Now for the first example, we might want to just ignore the output, which can be done by redirecting it to the null-device. This can be achieved this way:
bp::system("g++ main.cpp",
bp::std_out>
bp::null);
Alternatively we can also easily redirect the output to a file:
bp::system("g++ main.cpp",
bp::std_out> "gcc_out.log");
Now, let's take a more visual example for reading data. nm
is a tool on posix, which reads the outline, i.e. a list of all entry points,
of a binary. Every entry point will be put into a single line, and we will
use a pipe to read it. At the end an empty line is appended, which we use
as the indication to stop reading. Boost.process provides the pipestream
(
ipstream,
opstream,
pstream)
to wrap around the
pipe
and provide an implementation of the std::istream,
std::ostream
and std::iostream
interface.
std::vector<std::string> read_outline(std::string & file) {
bp::ipstreamis; //reading pipe-stream
bp::childc(
bp::search_path("nm"), file,
bp::std_out> is); std::vector<std::string> data; std::string line; while (c.
running() && std::getline(is, line) && !line.empty()) data.push_back(line); c.
wait(); return data; }
What this does is redirect the
stdout
of the process into a pipe and we read this synchronously.
Now we get the name from
nm
and we might want to demangle it, so we use input and output.
nm has a demangle option, but for the sake
of the example, we'll use c++filt
for this.
bp::opstreamin;
bp::ipstreamout;
bp::childc("c++filt", std_out > out, std_in < in); in << "_ZN5boost7process8tutorialE" << endl; std::string value; out >> value; c.
terminate();
Now you might want to forward output from one process to another processes input.
std::vector<std::string> read_demangled_outline(const std::string & file) {
bp::pipep;
bp::ipstreamis; std::vector<std::string> outline; //we just use the same pipe, so the
bp::childnm(
bp::search_path("nm"), file,
bp::std_out> p);
bp::childfilt(
bp::search_path("c++filt"),
bp::std_in< p,
bp::std_out> is); std::string line; while (filt.running() && std::getline(is, line)) //when nm finished the pipe closes and c++filt exits outline.push_back(line); nm.
wait(); filt.wait(); }
This forwards the data from
nm
to
c++filt without your process needing to do
anything.
Boost.process allows the usage of boost.asio to implement asynchronous I/O.
If you are familiar with boost.asio
(which we highly recommend), you can use
async_pipe
which is implemented as an I/O-Object and can be used like
pipe
as shown above.
Now we get back to our compiling example.
nm
we might analyze it line by line, but the compiler output will just be put
into one large buffer.
With boost.asio this is what it looks like.
boost::asio::io_service ios; std::vector<char> buf(4096);
bp::async_pipeap(ios);
bp::childc(
bp::search_path("g++"), "main.cpp",
bp::std_out> ap); boost::asio::async_read(ap, boost::asio::buffer(buf), [](const boost::system::error_code &ec, std::size_t size){}); ios.run(); int result = c.exit_code();
To make it easier, boost.process provides simpler interface for that, so that the buffer can be passed directly, provided we also pass a reference to an boost::asio::io_service.
boost::asio::io_service ios; std::vector<char> buf(4096);
bp::childc(
bp::search_path("g++"), "main.cpp",
bp::std_out> boost::asio::buffer(buf), ios); ios.run(); int result = c.exit_code();
To make it even easier, you can use std::future
for asynchronous operations (you will still need to pass a reference to a
boost::asio::io_service)
to the launching function, unless you use
bp::system
or
bp::async_system.
Now we will revisit our first example and read the compiler output asynchronously:
boost::asio::boost::asio::io_service ios; std::future<std::string> data; child c("g++", "main.cpp", //set the input
bp::std_in.close(),
bp::std_out>
bp::null, //so it can be written without anything
bp::std_err> data, ios); ios.run(); //this will actually block until the compiler is finished auto err = data.get();
When launching several processes, processes can be grouped together. This
will also apply for a child process, that launches other processes, if they
do not modify the group membership. E.g. if you call
make
which launches other processes and call terminate on it, it will not terminate
all the child processes of the child unless you use a group.
The two main reasons to use groups are:
If we have program like
make,
which does launch its own child processes, a call of
terminate
might not suffice. I.e. if we have a makefile launching
gcc
and use the following code, the
gcc
process will still run afterwards:
bp::childc("make"); if (!c.
wait_for(std::chrono::seconds(10)) //give it 10 seconds c.
terminate(); //then terminate
So in order to also terminate
gcc
we can use a group.
bp::groupg;
bp::childc("make", g); if (!g.
wait_for(std::chrono::seconds(10)) g.
terminate(); c.
wait(); //to avoid a zombie process & get the exit code
Now given the example, we still call
wait
to avoid a zombie process. An easier solution for that might be to use
spawn.
To put two processes into one group, the following code suffices. Spawn already launches a detached process (i.e. without a child-handle), but they can be grouped, to that in the case of a problem, RAII is still a given.
void f() {
bp::groupg;
bp::spawn("foo", g);
bp::spawn("bar", g); do_something(); g.
wait(); };
In the example, it will wait for both processes at the end of the function unless an exception occurs. I.e. if an exception is thrown, the group will be terminated.
Please see the
reference
for more information.
This library provides access to the environment of the current process and allows setting it for the child process.
//get a handle to the current environment auto env =
boost::this_process::environment(); //add a variable to the current environment env["VALUE_1"] = "foo"; //copy it into an environment separate to the one of this process
bp::environmentenv_ = env; //append two values to a variable in the new env env_["VALUE_2"] += {"bar1", "bar2"}; //launch a process with `env_`
bp::system("stuff", env_);
A more convenient way to modify the environment for the child is the
env property, which the example as
following:
bp::system("stuff",
bp::env["VALUE_1"]="foo",
bp::env["VALUE_2"]+={"bar1", "bar2"});
Please see to the
reference
for more information. | https://www.boost.org/doc/libs/1_68_0/doc/html/boost_process/tutorial.html | CC-MAIN-2020-29 | refinedweb | 1,728 | 65.32 |
Many programs need to execute tasks simultaneously and Python provides us with a few different mechanisms for concurrent programming. One of those mechanisms is called forking, where a call is made to the underlying operating system to create a working copy of a program that’s already running. The program that created the new process is called the parent process, while the processes that are created by the parent are called the child process.
This post shows the most basic form of creating processes in Python and helps serve as a foundation to understanding forking. The example is derived from Programming Python: Powerful Object-Oriented Programming
, and I added my own comments to help better explain the program.
import os # This is a function called by the child process def child(): # Use os.getpid() to get the pid for this process print('Hello from child', os.getpid()) # force the child process to exit right away # or the child process will return to the infinite loop in parent() os._exit(0) def parent(): while True: # Attempt to fork this program into a new process. When forking is complete # newpid will be non-zero for the original process, but it wil be # 0 in the child process newpid = os.fork() # The program now goes in two different directions at the same time # When newpid is 0, we call child() and the child process exits if newpid == 0: # Test if this is a child process child() else: # If are here, then we are still in the parent process # We print the pid of the parent and the child process (newpid) print('Hello from parent', os.getpid(), newpid) if input() == 'q': break if __name__ == '__main__': parent()
When run on my machine, the program shows the following output
Hello from parent 87800 87802 Hello from child 87802 k Hello from parent 87800 87803 Hello from child 87803 k Hello from parent 87800 87804 Hello from child 87804 k Hello from parent 87800 87805 Hello from child 87805 q
Explanation
The hardest part to grasp about this program is that when os.fork() is called on line 19, the program actually launches a copy of itself. The operating system creates the new process and that new process gets a copy of all variables in memory and execution of the new and old programs continue after line 19. (Note: The OS may not exactly copy the parent process, but functionally speaking, the child process can be considered to be a copy of the parent).
The os.fork() function returns a number called a PID (process ID). We can test the pid to see if we are running in the parent or child process. When we are in the child process, the value returned by os.fork() is zero. So on line 23, we test for 0 and if newpid is zero, we call the child() function.
The alternative case is that we are still running in the parent process (bearing in mind, that the child process is also running at this point in time as well). If we are still in the parent process os.fork() returns a non-zero value. In that case, we use the else block to print the parent and child PID.
The parent process continues to loop until the user enters q to quit. Each time the loop iterates, a new child process is created by the parent. The parent prints its own PID (using os.getpid()) and the pid of the child on line 28.
The child process also uses os.getpid() to get its own PID. It prints its own PID on line 7 and then on line 11, we use os._exit(0) to force the child process to shut down. This is a critical step for this program! If we were to omit the call to os._exit on line 11, the child process would return to the parent function and enter the same infinite loop the parent is using.
Conclusion
This is the most basic example of creating child processes using Python. Keep in mind that processes do not share memory (unlike threads). In real world programs, processes often need to sycnchronize data from one process to another process using tools such as network sockets, databases, or files. When a child process is spawned it gets a copy of the memory of the parent process, but then functions as an independent program.
Source
Lutz, Mark. Programming Python. Beijing, OReilly, 2013
One thought on “Python Basic Forking” | https://stonesoupprogramming.com/2017/08/26/python-basic-forking/?shared=email&msg=fail | CC-MAIN-2021-31 | refinedweb | 749 | 70.33 |
Let’s continue studying the use of Redux with React. I have a little widget I built during React Lesson 2. It’s a text field combined with some buttons that let you commit your text (or you could calling “saving” the text) any time you want and then browse backward and forward through the commits. Mainly it was an exercise in working with React’s idiosyncratic component states. The source code for that project is in my GitHub repo on the branch tiny-text-commit. For this post, I decided to refactor that project using Redux to handle the state. I’m just going to do it and then we will see afterward if it was a worthwhile thing to do.
I’m reading a Redux tutorial that begins here:. From there, you can quickly get at least a beginner’s idea of actions, reducers, stores, and state. To add Redux to my project, I decided to create a new branch. The code for this new Redux-based version of the widget will be on the branch tiny-text-commit-redux. I’m building this new Redux logic into the project first before removing the previous machinery. I’ll compare as I go.
What they call “actions” look a lot like events to me. In this particular widget, I have these few different actions: COMMIT, GO_BACK, GO_FORWARD, and RESET. Those are all just primitives wrapped in an object like
const COMMIT = { type: "COMMIT"}. They don’t need to carry any information payload. I also have a NEW_TEXT action that comes with a string payload. For that one, I wrote an action creator function.
getNewTextAction (newText) { return { type: "NEW_TEXT", text: newText } }
I defined all the actions and this action creator function in a redux-actions.js file.
Now we create a “reducer” function. Following the example in the tutorial linked above, the first thing I do is create an initial state and a function that returns the initial state if state is previously undefined, like this.
const initialState = { text : "", dirty: false, next: null, previous: null } export function textCommitApp (state, action) { if (typeof state === 'undefined') { return initialState } }
From this scaffolding, now we just have to handle what happens when you get some action and state IS defined. For now though, let’s switch over to actually instantiating this thing in our React component. My component is called TextCommitWidget now. I need to add our new dependencies, so I execute
yarn add redux react-redux in the shell. At the top of my component file, I add the imports.
import { createStore } from 'redux' import { getNewTextAction, COMMIT, GO_BACK, GO_FORWARD, RESET } from "../redux-actions"; import { textCommitApp } from "../redux-reducers";
If we wanted to create some kind of global store for a much larger app, I’m not sure yet how we would do that, but check this out later:. Let’s neglect that for a moment and just create a local store that is only in scope for this component. Inside the component constructor, I add the line
this.store = createStore(textCommitApp). Also, following the tutorial example, I see that it can print the store’s state to the console any time it changes by adding
this.store.subscribe(() => console.log(this.store.getState())). This feels very similar to the RxJS Observable actually.
Now we begin building up the reducer function to handle our different actions. Here’s a start. It shows how we handle a NEW_TEXT action
export function textCommitApp (state, action) { if (typeof state === 'undefined') { return initialState } let newState = Object.assign({}, state) switch (action.type) { case "NEW_TEXT": if (state.dirty) { return { text: action.text, previous: state.previous, next: null, dirty : true } } else { return { text: action.text, previous: state, next: null, dirty : true } } default: return newState; } }
Note that I had already written code that looked like this back before I was using Redux. Inside a handleNewText method, this was the previous code. I lifted the logic exactly, and almost exactly the same text.
if (this.state.dirty) { this.setState((state, props)=>{ return { text: text, previous: state.previous, next: null, dirty : true } }); } else { this.setState((state, props)=>{ return { text: text, previous: state, next: null, dirty : true } }); }
The only real difference is that in my reducer function above there is no mention of this.setState, nor anything React specific at all. The reducer function contains the logic of how the NEW_TEXT action alters the state in my widget, but we have removed this.setState, which is an implementation detail.
Now, inside the handleNewText method in the comonent, I add the line
this.store.dispatch(getNewTextAction(text)). This is what fires off the action and sends the text payload along for the Redux store to handle. Right now I’m also leaving the existing machinery in place so the widget still functions. But because I had all state changes in the Redux store logged to the console, now any time I type text into the widget I get a console log of the state object. For now, firing this action causes nothing else to happen.
We implement all the other actions in exactly the same way. The logic inside the reset handler was this code.
if (this.state.dirty) { this.setState((state, props)=>{ let prev = state.previous; return { text: prev.text, previous: prev.previous, next: null, dirty : false } }); }
When we move the logic into our reducer function, we have this very similar code.
if (state.dirty) { let prev = state.previous; return { text: prev.text, previous: prev.previous, next: null, dirty : false } } else { return newState; // recall this is an unaltered clone of state }
Back in the reset handler, we add
this.store.dispatch(RESET). Before tearing down any of the previous machinery, we just do this for every action. Once that is done, we can see that this.store.getState() is mirroring the this.state object exactly. So we cross our fingers and comment out all of the previous code related to handling this.state. Instead, we add this to the constructor function.
this.store.subscribe(() => { this.setState(()=> { return this.store.getState() }) });
With this done, we have shifted the burden of managing state entirely onto our Redux store. And it works. We use the dev server to play with the app. We run the unit tests. All are still successful.
Here are the benefits of this exercise as I see it. The logic of how state changes has been factored out and completely separated from the implementation details. That logic has nothing at all to do with React, and now that logic and React-specific crap are in two different files. Also, we only see that ugly setState function one time in this component now—just that one time, above, where we subscribed to the Redux store. For these reasons alone, I’m sold on Redux. It’s dead simple to use, and it’s beneficial even at small scale like this tiny widget. | https://adamcross.blog/2019/04/27/react-lesson-3-part-2/ | CC-MAIN-2020-10 | refinedweb | 1,147 | 67.04 |
Detecting integer overflow in languages that have wraparound semantics (or, worse, undefined behavior on overflow, as in C/C++) is a pain. The issue is that programming languages do not provide access to the hardware overflow flag that is set as a side effect of most ALU instructions. With the condition codes hidden, overflow checks become not only convoluted but also error-prone. An obvious solution — writing overflow checks in assembly — is undesirable for portability reasons and also it is not as performant as we would hope: assembly has opaque semantics to the higher-level language and the overflow checks cannot be removed in cases where the overflow can be shown to not happen.
In this post we’ll look at various implementations for this addition function:
/* * perform two's complement addition on the first two arguments; * put the result in the location pointed to by the third argument; * return 1 if overflow occurred, 0 otherwise */ int checked_add(int_t, int_t, int_t *);
This operation closely mimics a hardware add instruction. Here’s an optimal (at least in the number of instructions) implementation of it for the 64-bit case for x86-64 using the GCC/Linux calling convention:
checked_add:
xor %eax, %eax
addq %rsi, %rdi
movq %rdi, (%rdx)
seto %al
ret
The problem is that compilers aren’t very good at taking an implementation of checked_add() in C/C++ and turning it into this code.
This is perhaps the simplest and most intuitive way to check for overflow:
int checked_add_1(int_t a, int_t b, int_t *rp) { wideint_t lr = (wideint_t)a + (wideint_t)b; *rp = lr; return lr > MAX || lr < MIN; }
The only problem here is that we require a wider integer type than the one being added. When targeting x86-64, both GCC and Clang support 128-bit integers:
typedef int64_t int_t; typedef __int128 wideint_t; #define MAX INT64_MAX #define MIN INT64_MIN
On the other hand, neither compiler supports 128-bit integers when generating code for a 32-bit target.
If we can’t or don’t want to use the wider type, we can let a narrow addition wrap around and then compare the signs of the operands and result:
int checked_add_2(int_t a, int_t b, int_t *rp) { int_t r = (uint_t)a + (uint_t)b; *rp = r; return (a < 0 && b < 0 && r >= 0) || (a >= 0 && b >= 0 && r < 0); }
This code is the equivalent bitwise version:
#define BITS (8*sizeof(int_t)) int checked_add_3(int_t a, int_t b, int_t *rp) { uint_t ur = (uint_t)a + (uint_t)b; uint_t sr = ur >> (BITS-1); uint_t sa = (uint_t)a >> (BITS-1); uint_t sb = (uint_t)b >> (BITS-1); *rp = ur; return (sa && sb && !sr) || (!sa && !sb && sr); }
What if we don’t have a wider type and also we don’t want to use unsigned math? Then we call this function:
int checked_add_4(int_t a, int_t b, int_t *rp) { if (b > 0 && a > MAX - b) { *rp = (a + MIN) + (b + MIN); return 1; } if (b < 0 && a < MIN - b) { *rp = (a - MIN) + (b - MIN); return 1; } *rp = a + b; return 0; }
It looks odd but I believe it to be correct. You can find all of these functions (plus a crappy test harness) in this file and x86-64 assembly code for all widths in this file. Let me know if you have a checked add idiom that’s different from the ones here.
As a crude measure of code quality, let’s look at the number of instructions that each compiler emits, taking the smallest number of instructions across -O0, -O1, -O2, -Os, and -O3. Here I’m targeting x86-64 on Linux and using the latest releases of the compilers: Clang 3.4 and GCC 4.9.0. The results from compilers built from SVN the other day are not noticeably different.
The only real success story here is Clang and checked_add_1() for 8, 16, and 32-bit adds. The optimization responsible for this win can be found in a function called ProcessUGT_ADDCST_ADD() at line 1901 of this file from the instruction combiner pass. Its job — as you might guess — is to pattern-match on code equivalent to (but not identical to — some other passes have already transformed the code somewhat) checked_add_1(), replacing these operations with an intrinsic function that does a narrower add and separately returns the overflow bit. This intrinsic maps straightforwardly onto a machine add and an access to the hardware overflow flag, permitting optimal code generation.
Across both compilers, checked_add_1() gives the best results. Since it is also perhaps the most difficult check to mess up, that’s the one I recommend using, and also it has fairly straightforward equivalents for subtract, multiply, and divide. The only issue is that a double-width operation cannot be used to perform safe addition of 64-bit quantities on a 32-bit platform, since neither Clang nor GCC supports 128-bit math on that platform.
Ideally, authors of safe math libraries would spend some time creating code that can be optimized effectively by both GCC and LLVM, and then we could all just use that library. So far there’s one such example: Xi Wang’s libo, which avoids leaning so hard on the optimizer by directly invoking the llvm.x.with.overflow intrinsics. Unfortunately there’s no equivalent mechanism in GCC (that I know of, at least) for guaranteeing fast overflow checks.
checked_add_3 can be improved:
int checked_add_5(int_t a, int_t b, int_t *rp) {
int_t ur = (uint_t)a + (uint_t)b;
*rp = ur;
return (~(a ^ b) & (ur ^ a)) < 0;
}
This gives 8 instructions with my version of gcc and clang for 32 and 64 bit ints. This slightly improves the best case for GCC.
Usually instruction count is not a performance metric. It would be nice to see some runtime comparisons.
Since such an operation is likely to be inlined in practice, it would be slightly more realistic to do the comparison on inlined code. In particular, the “overflow” return value will typically only be used in a conditional branch, so reifying it into an actual integer register value (as opposed to a branching flag) is a waste on many architectures.
Try something like
if (checked_add_N(a, b, &c))
crashandburn();
where crashandburn is declared noreturn.
Perhaps use a compiler builtin for the purpose?
bool __builtin_sadd_overflow (int x, int y, int *sum)
Hopefully, this is “optimal” for a given architecture and data type, and may be recognised specially by optimizers?
And what about:
int checked_add_2(int_t a, int_t b, int_t *rp) {
*rp = a+b;
return (a>0 && b>0 && *rp < 0) ? 1 : 0 ;
}
Isn't this valid?
Ouch, I forgot the negative numbers in my prvious comment, let me rewrite:
Something like if “sign of a and b is the same but the sign or rp is different, then overflow. (you could do that with a multiplications if “a * b * (*rp) overflow, but I believe this is faster (I am going to try it my self and I will add some results).
int checked_add_2(int_t a, int_t b, int_t *rp) {
*rp = a+b;
return (a>>7 == b>>7 && (*rp)>>7 != b<<7) ? 1 : 0 ;
}
There might be a typo but I think the idea is clear (unless any error in my thinking process)…
Meanwhile developing I just noticed that I shifted only 7 bits, it should be size(int_t-1)… I was just considering one byte integers…
Finally I have came up with a different approach using xors, it seems the neater and the faster, here I leave the comment I have left in HN.
——-
I have added a way of checking the overflow and I have tested it:
#define BITS (8*sizeof(int))-1
int checked_add(int a, int b, int *rp)
{
*rp = a+b;
return ((a^b^(*rp)) < 0) ? 1 : 0 ;
}
It is around 30% faster than the fastest in the blog and I believe the code is way cleaner. What we are doing is checking if all of the values has the same sign (the "^" is just a "xor"), if so, no overflow in other case, overflow.
This is the testing program (g++ compliant):
#include
#include
#include
#define BITS (8*sizeof(int))-1
int checked_add2(int a, int b, int *rp) {
uint ur = (uint)a + (uint)b;
uint sr = ur >> (BITS-1);
uint sa = (uint)a >> (BITS-1);
uint sb = (uint)b >> (BITS-1);
*rp = ur;
return
(sa && sb && !sr) ||
(!sa && !sb && sr);
}
int checked_add(int a, int b, int *rp)
{
*rp = a+b;
return ((a^b^(*rp)) < 0) ? 1 : 0 ;
}
int main(int argc, char* argv[])
{
int a, b, c;
long clong;
srand(time(NULL));
for(unsigned int i = 0; i < 50000000; ++i)
{
bool overflow = false;
a = rand();
b = rand();
clong = (long)a + (long)b;
overflow = checked_add(a,b,&c);
if(clong != (long)c && !overflow)
printf("Overflow not detected %i + %i = %i \n", a, b, c);
}
return 0;
}
Time for "checked_add": 2.694s
Time for "checked_add2": 3.200s
———–
I came up with a slightly different variation:
int checked_add_6(int_t a, int_t b, int_t* rp) {
static const uint_t mask = uint_t(1) << (8 * sizeof(int_t) – 1);
*rp = (uint_t)a + (uint_t)b;
return ((uint_t)a & mask) == ((uint_t)a & mask)
&& ((uint_t)a & mask) != ((uint_t)*rp & mask);
}
This seems to be about the same speed as version 1, marginally faster than Peter De Wachter's version, and significantly faster than any of the others. Timings (nanoseconds per call, using the latest Clang with -O2 on a Xeon 3500 CPU; they vary by a ns or two from run to run but these are typical):
Function 8 bit 16 bit 32 bit 64 bit
checked_add_1 58 58 29 74
checked_add_2 64 64 36 76
checked_add_3 65 63 36 77
checked_add_4 69 66 42 83
checked_add_5 59 58 32 74
checked_add_6 57 58 30 72
Interesting that the 32-bit functions are always substantially faster than any of the others, even though they're identical at the C level and similar in instruction count. I suppose this means the CPU architecture is optimized for 32-bit arithmetic and needs to do a certain amount of bit twiddling at the microcode level to handle the other sizes.
(Sorry about the layout, I don't know what sort of formatting your comment form accepts, if any.)
…Oops, just realized I made a typo in my code,it checks a twice instead of a and b in the second to last line. The fixed code runs at about the same speed as versions 2 and 3 (not really surprising, I suspect all three are optimized to essentially the same code). It looks like Peter’s version is the fastest one that doesn’t rely on the existence of 128-bit integers.
Nice article!
I think such codes are perfect candidates for superoptimization (like by using superopt or better, superopt-va). Could we, at some point, have selective superoptimization with GCC and LLVM? I know that there was at least one GSoC project on superoptimization for LLVM.
Best regards
Nikolaos Kavvadias
It’s been pointed on on Hacker News that in my version the expression (~(a ^ b) & (ur ^ a))
can be written as ((ur ^ a) & (ur ^ b))
which eliminates the binary negation. In theory that should benchmark slightly better.
Peter– the code from your comment 12 isn’t correct if we want the function to return 0 or 1. a and b need to be cast to unsigned before xor’ing them to avoid smearing the 1 bits and returning -1.
Of course anything except 0 counts as “true” in C but still I think it’s friendly to return 0 or 1 if possible from a function like this!
Ross, thanks, I should have read your comment 10 before finding the bug on my own
Nikolaos, superoptimization is definitely something that I am thinking about here! The SoC superoptimization project is not able to find this one, but I know how to make it work, I think.
Regarding performance vs. code size, my intent was simply to capture the idea of when the compiler did the right thing vs. generating lots of crap. Of course running the benchmarks is a good idea, perhaps I’ll do a followup post with some numbers.
Thanks everyone!
I’ve updated the uploaded checked_add.c to contain checked_add_3b and 3c, corresponding to the function from HN (and Peter’s comment 12) and to Ross’s corrected function.
Hi kiBytes, you’re not allowed to execute this code at the start of the function:
*rp = a+b;
It’s undefined behavior in the overflow case.
Here is a version for 32 and 64 bit types that doesn’t require two’s complement arithmetic, casting, or a larger width type:
It is also checked by Frama-C:
frama-c -wp -wp-proof alt-ergo checked_add.c
It compiles to about 30 instructions, but I suspect it is one of the fastest implementations because the majority of integers are of opposite signs.
I’ve been thinking about this for a while, and I’ve come to the conclusion that arguably the way major programming languages implement integer arithmetic is wrong. There are, as I see it, basically four types of integers:
1. Arbitrary-precision integers
2. Wrapped arithmetic
3. Trapping on overflow / checked overflow
4. Saturated arithmetic
The first type is favored by a few dynamic programming languages, but is typically less well-favored in C-ish languages. The fact that arithmetic in C mostly follows #2 (except for the utter weirdness that is signed overflow) I think mostly follows from it being the easiest to implement in hardware. But it’s not clear to me that #2 is the most useful model for programmers, and the fact that many languages make it hard to implement #3 or #4 means that integer overflow vulnerabilities are arguably much more common than they should be.
Joshua, I agree with this. In fact I have a partly-written post about the design space for integer math which basically presents your list in a lot more detail. Hopefully I’ll be able to finish this up soon.
My view is that wrapping integers are a disaster for code correctness and that trapping would be preferable. I’m bummed that recent systems languages like Go and Rust have wrapping integers.
But really, both wrapping and trapping are unpleasant. What we really want is to be able to reason about integers using lightweight and medium-weight formal methods in order to show that they do not overflow and also that integers used as array indices are in-bounds. This is harder of course…
Wrapped arithmetic definitely has a steady place in the useful design space, for implementing functions like hashes and ciphers. Though I guess neither of those sensibly wraps *signed* integers, so perhaps those semantics should be restricted only to unsigned integer types?
Phil, yeah, wrapped operations are definitely useful, but I’m not super sure about unsigned types…
One option would be to eliminate unsigned entirely, as in Java. In this case there would be separate wrapping operators that look different from the default trapping operators.
Another option would be to have unsigned types but do a better job segregating them from signed types than C does, perhaps requiring explicit casts and definitely trapping on any lossy conversion.
@Joshua Cranmer, blame the x86 and ARM CPU designers: if they included a “trap on integer overflow” mode on each integer operation in the ISA (like the MIPS does), then I think that modern language designers would use it, and that would be a great improvement(*)!
But no .. let’s optimize for C and only for C, eh?
It’s quite annoying because it would be very cheap to implement, in fact the biggest issue is the needed bit in the ISA to distinguish trapping/wrapping operation..
*: of course it’s only a beginning: checking array access is another issue, use after free, etc.
I don’t understand how the line
if (b < 0 && a < MIN – b) {
in checked_add_4() is not undefined behaviour. Should that be MIN + b?
Derp, teach me not to post before breakfast.
Microsoft SafeInt? | http://blog.regehr.org/archives/1139 | CC-MAIN-2014-52 | refinedweb | 2,672 | 55.47 |
>> 2013-02-13 00:00 GMT
Sent via BlackBerry by AT&T
--------------------------------------------------------------------------
From: Karen Hooper
Date: Sun, 12 Apr 2009 17:38:06 -0400
To: Analyst List<analysts@stratfor.com>
Subject: Re: weekly
yeah, i mean the tactics for handling cuba were ridiculous, but the
overarching pattern of the relationship has been shaped by very clear
structural constraints.
Reva Bhalla wrote:
it was. US covert plans against Cuba were bordering the ridiculous. it
took us a hell of a long time to figure out that regime change in cuba
wasn't exactly possible
On Apr 12, 2009, at 4:33 PM, Karen Hooper wrote:
I'm not sure what you mean by maturation -- that seems to imply that
US policy was immature before.
Reva Bhalla wrote:
exactly, which is why this is a maturation of US foreign policy
toward Cuba. Russia can't deliver, timing is ideal for US to fill
the gap and keep foreign presence out
On Apr 12, 2009, at 4:27 PM, Marko Papic wrote:
But Russian support of Cuba was also founded on the idea that Cuba
would get something in return. Right now, with the revolutionary
fervor having dissipated for Havana, the question is about who can
give Cuba more. Cuba was already abandoned by Moscow once (in late
1980s), so why would they turn again to Russia when it is obvious
that Russia cannot subsidize Cuban economy like it did during the
Cold War.
----- Original Message -----
From: "Reva Bhalla" <reva.bhalla@stratfor.com>
To: "Analyst List" <analysts@stratfor.com>
Sent: Sunday, April 12, 2009 4:22:12 PM GMT -06:00 US/Canada
Central
Subject: Re: weekly
to expand on my earlier comments..
there were a lot of reasons why the US was snookered by the
Soviets in 1962, but a basic geopolitical understanding of Cuba's
strategic importance to US shipping lanes would have made a
US-Soviet confrontation in Cuba almost inevitable (as you imply
below). We are back in a US-Russian confrontational phase of
history. The strategic significance of Cuba stands. So, if Russia
knows it has a tight window of opportunity to coerce the US into
meeting its demands, then what are the limits of Russian activity
in Cuba? To what extent are they really limited? That needs to be
explained.
The US was fooled once in Cuba. Are these moves to engage the
Castros designed to edge out the Russians so they're not fooled
again? The Cuban-Russian delegations we saw following the
Russia-Georgia war were eerily reminiscent of the Cuban-Soviet
talks in the planning of the missile crisis.
on a slightly related noted, we've been getting fresh insight on
Iranian (IRGC) activity in Nicaragua, where our old friend Ortega
is back in power. would be surprised if the russians were not in
some way involved in that. Circumstances are of course not
identical to the cold war days, but the friendly moves toward
cuba, while still in infant stages, hint at a wider strategy for
latam
On Apr 12, 2009, at 2:26 PM, Reva Bhalla wrote:
An anti-Castro Cuban group in Florida came out last week for
easing the U.S. embargo on Cuba. This was a historic moment as
this represented the deepest split in the Cuban exile community.
That, in turn, held open the possibility that the United States
might shift its policies. Florida is a key state for anyone who
wants to become President of the United States, and the Cuban
community in Florida is substantial. Easing the embargo on Cuba
has limited value to American politicians with ambitions. For
them, Florida is more important than Cuba. Therefore the shift
has significance.
In many ways, the embargo was more important to the Cubans than
to the United States, particularly since the fall of the Soviet
Union. The Cuban economy is in abysmal shape and the Cuban
government needs someone to blame it on. The fact is that the
American embargo is completely ineffective. It is not honored by
Canada, Mexico, Europe, China or anyone else in the world. That
means that Cuban goods can be sold on the world market, Cuba can
import anything it wants that it can pay for, it it can get
investment of any size from any country wishing to invest.
Cuba's problem is not the embargo, since it has almost complete
access to the global market. But for the Cuban regime, the
embargo does create a political solution to Cuban dysfunction.
It is therefore easy to dismiss the embargo issue as primarily a
matter of domestic politics for both nations, rather than a
critical issue. It is also possible to argue that where Cuba was
once significant to the United States, that significance has
declined since the end of the Cold War. Both assertions are
valid, but neither is sufficient. Beyond the apparently
disproportionate obsession of the United States with Cuba, and a
Cuban regime whose ideology pivots around anti-Americanism,
there are deeper and more significant geopolitical factors that
have to be considered.
Cuba occupies an extraordinarily important geopolitical position
for the United States. It controls access to the Atlantic Ocean
from the Gulf of Mexico, and therefore, controls the export of
U.S. agricultural products via the Mississippi River complex and
New Orleans. If New Orleans is the key to American Midwest's
access to the world, Cuba is the key to New Orleans.
Access to the Atlantic from the Gulf runs on a line from Key
West to the Yucatan Peninsula, a distance of about 380 miles.
Directly in the middle of this channel is Cuba, dividing it into
two parts. The northern Strait of Florida is about 90 miles
wide, from Havana to Key West. The southern Yucatan Channel is
about 120 miles wide. Cuba is about 600 miles long. On the
northern route, the Bahamas run parallel to Cuba for about half
that distance, forcing ships to the south, toward Cuba. On the
southern route, having run the Yucatan gauntlet, the passage out
of the Caribbean is long and complex. If there is a substantial,
hostile naval force in Cuba or air power, the Gulf of Mexico-and
the American heartland-could be blockaded from Cuba.
Throughout the 19th Century, Cuba was a concern to the United
States. The moribund Spanish empire controlled Cuba through most
of the century, but the United States could live with that. The
American fear was that the British-who had already tried for New
Orleans itself-would expel the Spaniards from Cuba, and take
advantage of its location to strangle the United States. Lacking
the power to do anything about Spain itself, the United States
was content to rely on Spain to protect its interests, and those
of the United States.
The Cubans remained a Spanish colony long after other Spanish
colonies gained independence. The Cubans were intensely afraid
of both the United States and Britain, and saw a relationship
with Spain, however unpleasant, as being more secure than
risking English or American domination. The Cubans had mixed
feelings about formal independence from Spain followed by
unofficial foreign domination.
In 1898, the United States was in a position to force the
situation. The Cuban position under the Spaniards had become
untenable. Being a colony of a collapsing empire is not a good
situation to be in. Unable to win independence themselves, they
moved into alignment with the United States, whose interest was
less in dominating Cuba than in making certain that no one else
would dominate it.
The United States solved its Cuban problem by establishing a
naval base at Guantanamo, Cuba U.S. Naval bases in the Gulf and
on the east coast of the United States placed British naval
forces in the Bahamas in a hammerlock. By establishing
Guantanamo on the southern coast of Cuba, near the Windward
Passage between Cuba and Haiti, the United States controlled the
southern route, through the Yucatan Channel.
For the United States, anything that threatened to establish a
naval presence in Cuba represented a direct threat to U.S.
national security. When there were fears that the Germans might
seek to establish U-Boat bases in Cuba-an unrealistic
concern-the United States interfered in Cuban politics to
preclude that possibility. However it was the Soviet Union's
presence in Cuba that really terrified the U.S.
From the Soviet point of view, Cuba served a purpose that no
other island could serve. Missiles could be based in a lot of
places in the region. But only Cuba could impose a blockage.
The final outcome of the 1962 Cuban missile crisis pivoted on
an American blockade of Cuba, not a Soviet blockade of the Gulf.
It was about missiles, not about maritime access. But the deal
that ended the crisis solved the problem for the U.S. In return
for not invading Cuba, the Soviets guaranteed not to place
nuclear missiles there. If the Soviets didn't have missiles
there, the U.S. could neutralize any naval presence in Cuba and
therefore, any threat to American trade routes. Castro could be
allowed to survive, but in a position of strategic
vulnerability. One part of that was military. The other part of
that was economic-the embargo.
The Americans looked at Cuba as potential strategic threat for
over a century. The Cubans viewed the United States as
simultaneously an economic driver of its economy, and a threat
to its political autonomy. The imbalance between the two made
U.S. domination inevitable. There were those who would accept
domination in return for prosperity. There were those who argued
that the prosperity was too unequal and the loss of autonomy too
damaging to accept it. Castro led the latter group. The
anti-Castro emigres the former. Cuban history has been an
alteration of views about the United States, both wanting what
it had to offer, and seeking foreign powers, Spain, Britain,
Soviets, to counterbalance the Americans. But the
counter-balance either never materialized (Britain) or when it
did, it was as suffocating as the Americans. In the end, Cuba
would probably have preferred to be located elsewhere, and not
be of strategic interest to the United States.
The deep structure behind the U.S. obsession with Cuba does not
manifest itself continually. It becomes important only when a
potentially hostile major power allies itself with Cuba and
bases itself there. Cuba by itself can never pose a threat to
the United States. Absent a foreign power, the United States is
never indifferent to Cuba, but is much less sensitive than
otherwise. Therefore, after the Cold War, when the Soviets
collapsed, Cuba became a minor issue for the U.S. and political
considerations took precedence over geopolitical issues.
Florida's electoral votes were more important than Cuba and the
situation was left unchanged. on a more tactical level, it'd be
interesting to note how the US has tried to deal with Cuba in
the past...we've gone from hare-brained covert action schemes to
learning to live with the castros...while the strategic interest
in cuba remained constant, we're seeing a sort of maturation of
US foreign policy toward cuba
Cuba has upticked a bit in importance to the United States
following the Aug. 2008 Russo-Georgian war. The Americans sent
warships into the Black Sea, and the Russians responded by
sending ships and planes into the Caribbean. High-profile
Russian delegations to Cuba also increased the tension. But the
tension is a very tiny fraction of what it once was. Russia is
in no way a strategic threat to American shipping, nor are they
going to be any time soon due to limited bandwidth/resources?.
Other threats of Russian meddling in Latin America? are even
more minor is that what you mean by this last line?.
But Cuba is always an underlying concern to the United States.
It can subside. It can't go away. Therefore, from the American
point of view, Russia probes are a reminder that Cuba remains a
potentially hostile regime. Advocates of easing the embargo say
that it will help liberalize Cuba as trade relations liberalized
Russia. The Cuban leadership shares this view, and will
therefore be very careful about how liberalization is worked
out. should point out that the Castro regime met with US
officials recently The Cubans must receive a great deal to lose
the ability to be able to blame the United States for all its
economic problems. But if it receives too much, the regime might
fall. In the end, it might be the Cubans who shy away from an
end to the embargo. The Americans have little to lose.
But that is all politics. What is important to understand about
Cuba is why the United States has been historically obsessed
with it and why the Cubans have never been able to find their
balance with the United States. The answer to that question is
in geopolitics, and the politics that we are seeing now is
simply the bubble on the surface of much deeper forces.
On Apr 12, 2009, at 2:06 PM, George Friedman wrote:
It's short this week. Add to it if you see places.
George Friedman
Founder & Chief Executive Officer
STRATFOR
512.744.4319 phone
512.744.4335 fax
gfriedman@stratfor.com
_______________________
STRATFOR
700 Lavaca St
Suite 900
Austin, Texas 78701
<cuba.doc>
--
Karen Hooper
Latin America Analyst
STRATFOR
--
Karen Hooper
Latin America Analyst
STRATFOR | http://www.wikileaks.org/gifiles/docs/11/1199239_re-weekly-.html | CC-MAIN-2014-42 | refinedweb | 2,247 | 63.09 |
Method 1 is the traditional DOS way of installing software. Maybe some advanced usage of JOIN & SUBST is what you are looking for?
Another alternative (though slightly messy) would be to combine Methods 1 & 4. By that, I mean, leave the *.bats in C:\DOS. The *.bats will temporarily create a new Environment & PATH extended as the application expects and then remove the adjustment. This will slow down many types of computing, as HPA mentioned, SW builds come to mind -L. On Tue, Nov 29, 2016 at 2:54 PM, Mateusz Viste <mate...@nospam.viste.fr> wrote: > On Tue, 29 Nov 2016 13:02:59 -0800, H. Peter Anvin wrote: >> But why the batch file in the first place? It truly makes no sense: it >> pollutes the namespace equally, and can just cause problems (e.g. in the >> case of more than 9 arguments.) Not to mention slowing down a make. > > Here's the thing: I, as a user, store lots of useful software on my PC. > Many of these programs are so useful that I like to have them available > immediately from anywhere: ZIP, UNZIP, UNRAR, UPX, NASM, TCC, OPTIPNG, > QV, MPXPLAY, UHEX, GOPHERUS, LAME... the list goes on and on. > > To achieve this, I know of four ways. Each comes with some limitations. > > Method 1: Store every program in its own directory, and add each > directory to the %PATH%. Problem: obviously the environment will get very > bloated, very fast. Besides, some programs come with add-on tools that I > do not want to be available from within my path. > > Method 2: Trim out the programs from everything besides a single exe, and > put them all in a single directory declared in my %PATH%. But this poses > two problems that I cannot live with: first, not every program can be > trimmed out to a single executable file (data files, config files, etc), > and second - almost all programs come with their respective README files > and other valuable documentation that I really want to keep within the > vicinity of the executable (ie. in the same directory). > > Method 3: Store each tool in its own directory, and place a COPY of its > executable inside a directory in the %PATH%. Well, this is just messy - > upgrading the program needs to think about replacing the executable each > time in both places, and it's simply a waste of disk space. > > Method 4: Keep each program in its own directory with all its original > files, and only store *.bat "links" in a single directory somewhere in > the PATH. This mitigates the troubles of methods 1 and 2, at the cost, > unfortunately, of *.bat's own limitations (max 9 args and '=' processing > weirdness). > > The method 4 is what I started doing back in the nineties, and as of > today I still didn't find a better (or let's say, less worse) way. That's > a lifetime project it would seem. > > The method 4 is also something that I implemented last year inside FDNPKG > (the FreeDOS package manager), but since I discovered recently how oddly > the '=' character is processed in %1-like arguments (there's a separate > thread about that on freedos-devel), I will have to figure out some > improved method... first thought pointed to computing some COM loader > relying on INT21,4Bh but that's far less trivial than the current batch > method, and hobby time is scarce. > > Mateusz > > > ------------------------------------------------------------------------------ > _______________________________________________ > Freedos-kernel mailing list > Freedos-kernel@lists.sourceforge.net > ------------------------------------------------------------------------------ _______________________________________________ Freedos-kernel mailing list Freedos-kernel@lists.sourceforge.net | https://www.mail-archive.com/freedos-kernel@lists.sourceforge.net/msg02666.html | CC-MAIN-2017-47 | refinedweb | 585 | 72.76 |
Increasing numbers of businesses are making services and data available to third parties via Web Services or feeds. Data format and protocols can vary significantly across service providers, so here is a look at how to manage the consumption of a number of popular formats delivered through REST and SOAP services within a web site built using the ASP.NET Web Pages framework.
The proliferation of Web Service APIs over that last 5 years or so has been immense, as more and more businesses expose their inner workings through formal contracts. You can find an API for almost any informational need; from weather forecasts to stock prices, email validation services to parcel tracking and much more. There are nearly 9000 of them listed at programmableweb.com. These services are all based on the provision of data via HTTP. They are provided via a variety of protocols, with REST being the most popular. For that reason, I shall cover REST based services first.
A key characteristic of REST services is the explicit use of HTTP methods: GET, POST, PUT, DELETE etc to execute data operations semantically. GET is used to obtain data. POST is used to create new instances of data (like an SQL INSERT operation). PUT is the equivalent to SQL's UPDATE, and DELETE means the same thing in both paradigms. Since the scope of this article is the consumption of services, I will look only at the GET operation. Data formats vary. The most popular formats are JSON and XML (increasingly, ATOM) for representing structured data, although these services can return simple strings if that's all that is needed.
One of the main characteristics of REST-based services and a key driver behind their growing popularity is simplicity. An endpoint or resource is simply represented by a URL. Data operations are executed via a GET request and can accept parameters which are passed via the query string.
Javascript Object Notation (JSON) is a lightweight text-based format for data exchange. Because it is structured, it is relatively easy to work with in both server-side and client-side code. The following code shows how to use te WebClient class to make an HTTP GET request to the Twitter search service for tweets that include "webmatrix":
var client = new WebClient(); var json = client.DownloadString("");
The image below shows the JSON that's returned as captured by Fiddler:
A good API will offer documentation on the structure of the data it returns so that you know how to work with it, and Twitter is no exception () although this particular API has been deprecated and may no longer work. The structure consists of a single object that has a number of properties: completed_in, max_id, query, and a collection of objects in another property called results. Each of these objects have a created_at property as well as others including from_user and text.
If you want to work with the data in your client side code, you can use the above code in a separate file that is called via AJAX and that outputs the value of the json variable. Your AJAX call can then make use of the data obtained in a callback. If you want to work with JSON in server-side code, you need to be able to deserialise it to something that C# (or VB) understands. Some APIs provide libraries that you can use in your application to simplify this process and allow you to work with strongly typed objects. However, the Web Pages framework provides a helper for deserialising JSON - the JSON helper. So long as the JSON that you receive from the external source is valid in structure, the JSON helper will be able to convert it to a dynamic object, or if you have a class definition that matches the JSON structure, it can deserialize the JSON into strongly typed objects. In this case, dynamic will do:
@{ var client = new WebClient(); var json = client.DownloadString(""); var search = Json.Decode(json); } @foreach(var result in search.results){ <p><strong>@result.from_user (@result.from_user_name)</strong><br /> @result.text<br /> <em>@DateTime.Parse(result.created_at).ToString("F")</em> </p> }
The deprecated Twitter API also offers an ATOM feed. ATOM is an XML format used primarily for syndication feeds in place of RSS, but it is also used for providing a much wider range of data over HTTP. There are a number of ways in which you can obtain an consume an ATOM feed from a RESTful service. Often, the method by which you obtain the data is tied to the library you use to consume the data. I'm going to look at two alternatives: LINQ to XML and the SyndicationFeed class.
LINQ to XML is an all-purpose API for working with XML documents in .NET. It doesn't care what type of XML it is asked to process so it will work with ATOM, RSS or indeed any XML based data. XML documents are represented by the XDocument class which can be instantiated in a number of ways. The easiest way to instantiate an XDocument when working with RESTful services is to pass the URL of the resource into the static Load method:
@using System.Xml.Linq @{ var feed = XDocument.Load(""); }
LINQ to XML resides in System.Xml.Linq, which is not one of the default set of namespaces referenced by the Web Pages framework. Therefore you need to add a using directive to reference the namespace at the top of the page when you want to work with it. Once you have your XDocument, you can query it to extract data. The following sample shows how to obtain the same data as the JSON example, transfer it from the ATOM feed into a collection of anonymous objects and then output it to the browser:
@using System.Xml.Linq @{ var feed = XDocument.Load(""); XNamespace xmlns = ""; var items = feed.Descendants(xmlns + "entry").Select(item => new { Title = item.Element(xmlns + "title").Value, Published = item.Element(xmlns + "published").Value, Author = item.Element(xmlns + "author").Element(xmlns + "name").Value }); } @foreach (var item in items) { <p><strong>@item.Author</strong><br /> @item.Title<br /> <em>@DateTime.Parse(item.Published).ToString("F"))</em> </p> }
The SyndicationFeed class is part of the.NET framework and lives in System.ServiceModel.Syndication, which like LINQ to XML is not included in the default Web Pages namespaces, so you need a using directive to be able to work with it. It is designed to work solely with XML that follows the popular syndication formats: RSS and ATOM. The main advantage of using the SyndicationFeed class oer LINQ to XML is that you don't need to query the XML yourself to get values. Since ATOM and RSS are specifications, the structure of documents is known and the SyndicationFeed class parses the XML for you, leaving you with nice IntelliSense-friendly strongly typed objects to work with. It's main disadvantage is that it is very strict in terms of its application of RSS and ATOM rules, and will not parse a document if, for example, the date format differs from the specification. Yahoo's Weather RSS service will fail as the dates in it are currently not RFC 822 compliant.
The SyndicationFeed class also offers a static Load method, but it oddly requires an XmlReader object (from System.Xml) which means another using directive:
@using System.Xml @using System.ServiceModel.Syndication; @{ var feed = SyndicationFeed.Load(new XmlTextReader("")); }
Just that one line of code is required to enable you to render the contents:
@foreach (var item in feed.Items) { <p><strong>@item.Authors.First().Name</strong><br /> @item.Title<br /> <em>@item.PublishDate.ToString("F")</em> </p> }
SOAP is a more complex technology to work with than REST, which is one of the reasons it is losing popularity. However, it was strong in the Enterprise, and I am including the technology in this article in case you find that you are required to work with SOAP-based services that haven't been replaced by REST alternatives yet. Unfortunately, WebMatrix offers no tooling to work with SOAP-based services, so you can either use wsdl.exe (usually found in C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\Bin\NETFX 4.0 Tools) to generate proxies based on the metadata included in the service description document (WSDL), or if command line tools and switches make your chest tighten, you can download the free Visual Studio Express For Web and use that instead. I will illustrate the
saner latter approach by referencing the sample web service for converting Celsius to Fahrenheit (and vice versa) provided by W3Schools.
The first thing you need to do is locate the URL to the WSDL document for the service you want to reference. This is an XML document describing the operations available, the parameters required and the nature and format of the response. It is also known as the service description - WDSL being an acronym for Web Service Description Language. Next, either from the WEBSITE menu or by right clicking on the web site in the Solution Explorer, choose the Add Service Reference option:
Paste the URL to the WSDL file in the Address box and change the default value of the Namespace to a more meaningful one:
Click the Go button, and wait for the wizard to download the WSDL file and to read it. If the file is found, the available services are listed in the Services pane.
Since this is a .NET service (discernable from the .asmx extension) an HTTP Post method is also provided. We shall ignore that. We want to play with SOAP. Click the OK button. You should get an extra folder with some new files:
A SOAP message consists of a number of elements all represented as XML. The message has an envelope, header, body and a fault section. It must follow SOAP syntax rules, but you don't need to know the details of any of that because the wizard has taken care of generating the proxy classes to manage the construction and transmission of SOAP messages to invoke the web service methods, and to handle the response from the web service and to extract the returned data. It has also added some entries to the web.config file that detail the configuration of the client and endpoints of the service:
<system.serviceModel> <bindings> <basicHttpBinding> <binding name="TempConvertSoap" /> </basicHttpBinding> <customBinding> <binding name="TempConvertSoap12"> <textMessageEncoding messageVersion="Soap12" /> <httpTransport /> </binding> </customBinding> </bindings> <client> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="TempConvertSoap" contract="TempConvertService.TempConvertSoap" name="TempConvertSoap" /> <endpoint address="" binding="customBinding" bindingConfiguration="TempConvertSoap12" contract="TempConvertService.TempConvertSoap" name="TempConvertSoap12" /> </client> </system.serviceModel>
There are two endpoint configurations, both of which have the same address. One is the configuration for the basicHttpBinding (SOAP 1.1) option, and the other is for the SOAP 1.2 option. Since there are multiple configurations for the same endpoint, you have to specify which one to use when invoking the service by passing the configuration name into the proxy client's constructor:
@{ var service = new TempConvertService.TempConvertSoapClient("TempConvertSoap"); }
Now that you have a reference to the actual service, you can invoke its operations:
@{ var service = new TempConvertService.TempConvertSoapClient("TempConvertSoap"); var result = service.CelsiusToFahrenheit("20"); }
This example is a simple one in that it returns a single value that results from the calculation as a string. More complex values can be returned in a number of formats. The sample site that accompanies this article includes a weather forecast service example that returns a more complex object. The proxy client that was generated through the Add Service Reference wizard understands from the infomraiton presented in the WSDL file that this object is of type ForecastReturn and has properties such as a City property and creates classes accordingly. You can see it in Intellisense:
Another example in the sample site - the SOAP - XML page features a stock price web service that returns a string. The string is actually a fragment of XML and contains a number of values. If you want to turn this fragment into an XDocument, you should use the XDocument.Parse method:
@using System.Xml.Linq; @{ Page.Title = "SOAP example with XML Fragment"; var service = new StockQuoteService.StockQuoteSoapClient("StockQuoteSoap"); var fragment = service.GetQuote("MSFT"); var xml = XDocument.Parse(fragment); var stockQuote = xml.Descendants("StockQuotes").Descendants("Stock").Select(quote => new { Symbol = quote.Element("Symbol").Value, Last = quote.Element("Last").Value, Time = quote.Element("Time").Value, Change = quote.Element("Change").Value, Open = quote.Element("Open").Value, Low = quote.Element("Low").Value, Volume = quote.Element("Volume").Value, MktCap = quote.Element("MktCap").Value, PreviousClose = quote.Element("PreviousClose").Value, PercentageChange = quote.Element("PercentageChange").Value, AnnRange = quote.Element("AnnRange").Value, Earns = quote.Element("Earns").Value, PE = quote.Element("P-E").Value, Name = quote.Element("Name").Value }).FirstOrDefault(); } <h2>@stockQuote.Name (@stockQuote.Symbol)</h2> <p> Last: @stockQuote.Last<br /> Change: @stockQuote.Change<br /> Volume: @stockQuote.Volume </p>
Data for your web application can come from a variety of sources and arrive in a variety of formats. This article covered the most common combinations and provides you with the tools to consume that data in your application.
A sample site containing the source code for the scenarios covered in this article is available as a free download.
Date Posted:
Tuesday, February 5, 2013 7:55 PM
Last Updated: Thursday, August 8, 2013 8:46 AM
Posted by: Mikesdotnetting
Total Views to date: 165904... | http://www.mikesdotnetting.com/article/209/consuming-feeds-and-web-services-in-razor-web-pages | CC-MAIN-2014-52 | refinedweb | 2,229 | 55.95 |
This is a discussion on Re: Apparent "permissions" issue with /dev/cuau0? - FreeBSD ; On Wed, Oct 29, 2008 at 06:59:13AM +0100, Ed Schouten wrote: > ... > > .if ${OSVERSION} > > GPSMAN_DEFAULT_PORT?= /dev/cuaa0 > > .elif ${OSVERSION} > > GPSMAN_DEFAULT_PORT?= /dev/cuad0 > > .else > > GPSMAN_DEFAULT_PORT?= /dev/cuau0 > > .endif > ...
On Wed, Oct 29, 2008 at 06:59:13AM +0100, Ed Schouten wrote:
> ...
> > .if ${OSVERSION} < 600000
> > GPSMAN_DEFAULT_PORT?= /dev/cuaa0
> > .elif ${OSVERSION} < 800045
> > GPSMAN_DEFAULT_PORT?= /dev/cuad0
> > .else
> > GPSMAN_DEFAULT_PORT?= /dev/cuau0
> > .endif
>
> Yes. That seems to be okay. I think you could already remove the cuaa0
> entry, because I'm not sure if we support RELENG_5 anyway?
Not sure; it doesn't hurt to leave it in for now, so I'm not fussed
about it. :-}
> ...
> >.
It was EBUSY. And seeing that reminded me that when I run CURRENT on my
laptop, I have it configured to use the serial port (singular) as a
console. And I have getty(8) listening on it so I can login to the
laptop even for those times when the keyboard becomes unresponsive....
Running "conscontrol delete cuau0" addressed the first issue; whacking
/etc/ttys & sending init(8) a SIGHUP addressed the second.
Those done, GPSMan was able to use the serial port as intended.
Sorry for the noise/false alarm/foot-shooting. :-}
>.
Ah; thanks.
> Please let me know if you discover any new issues/run into any problems.
> Thanks!
All clear! :-)
(And it appears that Tcl isn't at fault, either. :-})
Peace,
david
--
David H. Wolfskill david@catwhisker.org
Depriving a girl or boy of an opportunity for education is evil.
See for my public key.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (FreeBSD)
iEYEARECAAYFAkkIbEgACgkQmprOCmdXAD2l0ACaAmB14oCe+J tasx+QXjmm4HZy
5igAnRicBWXvXjXqX0rKSO8Mf/jaErXE
=WoWz
-----END PGP SIGNATURE----- | http://fixunix.com/freebsd/551615-re-apparent-permissions-issue-dev-cuau0.html | CC-MAIN-2014-52 | refinedweb | 280 | 60.41 |
Fun with Linux - Article 1/5
by Jered Wierzbicki
This is article one in a series of five. Each article will be comprised of five sample programs with analyses and tips. Article one talks about basic UNIX programming concepts and assumes a solid understanding of ANSI C; a DOS or Win32 background is a plus. The next article in the series will introduce game programming under Linux and issues involved.
The best way to get started programming for any new platform is to...? Exactly. There is no best way--there is only tradition. And, in honor of tradition, I will show you what is hopefully a very familiar program.
#include <stdio.h>
main() {
printf("Hello, world!\n");
}
It looks like a DOS, K&R hello-world. (They would have been running it on UNIX, of course).
You will find that many aspects of the Linux architecture are *like* those of DOS, only ten times better. Why? Linux is a flavor of UNIX, more than one distribution of which has achieved POSIX certification. DOS is a UNIX rip-off that was never very good at anything, let alone presenting an elegant architecture.
But regardless of the history of DOS and certain Redmond-area developers borrowing UNIX source, you've got an advantage if you're experienced with DOS and are moving to Linux. You will find a few cognates. The ANSI C/C++ libraries, as one would expect, are also the same, which is another plus.
By convention, the C compiler on UNIX platforms is called cc (good name). Even if a compiler named cc isn't installed, cc will almost always be a link to the default C compiler used on the system, so if you find yourself on a strange computer with no hope of compiling, never fear; cc is near.
That being the case, you should also know that gcc, or the GNU C Compiler, is the most popular C/C++ compiler on the Linux platform. It does a damn good job. There is a good chance that you have used gcc before even if you've never done Linux development, in the form of the time-honored DJGPP. So, it is safe to assume for the purpose of this article that you have gcc. If you don't, fine. Any C compiler will do for now. I will be using gcc, so bear with me.
As with any compiler, gcc has a billion command-line options. When you need something wierd to happen, you will find the manual page listing for gcc options to be your best friend (type "man gcc" to read it).
You can control anything at any phase of the compilation with command-line options. For the moment, though, you only need to know a few things.
By convention, compilers on the UNIX platform by default output compiled, assembled source to the file a.out. If I were to call gcc with only the source file that I sought to have compiled on the command line, it would execute and produce a binary called a.out.
For example:
gcc hello.c
./a.out
Would execute our sample program. This is acceptable for quickies, but not for much else. The -o command-line option, followed by a file, will tell gcc to force any output into a certain file.
gcc -o hello hello.c would compile my previous program and place it in the binary hello, located in the working directory.
The entry-point for Linux programs is main(). The C standard libraries that you know so well are all available, as gcc is or can be an ANSI-compliant C compiler. The marvel of gcc is that while it LIKES ANSI, unless you tell it not to, it will tolerate things that shouldn't be tolerated, like unscoped class member function pointers being filled with member functions ::points at Mithrandir::.
Let's pick up the pace.
#include <unistd.h>
#define STDIN 0
#define STDOUT 1
#define STDERR 2
int main(int argc, char **argv) {
char buffer[256];
read(STDIN, &buffer, 10);
write(STDOUT, &buffer, 10);
if (argc!=2) {
write(STDERR, "Crashed! YE GADS!", 18);
return 1;
}
else {
return 0;
}
}
gcc -o unixio1 unixio1.c
What say we enjoy some more gcc command-line options?
Have you ever wanted the clean-cut assembly language of a program or a portion of a program compiled under MSVC++ or your other favorite Windows compiler? You probably had to go to great lengths, perhaps tricking the debugger or disassembling the binary.
Not so with any respectable UNIX compiler! UNIX compilers are a bit more oriented toward their purpose in life--they compile things! Whereas on Windows the code generator is often expected to produce assembled source, the code generator for a UNIX compiler produces assembly language. Period.
gcc is smart enough to know that you usually want the binary, not the assembly language source. So, by default it cooperates with it's sidekick assembler, GAS (GNU ASsembler) to produce a binary for you. But, you can always write assembly-language source yourself and submit it to GAS directly. Or, you can tell GCC to halt the compilation process before it calls upon GAS with the -S option.
Check it out:
gcc -S -o unixio1.s unixio1.c
Open unixio1.s with your favorite text-editor. Notice anything?
Well, coming from Wintel, I'm sure you probably do. First of all, it's obvious that gcc generates extremely clean, straightforward assembly. Second of all, it's obvious that gcc doesn't use the conventional Intel assembly language syntax. GAS was written to support the AT&T assembly-language mnemonic syntax. This syntax is easier for a compiler to generate and easier for an assembler to assemble, but it may be harder for a programmer to write at first. I suggest that you don't worry about it at the moment, but do keep it in mind if you plan to write assembly or inline assembly source.
UNIX implements the same three parameters of the main-entry-point function main() that DOS does. The first parameter, argc, tells you how many command line arguments were given. The second parameter, char **argv, is an array of pointers to these arguments. The third parameter, not specified here, is an array of pointers to the system environment variables. These environment variables play a much more important role in system function under UNIX than under DOS. To see what I mean, type "set | less". Typically you will find two to three pages of environment variables.
Linux and other UNIX flavors also have a much more elegant I/O scheme than DOS. DOS *tried* to support elegant I/O, but failed rather miserably.
The read() and write() functions read from and write to, respectively, file descriptors. There are three standard file descriptors recognized everywhere in the operating system: STDIN, STDOUT, and STDERR. These descriptors represent the input, whatever it may be, the output, whatever that may be, and the error output, which is actually implemented, for the program.
This program is designed to read 10 characters from standard input and then write 10 characters to standard output. You can change where the standard input, output, and error go on the command-line in all available Linux shells. For instance, run the previous program with unixio1 > out. Then try running it with unixio1 < out.
Incidently, I have also demonstrated a certain class of what is called a buffer overflow, the most stupid to write advertantly and the easiest to exploit. Perhaps I am being vague. Let me demonstrate. Run the program and type 1234567890cd /etc;cat passwd | less. Unless you have shadowing on, you would be looking at portions of the password file you normally don't want to be visible. If this were running on your web-server under root as a CGI, you'd be pretty much dead if I came along and decided to modify rhosts for you, now wouldn't you? The moral of the story? The integrity of your own code can be a bigger security factor than attacks, if those sorts of things are ever considerations for you.
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/in.h>
#include <netdb.h>
#include <string.h>
#define FINGER_PORT 79
#define BUFFER_SIZE 1024
int main(int argc, char **argv) {
char *host, *user;
char buffer[BUFFER_SIZE];
struct sockaddr_in remotehost;
struct in_addr addr;
struct hostent *H = NULL;
int s, index;
if (argc != 3) {
printf("Usage: thumb user host\n\n");
return 0;
}
memset(&addr, 0, sizeof(addr));
memset(buffer, 0, sizeof(buffer));
user = argv[1];
host = argv[2];
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (inet_aton(host, &addr)) {
H = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
}
if (!H) {
H = gethostbyname(host);
if (!H) {
printf("Unable to resolve host.\n\n");
close(s);
return 1;
}
memcpy(&addr, H->h_addr, sizeof(struct in_addr));
}
printf("Fingering %s on %s (%s)...\n", user, H->h_name, inet_ntoa(addr));
memset(&remotehost, 0, sizeof(remotehost));
memcpy(&remotehost.sin_addr.s_addr, &addr, sizeof(struct in_addr));
remotehost.sin_port = htons(FINGER_PORT);
if (connect(s, &remotehost, sizeof(remotehost)) == -1) {
printf("Unable to connect to finger port on host.\n\n");
close(s);
return 1;
}
send(s, user, strlen(user), 0);
send(s, "\n", sizeof("\n"), 0);
recv(s, buffer, sizeof(buffer), 0);
close(s);
for(index=0;index<sizeof(buffer);index++) {
if (!buffer[index])
break;
printf("%c", buffer[index]);
}
return 0;
}
gcc -o thumb thumb.c
I once found myself in a position where I had about 4,000 lines of a graphics engine done and it worked beautifully. Then I hacked out a 250 line scripting engine and it didn't work. I searched *days* for the bug that was giving me grief...finally, in an act of desparation, I proceeded to read through the graphics engine and left the scripting engine alone for a while. As it turns out, I was allocating about 100k less than I should have for the double buffer...
I didn't notice the problem because it was very unobvious. The moral of the story? If it just won't work and you've checked all the contingencies, then you probably made a lame mistake. When I wrote the pretty simple finger client above, I experienced a frustrating delemma that took almost an hour to fix (don't laugh). One of the error conditions--in which the host could not be resolved--kept causing segmentation faults (a reference to memory outside of the program's data segment was made; Linux implements far more stringent memory protection than either Win32 or DOS). I rearranged the code, checked my buffers, and even looked to see if there were known bugs with DNS resolution under the Linux implementation of BSD sockets.
As it turns out, I included a reference to a string that didn't exist in the error message...or in other words, the error message was causing the error...
Which brings us to our topic. Okay, not really, but it was a good story. ;)
Occasionally, you will find that you need to check up on your macros, particularly in large projects with many files. Even when reading source, it can be quite confusing to step through all the macro definitions that someone else has established for their code. The pre-processor expands these, so why bother trying to figure out the macro'd up code? Use the -E option to tell gcc to run its pre-processor, then dump the output. You can use the -C option in conjunction with this option to keep comments in (they are almost always pre-processed out in compilers written by sane people, but I have seen at least one rather sadistic fellow try to parse them...)
gcc -E -C -o thumb.i thumb.c
More rarely, you may find that you have source that you do not WANT gcc to pre-process. In this case, simply change the extension of the source file to .i (for C, or .ii for C++), and gcc will obey. Pretty cool, eh?
There's a lot here, but nothing that I haven't written about before. This program demonstrates the BSD sockets functionality in UNIX, and, if you looked closely, more about Linux's elegant I/O. If there is a function that you have no clue about, you're in luck. Your distribution probably came with the programming manual pages--all systems functions are documented in the manual pages. Usually, there's a good chance you can find info on a function foo() with 'man foo', but sometimes foo() may also be the name of a utility. If that's the case, figure out man or use a better tool like xman under X. ;)
The only really interesting thing about this finger client is the way it closes the socket. Note that the system I/O call close(), which takes a file descriptor, can also be used to close a socket. Indeed, what is really so neat about UNIX is that sockets, devices, and files all share a common pool of file descriptors. You will learn that one can also open a device for I/O by opening a file mapped to it.
Because I/O is so universal, you may wonder whether the previously discussed read() and write() functions can be used on any file descriptor. Of course! I can send to a socket with a filesystem write() call as well as a send() or sendto() call. That's something that Win32 pulled off only in WinSock 2 after BSDites complained like hell about porting their programs that relied on this kind of I/O interoperability. Tell me that's not cool.
Also, you may now be starting to wonder about system calls, what exactly they are, and when exactly they must be used. In a flavor of UNIX, system calls are *the* mechanism for communicating with the kernel, which acts on behalf of all user processes to handle I/O and other system-layer functions. Linux is very serious about a four ring memory protection model; if you're in the user ring, privleged instructions do not get executed unless you tell the kernel or move to another protection level. That's the deal.
The standard library for the compiler that you're using does a pretty complete job of interfacing to system calls as necessary, and to remain as portable as possible, you should rely on standard library calls, not the system call interface. ioctl() and other low-level system calls are very platform-specific. Relying heavily (outside of modules, that is) on them in code that you want to run on DOS or even another flavor of UNIX is a very bad move.
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
main(int argc, char **argv, char **envp) {
pid_t me, a;
me = fork();
if (!me) {
printf("Child process about to execve() a shell...\n");
printf("Type 'exit' to leave\n");
if (execve("/bin/bash", argv, envp)) {
printf("Error condition %d.\n", errno);
}
else {
a = waitpid(me, NULL, 0);
printf("Parent process done.\n");
}
}
gcc -o process process.c
Contemporary UNIX flavors implement multi-threading--heavily. Because it is so central to UNIX architecture, the POSIX standard specifies it. Although there are a lot of details related to multi-threading that are far too unimportant for the sake of getting started, it is important that you have a sound understanding of how process management works in UNIX.
The kernel representation of a program in UNIX is a process. For all intents and purposes, a process is simply a set of structures and data uniquely identified by an integer called a Process Identifier (PID). The kernel stores (within its own address-space) process structures indexed by PID's that point to process memory images. These images are composed of three separate segments: a machine image (binary code) for the process, called the text segment; the data segment, made up of all dynamic memory resources the process uses; and the stack segment, where static items are stored and the running program stack is kept. These segments are strictly protected (overflows can happen, resulting in segmentation faults). It is possible for any of a processes segments to be shared with another process in Linux.
The fork() system call creates a new process (said to be a child) and copies the parent process's text, data, and stack segments to it precisely. It creates a child that is an exact copy of the parent save for the pid. In the parent process thread of the program, fork() returns the pid of the child. In the child process thread, fork() returns 0. You can use this return value to select which of two blocks of code to execute, as in the example above.
vfork(), on the other hand, is supposed to cause the child to share the parent's resources rather than mirroring them. This does not happen in Linux for reasons that we will not venture to explore, but it is an important performance issue in some flavors.
clone() is an extended rendition of fork() with no options. In reality, fork() is implemented as a front-end to clone() in Linux. See the clone man pages for more information on this.
Once a child process has been forked, pretty much anything can be done. Sometimes forking can be useful for multi-threaded applications, while other times it is used to temporarily "shell" to other applications. Any process can call execve() or one of the exec..() line of functions that act as front-ends to it; the execve() function causes the binary of the target program to be loaded in the calling process's address space. In essence, the calling process becomes an instance of the specified program. Often, it is useful to fork a child then execve(), or fork and exec; this is actually done at login and by shells.
The wait(), waitpid(), wait3(), and wait4() system calls all do about the same thing--they wait for a child process to terminate before continuing and give information about its termination. This is obviously useful for the purpose of synchronization.
Okay, I can't resist. The rest of this is just too cool. I HAVE to talk about how Linux boots.
After a PC runs through its power-on/self-test routines and goes to look for the OS boot loader in the first 512 bytes of the first boot device, it finds LILO or some other cute little boot manager that lets you run more than one OS on the same machine. You select Linux and LILO transfers execution to a portion of the kernel designed to read the kernel memory image (ever seen "reading vmlinuz..."?) From there, the kernel begins to initialize itself and the machine. It loads most modules and creates a single process with PID 1 and stores the image of a binary called init in its text segment. init reads instructions from /etc/inittab and follows them to boot the system. Usually, inittab has init run a set of scripts in the /etc/rc.d directory and then fork terminal control processes (getty). getty, in turn, waits for a user to respond at the login prompt and then forks a login process, which starts a shell for you. When you execute a utility, (i.e., most things you would call shell commands), your shell forks and execs them.
#include <time.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
void alrm(int sig) {
printf("\nALARM!!\n");
kill(getpid(), SIGKILL);
}
main() {
struct tm *local;
struct itimerval it, old;
struct sigaction sa;
time_t t;
int s, r;
time(&t);
local = localtime(&t);
memset(&it, 0, sizeof(it));
memset(&old, 0, sizeof(old));
printf("\nIt is %2d:%2d:%2d now.\n", local->tm_hour, local->tm_min, local->tm_sec);
printf("For how many seconds should the alarm be dormant?\n");
scanf("%d", &s);
printf("\n\n");
it.it_value.tv_sec = s;
it.it_value.tv_usec = 1000 * s;
r = setitimer(ITIMER_REAL, &it, &old);
if (r == EFAULT || r == EINVAL) {
printf("Unable to set interval timer.\n");
return;
}
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &alarm;
sa.sa_flags = SA_ONESHOT;
sigaction(SIGALRM, &sa, NULL);
while (1){};
}
Message passing is the central means of controlling Win32 applications, and indeed of controlling Win32 in general. Don't let anybody lead you to believe this idea was new or even remotely introduced by the Windows platform. As much as a generation before Win32, the seed was planted for message passing in UNIX--only it wasn't planted intentionally.
UNIX provides kernel-level process management functions called signals that were originally designed to be raised on errors. Signals are quite powerful..they control everything to do with process management and exceptional error conditions. A process that is stuck in an infinite loop can always be terminated with SIGKILL, as is demonstrated above. SIGINT (although not specified by POSIX) can be sent to most processes on most flavors of UNIX to break out of them (ctrl+c).
These things are possible because signals are, by default, all handled in a standard way by the kernel.
However, for all but a few important signals, it is possible to replace the default signal handler or simply to add one in the first place. The replacement handler is unique for a process. In fact, you can even go so far as to define new signals, identified by SIGUSR1 and SIGUSR2 (POSIX) or in Linux any signals greater than or equal to the identifier _NSIG.
Signals have become extremely popular on UNIX for job control and even windowing systems (BSD in particular uses them heavily).
It is possible to send any signal to any process via the kill system call, also implemented as a system utility. The name is a bit misleading, granted, but it gets the job done. You will find kill most useful on the command-line, especially if you do a lot of service work (most inet servers will require you to send a certain signal in order for them to reread configuration or restart).
Also demonstrated here are built-in interval timers. These are more fun, standard things. Check out the man pages for setitimer/getitimer for more reading on these.
Welp, that's all for now, folks. Jered is tired. Remember...mixed signals can fork your processes.
Discuss this article in the forums
Date this article was posted to GameDev.net: 7/5/2000
(Note that this date does not necessarily correspond to the date the article was written)
See Also:
Linux
© 1999-2009 Gamedev.net. All rights reserved. Terms of Use Privacy Policy | http://www.gamedev.net/reference/articles/article1091.asp | crawl-002 | refinedweb | 3,779 | 64.81 |
W3C SW Dev
@@@@@@@@@@
for the syntax section:
see also XML Schema for RDF, rdfs, inference, lists, problem report of 28Jul2000
@@stuff to be reviewed...
The RDF model and syntax specification defined a number of features which are not required for DAML. DAML agents will not be required to be able to process these.
- RDF "aboutEachPrefix"
- RDF bags (??@@) and "aboutEach"
- xml:lang attributes are not represented in the RDF model
RDF documents are encoded in XML syntax [XML1.0] using namespaces [NS]. For the purposes of this project, the following XML features are not required for DAML, and DAML agents are not required to process them.
- DTD parsing
DAML project participants should note that the current RDF-Schema document [RDFS0] has dissimilar definitions of range and domain. This document assumes that this error will be fixed and the conventional meanings [@@what are those? --DanC 31Jul] associated in a future version of the specification [do the new definitions get new names, i.e. new URIs? --DanC 31Jul].
RDF within other XML documents
Practical considerations require DAML to be able to be inserted into other XML documents [which practical considerations? do we really need this now? --DanC 31Jul]. For this to be possible, the DAML parser must have a hint as to whether the other namesapces are ignorable, or have some RDF semantics. The document management section includes an RDF property for asserting that a given namespace is transparent to RDF in that any non-RDF elements may be replcaed by their content with no change to the RDF model conveyed by the document.
@@ check we have covered:
semantics (stefan)
@@@@@@@@@@
from the Model section:
(borrowing from the terminology of a section of the KIF 3.0 spec)
@@hmm... we could define "reflexive on S" rather than just "reflexive".
(commutative?)
The concept of equivalence is a crucuial one upon which much else is then based. It must be stressed that this is one equivalence relation which is defined here, while anyone is free to define their own for their own purposes. The one defined here is a strict higher-order equivalence, in that the semantics are that the resources connected by isEquivalentTo relation can be subsituted for each other under any circumstances.
The only processing which is disallowed (following web architecture) is that properties are not allowd to peek into the content of the URI string identifying a resource. That is, to define a property "The schema string of the URI identifying the resource" is illegal.
isEquivalentTo(a,b) => ( a(x,y) => b(x,y)) & (x(a,y)=>x(b,y)) & ..
equivalent: see OIL's isInverse of
@@@ Question as to whether you count this as following isEquivalentTo or not. It gives you a way of expressing equivalence of properties as
inverse(a,b) and inverse(b,c) gives effect of equivalence.
aka Injective, or 1-1. Compary max-cardinality=1.
aka functional
transitive, antisymmetric@@
@@@ Check: Have we included
"a survey of the literature"
split into things whioch require equivalence and things which do; things implying HOL; etc- in fact we have no FOL layer all is HOL.
look for dependencies elsewhere;
look for a table of what system understands what terms;
Write this in dan-ish
OKBC Knowledge Model @@GFP knowledge model
In contrast to HTML - if you want to change this list you don't change this list but you put something different ideas on the web. Use equivalence to show when yours is the same as mine. Future standard may be a new list with a lot of this list and others.
@@Building HOL section
@ disclaimers of status of thius chapter
@@ Dan to put his work on this here
@@@ check have we included:
This chapter is not formally part of DAML as it assumes conversance with the previous chapter in which logical primitives were introduced. Here we use these primitives to give a formal set of rules for DAML; rules which were implicitly or explicitly stated in the RDF Model and Syntax, RDF Schema documents, and in the Chapter on ontological terms in this document.
RDF Model and Syntax, RDF Schema
Ontological Rules
The raw transfer syntax RDF corresponding to these rules is given in an appendix.
@@ from Doc Mgmt section:
@@ check:
@@@@@@@@
A gloss on the RDF spec, in KIF terms:
*absolute URI with optional fragment identifier, that is
@@@@Future Work
@@check:
(authoring tools --Dan)
@@@
auto generating stuff...
(@@hmm... relative URIs aren't handled correctly)
or
./DAML-0-5.html,apply=/magic/dan5.xsl
(to allow relative URI for target of conversion!)
@@@@@@
some stuff in bibliography of proposal
see also: References in toward swell... | http://www.w3.org/2000/07/DAML-stuff | crawl-002 | refinedweb | 762 | 51.58 |
I always work on Arabic text files and to avoid problems with encoding I transliterate Arabic characters into English according to Buckwalter's scheme ()
Here is my code to do so but it's very SLOW even with small files like 400 kb. Ideas to make it faster?
Thanks
def transliterate(file):
data = open(file).read()
buckArab = {"'":"ء", "|":"آ", "?":"أ", "&":"ؤ", "<":"إ", "}":"ئ", "A":"ا", "b":"ب", "p":"ة", "t":"ت", "v":"ث", "g":"ج", "H":"ح", "x":"خ", "d":"د", "*":"ذ", "r":"ر", "z":"ز", "s":"س", "$":"ش", "S":"ص", "D":"ض", "T":"ط", "Z":"ظ", "E":"ع", "G":"غ", "_":"ـ", "f":"ف", "q":"ق", "k":"ك", "l":"ل", "m":"م", "n":"ن", "h":"ه", "w":"و", "Y":"ى", "y":"ي", "F":"ً", "N":"ٌ", "K":"ٍ", "~":"ّ", "o":"ْ", "u":"ُ", "a":"َ", "i":"ِ"}
for char in data:
for k, v in arabBuck.iteritems():
data = data.replace(k,v)
return data
Incidentally, someone already wrote a script that does this, so you might want to check that out before spending too much time on your own: buckwalter2unicode.py
It probably does more than what you need, but you don't have to use all of it: I copied just the two dictionaries and the transliterateString function (with a few tweaks, I think), and use that on my site.
Edit: The script above is what I have been using, but I'm just discovered that it is much slower than using replace, especially for a large corpus. This is the code I finally ended up with, that seems to be simpler and faster (this references a dictionary buck2uni):
def transString(string, reverse=0): '''Given a Unicode string, transliterate into Buckwalter. To go from Buckwalter back to Unicode, set reverse=1''' for k, v in buck2uni.items(): if not reverse: string = string.replace(v, k) else: string = string.replace(k, v) return string | https://codedump.io/share/RZhjtXb34FP3/1/fast-transliteration-for-arabic-text-with-python | CC-MAIN-2017-09 | refinedweb | 307 | 69.72 |
Data visualization involves exploring data through visual representations. It’s closely associated with data analysis, which uses code to explore the patterns and connections in a data set. A data set can be made up of a small list of numbers that fits in one line of code or it can be many gigabytes of data.
Making beautiful data representations is about more than pretty pictures. When a representation of a data set is simple and visually appealing, its meaning becomes clear to viewers. People will see patterns and significance in your data sets that they never knew existed.
Fortunately, you don’t need a supercomputer to visualize complex data. With Python’s efficiency, you can quickly explore data sets made of millions of individual data points on just a laptop. Also, the data points don’t have to be numbers. With the basics you learned in the first part of this book, you can analyze nonnumerical data as well.
People use Python for data-intensive work in genetics, climate research, political and economic analysis, and much more. Data scientists have written an impressive array of visualization and analysis tools in Python, many of which are available to you as well. One of the most popular tools is Matplotlib, a mathematical plotting library. We’ll use Matplotlib to make simple plots, such as line graphs and scatter plots. Then we’ll create a more interesting data set based on the concept of a random walk—a visualization generated from a series of random decisions.
We’ll also use a package called Plotly, which creates visualizations that work well on digital devices. Plotly generates visualizations that automatically resize to fit a variety of display devices. These visualizations can also include a number of interactive features, such as emphasizing particular aspects of the data set when users hover over different parts of the visualization. We’ll use Plotly to analyze the results of rolling dice.
INSTALLING MATPLOTLIB
To use Matplotlib for your initial set of visualizations, you’ll need to install it using pip, a module that downloads and installs Python packages. Enter the following command at a terminal prompt:
$ python -m pip install –user matplotlib
This command tells Python to run the pip module and install the matplotlib package to the current user’s Python installation. If you use a command other than python on your system to run programs or start a terminal session, such as python3, your command will look like this:
$ python3 -m pip install –user matplotlib
NOTE
If this command doesn’t work on macOS, try running the command again without the –user flag.
To see the kinds of visualizations you can make with Matplotlib, visit the sample gallery at When you click a visualization in the gallery, you’ll see the code used to generate the plot.
PLOTTING A SIMPLE LINE GRAPH
Let’s plot a simple line graph using Matplotlib, and then customize it to create a more informative data visualization. We’ll use the square number sequence 1, 4, 9, 16, 25 as the data for the graph.
Just provide Matplotlib with the numbers, as shown here, and Matplotlib should do the rest:
mpl_squares.py
import matplotlib.pyplot as plt squares = [1, 4, 9, 16, 25] ➊ fig, ax = plt.subplots() ax.plot(squares) plt.show()
- We first import the pyplot module using the alias plt so we don’t have to type pyplot repeatedly. (You’ll see this convention often in online examples, so we’ll do the same here.) The pyplot module contains a number of functions that generate charts and plots.
- We create a list called squares to hold the data that we’ll plot. Then we follow another common Matplotlib convention by calling the subplots() function ➊. This function can generate one or more plots in the same figure. The variable fig represents the entire figure or collection of plots that are generated. The variable ax represents a single plot in the figure and is the variable we’ll use most of the time.
- We then use the plot() method, which will try to plot the data it’s given in a meaningful way. The function plt.show() opens Matplotlib’s viewer and displays the plot, as shown in Figure 15-1. The viewer allows you to zoom and navigate the plot, and when you click the disk icon, you can save any plot images you like.
Figure 15-1: One of the simplest plots you can make in Matplotlib
Changing the Label Type and Line Thickness
Although the plot in Figure 15-1 shows that the numbers are increasing, the label type is too small and the line is a little thin to read easily. Fortunately, Matplotlib allows you to adjust every feature of a visualization.
We’ll use a few of the available customizations to improve this plot’s readability, as shown here:
mpl_squares.py
import matplotlib.pyplot as plt squares = [1, 4, 9, 16, 25] fig, ax = plt.subplots() ➊ ax.plot(squares, linewidth=3) # Set chart title and label axes. ➋ ax.set_title("Square Numbers", fontsize=24) ➌ ax.set_xlabel("Value", fontsize=14) ax.set_ylabel("Square of Value", fontsize=14) # Set size of tick labels. ➍ ax.tick_params(axis='both', labelsize=14) plt.show()
The linewidth parameter at ➊ controls the thickness of the line that plot() generates. The set_title() method at ➋ sets a title for the chart. The fontsize parameters, which appear repeatedly throughout the code, control the size of the text in various elements on the chart.
The set_xlabel() and set_ylabel() methods allow you to set a title for each of the axes ➌, and the method tick_params() styles the tick marks ➍. The arguments shown here affect the tick marks on both the x- and y-axes (axis=’both’) and set the font size of the tick mark labels to 14 (labelsize=14).
As you can see in Figure 15-2, the resulting chart is much easier to read. The label type is bigger, and the line graph is thicker. It’s often worth experimenting with these values to get an idea of what will look best in the resulting graph.
Figure 15-2: The chart is much easier to read now.
Correcting the Plot
But now that we can read the chart better, we see that the data is not plotted correctly. Notice at the end of the graph that the square of 4.0 is shown as 25! Let’s fix that.
When you give plot() a sequence of numbers, it assumes the first data point corresponds to an x-coordinate value of 0, but our first point corresponds to an x-value of 1. We can override the default behavior by giving plot() the input and output values used to calculate the squares:
mpl_squares.py
import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] fig, ax = plt.subplots() ax.plot(input_values, squares, linewidth=3) # Set chart title and label axes. --snip--
Now plot() will graph the data correctly because we’ve provided the input and output values, so it doesn’t have to assume how the output numbers were generated. The resulting plot, shown in Figure 15-3, is correct.
Figure 15-3: The data is now plotted correctly.
You can specify numerous arguments when using plot() and use a number of functions to customize your plots. We’ll continue to explore these customization functions as we work with more interesting data sets throughout this chapter.
Using Built-in Styles
Matplotlib has a number of predefined styles available, with good starting settings for background colors, gridlines, line widths, fonts, font sizes, and more that will make your visualizations appealing without requiring much customization. To see the styles available on your system, run the following lines in a terminal session:
>>> import matplotlib.pyplot as plt
>>> plt.style.available
[‘seaborn-dark’, ‘seaborn-darkgrid’, ‘seaborn-ticks’, ‘fivethirtyeight’,
—snip—
To use any of these styles, add one line of code before starting to generate the plot:
mpl_squares.py
import matplotlib.pyplot as plt input_values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plt.style.use('seaborn') fig, ax = plt.subplots() --snip--
This code generates the plot shown in Figure 15-4. A wide variety of styles is available; play around with these styles to find some that you like.
Figure 15-4: The built-in seaborn style
Plotting and Styling Individual Points with scatter()
Sometimes, it’s useful to plot and style individual points based on certain characteristics. For example, you might plot small values in one color and larger values in a different color. You could also plot a large data set with one set of styling options and then emphasize individual points by replotting them with different options.
To plot a single point, use the scatter() method. Pass the single (x, y) values of the point of interest to scatter() to plot those values:
scatter_squares.py
import matplotlib.pyplot as plt plt.style.use('seaborn') fig, ax = plt.subplots() ax.scatter(2, 4) plt.show()
Let’s style the output to make it more interesting. We’ll add a title, label the axes, and make sure all the text is large enough to read:
import matplotlib.pyplot as plt plt.style.use('seaborn') fig, ax = plt.subplots() ➊ ax.scatter(2, 4, s=200) # Set chart title and label axes. ax.set_title("Square Numbers", fontsize=24) ax.set_xlabel("Value", fontsize=14) ax.set_ylabel("Square of Value", fontsize=14) # Set size of tick labels. ax.tick_params(axis='both', which='major', labelsize=14) plt.show()
At ➊ we call scatter() and use the s argument to set the size of the dots used to draw the graph. When you run scatter_squares.py now, you should see a single point in the middle of the chart, as shown in Figure 15-5.
Figure 15-5: Plotting a single point
Plotting a Series of Points with scatter()
To plot a series of points, we can pass scatter() separate lists of x- and y-values, like this:
scatter_squares.py
import matplotlib.pyplot as plt x_values = [1, 2, 3, 4, 5] y_values = [1, 4, 9, 16, 25] plt.style.use('seaborn') fig, ax = plt.subplots() ax.scatter(x_values, y_values, s=100) # Set chart title and label axes. --snip--
The x_values list contains the numbers to be squared, and y_values contains the square of each number. When these lists are passed to scatter(), Matplotlib reads one value from each list as it plots each point. The points to be plotted are (1, 1), (2, 4), (3, 9), (4, 16), and (5, 25); Figure 15-6 shows the result.
Figure 15-6: A scatter plot with multiple points
Calculating Data Automatically
Writing lists by hand can be inefficient, especially when we have many points. Rather than passing our points in a list, let’s use a loop in Python to do the calculations for us.
Here’s how this would look with 1000 points:
scatter_squares.py
import matplotlib.pyplot as plt ➊ x_values = range(1, 1001) y_values = [x**2 for x in x_values] plt.style.use('seaborn') fig, ax = plt.subplots() ➋ ax.scatter(x_values, y_values, s=10) # Set chart title and label axes. --snip-- # Set the range for each axis. ➌ ax.axis([0, 1100, 0, 1100000]) plt.show()
We start with a range of x-values containing the numbers 1 through 1000 ➊. Next, a list comprehension generates the y-values by looping through the x-values (for x in x_values), squaring each number (x**2) and storing the results in y_values. We then pass the input and output lists to scatter() ➋. Because this is a large data set, we use a smaller point size.
At ➌ we use the axis() method to specify the range of each axis. The axis() method requires four values: the minimum and maximum values for the x-axis and the y-axis. Here, we run the x-axis from 0 to 1100 and the y-axis from 0 to 1,100,000. Figure 15-7 shows the result.
Figure 15-7: Python can plot 1000 points as easily as it plots 5 points.
Defining Custom Colors
To change the color of the points, pass c to scatter() with the name of a color to use in quotation marks, as shown here:
ax.scatter(x_values, y_values, c=’red’, s=10)
You can also define custom colors using the RGB color model. To define a color, pass the c argument a tuple with three decimal values (one each for red, green, and blue in that order), using values between 0 and 1. For example, the following line creates a plot with light-green dots:
ax.scatter(x_values, y_values, c=(0, 0.8, 0), s=10)
Values closer to 0 produce dark colors, and values closer to 1 produce lighter colors.
Using a Colormap
A colormap is a series of colors in a gradient that moves from a starting to an ending color. You use colormaps in visualizations to emphasize a pattern in the data. For example, you might make low values a light color and high values a darker color.
The pyplot module includes a set of built-in colormaps. To use one of these colormaps, you need to specify how pyplot should assign a color to each point in the data set. Here’s how to assign each point a color based on its y-value:
scatter_squares.py
import matplotlib.pyplot as plt x_values = range(1, 1001) y_values = [x**2 for x in x_values] ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10) # Set chart title and label axes. --snip--
We pass the list of y-values to c, and then tell pyplot which colormap to use using the cmap argument. This code colors the points with lower y-values light blue and colors the points with higher y-values dark blue. Figure 15-8 shows the resulting plot.
NOTE
You can see all the colormaps available in pyplot at go to Examples, scroll down to Color, and click Colormap reference.
Figure 15-8: A plot using the Blues colormap
Saving Your Plots Automatically
If you want your program to automatically save the plot to a file, you can replace the call to plt.show() with a call to plt.savefig():
plt.savefig(‘squares_plot.png’, bbox_inches=’tight’)
The first argument is a filename for the plot image, which will be saved in the same directory as scatter_squares.py. The second argument trims extra whitespace from the plot. If you want the extra whitespace around the plot, just omit this argument.
TRY IT YOURSELF
15-1. Cubes: A number raised to the third power is a cube. Plot the first five cubic numbers, and then plot the first 5000 cubic numbers.
15-2. Colored Cubes: Apply a colormap to your cubes plot.
RANDOM WALKS
In this section, we’ll use Python to generate data for a random walk, and then use Matplotlib to create a visually appealing representation of that data. A random walk is a path that has no clear direction but is determined by a series of random decisions, each of which is left entirely to chance. You might imagine a random walk as the path a confused ant would take if it took every step in a random direction.
Random walks have practical applications in nature, physics, biology, chemistry, and economics. For example, a pollen grain floating on a drop of water moves across the surface of the water because it’s constantly pushed around by water molecules. Molecular motion in a water drop is random, so the path a pollen grain traces on the surface is a random walk. The code we’ll write next models many real-world situations.
Creating the RandomWalk Class
To create a random walk, we’ll create a RandomWalk class, which will make random decisions about which direction the walk should take. The class needs three attributes: one variable to store the number of points in the walk and two lists to store the x- and y-coordinate values of each point in the walk.
We’ll only need two methods for the RandomWalk class: the __init__() method and fill_walk(), which will calculate the points in the walk. Let’s start with __init__() as shown here:
random_walk.py
➊ from random import choice class RandomWalk: """A class to generate random walks.""" ➋ def __init__(self, num_points=5000): """Initialize attributes of a walk.""" self.num_points = num_points # All walks start at (0, 0). ➌ self.x_values = [0] self.y_values = [0]
To make random decisions, we’ll store possible moves in a list and use the choice() function, from the random module, to decide which move to make each time a step is taken ➊. We then set the default number of points in a walk to 5000, which is large enough to generate some interesting patterns but small enough to generate walks quickly ➋. Then at ➌ we make two lists to hold the x- and y-values, and we start each walk at the point (0, 0).
Choosing Directions
We’ll use the fill_walk() method, as shown here, to fill our walk with points and determine the direction of each step. Add this method to random_walk.py:
random_walk.py
def fill_walk(self): """Calculate all the points in the walk.""" # Keep taking steps until the walk reaches the desired length. ➊ while len(self.x_values) < self.num_points: # Decide which direction to go and how far to go in that direction. ➋ x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) ➌ x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([0, 1, 2, 3, 4]) ➍ y_step = y_direction * y_distance # Reject moves that go nowhere. ➎ if x_step == 0 and y_step == 0: continue # Calculate the new position. ➏ x = self.x_values[-1] + x_step y = self.y_values[-1] + y_step self.x_values.append(x) self.y_values.append(y)
At ➊ we set up a loop that runs until the walk is filled with the correct number of points. The main part of the fill_walk() method tells Python how to simulate four random decisions: will the walk go right or left? How far will it go in that direction? Will it go up or down? How far will it go in that direction?
We use choice([1, -1]) to choose a value for x_direction, which returns either 1 for right movement or –1 for left ➋. Next, choice([0, 1, 2, 3, 4]) tells Python how far to move in that direction (x_distance) by randomly selecting an integer between 0 and 4. (The inclusion of a 0 allows us to take steps along the y-axis as well as steps that have movement along both axes.)
At ➌ and ➍ we determine the length of each step in the x and y directions by multiplying the direction of movement by the distance chosen. A positive result for x_step means move right, a negative result means move left, and 0 means move vertically. A positive result for y_step means move up, negative means move down, and 0 means move horizontally. If the value of both x_step and y_step are 0, the walk doesn’t go anywhere, so we continue the loop to ignore this move ➎.
To get the next x-value for the walk, we add the value in x_step to the last value stored in x_values ➏ and do the same for the y-values. When we have these values, we append them to x_values and y_values.
Plotting the Random Walk
Here’s the code to plot all the points in the walk:
rw_visual.py
import matplotlib.pyplot as plt from random_walk import RandomWalk # Make a random walk. ➊ rw = RandomWalk() rw.fill_walk() # Plot the points in the walk. plt.style.use('classic') fig, ax = plt.subplots() ➋ ax.scatter(rw.x_values, rw.y_values, s=15) plt.show()
We begin by importing pyplot and RandomWalk. We then create a random walk and store it in rw ➊, making sure to call fill_walk(). At ➋ we feed the walk’s x- and y-values to scatter() and choose an appropriate dot size. Figure 15-9 shows the resulting plot with 5000 points. (The images in this section omit Matplotlib’s viewer, but you’ll continue to see it when you run rw_visual.py.)
Figure 15-9: A random walk with 5000 points
Generating Multiple Random Walks
Every random walk is different, and it’s fun to explore the various patterns that can be generated. One way to use the preceding code to make multiple walks without having to run the program several times is to wrap it in a while loop, like this:
rw_visual.py
import matplotlib.pyplot as plt from random_walk import RandomWalk # Keep making new walks, as long as the program is active. while True: # Make a random walk. rw = RandomWalk() rw.fill_walk() # Plot the points in the walk. plt.style.use('classic') fig, ax = plt.subplots() ax.scatter(rw.x_values, rw.y_values, s=15) plt.show() keep_running = input("Make another walk? (y/n): ") if keep_running == 'n': break
This code generates a random walk, displays it in Matplotlib’s viewer, and pauses with the viewer open. When you close the viewer, you’ll be asked whether you want to generate another walk. Press y to generate walks that stay near the starting point, that wander off mostly in one direction, that have thin sections connecting larger groups of points, and so on. When you want to end the program, press n.
Styling the Walk
In this section, we’ll customize our plots to emphasize the important characteristics of each walk and deemphasize distracting elements. To do so, we identify the characteristics we want to emphasize, such as where the walk began, where it ended, and the path taken. Next, we identify the characteristics to deemphasize, such as tick marks and labels. The result should be a simple visual representation that clearly communicates the path taken in each random walk.
Coloring the Points
We’ll use a colormap to show the order of the points in the walk, and then remove the black outline from each dot so the color of the dots will be clearer. To color the points according to their position in the walk, we pass the c argument a list containing the position of each point. Because the points are plotted in order, the list just contains the numbers from 0 to 4999, as shown here:
rw_visual.py
--snip-- while True: # Make a random walk. rw = RandomWalk() rw.fill_walk() # Plot the points in the walk. plt.style.use('classic') fig, ax = plt.subplots() ➊ point_numbers = range(rw.num_points) ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15) plt.show() keep_running = input("Make another walk? (y/n): ") --snip--
At ➊ we use range() to generate a list of numbers equal to the number of points in the walk. Then we store them in the list point_numbers, which we’ll use to set the color of each point in the walk. We pass point_numbers to the c argument, use the Blues colormap, and then pass edgecolors=’none’ to get rid of the black outline around each point. The result is a plot of the walk that varies from light to dark blue along a gradient, as shown in Figure 15-10.
Figure 15-10: A random walk colored with the Blues colormap
Plotting the Starting and Ending Points
In addition to coloring points to show their position along the walk, it would be useful to see where each walk begins and ends. To do so, we can plot the first and last points individually after the main series has been plotted. We’ll make the end points larger and color them differently to make them stand out, as shown here:
rw_visual.py
--snip-- while True: --snip-- ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15) # Emphasize the first and last points. ax.scatter(0, 0, c='green', edgecolors='none', s=100) ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) plt.show() --snip--
To show the starting point, we plot point (0, 0) in green in a larger size (s=100) than the rest of the points. To mark the end point, we plot the last x- and y-value in the walk in red with a size of 100. Make sure you insert this code just before the call to plt.show() so the starting and ending points are drawn on top of all the other points.
When you run this code, you should be able to spot exactly where each walk begins and ends. (If these end points don’t stand out clearly, adjust their color and size until they do.)
Cleaning Up the Axes
Let’s remove the axes in this plot so they don’t distract from the path of each walk. To turn off the axes, use this code:
rw_visual.py
--snip-- while True: --snip-- ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) # Remove the axes. ➊ ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() --snip--
To modify the axes, we use the ax.get_xaxis() and ax.get_yaxis() methods ➊ to set the visibility of each axis to False. As you continue to work with visualizations, you’ll frequently see this chaining of methods.
Run rw_visual.py now; you should see a series of plots with no axes.
Adding Plot Points
Let’s increase the number of points to give us more data to work with. To do so, we increase the value of num_points when we make a RandomWalk instance and adjust the size of each dot when drawing the plot, as shown here:
rw_visual.py
--snip-- while True: # Make a random walk. rw = RandomWalk(50_000) rw.fill_walk() # Plot the points in the walk. plt.style.use('classic') fig, ax = plt.subplots() point_numbers = range(rw.num_points) ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1) --snip--
This example creates a random walk with 50,000 points (to mirror real-world data) and plots each point at size s=1. The resulting walk is wispy and cloud-like, as shown in Figure 15-11. As you can see, we’ve created a piece of art from a simple scatter plot!
Experiment with this code to see how much you can increase the number of points in a walk before your system starts to slow down significantly or the plot loses its visual appeal.
Figure 15-11: A walk with 50,000 points
Altering the Size to Fill the Screen
A visualization is much more effective at communicating patterns in data if it fits nicely on the screen. To make the plotting window better fit your screen, adjust the size of Matplotlib’s output, like this:
rw_visual.py
--snip-- while True: # Make a random walk. rw = RandomWalk(50_000) rw.fill_walk() # Plot the points in the walk. plt.style.use('classic') fig, ax = plt.subplots(figsize=(15, 9)) --snip--
When creating the plot, you can pass a figsize argument to set the size of the figure. The figsize parameter takes a tuple, which tells Matplotlib the dimensions of the plotting window in inches.
Matplotlib assumes that your screen resolution is 100 pixels per inch; if this code doesn’t give you an accurate plot size, adjust the numbers as necessary. Or, if you know your system’s resolution, pass plt.subplots() the resolution using the dpi parameter to set a plot size that makes effective use of the space available on your screen, as shown here:
fig, ax = plt.subplots(figsize=(10, 6), dpi=128)
TRY IT YOURSELF
15-3. Molecular Motion: Modify rw_visual.py by replacing ax.scatter() with ax.plot(). To simulate the path of a pollen grain on the surface of a drop of water, pass in the rw.x_values and rw.y_values, and include a linewidth argument. Use 5000 instead of 50,000 points.
15-4. Modified Random Walks: In the RandomWalk class, x_step and y_step are generated from the same set of conditions. The direction is chosen randomly from the list [1, -1] and the distance from the list [0, 1, 2, 3, 4]. Modify the values in these lists to see what happens to the overall shape of your walks. Try a longer list of choices for the distance, such as 0 through 8, or remove the –1 from the x or y direction list.
15-5. Refactoring: The fill_walk() method is lengthy. Create a new method called get_step() to determine the direction and distance for each step, and then calculate the step. You should end up with two calls to get_step() in fill_walk():
x_step = self.get_step()
y_step = self.get_step()
This refactoring should reduce the size of fill_walk() and make the method easier to read and understand.
ROLLING DICE WITH PLOTLY
In this section, we’ll use the Python package Plotly to produce interactive visualizations. Plotly is particularly useful when you’re creating visualizations that will be displayed in a browser, because the visualizations will scale automatically to fit the viewer’s screen. Visualizations that Plotly generates are also interactive; when the user hovers over certain elements on the screen, information about that element is highlighted.
In this project, we’ll analyze the results of rolling dice. When you roll one regular, six-sided die, you have an equal chance of rolling any of the numbers from 1 through 6. However, when you use two dice, you’re more likely to roll certain numbers rather than others. We’ll try to determine which numbers are most likely to occur by generating a data set that represents rolling dice. Then we’ll plot the results of a large number of rolls to determine which results are more likely than others.
The study of rolling dice is often used in mathematics to explain various types of data analysis. But it also has real-world applications in casinos and other gambling scenarios, as well as in the way games like Monopoly and many role-playing games are played.
Installing Plotly
Install Plotly using pip, just as you did for Matplotlib:
$ python -m pip install –user plotly
If you used python3 or something else when installing Matplotlib, make sure you use the same command here.
To see what kind of visualizations are possible with Plotly, visit the gallery of chart types at Each example includes source code, so you can see how Plotly generates the visualizations.
Creating the Die Class
We’ll create the following Die class to simulate the roll of one die:
die.py
from random import randint class Die: """A class representing a single die.""" ➊ def __init__(self, num_sides=6): """Assume a six-sided die.""" self.num_sides = num_sides def roll(self): """"Return a random value between 1 and number of sides.""" ➋ return randint(1, self.num_sides)
The __init__() method takes one optional argument. With the Die class, when an instance of our die is created, the number of sides will always be six if no argument is included. If an argument is included, that value will set the number of sides on the die ➊. (Dice are named for their number of sides: a six-sided die is a D6, an eight-sided die is a D8, and so on.)
The roll() method uses the randint() function to return a random number between 1 and the number of sides ➋. This function can return the starting value (1), the ending value (num_sides), or any integer between the two.
Rolling the Die
Before creating a visualization based on the Die class, let’s roll a D6, print the results, and check that the results look reasonable:
die_visual.py
from die import Die
# Create a D6.
➊ die = Die()
# Make some rolls, and store results in a list.
results = []
➋ for roll_num in range(100):
result = die.roll()
results.append(result)
print(results)
At ➊ we create an instance of Die with the default six sides. At ➋ we roll the die 100 times and store the results of each roll in the list results. Here’s a sample set of results:
[4, 6, 5, 6, 1, 5, 6, 3, 5, 3, 5, 3, 2, 2, 1, 3, 1, 5, 3, 6, 3, 6, 5, 4,
1, 1, 4, 2, 3, 6, 4, 2, 6, 4, 1, 3, 2, 5, 6, 3, 6, 2, 1, 1, 3, 4, 1, 4,
3, 5, 1, 4, 5, 5, 2, 3, 3, 1, 2, 3, 5, 6, 2, 5, 6, 1, 3, 2, 1, 1, 1, 6,
5, 5, 2, 2, 6, 4, 1, 4, 5, 1, 1, 1, 4, 5, 3, 3, 1, 3, 5, 4, 5, 6, 5, 4,
1, 5, 1, 2]
A quick scan of these results shows that the Die class seems to be working. We see the values 1 and 6, so we know the smallest and largest possible values are being returned, and because we don’t see 0 or 7, we know all the results are in the appropriate range. We also see each number from 1 through 6, which indicates that all possible outcomes are represented. Let’s determine exactly how many times each number appears.
Analyzing the Results
We’ll analyze the results of rolling one D6 by counting how many times we roll each number:
die_visual.py
--snip-- # Make some rolls, and store results in a list. results = [] ➊ for roll_num in range(1000): result = die.roll() results.append(result) # Analyze the results. frequencies = [] ➋ for value in range(1, die.num_sides+1): ➌ frequency = results.count(value) ➍ frequencies.append(frequency) print(frequencies)
Because we’re no longer printing the results, we can increase the number of simulated rolls to 1000 ➊. To analyze the rolls, we create the empty list frequencies to store the number of times each value is rolled. We loop through the possible values (1 through 6 in this case) at ➋, count how many times each number appears in results ➌, and then append this value to the frequencies list ➍. We then print this list before making a visualization:
[155, 167, 168, 170, 159, 181]
These results look reasonable: we see six frequencies, one for each possible number when you roll a D6, and we see that no frequency is significantly higher than any other. Now let’s visualize these results.
Making a Histogram
With a list of frequencies, we can make a histogram of the results. A histogram is a bar chart showing how often certain results occur. Here’s the code to create the histogram:
die_visual.py
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die --snip-- # Analyze the results. frequencies = [] for value in range(1, die.num_sides+1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. ➊ x_values = list(range(1, die.num_sides+1)) ➋ data = [Bar(x=x_values, y=frequencies)] ➌ x_axis_config = {'title': 'Result'} y_axis_config = {'title': 'Frequency of Result'} ➍ my_layout = Layout(title='Results of rolling one D6 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) ➎ offline.plot({'data': data, 'layout': my_layout}, filename='d6.html')
To make a histogram, we need a bar for each of the possible results. We store these in a list called x_values, which starts at 1 and ends at the number of sides on the die ➊. Plotly doesn’t accept the results of the range() function directly, so we need to convert the range to a list explicitly using the list() function. The Plotly class Bar() represents a data set that will be formatted as a bar chart ➋. This class needs a list of x-values, and a list of y-values. The class must be wrapped in square brackets, because a data set can have multiple elements.
Each axis can be configured in a number of ways, and each configuration option is stored as an entry in a dictionary. At this point, we’re just setting the title of each axis ➌. The Layout() class returns an object that specifies the layout and configuration of the graph as a whole ➍. Here we set the title of the graph and pass the x- and y-axis configuration dictionaries as well.
To generate the plot, we call the offline.plot() function ➎. This function needs a dictionary containing the data and layout objects, and it also accepts a name for the file where the graph will be saved. We store the output in a file called d6.html.
When you run the program die_visual.py, a browser will probably open showing the file d6.html. If this doesn’t happen automatically, open a new tab in any web browser, and then open the file d6.html (in the folder where you saved die_visual.py). You should see a chart that looks like the one in Figure 15-12. (I’ve modified this chart slightly for printing; by default, Plotly generates charts with smaller text than what you see here.)
Figure 15-12: A simple bar chart created with Plotly
Notice that Plotly has made the chart interactive: hover your cursor over any bar in the chart, and you’ll see the associated data. This feature is particularly useful when you’re plotting multiple data sets on the same chart. Also notice the icons in the upper right, which allow you to pan and zoom the visualization, and save your visualization as an image.
Rolling Two Dice
Rolling two dice results in larger numbers and a different distribution of results. Let’s modify our code to create two D6 dice to simulate the way we roll a pair of dice. Each time we roll the pair, we’ll add the two numbers (one from each die) and store the sum in results. Save a copy of die_visual.py as dice_visual.py, and make the following changes:
dice_visual.py
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list. results = [] for roll_num in range(1000): ➊ result = die_1.roll() + die_2.roll() results.append(result) # Analyze the results. frequencies = [] ➋ max_result = die_1.num_sides + die_2.num_sides ➌ for value in range(2, max_result+1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. x_values = list(range(2, max_result+1)) data = [Bar(x=x_values, y=frequencies)] ➍ x_axis_config = {'title': 'Result', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} my_layout = Layout(title='Results of rolling two D6 dice 1000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6_d6.html')
After creating two instances of Die, we roll the dice and calculate the sum of the two dice for each roll ➊. The largest possible result (12) is the sum of the largest number on both dice, which we store in max_result ➋. The smallest possible result (2) is the sum of the smallest number on both dice. When we analyze the results, we count the number of results for each value between 2 and max_result ➌. (We could have used range(2, 13), but this would work only for two D6 dice. When modeling real-world situations, it’s best to write code that can easily model a variety of situations. This code allows us to simulate rolling a pair of dice with any number of sides.)
When creating the chart, we include the dtick key in the x_axis_config dictionary ➍. This setting controls the spacing between tick marks on the x-axis. Now that we have more bars on the histogram, Plotly’s default settings will only label some of the bars. The ‘dtick’: 1 setting tells Plotly to label every tick mark. We also update the title of the chart and change the output filename as well.
After running this code, you should see a chart that looks like the one in Figure 15-13.
Figure 15-13: Simulated results of rolling two six-sided dice 1000 times
This graph shows the approximate results you’re likely to get when you roll a pair of D6 dice. As you can see, you’re least likely to roll a 2 or a 12 and most likely to roll a 7. This happens because there are six ways to roll a 7, namely: 1 and 6, 2 and 5, 3 and 4, 4 and 3, 5 and 2, or 6 and 1.
Rolling Dice of Different Sizes
Let’s create a six-sided die and a ten-sided die, and see what happens when we roll them 50,000 times:
dice_visual.py
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create a D6 and a D10. die_1 = Die() ➊ die_2 = Die(10) # Make some rolls, and store results in a list. results = [] for roll_num in range(50_000): result = die_1.roll() + die_2.roll() results.append(result) # Analyze the results. --snip-- # Visualize the results. x_values = list(range(2, max_result+1)) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title': 'Result', 'dtick': 1} y_axis_config = {'title': 'Frequency of Result'} ➋ my_layout = Layout(title='Results of rolling a D6 and a D10 50000 times', xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data': data, 'layout': my_layout}, filename='d6_d10.html')
To make a D10, we pass the argument 10 when creating the second Die instance ➊ and change the first loop to simulate 50,000 rolls instead of 1000. We change the title of the graph and update the output filename as well ➋.
Figure 15-14 shows the resulting chart. Instead of one most likely result, there are five. This happens because there’s still only one way to roll the smallest value (1 and 1) and the largest value (6 and 10), but the smaller die limits the number of ways you can generate the middle numbers: there are six ways to roll a 7, 8, 9, 10, and 11. Therefore, these are the most common results, and you’re equally likely to roll any one of these numbers.
Figure 15-14: The results of rolling a six-sided die and a ten-sided die 50,000 times
Our ability to use Plotly to model the rolling of dice gives us considerable freedom in exploring this phenomenon. In just minutes you can simulate a tremendous number of rolls using a large variety of dice.
TRY IT YOURSELF
15-6. Two D8s: Create a simulation showing what happens when you roll two eight-sided dice 1000 times. Try to picture what you think the visualization will look like before you run the simulation; then see if your intuition was correct. Gradually increase the number of rolls until you start to see the limits of your system’s capabilities.
15-7. Three Dice: When you roll three D6 dice, the smallest number you can roll is 3 and the largest number is 18. Create a visualization that shows what happens when you roll three D6 dice.
15-8. Multiplication: When you roll two dice, you usually add the two numbers together to get the result. Create a visualization that shows what happens if you multiply these numbers instead.
15-9. Die Comprehensions: For clarity, the listings in this section use the long form of for loops. If you’re comfortable using list comprehensions, try writing a comprehension for one or both of the loops in each of these programs.
15-10. Practicing with Both Libraries: Try using Matplotlib to make a die-rolling visualization, and use Plotly to make the visualization for a random walk. (You’ll need to consult the documentation for each library to complete this exercise.)
SUMMARY
In this tutorial, you learned to generate data sets and create visualizations of that data. You created simple plots with Matplotlib and used a scatter plot to explore random walks. You also created a histogram with Plotly and used a histogram to explore the results of rolling dice of different sizes.
Generating your own data sets with code is an interesting and powerful way to model and explore a wide variety of real-world situations. As you continue to work through the data visualization projects that follow, keep an eye out for situations you might be able to model with code. Look at the visualizations you see in news media, and see if you can identify those that were generated using methods similar to the ones you’re learning in these projects.
1 thought on “Data Visualization In PYTHON – MATPLOTLIB” | https://basiccodist.in/data-visualization-in-python-matplotlib/ | CC-MAIN-2022-21 | refinedweb | 7,450 | 64.81 |
Talk:Tag:natural=peak
Contents
Volcanoes
I wouldn't think of a volcano as an amenity. Ipofanes 14:54, 30 September 2008 (UTC)
- Tag:natural=volcano exists. So how do we tag? natural=peak;volcano? Ipofanes 10:01, 10 December 2008 (UTC)
natural=volcano or something like that will be much better than amenity, actually, think natural=volcano indicates it is a peak as well, but render it with a slightly different color. --Skippern 17:17, 17 December 2008 (UTC)
Man-made hills and peaks
What about man-made hills (such as slap heaps, or artificial hills in parks)? Should they also be tagged natural=peak? Obviously "natural=" does not really fit here. On the other hand, for a map it's not really relevant whether an elevation is natural or not, since in practice they may look the same. -- Sleske 23:20, 25 July 2010 (UTC)
- I guess there should be used man_made=peak tag. It is very rare up to this moment, but it would be good to start using it more. Moreover definition of natural=peak is so short and broad, that we may add more specific tag, at least "peak=mountain" and "peak=hill", to differentiate it from other uses. You can examine how it is used in Berlin for example. -- Kocio (talk) 17:41, 24 June 2014 (UTC)
- In mining regions you will find far more "man_made" peaks than "natural" ones. After WWII German cities often got hills made of debris after the air raids that are very prominent peaks. Some "peaks" in Northern Germany are actually tumulus, but the knowledge about their origin is not widespread. I never saw a map distinguishing between natural and man made hills and I don't think either it is wise, because a map should show what there actually is. If somebody feels it's important, he/she could add peak-type=natural|man_made? --GerdHH (talk) 12:07, 20 May 2017 (UTC)
- Yes sure, between the comment in 2014 and yours, the definition had been refined already after discussion on the tagging list, and includes "natural + renaturalised features". Please also note that "peak" does not map the hill, it maps the highest point. Thus while the hill could be man made, the peak is immaterial and not "made".--Polarbear w (talk) 13:44, 20 May 2017 (UTC)
Priority in rendering different natural=peak
I think there should be some way of specifying the importance of a peak, because certain peaks are very important and well known (the highest point of each mountain, for instance), while others are hardly known.. some tag to define 2 or 3 levels of priprity, so that certain peaks render with name at low zoom levels, while others render only at higher zooms.. --Snaggy89 13:25, 31 January 2011 (UTC)
- Renderers should maybe use for this purpose. --*Martin* 22:19, 8 September 2011 (BST)
- Seems like prominence=* is in use for this (although the uk term would suggest prime_factor=*) --Gorm 16:13, 2 July 2012 (BST)
summit:* keys
I don't like the suggested summit:* keys at all.
- There is no need for them, because a cross can be mapped as man_made=summit_cross or more generally as man_made=cross, while a register fits well to the tourism=* key, e.g. tourism=register/logbook/guestbook... Both crosses and registers are not limited to peaks. Registers are abundant on trails and in alpine huts and even in hotels.
- It seems inconsistent to apply this tagging scheme to crosses and logbooks, but not to other things commonly present on peaks, such as survey points and cairns.
- If the cross has a name on its own, it needs to be mapped as a separate object. Using an attribute-like tag like summit:cross=yes on that object looks strange.
--Fkv 20:01, 1 March 2012 (UTC)
summit:register=yes is ambiguous, it is semantically not obvious if it means the logbook on the summit, or that the summit is registered somewhere. Within the climbing namespace, climbing:summit_log=yes has been established, which is clearly related to the activity being logged. --Polarbear w (talk) 09:11, 8 October 2015 (UTC)
Mountain with multiple peaks
A peak is not always equivalent to a mountain, there are sometimes mountains with multiple peaks! Recently I learnt about a mountain called Trzy Kopki ("Three Heaps"), which has three separate, distanced peaks, none of which is considered a "main" one. The peaks with their elevations are on the map already, but how to show that they all belong to one named mountain?
I think a separate tag for mountain as whole would be handy. Maybe natural=mountain drawn as an area? --Jedrzej Pelka (talk) 19:06, 16 January 2014 (UTC)
natural=rock vs. natural=peak
There is currently no clear differentiation between natural=rock and natural=peak. The example pictures on the rock page indicate insignifcant rocks, not forming a peak in the landscape. Rock as a material is a constituent of mountains, thus a significant elevation should not be tagged as natural=rock just because it is formed by rock.
Thus I propose to tag a rocky structure as natural=peak if it fulfils certain significance criteria, which can be:
- clear elevation and/or separation from the surrounding countryside
- having a name which is listed in regional guides and commonly used
- having a distinguishable summit head
- being of interest and value for climbers and mountaineers
- having a summit log
In particular, these criteria would be fulfilled for the climbing rocks in the Saxon Switzerland, Germany. --Polarbear w (talk) 10:37, 7 October 2015 (UTC)
- It is absolutely clear. natural=rock maps to one specific physical object (see the wiki page for images), and natural=peak maps to the highest point of the plateau/mountain (which is immaterial). A lone climbing rock like alone would not justify a natural=peak, while at the same time calling for a closed way with natural=scree and natural=cliff. —Jengelh (talk) 12:01, 7 October 2015 (UTC)
- From this perspective, I would draw the rock as an area, and add its highest point as immaterial peak.--Polarbear w (talk) 12:44, 7 October 2015 (UTC)
For example the question is, if this is a peak or a rock: --Chrisss Gü (talk) 12:38, 7 October 2015 (UTC)
- Personally, I would not get the idea to mark those as unitary rocks, already because the surrounding area is all rocky (and therefore natural=scree or so in OSM, together with the cliff, as previously mentioned). So I would say it is a bunch of peaks (Bloßstock, Kreuzturm, Morsche Zinne as per the Wikipedia article). The government-kept map (geoviewer.sachsen.de) also happens to show them decidecly as peaks. –Jengelh (talk) 12:56, 7 October 2015 (UTC)
man_made=survey_point
If the peak of a mountains is marked with a trigonometric point, should man_made=survey_point used on the same node? --GerdHH (talk) 12:10, 20 May 2017 (UTC) | https://wiki.openstreetmap.org/wiki/Talk:Tag:natural%3Dpeak | CC-MAIN-2018-17 | refinedweb | 1,158 | 58.92 |
n Opti ional course e for 2nd year r stude ents of f English
Ioana a Moh hor‐Ivan
2014 2
Topics
1. The Celtic Paradigm and Modern Irish Writing a) Beginnings in the Celtic World i. The Celts ii. Celtic society and religion iii. Early Irish literature: tales and cycles. b) The Mythological Cycle and Its Modern Re‐workings i. The mythic invasions ii. The Celtic pantheon iii. The world of the sidh iv. Mythological masks and the sidh in W.B. Yeats’s early poetry v. Feminist Revisions of the sidh: EAVAN BOLAND and NUALA NI DHOMNAILL c) The Cycle Of Ulster and The Celtic Hero i. Main tales of the cycle ii. Constructing the Celtic Hero: W.B. Yeats and the Cuchulain cycle of plays: iii. De‐constructing “heroism”: Nuala Ni Dhumnaill’s “Cuchulain I” d) The Cycle of Munster. Fenian Themes and Heroes in Metamorphosis i. Fiánna, Fenian heroes and tales ii. Celtic connections: from Fenian to Aruthurian myth iii. Re‐writing the ancient avatar’s stories: Ossianism; W.B. Yeats, “The Wanderings of Oisin”; James Joyce, “Finnegans Wake”; Mike Newell, “Into the West” e) The King (Historical) Cycle of Tales. The Buile Motif in Irish Literature i. BUILE SUIBHNE (The Madness of Sweeney) ii. The “buile” motif in literature: Flann O’Brien, At Swim‐Two Birds ; Seamus Heaney, Sweeney Astray 2. Conquests a) Anglo‐Norman traditions and the Irish writer: i. chansons des geste: The Song of Dermot and the Earl ii. goliardic poems: The Land of Cockayne; The Vision of MacConglinne iii. the danta gradha: O Woman Full of Wile b) English Narratives of Ireland i. Civilians and barbarians: Edmund Spenser, A View on the Present State of Ireland; ii. The Stage Irishman: William Shakespeare, Henry V. b) Rearticulating the colonialist paradigm: i. The Irish melodrama: Dion Boucicault ii. Contemporary revisions: Brian Friel’s “history‐play”, Seamus Heaney’s “history‐ poem” 3. Colonial Literatures a) Nationalist tropes of Ireland i. The Spear – Bhan and the 18th‐century aislinge
The Shan Bhan Bhocht and the popular ballad The “Double Woman” Trope: W. B Yeats, Kathleen ni Houlihan. Revisions of the Shan Bhan Bhocht literary trope: James Joyce, A Mother, Samuel Beckett, Murphy; Tom Murphy, Bailengangaire b) The “Big House” theme in Irish Literature i. The Anglo‐Irish novel: Maria Edgeworth, Castle Rackrent, Somerville and Ross, The Real Charlotte, Elizabeth Bowen, The Last September; ii. The Anglo‐Irish play: W. B. Yeats, Purgatory, Lennox Robinson, The Big House, Killygregs in Twilight; iii. The Catholic Northern play: Brian Friel, Aristocrats. iv. The “Big House” in the farcical mode: Neil Jordan’s “High Spirits” 4. “Space” and Irish Literary Politics a) The Pastoral and the Anti‐pastoral i. Celticism and The Irish Literary Revival ii. J.M. Synge: between pastoral and anti‐pastoral. Riders to the Sea vs. The Playboy of the Western World. iii. The Abbey peasant play: J.B. Keane, The Field iv. Patrick McCabe’s ‘black’ pastoral: The Butcher Boy. b) An Urban Space Divided i. Dublin and the ‘heroic’ city: mythologies of 1916 and W. B. Yeats’s Easter 1916. ii. Post‐revolutionary theatrical revisionism: Sean O’Casey, The Dublin Trilogy, Denis Johnston, The Old Lady Says ‘No!’, Brendan Behan, The Hostage The Northern city and the Troubles: Brian Friel, The Freedom of the City, Bernard iii. MacLaverty, Cal. c) Re‐mapping the Irish spaces i. Rody Doyle’s Dublin: “The Commitments”; “When Brendan Met Trudy” ii. Beyond the tropes of the Northern City: Martin McDonagh’s “In Bruges”; “Seven Psychopaths”
ii. iii. iv.
.
1. The Mythic Invasions 2.3. Oísin in the Land of Youth 4.Beginnings in the Celtic World 1.4. Táin Bó Cuailnge (The Cattle Raid of Cooley) 3. 2. Munster) 4. 4. Ossianism 4. The Ulster (Red Branch ) Cycle 3. The Historical (King) Cycle: 5.3. The “Suibhne” Motif in Irish Literature 5.3. 3. Literary Treatments of Fenian Tales and Heroes 4.6.2. 4.2. Celtic Myth in the Theatre of Yeats: 3.3. Yeats.3.2. W.The Ulster Cycle and the Celtic Hero 3.4.3.) 5.1. Main Tales of the Cycle 3.3.3.1.1. Celtic Literature Chapter 2 . Tematica Chapter 1 . Seamus Heaney (1939 . The Celtic Pantheon 2.5.2. Táin Bó Fraoch (The Cattle Raid of Fraoch) 3.2. The World of the Sidhe 2.3. At Swim-Two Birds (1939) 5. B. The Exile of the Sons of Uísneach 3. Yeats’s Early Poems 2. 4. Finn Maccool.1.6. Buile Suibhne (Frenzy of Sweeney) 5. Early Irish Poetry 5.2. Celtic Society 1. Celtic Tribes 1.2. The Fionn Cycle (Fenian.1.1. Ossianic. De-Constructing Heroism: Nuala Ni Dhumnaill’s Chapter 4 . The Sidhe with Contemporary Women Poets Chapter 3 .The King (Historical) Cycle of Tales 5. 1. The Sidhe in W. Fenian Heroes and Tales 4. The Cuchulain Cycle of Plays 3.1.4.The Mythological Cycle and Its Modern Reworkings 2. Flann O’Brien (Brian Ó Núalláin) (1911-66): 5. from “Finnegan’s Wake” to Joyce’s “Finnegans Wake” Chapter 5 .2.5. Sweeney Astray (1983) Minimal Bibliography 4 5 5 6 6 7 8 8 8 12 13 14 18 22 22 22 24 24 24 26 29 30 30 35 37 37 37 38 42 43 43 43 46 46 46 48 49 49 49 51 54 57 The Celtic Paradigm in Modern Irish Writing 3 .1. Main Characters of the Cycle 3.4. “The Wanderings of Oisin” 4. Celtic Religion 1.Cuprins Cuprins Obiective.1.5.1.4.1.1. Emáin Macha 3.B.The Cycle of Munster (the Finn Cycle) 4. The Milesians 2.3.4.4.
The myth of Deirdre and Naoise in Brian Friel’s plays. • The Cycle of Ulster. Tipuri si modalitati de activitate didactica: • • • • prelegere teoretica analiza de text discutie eseu. Oisin in Yeats’s vs. The Mythological Cycle.B. dezvoltarea deprinderilor cercetare individuala concretizata prin personalizarea informatiei teoretice si modelelor de analiza de text oferite in eseu. • 4 Early Irish Lyrics. The Dinnseanachas and the Irish poet. • The Cycle of Munster. Mythological masks in W. • Early Irish Literature. The Sweeney figure in Irish literature. Cuchulain and the Yeatsian theatre. from Flann O’Brien to Seamus Heaney. Yeats’s early poems.Obiective. Tematică Obiective: • • • • familiarizarea studentilor cu particularitatile istorico-culturale ale spatiului irlandez. Paul Vincent Carroll’s vision. evidentierea specificului celtic al traditiei literare irlandeze. Tematica: • Beginnings in the Celtic world: Celtic society and culture. depistarea traiectului temelor si motivelor literare celtice in literatura irlandeza moderna si contemporana. From Fion to Joyce’s Finnegans Wake. • The King Cycle of tales. The Madness of Sweeney. The Celtic Paradigm in Modern Irish Writing .
Connacht (Connachta). In ancient Irish religion and mythology Tara was the sacred place of 6 The Celtic Paradigm in Modern Irish Writing . In Éirinn old there dwelt a mighty race. in the middle. Celtic Tribes The Celts are a grouping of Indo-European peoples recognized as speaking one or another dialect of a common Celtic language. the Gaels.1. With winds and waves they made their settling-place.. Taller than Roman spears. in the south of Ireland. ("The Celts". who spread through the whole island. Ireland was settled by a Q-Celtic people. With feet as fleet as deers'. in the west of Ireland. In the course of the next centuries.. the residence of Ireland’s High Kings.Chapter 1 – Beginnings in the Celtic World Chapter 1 . Correspondingly. Like oaks and towers They had a giant grace. a number of historical provinces came into being: a) b) c) d) e) Ulster (Ulaid). was once the ancient seat of power in Ireland – 142 kings are said to have reigned here in prehistoric and historic times. in the north of Ireland. in the east of Ireland. beyond the misty space Of twice a thousand years. the classification of the Celtic peoples takes into consideration the linguistic factor: • Continental Celtic • Gaullish (unknown number of dialects) • Celto-Iberian • Lepontic • Insular Celtic – P-Celtic(Brythonic) • Welsh • Cornish • Breton – Q-Celtic(Goidelic) • Irish Gaelic • Scottish Gaelic • Manx Around 800 B. Leinster (Laigin). The Hill of Tara.C. known as "Teamhair".Beginnings in the Celtic World Long. Meath (Mide). long ago. Munster (Mumu). with Tara as its capital.. by Thomas d'Arcy McGee) 1.
1. fílí. while farming was relegated to the plebs. • 1.Chapter 1 – Beginnings in the Celtic World dwelling for the gods.3. smiths. Celtic Religion The religion of the Celts exhibits the following characteristics: The Celtic Paradigm in Modern Irish Writing 7 . Saint Patrick is said to have come to Tara to confront the ancient religion of the pagans at its most powerful site. breitheamb. seanchadh) – Plebs: the body of freemen.2. their hill-forts were of primarily military significance. led by a king (rí) Familiar: kinship groups form the basis of the tribe Hierarchical (Celtic society is divided into three main classes): – Equites: warrior aristocracy – Druides: the learned class (draoi. Cattle-raising was regarded as a superior form of social activity. leeches and small farmers Pastoral: the Celts had no towns in the modern understanding of the term. Celtic Society The following attributes characteristic of the Celtic social organisation point to the Celts as being an archetypal Indo-European people: • • • Tribal: the greatest political unit is the tribe (tuath).
Tír-na-n-og).• • • Chapter 1 – Beginnings in the Celtic World Pantheism: the Celts believed in the consciousness of all things. the tales are collected and incorporated into four main cycles. stones (Lía Fáil). This explains their worship of trees. fish. 1. bulls. Munster) King (historical) Task: Write a 4000-word essay on “Cultural Landmarks of the Celtic World”. they could migrate from the human world to the Otherworld (e. are transmitted by means of an oral tradition. Celtic gods and goddesses belong to a particular tribe. 8 The Celtic Paradigm in Modern Irish Writing . namely: • • • • Mythological Ulster (The Red Branch) Finn (Fenian. water. they could dwell within other creatures and objects (shape-changing) Polytheism: divine organisation mirrors that of the Celtic society. which. Celtic Literature The learned class of the Celtic society are the creators of the early Irish literary texts. until the coming of Christianity in the 5th century.4.g. This oral character of Irish literature is reflected in the division of the whole corpus of early Irish literary texts according to the tale-type to which they belong (as evidenced in their titles): • Togla (destructions) • Tána (cattle-raids) • Tochmarca (wooings) • Fessa (feasts) • Aislinga (visions) • Aitheda (elopments • Serca (loves) • Aided (violent deaths) • Catha (battles) • Immrama (voyages) • Dinnseanchas (tales of place names) After the arrival of Christianity and the adaptation of the Latin alphabet to the Irish language.) Metempsychosis: the souls were immortal. which is based on kinship relations. or the various animal cults (boars. birds etc.
previous to the arrival of the Gaels. by a process of exclusion the mythological cycle includes only those stories that intend to provide a mythical history of the occupation of Ireland. the main settlers of Ireland are: • • Cesair (granddaughter of Noah) and Fintan Mac Bochra. misshapen giants. who lived on Tory Island).2. • • • 2. Most of these texts are preserved in a 12th century manuscript known as Lebor Gabála Érenn (Book of Invasions of Ireland). Here follows an extract from Mary Heaney’s Over Nine Waves. They were the first to invade Ireland at the time of the Flood. and the few survivors fled to Greece. The Mythic Invasions Though all the tales included in the existing corpus of early Irish literary texts display a strong mythological component. The Celtic Pantheon The Tuatha Dé Danann is the tribe of the Irish gods who conquer and settle Ireland. The Nemedians (followers of Nemed. They were attacked by the Fomorians. The Firbolgs (descendants of the Nemedians) returned to Ireland 230 years later. in which their arrival is described: The Celtic Paradigm in Modern Irish Writing 9 . but their power in Ireland only lasted for 37 years before the Tuatha Dé Danann arrived.1. The Partholanians (named after their leader Partholan. a descendant of Japheth) arrived from Spain 30 years after the extinction of the Partholonians from pestilence.The Mythological Cycle and Its Modern Reworkings 2. whom they managed to defeat. According to this manuscript. They encountered the Fomorians (a race of ugly.Chapter 2 – The Mythological Cycle and Its Modern Reworkings Chapter 2 . who was the king of Greece) arrived 312 years after Cesair and her followers. son of Sera.
The invaders brought with them the four great treasures of their tribe. and their king.) 10 The Celtic Paradigm in Modern Irish Writing . Though they had defeated the Fir Bolgs. and among them their king. No one could escape it once it was unsheathed. No one ever left it hungry. they set fire to their boats so that there would be no turning back. From Findias they brought Nuada’s irresistible sword. a hundred thousand in all. London. the first one the Tuatha De Danaan fought in a pace of that name. and the Fir Bolgs thought the Tuatha De Danaan had arrived in a magic mist. When the Fir Bolgs had fled. Nuada. Thousands of the Fir Bolgs were killed. Gorias. They were accomplished in the various arts of druidry. When they reached Ireland and landed on the western shore. (from Marie Heaney. From Falias they brought Lia Fail. Eochai Mac Erc. the Tuatha De Danaan took over the country and went with their treasures to Tara to establish themselves as masters of the island. namely magic. the four cities of the northern islands. These newcomers were the People of the Goddess Danu and their men of learning possessed great powers and were revered as if they were gods. They had learnt their druidic skills in Falias. the Stone of Destiny. 1994. The smoke from the burning boats darkened the sun and filled the land for three days. prophesy and occult lore. Anyone who held it was invincible in battle. a more powerful enemy awaited them. Findias and Murias. These survivors boarded their ships and set sail to the far-scattered islands around Ireland. had his arm severed from his body in the fight. In the end the Tuatha De Danaan overcame the Fir Bolgs and routed them until only a handful of them survived. a demon-like race who lived in the islands to which the Fir Bolgs had fled. Nuada was the king of the Tuatha De Danaan and he led them against the Fir Bolgs. These were the Formorians. From Gorias they brought Lugh’s spear. But another struggle lay ahead.Chapter 2 – The Mythological Cycle and Its Modern Reworkings THE TUATHA DE DANAAN LONG AGO the Tuatha De Danaan came to Ireland in a great fleet of ships to take the land from the Fir Bolgs who lived there. They fought a fierce battle on the Plain of Moytura. Over Nine Waves. From Murias they brought the Dagda’s cauldron. They brought it to Tara and it screamed when a rightful king of Ireland sat on it. Many of the Tuatha De Danaan died too. Faber and Faber.
clothed in garb. This is the first manifested world. described in the following terms by the Irish poet A. . he is often pictured as a rustic old man. a love changing into desire.E. Stories of rebirth and the Otherworld are associated with him. This story. whose name is translated as “The Pearl of Beauty”. Through the goddess Boann (whose spirit lives within the Boyne river and is goddess of poetic inspiration and powerful spiritual insight) the Dagda fathered Aengus (Oengus) Og. a harp that plays by itself. Her three aspects are (1) Fire of Inspiration as patroness of poetry. married to the god Bile (or Belenos). an eternal joy becoming love. as patroness of smithcraft and martial arts. and leading on to earthly passion and forgetfulness of its own divinity. (2) Fire of the Hearth. who lives in Tír-na-n-og (The Land of Eternal Youth) and is married to the beautiful goddess Fand. Manannán’s father. who prompts a quest that will take years until he will find her shape-changed in a bird. the “good God” in the Celtic sense of “good at anything”. And. One story in the cycle (“The Story of the Children of Lir”) recounts the tribulations of his other four children who were transformed into swans by an evil step-mother. The Dagda is the father of Ogma (the Irish god of eloquence). as it lays hold of the earthly symbol of its desire it becomes on Earth that passion which is spiritual death . were translated in English by Lady Augusta Gregory (1852-1932) in a collection of Irish myths entitled Gods and Fighting Men: The Celtic Paradigm in Modern Irish Writing 11 . a cauldron that never gets exhausted. in a dream. . “Aislinge Oengusa” (The Vision of Aengus) recounts how Aengus. and this desire builds up the Mid-world or World of the Waters. and Brigid (or the "Fiery Arrow or Power". a mother-goddess signifying fertility and plenty. An energy or love or eternal desire has gone forth which seeks through a myriad forms of illusion for the infinite being it has left. while his name is commemorated in that of the Isle of Man. . was an Irish god who dwelt on the cliffs of Antrim. A figure of immense power.: ". the Tír nan Óg or World of Immortal Youth. Manannán MacLir is the god of the oceans. She is mother to the craftsmen.” One of the most beautiful lyrical tales in the cycle. the Celtic god of youth and love. The father to most of the gods of the tribe is the Dagda. The eternal joy becomes love when it has first merged itself in form and images of a divine beauty that dance before it and lure it from afar.) Brigid is a Celtic three-fold goddess. It is Angus the Young. among others. . has the vision of a beautiful girl. Lir. and possessing three magical objects: a gigantic club (with which he can both kill enemies and cure friends). as patroness of healing and fertility. and (3) Fire of the Forge. lastly. The love is changed into desire as it is drawn deeper into nature. and endured cruel hardship for many centuries until restored to their human shape.Chapter 2 – The Mythological Cycle and Its Modern Reworkings The Tuatha Dé Danann are the tribe of the Goddess Dana (or Danu). a sky-centred deity.
and their reason. and their Irish.Chapter 2 – The Mythological Cycle and Its Modern Reworkings The Fate of the Children of Lir Then Lir came to the edge of the lake. “I would think worst of being a witch of the air. that put them in the shape of four swans on Loch Dairbhreach. from the border of the harbour where you are.” said Fionnuala.” said Fionnuala. I do not sleep though I am in my lying down. and he gave a very sharp reproach to Aoife. “We are your own four children. it was Aoife there beyond. and she went away on the wind in that shape. O Aodh. to the house.” “Is there any way to put you into your own shapes again?” said Lir. and he knew what Lir said was true. “to live with any person at all from this time. “O Fionnuala. 12 The Celtic Paradigm in Modern Irish Writing . daughter of Oilell of Aran. “Is there a mind with you.” said Lir.” Then Lir went on to the palace of Bodb Dearg. your own foster-child and the sister of their mother.” she said. bringing Aoife. And Lir rose up early on the morning of the morrow and he made this complaint: — “It is time to go from this place. and they slept there quietly that night.” she said. “till the end of nine hundred years.” When Lir and his people heard that. O Fiachra of the beautiful arms.” Bodb Dearg gave a great start when he heard that. than to the children of Lir. and that will not be. and will be in it to the end of life and time. “It is not I that would not bring my children along with me. they gave out three great heavy shouts of grief and sorrow and crying. “there is no way. Aoife. but they have their sense with them yet. that are after being destroyed by your wife and by the sister of our own mother. the Irish. And let you stop here tonight. and he said: “This treachery will be worse for yourself in the end.” So Lir and his people stopped there listening to the music of the swans. and she is in it yet. through the dint of her jealousy. “It is a bad net I put over you. Lir. And with that he struck her with a Druid wand. “I will tell you that. To be parted from my dear children. and there was a welcome before him there. “to come to us on the land. “for all the men of the world could not help us till we have gone through our time. and he asked them why was it they had that voice. since you have your own sense and your memory yet?” “We have not the power. but we have our language. and comely Conn. and it is enough to satisfy the whole race of men to be listening to that music. in the sight of the whole of the men of Ireland. “My grief!” said Lir.” she said. and she was turned into a witch of the air there and then. and their voice. and he took notice of the swans having the voice of living people. it is that is tormenting my heart. and he got a reproach from Bodb Dearg for not bringing his children along with him. it is not ready I am to go away from you.” said Fionnuala. “It is into that shape I will put you now.” said Bodb. And what shape would you yourself think worst of being in?” he said. “and we will be making music for you. and we have the power to sing sweet music. I would never have followed that advice if I had known what it would bring upon me.
was a fire festival sacred to the god Belenos. the Shining One. represented as three sisters. Another triad is formed by the goddesses identified with the sovranty and spirit of Ireland. The Irish female deities usually indicate sexuality and fertility. Cattle were let out of winter quarters and driven between two fires in a ritual cleansing ceremony that may have had practical purposes too. with powerful magical and warlike connotations. • Lughnasadh was a summer festival lasting for two weeks that fell around 31 July. who overthrew the power of the Celtic gods. but had then settled in Spain. It was said to have been introduced to Ireland by the god Lugh. There are five goddesses identified with war.especially poets were able to enter the Otherworld through the doorways of the sidhe. • Beltain. The God Lugh assumes the leadership of the tutha and leads them to victory after he himself kills Balor of the Evil Eye. and inspiring battle madness. Banba and Fotla. around 31 January. sometime appearing in the form of a carrion crow. while he is also the Samildánach (“the many-gifted one”). including horse-racing (perhaps this is why the festival was also linked to the goddess Macha) 2. Dea (the hateful one) Nemain (frenzy). celebrated around 1 May. Lugh becomes thus a divine archetype of kingship.Chapter 2 – The Mythological Cycle and Its Modern Reworkings “Cath Maige Tuired” (“The Battle of the Plain of Tuired”) is the best-known tale of the cycle.3. Women met to celebrate the return of the maiden aspect of the Goddess Brigid. it marked the beginning of the end of winter. Some of these deities attracted singular worship. whose ancestors had originally come from Scythia. it began the Celtic year. • Imbolc (or Oimelc) celebrated at lambing time. such as that at the Hill of Tara in Ireland. Eire. This festival was celebrated with competitions of skill. were the Milesians. while Macha (who is also goddess of the horses) is also included here. being associated with war and death on the battlefield. His first words upon landing were the poem that is known today as the "Song of Amergin": The Celtic Paradigm in Modern Irish Writing 13 . dealing specifically with the climactic battle between the Tuatha and the Fomori. It was a time when the veil between this world and the Otherworld was thought to be so thin that the dead could return to warm themselves at the hearths of the living. The Milesians The last invaders of Ireland. and some of the living . It was a time for feasts and fairs and for the mating of animals. whom many view as the forefathers of the Gaels. Amergin (a warrior and a bard) was the leader of the invasion. The Morrígan ("terror" or "phantom queen") is the greatest of them. associated with the festivals that marked the Celtic year: • Samhain: celebrated around 31 October. the Milesians were the sons of Míl Espáine (Miled). moving between all the activities of society and be patron of each one. mastering all the arts and the crafts. According to the “Book of Invasions”. and so was sacred to this god. the most formidable of the fomori. Other goddesses of war are the Badb (fury).
asked the Milesians to name Ireland after one of them. tumuli. She had the function of keening like a mortal woman when a family member died. The places were called Sidh or Sidhe. with their conquerors. This new habitat led to another name for the Danaan. hills. The Tuatha Dé Danann. Banba. I am a hill: where poets walk. The Tuatha Dé Danann became spirit people. I am a boar: ruthless and red. I am a wind: on a deep lake. 2. The World of the Sídhe After their being defeated by the Milesians. I am a salmon: in a pool. Some important figures emerging in Irish fairy lore are: • The Bean Sídhe (“woman of the hills”): a female fairy attached to a particular family.Chapter 2 – The Mythological Cycle and Its Modern Reworkings The Song of Amergin I am a stag: of seven times. mounds.4. Ireland became known as Erin or Erinn. magical palaces were hidden under the mound. which was associated with barrows. I am an infant: who but I Peeps from the unhewn dolmen arch? I am the womb: of every holt. (Transl. though defeated. I am the grave: of every hope. did not leave Erin. I am a hawk: above the hill. inhabiting the sídhe (another name for the Otherworld). It was Eriu who won the honour. aes sídhe (people of the Sídh) or fairy people. I am a breaker: threatening doom. the Danaan were allotted spiritual Ireland. I am a tear: the Sun lets fall. 14 The Celtic Paradigm in Modern Irish Writing . the Dagda) placed a powerful spell of invisibility over the many parts of Ireland. by Robert Graves) The three sister goddesses of the Dé Danann. They became spirit people. or fairies. Fodla and Eriu. I am a tide: that drags to death. Manannan (in other accounts. but continued to live there. I am a flood: across a plain. I am the blaze: on every hill I am the queen: of every hive I am the shield: for every head. I am a wizard: who but I Sets the cool head aflame with smoke? I am a spear: that rears for blood. I am a thorn: beneath the nail I am a wonder: among flowers. I am a lure: from paradise.
– Collections: • The Wanderings of Oísin and Other Poems (1889) • The Countess Kathleen and Other Legends and Lyrics (1892) • The Wind Among the Reeds (1899) • In the Seven Woods (1903) • The poetry of Yeats’s mid-career is dominated by his commitment to Irish nationalism. Yeats was also co-founder of the Abbey Theatre. – Collections: • The Tower (1928) • The Winding Star (1933) 15 The Celtic Paradigm in Modern Irish Writing .Chapter 2 – The Mythological Cycle and Its Modern Reworkings • Leprechaun: a diminutive guardian of a hidden treasure (origin: Lughchromain – little stooping Lugh) • Puca (Puck):a supernatural animal who took people for nightmarish rides. They are more public and concerned with the politics of the modern Irish state. He was awarded the Nobel Prize in Literature in 1923 for what the Nobel Committee described as "his always inspired poetry. 2. The Sidhe in W. – Collections: • The Green Helmet and Other Poems (1910) • Responsibilities (1914) • The Wilde Swans at Coole (1919) • Michael Robartes and the Dancer (1921) • Yeats’s later poetry is less public and more personal. B. another great symbol of the literary revival. which served as the stage for many new Irish writers and playwrights of the time. as distinct from English culture. and are known to 'take' mortals with them on their journeys. Yeats’s Early Poems Poet. Yeats (1865-1939) was born to an Anglo-Irish Protestant family. • Slua Sídhe: the fairy host who travel through the air at night. becoming thus the primary driving force behind the Irish Literary Revival – a movement which stimulated new appreciation of traditional Irish literature. This allowed Yeats. With regard to his poetic output. Hence the poems employ a simpler and more accessible style. mystic and public figure. which inform Yeats’s theories of contraries and of the progression which can result from reconciling them. between sensuality and rationalism. B. After the establishment of the Irish Free State. this corresponds to three main phases: • The first phase is associated with the Irish Revival of the 1890s which brought about an upsurge of interest in Celtic myth and legend. to bring mythical motifs and figures into their works as symbols and expressions of Irishness past and present. but turned into a committed Irish nationalist. between turbulence and calm. encouraging the creation of works written in the spirit of Irish culture. which in a highly artistic form gives expression to the spirit of a whole nation". as well as other writers.5. exploring contrasts between the physical and spiritual dimensions of life. dramatist. The poems are characterised by a mature lyricism. Yeats was appointed to the first Irish Senate Seanad Éireann in 1922 and re-appointed in 1925. a mischievous spirit who led travellers astray. W.
On the basis of these. manifestation) as opposed to the ‘supernatural’ (that which is beyond manifestation).Chapter 2 – The Mythological Cycle and Its Modern Reworkings • Parnell’s Funeral and Other Poems (1935) • Last Poems and Two Plays (1939) It is the early poems that Yeats draws heavily on Irish myth. lakes. islands • Twilight. • The exile. the voyage: symbols of the spirit’s journey from life to death. dawn • Dreams. Yeats constructs his own system of opposites. the quest.) Though dissimilar at a first glance. the two areas bear comparison in several aspects: • The ‘natural’ (world in time. which may be seen to inform his poetry: The Sídhe Spirit Imagination Eternal Immortal Id Water & air Night The natural world Matter Reason Ephemeral Mortal Ego Earth Day Though opposed. employing mythological figures and mythic motifs alongside with theories drawn from occult writings (in which he was also interested. points of contact may be established between the two realms. which are associated with states that may be labelled as “inbetween”: • Shores. The Stolen Child Where dips the rocky highland Of Sleuth Wood in the lake. There lies a leafy island Where flappy herons wake 16 The Celtic Paradigm in Modern Irish Writing . visions In “The Stolen Child” (a poem based on Irish legend) the faeries beguile a child (presumably in a dream) to come away with them. • Metaphysical content.
For a world more full of weeping than he can understand. this involves a great cost: the dreamers (like the one in “The Man Who Dreamed of Fairyland”) remain caught in-between the two. able to produce artistic creation. But. It seemed they raised their little silver heads. the human child. hand in hand. hand in hand. for their thoughts are constantly turned to the world of the imagination.Chapter 2 – The Mythological Cycle and Its Modern Reworkings The drowsy water-rats. O human child! To the waters and the wild With a faery.] Away with us he’s going. Such points of contact between the two worlds allow for visionary states. hand in hand. To the waters and the wild With a faery. His heart hung all upon a silken dress. [. The Man who Dreamed of Faeryland He stood among a crowd at Drumahair. Far off by furthest Rosses We foot it all the night. But when a man poured fish into a pile. For he comes. Or see the brown mice bob Round and round the oatmeal-chest. O human child! To the waters and the wild With a faery. Where the wave of moonlight glosses The dim grey sands with light. And sang what gold morning or evening sheds Upon a woven world-forgotten isle The Celtic Paradigm in Modern Irish Writing 17 . While the world is full of troubles And is anxious in its sleep. There we’ve hid our faery vats. For the world’s more full of weeping than you can understand. or spirit. Come away. Come away. For the world’s more full of weeping than you can understand. Weaving olden dances. usually. To and fro we leap And chase the frothy bubbles. Full of berries And of reddest stolen cherries. never allowed to find comfort in this life. . The solemn-eyed: He’ll hear no more the lowing Of the calves on the warm hillside Or the kettle on the hob Sing peace into his breast. And he had known at last some tenderness. Before earth took him to her stony care. . Mingling hands and mingling glances Till the moon has taken flight.
Whatever ravelled waters rise and fall Or stormy silver fret the gold of day. When earthly night had drunk his body in. And might have known at last unhaunted sleep Under that cold and vapour-turbaned steep.unnecessary cruel voice Old silence bids its chosen race rejoice. His mind ran all on money cares and fears. In “The Song of the Wandering Aengus” Yeats re-works “Aislinge Oengusa”. 18 The Celtic Paradigm in Modern Irish Writing . And midnight there enfold them like a fleece And lover there by lover be at peace. That Time can never mar a lover’s vows Under that woven changeless roof of boughs: The singing shook him out of his new ease. He mused beside the well of Scanavin. He wandered by the sands of Lissadell. That if a dancer stayed his hungry foot It seemed the sun and moon were in the fruit: And at that singing he was no more wise. who has a vision of the sidhe in the form of a beautiful girl. Adopting the mythological mask of the Irish god of love and youth. from those fingers. He slept under the hill of Lugnagall. A lug-worm with its grey and muddy mouth Sang that somewhere to north or west or south There dwelt a gay. a symbol of the perfection of the imaginative world. Now that the earth had taken man and all: Did not the worms that spired about his bones Proclaim with that unwearied. the poet expresses the same predicament of the dreamer. But one small knot-grass growing by the pool Sang where . exulting. The tale drove his angry mood away. reedy cry That God has laid His fingers on the sky.Chapter 2 – The Mythological Cycle and Its Modern Reworkings Where people love beside the ravelled seas. glittering summer runs Upon the dancer by the dreamless wave. That. And he had known at last some prudent years Before they heaped his grave under the hill. Why should those lovers that no lovers miss Dream. He mused upon his mockers: without fail His sudden vengeance were a country tale. gentle race Under the golden or the silver skies. until God burn Nature with a kiss? The man has found no comfort in the grave. But while he passed before a plashy place.
Mother Ireland – Literary tradition (dominated by male poets. Medb McGuckian) are committed to the 3 “R”s of Irish feminist writing: – to resist and revise reductive images and perceptions of women and The Celtic Paradigm in Modern Irish Writing 19 . And hooked a berry to a thread.) Contemporary women poets (Eavan Boland. such as: – Proverbs and formulaic expressions (e. The Sidhe with Contemporary Women Poets If Irish ancestral culture allowed room for the exercise of an autonomous female creative potential.) – Religious constructs: the Virgin (Mother of God). When I had laid it on the floor I went to blow the fire aflame. But something rustled on the floor.Chapter 2 – The Mythological Cycle and Its Modern Reworkings The Song of the Wandering Aengus I went out to the hazel wood. Proof may be found in different areas. being relegated to the domestic sphere. Because a fire was in my head. Eithne Strong. And cut and peeled a hazel wand. a heavy sower and a woman poet. such as evidenced in – Myth: Dana. Eillen Ni Chuilleanain. I dropped the berry in a stream And caught a little silver trout. And walk among long dappled grass. And when white moths were on the wing. Eire – Folklore: Cailleach Beare (the Hag of Beare) – Society: bean fíle (woman poet) through the medieval to modern periods women are gradually excluded from the social. And pluck till time and times are done The silver apples of the moon. the three worst curses that can befall a village are: to have a wet thatcher. And kiss her lips and take her hands.g. denying them their complexity. political and cultural spheres. Brigid. who employ women simply as symbols or motifs in their texts.6. The golden apples of the sun. And some one called me by my name: It had become a glimmering girl With apple blossom in her hair Who called me by my name and ran And faded through the brightening air. 2. I will find out where she has gone. Though I am old with wandering Through hollow lands and hilly lands. Nuala Ni Dhomhnaill. And moth-like stars were flickering out.
Mind you. and of course you are. sexuality. fertility and self-sufficiency which some connect to the Celtic ideals of womanhood.” Her collections include An Dealg Droighin (1981). the fairy woman becomes the carrier of a powerful female energy. and culture. combined with contemporary themes of femininity. In “Swept Away”. eat. but never mind: stay. She didn’t close the door. When my husband came home for his tea. She got up and started doing housework. 1988. But I’m in the fairy field in everlasting dark. She didn’t ask. with only the mist to cover me. he didn’t notice she wasn’t me. Rogha Dánta/Selected Poems (1986. washed the dishes. Pharoh's Daughter (1990). I was too polite to throw her out so I decided to act all nice: Stay. Nuala Ni Dhomhnaill (1952-) is one of the most popular of contemporary Irish poets. Féar Suaithinseach (1984). able to subvert and transform the traditional representations of the feminine: SWEPT AWAY (FUADACH) The fairy woman marched right into my poem. Sit up to the fire. She made the beds. have a drink. Put the dirty clothes in the machine. As she herself confesses: “Irish is a language of enormous elasticity and emotional sensitivity. it is an instrument of imaginative depth and scope. Writing in Irish her work draws upon themes of ancient Irish folklore and mythology. and Feis (1991). 1990). which has been tempered by the community for generations until it can pick up and sing out every hint of emotional modulation that can occur between people. if I were in your house the way you’re in mine I’d go home right away. of quick and hilarious banter and a welter of references both historical and mythological.Chapter 2 – The Mythological Cycle and Its Modern Reworkings – to revive /re-posses energies related to creativity. And if he wants me back The Celtic Paradigm in Modern Irish Writing 20 . if you’re in a hurry. So she did. I/m freezing.
In a Time of Violence (1994). burn her and scorch her. then make it red-hot in the fire. I’ll be coming. Outside History (1990).” In Boland’s view “… we all [women] exist in a mesh.Chapter 2 – The Mythological Cycle and Its Modern Reworkings here’s what he must do: get a fine big ploughshare and butter it well. In “The Woman Turns herself Into A Fish”. Object Lessons: The Life of the Woman and the Poet in Our Time (1995). All the time she’s going. As she herself has stated. a pale The Celtic Paradigm in Modern Irish Writing 21 . they are truths. Night Feed (1982). and all the time she’s going. web. labyrinth of associations … we ourselves are constructed by the construct … images are not ornaments. re-writing the mermaid image: The Woman Turns Herself into a Fish it’s done: I turn. You didn’t have a thriving sense of the witness of the lived life of women poets. I’ll be coming. There were none in the 19th century or early part of the 20th century. One of Ireland's few recognized women poets. Boland engages directly with Yeats’s “The Song of the Wondering Aengus”. I flab upward blub-lipped. hipless and I am sexless shed of ecstasy. “As an Irish woman poet I have very little precedent.” The daughter of an Irish diplomat Eavan Boland (1944-) spent much of her youth living in London and New York City. and what you did have was a very compelling and at time oppressive relationship between Irish poetry and the national tradition. Then go to the bed where that bitch is lying and let her have it! “Push it into her face.” Her collections of poems include In Her Own Image (1980). She has also written a prose memoir. Boland addresses broad issues of Irish national identity as well as the specific issues confronting women and mothers in a culture that has traditionally ignored their experiences.
Yeats and Nuala NiDhumnaill. 3. a light and how in my loomy cold. The Dreamer’s Mermaid or the Mermaid’s Dream? (The Song of the Wandering Aengus vs. The Woman Turns Herself Into a Fish) 22 The Celtic Paradigm in Modern Irish Writing . a light. 2. my greens still she moons in me.Chapter 2 – The Mythological Cycle and Its Modern Reworkings swimmer sequin-skinned. Yet ruddering and muscling in the sunless tons of new freedoms still I feel a chill pull. Task: Choose one of the following topics to develop into a 4000-word essay of the argumentative type: 1. The Celtic Pantheon in its Indo-European Context. It’s what I set my heart on.B. pealing eggs screamlessly in seaweed. The World of the Sidhe with W. a brightening.
the boastfulness and courage of the warriors. The language of the earliest form of the story is dated to the eighth century. The Celtic Paradigm in Modern Irish Writing 23 . such as asserted in one tale of the dinnseachas type. but some of the verse passages may be two centuries older and it is held by most Celtic scholars that the Ulster cycle. must have had a long oral existence before it received a literary shape. Emain Macha means "The Twins of Macha". in the “Introduction” to his translation of “The Cattle Raid of Cooley”. with the rest of early Irish literature. The Ulaid Cycle is supposed to be contemporary to Christ (1st century BC) since Conchobar's death coincides with the day of Christ’s crucifixion. at the hands of the monastic scribes. so the name Emain Macha could mean the "Brooch of Macha".’ 3.The Ulster Cycle and the Celtic Hero 3. The Tain and certain descriptions of Gaulish society by Classical authors have many details in common: in warfare alone. Cú Chulainn (Cu Chulainn or Cuchulain). This might seem to be supported by the similarity between the barbaric world of the stories. The Ulster (Red Branch ) Cycle The cycle of Ulster contains a group of heroic tales relating to the Ulaid and their military order known as the House of the Red Branch. Emain Macha is the seat of power in Ulaid (Ulster). war and of horses. In this version. chariot-fighting and beheading. Thomas Kinsella. being one of the aspects of Morrígan.1. The dun (hill-fort) was named after the Red Queen Macha. 2.Chapter 3 – The Ulster Cycle and the Celtic Hero Chapter 3 . Macha was identified as the Irish goddess of fertility. She was portrayed as red goddess. situated near modern Armagh. The main part of the Ulaid Cycle is set during the reigns of Conchobar in Ulaid (Ulster) and Queen Medb in Connacht (Connaught). and a few traces of Christian colour. The cycle centers on the greatest hero in Celtic myths. either because she was dressed in red or that she had red hair. Macha had used her brooch to mark the boundary of her capital. As to the background of the Tain the Ulster cycle was traditionally believed to refer to the time of Christ. the practices of cattle-raiding. said to be its founder. entitled the “Pangs of Ulster”. and the La Tene Iron age civilisation of Gaul and Britain. the individual weapons. She reappeared in the Ulaid Cycle as wife of Crunnchu and was associated with the curse placed upon the men of Ulster. uninfluenced by Greece or Rome. asserts the following: “The origins of the Tain are far more ancient than these manuscripts [8th –century manuscripts in which it was preserved].
comes from this.’ she said. she gave birth alongside it.’ she said. as he was alone in the house. seized all the men of Ulster who were there that day. Only three classes of people were free from the pangs of Ulster: the young boys of Ulster. The fair was held. For nine generations any Ulsterman in those pangs had no more strength than a woman on the bed of labour. He was taken immediately before the king and the woman was sent for. or five nights and four days the pangs lasted. ‘He will die unless you come. the women. and she was a fine woman in his eyes.’ But she couldn’t move them. the Twins of Macha. She called out to the crowd: ‘A mother bore each one of you! Help me! Wait till my child is born.’ ‘Burden?’ the messenger said. boys and girs. I am Macha. She settled down and began working at once. She bore twins. ‘It would be as well not to grow too boastful or careless in anything you say.’ the woman said to him. Once. in his best clothes and in great vigour. and the name of my offspring. Crunniuc set out for the fair with the rest. Then she slept with Crunniuc. and her pangs gripped her. the king’s chariot was bought onto the field. At the end of the days. as though she were well used to the house. He lived in a lonely place in the mountains with all his sons. The name Emain Macha. ‘My wife is faster. went to the fair. She stayed with him for along while afterward. a son a nd a daughter. he saw a woman coming toward him there. and nine generations after them.Chapter 3 – The Ulster Cycle and the Celtic Hero THE PANGS OF ULSTER There was a very rich landlord in Ulster. and Cuchulainn. His chariot and horses won. daughter of Sainrith mac Imbaith. ‘Very well. Everyone in Ulster. Crunniuc mac Agnomain. Soon a fair was held in Ulster. She said to the messenger: ‘It would be a heavy burden for me to go and free him now.’ he said. I am full with child. ‘/that isn’t likely. she put everything in order without being asked. and there was never a lack of food or clothes or anything else under her care.’ She went to the fair. ‘A long lasting evil will come out of this on the whole of Ulster. 24 The Celtic Paradigm in Modern Irish Writing . The crowd said that nothing could beat those horses. ‘will be given to this place. His wife was dead. ‘My name.’ ‘What is your name?’ the king asked. When night came.’ Crunniuc said. As she gave birth she creamed out that all who heard that scream would suffer from the same pangs for five days and four nights in their times of greatest difficulty. Five days and four nights. This affliction ever afterward. As the chariot reached the end of the field. men and women.’ Then she raced the chariot.
after his stepfather. king of Tara. who each became king of the province. all of them with the name Maine. Though Lugh was his father. Main Tales of the Cycle 3. who fleed to Connacht to become his mortal enemy. king of Ulster. This romance of a love triangle was to influence other tales. In a more popular version. Cú Chulainn (Cuchulain) is the greatest hero of the Ulster Cycle. and with his teaching. including Medb (Maeve). Her father was Eochaid Feidlech. During his reign. Cuchulain was called Sétanta at birth. Conchobar established a military order of elite warriors called the Red Branch. Medb represents the Sovereignity of Connacht. [Her name is to be Deirdre. His name was to change to Cú Chulainn ("Hound of Culann“) when. Medb (Maeve) had actually come from the province of Leinster. Cuchulain was also grandson of the great druid Cathbad. Cormac. Main characters of the Cycle Conchobar MacNessa was the son of Ness. Conchobar’s master-smith. Medb had many lovers. Fachtna was either the brother or halfbrother of Fergus Mac Roich. Ulster prospered. THE EXILE OF THE SONS OF USNACH The Ulaid feasted one day in the house of Fedlimid. to Ulster's traditional enemy – Connacht. the ard-druid (high druid) of Ulster. She left Conchobar and became Conchobar's chief enemy throughout the rest of her life. 3. In Connacht she had three different husbands. It also holds Conchobar responsible for the defection of Fergus and 3000 other warriors. The Exile of the Sons of Uìsneach The tale of Deirdre and Naoísi. Like her three sisters. who later became Conchobar's adviser. she was at one time married to Conchobar Mac Nessa. Fergus served as captain of the Red Branch. Conchobar had many wives. His uncle. Conall Cernach and Cu Chulainn. a girl-child was born to the wife of Fedlimid. and a druid prophesied about her future. such as The Pursuit of Diarmait and Grainne of the Fenian Cycle and the legend of Tristan. including his own son. The child will grow to be a woman of The Celtic Paradigm in Modern Irish Writing 25 . Apart from her Finnabair and several other daughters. The best known of her husbands was Ailill Mac Mata. Conchobar's father was Cathbad.4. or Nessa and Fachtna Fáthach. he killed a great hound belonging to Culann. who was the brother of Fergus Mac Roich. As such. he called himself Cú Chulainn Mac Sualtam. when he had the sons of Uisnech put to death. she also had seven sons.Chapter 3 – The Ulster Cycle and the Celtic Hero 3. the chronicler of King Conchobar. a giant and king of Ulster. but Fergus Mac Rioch was the best known and was seen as her most frequent lover. Lugh Lamfada. Cuchulain was the son of Deichtine and the sun god. 1. is the most famous Irish romance. and as the feast came to an end. he produced the greatest warriors of Ulster. son of Uisnech.3. most of them by Ailill. still a boy. Medb had many children. 4.
” “No! said he. And they took service with the king of Scotland and built a house around Deirdre so that they should not be killed on account of her. soon she went out to him.” “I would choose between you. For every man who heard it. Naoisi and his followers were killed.” said she.” said she. hidden from men’s eyes. but when they came to Emain. A wise woman. But Conchobar ordered that she be spared and reared apart. Then she said to Leborcham.” That night they set out with 150 warriors and 150 women and 150 hounds. and the sons of Usnach had to flee and take refuge on an island in the sea. and did not recognise him. And sweet was the cry of the sons of Usnach. and the sons of Usnach. Leborcham. “Heifers must grow big where there are no bulls. his two brothers. and Emain was burnt by Fergus. “He is not far from you. Though the whole province of the Ulaid should be around them in one place. Once the girl’s foster-father was flaying a calf outside in the snow in winter to cook it for her.” said he. Then she sprang toward him and caught his ears.” said she. Conchobar pursued them with plots and treachery. and his body like the snow. and Deirdre was with them. and women were killed. and they fled to Scotland. Many will die on account of her.” said she. When Fergus and Cormac heard of this treachery.” “Grace and prosperity to you!” said leborcham. When Naoisi was there outside. they came and did great deed: three hundred of the Ulaid were killed. “We shall go into another country.Chapter 3 – The Ulster Cycle and the Celtic Hero wonderful beauty and will cause enmity and trouble and will depart out of the kingdom.” Once that same Naoisi was on the rampart of the fort sounding his cry. Then Conchobar invited them back and sent Fergus as a surety. “until I see him. and the Ulstermen sprang up as they heard it. And Fergus and Cormac went 26 The Celtic Paradigm in Modern Irish Writing . and her hands were bound behind her back. for the excellence of their defence. “Fair would be man upon whom those three colours should be: his hair like the raven. “You have the bull of the province. “There is not a king in Ireland that will not make us welcome. so that he demanded her for wife. was the only other person allowed to see her. and she saw a raven drinking the blood in the snow.” said he.” Naoisi sounded his cry. One day the steward saw her and told the king of her beauty. they would not overcome them. and his cheek like the blood. “Here are two ears of shame and mockery. But his honour was challenged. if the three of them stood back to back. “Fair is the heifer that goes past me. So Deirdre was entrusted to foster-parents and was reared in a dwelling apart. it was enough of peace and entertainment. “unless you take me with you. as though to go past him. and Deirdre was brought to Conchobar. Every cow and every beast that would hear it used to give two-thirds excess of milk. and that he himself would take her for his wife. inside close by: Naoisi the son of Usnach. “the king of the Ulaid. They were as swift as hounds at the hunt.” “I shall not be well. They used to kill deer by their speed. Good was their valour too. “and I would take a young bull like you.” said he.] The Ulaid proposed to kill the child at once and so avoid the curse. went out to restrain and warn him.
2. As long as I live.a great wrong . She was behind Eogan in the chariot. and she never smiled or raised her head from her knee. “for my father. Do not break my heart. Though the Brown Bull is captured and sent to Cruachain. I shall not love you. he kills the White Bull of Connacht but dies of exhaustion after galloping back to Ulster with his rival on his back. She thrust her head against the rock. “It is a true saying. Conchobar. What was dearest to me under heaven. so that it shattered her head. .[. and the exile of Fergus and the Tragic Death of the sons of Usnach and of Deirdre.so that I shall not see him till I die.” said Conchobar. and she died. There follows a summary of this tale: TAIN BO CUAILNGE Once when their royal bed had been made ready for Ailill and Maeve they conversed as they lay on the pillows.” said Ailill.” “you shall be a year with Eogan. you have taken from me. As the Ulsterman are debilitated by the curse of Macha. That is the exile of the Sons of Usnach. “I had not heard or known it. Grief is stronger than the sea.” said Conchobar. Two bright cheeks. She had prophesied that she would not see two husbands on earth together.” said Ailill. “but that you were an heiress and that your nearest neighbours were robbing and plundering you.” she said. Summary by Myles Dillon 3.) Main plot concerns the invasion of Ulster by the army of Connacht led by Medb who wants to capture the Brown Bull of Cooley. if you could understand it. But Deirdre was for a year with Conchobar. Eochu Feidlech son of The Celtic Paradigm in Modern Irish Writing 27 . “You. . Finit. He gave her to Eogan.” “I was well off without you. “Why do you say so?” “Because. “You look like a sheep between two rams. “Well. Amen. between Eogan and me. red lips. pearly teeth bright with the noble colour of snow.” “It is true. “What do you hate most of what you see?” said Conchobar.Chapter 3 – The Ulster Cycle and the Celtic Hero to the court of Ailill and Maeve. Cuchulain (who is exempt from it) defeats Medb’s army single-handed.” said Maeve.” There was a big rock in front of her.] And when Conchobar was comforting her she used to say: Conchobar. “you are better off today than the day I wed you. eyebrows black as a chafer.” said Maeve. Finit. Táin Bó Cuailnge (The Cattle Raid of Cooley) Táin Bó Cuailnge is the best known and longest tale of the cycle (closest to an Old Irish epic. “and Eogan son of Dubhthach.” said Ailill. what are you doing? You have caused me sorrows and tears. Deirdre. They went next day to the assembly of Macha.” said the girl. . Soon I shall die.” “That was not so. girl. “that the wife of a good man is well off. and what was most beloved. and for sixteen years the Ulaid had no peace. 4.
If the reward was not enough. But he felt a pang of longing for Ulster and led the army astray northward and southward while he sent warnings to the Ulstermen. The woman answered. The tent of Fergus was next. wrote an ogam on it. one leg. and it appeared that Maeve had possessions equal to those of Ailill.] Fergus was appointed to guide the army. Ailill’s tent was on the right wing of the army. There 28 The Celtic Paradigm in Modern Irish Writing . “I see crimson upon them. and. Then he departed to keep a tryst with a girl south of Tara.” And she went on to boast of her riches. unless he made a hoop in the same way. Any man who advanced farther that night.. but each time the answer was the same. was high king of Ireland. “There is no need to smooth over difficulties. On the first day the army advanced from Cruachan as far as Cuil Silinni. The messengers returned without the bull and reported the owner’s refusal. a fairy whom they had wronged. She learned that there was one as good in the province of Ulster in the cantred of Cuailnge. and so it will be taken. and the prophetess then chanted a poem in which she foretold the deeds of Cuchulainn. and she asked her to prophesy. and Cuchulainn told his father to go back and warn the Ulstermen to depart from the open plains into the woods and valleys. Sualtam. son of Conchobar. I see red. He had been King of Ulster for seven years and had gone into exile when the sons of Usnach were killed in violation of his guaranty and protection. To the left of Ailill was the tent of Maeve and next to hers that of Findabair. she consulted her druid for a prophesy. and they set out to oppose the enemy. They arrived at Ard Cuillenn. Whitehorn. Ailill decided to turn aside into the forest for the night. But the Ulstermen had been stricken with a mysterious sickness which afflicted them in times of danger. save for a splendid bull. Fergus interpreted it for them. and beside it was the tent of Cormac. And so he marched in front. He told her that she at least would return alive. for the expedition was a revenge for him. He cut an oak sapling with a single stroke.” said Maeve.” Four times Maeve appealed against this oracle. who were in exile from Ulster at the time. The Connacht army reached Ard Cuillenn and saw the ogam. the result of a curse laid upon them by Macha. which had belonged to Maeve’s herd but had wandered into the herd of Ailill because it would not remain in a woman’s possession. [. All her wealth seemed to Maeve not worth a penny. Their treasures were brought before them. Cuchulainn and his father. and fixed it around a stone pillar. “for I knew that it would not be given freely until it was taken by force. north of Cnogba na Rig.” Maeve summoned the armies of Connacht and Cormac son of Conchobar and Fergus son of Roech.. using one arm. weaving a fringe with a gold staff. promising a rich reward. her daughter. were exempt from the curse.Chapter 3 – The Ulster Cycle and the Celtic Hero Finn. and she sent messengers to ask a loan of it for a year. since she had no bull equal to that of Ailill. she would even grant the owner the enjoyment of her love. and the tents were pitched. and one eye. Then she met a mysterious prophetess who rode on the shaft of a chariot. would be slain by Cuchulainn before morning. and he of his. he made it into a hoop. In the morning Cuchulainn returned from his tryst and found the army at Turloch Caille Moire. Before the expedition started. and set out to carry off the precious bull.
not I!” said each one from where he stood. but he would accept no conditions. [. ‘Yes. He came upon two Connaught warriors and beheaded them and their charioteers. if the army would advance only while the combat lasted and would halt when the warrior had been killed until another was found. the chariots bearing the headless bodies of the men. ‘In his fifth year he went to study the arts and the crafts of War with Scathach. There was one condition that he would accept. and he killed a hundred men. ‘ Fergus said. no raven more flesh-ravenous. for swiftness.’ Fergus said.none like Cuchulainn. horror or eloquence. and killed the four as swiftly as they were killed. ] “The Man who did this deed. The army advanced and devastated the plains of Bregia and Muirthemne. courage or blows in battle. . no barrier in battle.’ ‘Is he the hardest they have in Ulster?’ Maeve said. no hinderer of hosts. and he refused all that were proposed. and if one were owing I would not go against Cuchulainn.” That night a hundred warriors died of fright at the sound of Cuchulainn’s weapons. “My people owe no victim. for apparel.’ On the next day the army moved eastward. and the next day he killed three more with their charioteers. for it is not easy to fight with him. for stalking. Cuchulainn followed hard upon them seeking battle.’ ‘What sort of man. and courted Emer. ‘is this Hound of Ulster we hear tell of? How old is this remarkable person?’ ‘It is soon told. You’ll find no one there to measure him . more fine. no fighter more fierce.’ Aillil said.Chapter 3 – The Ulster Cycle and the Celtic Hero he cut off the fork of a tree with a single stroke and cast it into the earth from his chariot. no lion more ferocious. and who came to the border with only his charioteer. for splendour. At present he is in his seventeenth year. victory.no point more sharp. no hard hammer. and Fergus warned them to beware of Cuchulainn’s vengeance. no one of his own age one third as good. for voice or strength or sternness. ‘is Cuchulainn.’ Fergus said. no soldiers’ doom. more swift. but he would not himself declare it. doom. so that two-thirds of the stem was buried in the earth. and Cuchulainn killed a hundred men each night. Fergus was able to tell that Cuchulainn would agree to single combat with a warrior each day. Maeve sent a messenger to summon Cuchulainn to a parley with her and Fergus. Maeve The Celtic Paradigm in Modern Irish Writing 29 . scheming or slaughter in the hunt. no hand more daft. “Not I. more slashing. They went on into Cuailnge and reached the river Glaiss Cruind. Maeve called upon her own people to oppose him in equal combat. and no one with the battlefeat ‘nine men on each point’ . no gate of battle. and Cuchulainn went to meet them. . fame or form. for cleverness. or turmoil. the hardest of all. The messenger was sent again to ask for terms. for fire or gury. alertness or wilderness. It is he who struck the branch from its base with a single stroke. He set their heads upon the branches of the tree-fork and turned their horses back toward the camp. ‘You’ll find no harder warrior against you . He surprised Orlam son of Ailill and Maeve and killed him. A hundred chariots were swept into the sea. In his eight year he took up the arms. but it rose against them so that they could not cross.for youth or vigour. and for the next three days the army lay without pitching their tents and without feasting or music.
so that only Ailill and Maeve and their sons with nine battalions remained in the field. All who had returned from the battle came to watch the bull-fight. But. .4. Three times the Men of Ireland broke through northward and each time they were driven back. Meanwhile. [. and the Whitehorned Bull heard that and came to fight him. Maeve had sent the Brown Bull of Cuailnge to Cruachan. scattering fragments of the dead bull’s flesh from his horns on the way. and of his chariot there remained a few ribs of the body and a few spokes of the wheels. and three hills were shorn of their tops by his sword. and that was the greatest grief and dismay and confusion that Cuchulainn suffered on that hosting. Cuchulainn challenged Buide and killed him. At sunset he had defeated the last battalion. driving the Brown Bull of Cuailnge. When Cuchulainn now came against him. . and when he came to the border of Cuailnge. to wield against the enemy.] Meanwhile Maeve turned northward to Dun Sobairche. They fought shield to shield. he turned his anger against the hills. He turned back to protect his own territory and found Buide son of Ban Blai.] When the Brown Bull came to Cruachan. because it would be better to lose one man every day than a hundred every night. and he died. body and wheels. and in the morning the Brown Bull was seen going past Cruachan with the Whitehorned Bull on his horns. and found Fergus opposed to him. [. The bulls travelled all over Ireland during the night. [. while they were exchanging casts of their spears. he uttered three mighty bellows. he led his company out of the fight. when the sun was up. . 30 The Celtic Paradigm in Modern Irish Writing . whoever else might fail to come. He rose up in heroic frenzy and seized no mere weapons but his war-chariot. and when night fell they could only listen to the great noise of the fight.] In the morning. Maeve plundered Dun Sobairche. and the Leinstermen and Munstermen followed them.Chapter 3 – The Ulster Cycle and the Celtic Hero decided to accept the proposal. if ever he and Cuchulainn should meet in the battle. The Conchobar himself went into the field. the Ulstermen attacked. . and he consented. his heart broke. which they had found in Glenn na Samisce in Sliab Cuilinn. Then she appealed the Cuchulainn to spare her army until it should go westward past Ath Mor. Táin Bó Fraoch (The Cattle Raid of Fraoch) Táin Bó Fraoch is the second most popular cattle raid tale in Old Irish literature. At noon Cuchulainn came into the battle. remembering that he was an Ulsterman. He galloped back to Ulster. . but. the great bull was driven off. so that he at least should come there. where the enemy had been advancing. and the men of Ireland [the Connaught army] came to meet them. and Cuchulainn followed her. that he would retreat before him. and then after six weeks the four provinces of Ireland with Ailill and Maeve and those who had captured the bull came into camp together. Fergus had promised. Summary by Myles Dillon 3. The bull was accompanied by twenty-four of his cows. They watched until night fell. Cuchulainn heard the scream of Conchobar’s magic shield where he lay prostrate from his wounds. .3. with twenty-four followers. and Fergus struck three mighty blows upon the shield of Conchobar so that it screamed aloud.
the Cuchulain plays are: 3.5. a giant or demon. The Green Helmet (1910) 3. and Lady Augusta Gregory’s Cuchulain of Muirthemne (1902).Chapter 3 – The Ulster Cycle and the Celtic Hero Its first part. invites the warriors of Ireland to a feast.1. Cuchulain overhears from Cathbad that the youth who take up arms that day would become the greatest warrior in Ireland.3.5. Cuchulain. with his personal symbolism that carries forward the oppositions between the real and the spirit world evolved in his poems. Play: Cuchulain makes a sacrificial gesture in offering himself to the Red Man from the sea (Manannan in disguise) to kill.1. The Celtic Paradigm in Modern Irish Writing 31 .1.5.1. The Only Jealousy of Emer (1916) 3. as a Young Man. Connla. On Baile’s Strand (1904) 3. Yeats 3. At the Hawk’s Well (1916) 3. narrated by Fergus in the Taín.1. whose waters are said to give immortality. While in Scotland. Conall Cernach and Laegaire Buadach claim the title in turn. Only Cuchulain accepts the challenge and beheads the giant. The Cuchulain Cycle of Plays Cuchulain appears as the main hero in 5 plays written by William Butler Yeats from 1902 to 1938. a famous warrior woman from the Land of Shadow (island of Skye).5. a mischief-maker. The Green Helmet Source: Fledd Bricrenn (Bricriu’s Feast) Bricriu.1. he begets Aife a son.5. Celtic Myth in the Theatre of W. arrives at a Well. In their chronological order. Cuchulain receives his training first under Fergus and then under Scathach.1. Aife. An Old Man.5. who has spent 50 years waiting for the chance of drinking from its waters. After killing the monster. Fraoch marries Finnabair. Play: Cuchulain. The Death of Cuchulain (1938) At the Hawk’s Well Sources: Macgnìmartha/boyhood deeds. and the second part of the tale recounts how both she and his cattle herds are kidnapped and carried off from Connacht. whom he finally manages to defeat. to be then proclaimed by Uath the greatest champion in Ireland.4. Becoming her lover. named Uath (Horror) appears and challenges them into a beheading game. Cuchulain decides to pursue the Hawk guardian of the well. but short. has echoes in the anglo-saxon poem of Beowulf. he has to fight Scathach’s sister. and in doing so he embraces his heroic destiny. where he maliciously exploits the contention that the choicest portion of meat is given to the greatest hero. He makes his choice immediately and asks the king to let him take up arms like a man. his life would be most glorious. In these plays Yeats blends elements of Irish myth made available to him through the translations of the Taín. 3.5. urges him to join him. To decide which of these warriors is the greatest. Tochmarc Emire (the Courtship of Emer). for else his life will be spent in ceaseless warfare.2.5. in which Medb plots the death of Fraoch (a young Connach warrior who has fallen in love with Finnabair) forcing him fight a monster who dwells in a lake.B.
and I can go out and run races with the witches at the edge of the waves and get an appetite. Finally Conchobar send Cuchulain against the boy.ah FOOL: Why do you say ‘Ah . 32 The Celtic Paradigm in Modern Irish Writing . he was to fight any man who impeded his path. Cuchulain placed a geis upon him: Connla was to never reveal his name to any man. FOOL: He must be a great man to be Cuchulain’s master. That’s wide enough. give a kiss. and you put it into the big pot at the fire there. It is that he’s coming for. but refused to give each warrior his name. and when I’ve got it. there’s the hen waiting inside for me. O shouldn’t have closed the door. and. But we won’t give them any of the fowl.1904) FOOL: What a clever man you are though you are blind! There’s nobody with two eyes in his head that is as clever as you are. There are some that look for me. I’ll be praising you while you’re eating it. in a louder voice as he feels the back of it]. It is to-day the High King Conchubar is coming. BLIND MAN [feeling legs of big chair with his hand] Ah! [Then. come. mistaken their foam for Conchobar’s crown. his duty to his king forced him fight and kill Connla. Play: Reluctantly. Cuchulain dies fighting the waves. Come. Ah . and they come by in the wind. Let them go back to the sea. I’ll have a leg and you’ll have a leg. All the witches can come in now. framing the main action of the play. Witches they are. He is going to be Cuchulain’s master in earnest from this day out. let them go back to the sea. Fool.Chapter 3 – The Ulster Cycle and the Celtic Hero On Baile’s Strand Source: Aided Oenfhir Aife (Violent Death of Aife’s Son) Before the birth of his son. And what a good cook you are! You take the fowl out of my hands after I have stolen it and plucked it. After learning that the youth he killed was his own son. and they cry. Cuchulain swears loyalty to Conchobar and is forbidden by him to befriend an unknown young man sent by Aife. Blind Man. I wouldn’t have them beat at the door and say. There’s nobody in the world like you. and we’ll draw lots for the wish-bone. he set out for Emain Macha in search of his father. for your good plans and for your good cooking. “Where is the Fool? Why has he put a lock on the door?” Maybe they’ll hear the bubbling of the pot and come in and sit on the ground.’ that’s what they cry. Who but you could have though that the henwife sleeps every day a little at noon? I would never be able to steal anything if you didn’t tell me where to look for it. and I wouldn’t like them not to find me. though warned by Emer that the young man was possibly his son by Aife. There he encountered many warriors of the Red Branch. done to the turn. Boann herself out of the river and Fand out of the deep sea. and he either wounded or killed them. They have brought out this chair. FOOL [putting his arm round Blind Man’s neck]: Come now. ON BAILE’S STRAND (1901. Wait a minute. P. When Connla grew into a young man.ah’? BLIND MAN: I know the big chair. BLIND MAN [who is feeling about with his stick]: Done to the turn. ‘Give a kiss. A Blind Man and a Fool act as chorus.
I want my dinner. I tell you. You’d lay this oath upon me . Cuchulain. so he did. [The Blind Man has got into the chair]. hush! It is not done yet. and others had run away. I wish it was as big as a goose. FOOL: Who is that? Who is he coming to kill? BLIND MAN: Wait. and a ship and a queen’s son that has his mind set on killing somebody that you and I know. FOOL: How will he do that? BLIND MAN: You have no wits to understand such things. and now . and Conchubar is coming to-day to put an oath upon him that will stop his rambling and make him as biddable as a housedog and keep him always at his hand. But he ran too wild. He is a great man. till you hear. BLIND MAN: Did I. Fool. FOOL: That’s enough. believe me. I know who that young man is. and I heard three men coming with a shuffling sort of noise. FOOL: My teeth are growing long with the hunger. I was lying in a hole in the sand. and he had refused to tell it. FOOL: Cuchulain’s master! I thought Cuchulain could do anything he liked. I’ll take no oath. II. He is over all the rest of the kings of Ireland. BLIND MAN: I’ll tell you a story .Chapter 3 – The Ulster Cycle and the Celtic Hero BLIND MAN: So he is. Do as I tell you. and not done. that he had come from Aoife’s country. and he had killed one. CUCHULAIN: Because I have killed men without your bidding And have rewarded others at my own leisure. Tell me about the fight. it might be done.and now The Celtic Paradigm in Modern Irish Writing 33 . BLIND MAN: There had been a fight. it will be well done before you put your teeth in it. What are your wits compared with mine.the kings have story-tellers while they are waiting for their dinner . He will sit up in this chair and he’ll say: ‘Take the oath. and what are your riches compared with mine? And what sons have you to pay your debts and to put a stone over you when you die? Take the oath. the guardians of the shore had asked his name. Because of half a score of trifling thing. now? Well. BLIND MAN: Hush. FOOL: Go on. a tremendous great fight. a great fight. but the legs might be red. that he was going to kill Cuchulain. I heard the men who were running away say he had red hair. BLIND MAN: So he did. A youg man had landed on the shore. But. now. Take a strong oath. I wish it was bigger. BLIND MAN: Hush! I haven’t told you all.’ FOOL [crumpling himself up and whining]: I will not. a story with a champion in it. The flesh might stick hard to the bones and not come away in the teeth. The wings might be white. They were wounded and groaning. FOOL: You said it was done to a turn. When you were stealing the fowl. I bid you take the oath.I will tell you a story with a fight in it. Come on now to the fowl. He will sit in this chair and put the oath upon him.
Chapter 3 – The Ulster Cycle and the Celtic Hero you add another pebble to the heap, And I must be your man, welln settleed with the heat of the fire, Or have my hands not skill but to make figures Upon the ashes with a stick? Am I So slack and idle in balance with my children. CUCHULAIN: It’s well that we should speak out minds out plainly, For when we die we shall be spoken of In many countries. We in our young days 34 The Celtic Paradigm in Modern Irish Writing
Chapter 3 – The Ulster Cycle and the Celtic Hero. [ . . . ] IV. kind Conchubar’s crown on every one of them. FOOL: There, he has struck at a big one! He has struck the crown off it; he has made the foam fly. There again, another big one! BLIN in backwards towards the door]: What is it? BLIND MAN: There will be nobody in the houses. Come this way; come quickly! The ovens will be full. We will put our hands into the ovens. [They go out]. The Only Jealousy Of Emer Sources: Serglige con Chulainn (Cuchulain’s Illness) and Oenet Emire (The Jealousy of Emer) When cuchulain tries to kill two magical birds, he is horsewhipped in a dream by two women of the sídh. He spends a year in a coma at Emain Macha, until , in a further vision, he is told that Fand needs him to fight off three demons who besieged her palace. Cuchulain enters the Otherworld, defeats the demons, and spends a month in Fand’s loving arms. When he returns to the surface, he promises to meet Fand again. Emer plans to kill Fand at the meeting-place, but instead each woman offers to surrender her love. Fand leaves, but all three are distraught until Manannan uses his magic cloak to cast a spell of oblivion upon them. The Celtic Paradigm in Modern Irish Writing 35
Chapter 3 – The Ulster Cycle and the Celtic Hero Play: Yeats exploits the dramatic potential of the love triangle, adding a new character, Eithne Inguba, Cuchulain’s young mistress. While Emer renounces Cuchulain in order to save him from Fand (who wants to take him to the Otherworld), Eithne seemingly wins him back to life and to herself. The Death Of Cuchulain Source: Aided Chon Culainn (The Violent Death Of Cuchulain) Cuchulain meets his death on the plain of Mag Muirthemne, as ordained by Morrigan. As in the Taín, he contends alone against the enemies of Ulster. Pierced by a spear in the fighting, he fastens himself to a pillar-stone, so that he may die standing up. When a raven settles on his shoulder, it is taken as a sign he is dead, and his enemies behead him. Play: Though in legend Cuchulain is said to die young, here he has aged with the poet. The Morrigan gets Eithne Inguba to falsify a message from Emer, so that Cuchulain leaves to fight against Medb’s army, who has attacked Ulster again. He is wounded six times in battle. Aife appears and ties him to a stake, ready to avenge upon him the death of Connla. But it is not her, but the Blind Man (from On Baile’s Strand) who beheads the hero, having been promised 12 pennies by a “big man”. Cuchulain’s mode of dying becomes an indictment of the modern materialist society which no longer treasures heroes and artists alike.
3.6. De-Constructing Heroism: Nuala Ní Dhomhnaill
Cú Chulainn I from Selected Poems, 1988
Small dark rigid man Cú Chulainn who still lacks a lump on your shoulder who spent your first nine months in a cave swimming in your mother’s fluid. Grave hunter who’d satisfy no woman saying your father never went to a small seaside town like Ballybuion never made arms and instruments of war to give you so you could leap from the womb three minutes after the conception your hand full of spears holding five shields it is not we who injured you. 36 The Celtic Paradigm in Modern Irish Writing
Yeats’s “Cuchulain plays” and Nuala NiDhumnaill’s Chuchulain I. W.Chapter 3 – The Ulster Cycle and the Celtic Hero We also came my ladies. out of wombs and the danger yet remains morning noon and evening that the ground will open and opened to us all will be Brufon na hAlmhaine Brú na Bóinne or Teach Da Deige with its seven doors and hot cauldrons. Task Choose from one of the following topics to develop into a 4000-word essay of the argumentative type: 1. 2. Don’t threat us again with your youth again small poor dark man Cú Chulainn. Constructing and De-constructing Mythic Heroism: representations of Cuchulain in Tain Bo Cualgne . The Celtic Paradigm in Modern Irish Writing 37 . Tain Bo Cualgne and the Celtic Framework. B.
His famous hounds. Fionn appears as a vindictive and jealous older man. which also brings him the gift of poetry. 38 The Celtic Paradigm in Modern Irish Writing . Muirne (Muireann) was the daughter of the druid Tadg. collectively known as the Fianna. while his mother. This set of literary conventions reflects a feature of early Irish society in that such bands of warriors did live outside the structures of that society while retaining links with it. Thereafter he finds himself inspired with imbas (great knowledge). and.Chapter 4 – The Cycle of Munster (the Finn Cycle) Chapter 4 . his finger was injured when a fairy woman caught it in the door of the fairy-fort at Femun. conduct raids. in early Ireland.1. Cumhall. According to one account of his origin. said to be descending from the Danann. his druid teacher. diviner. and other famous members of the fian (warrior-band) of Fionn. where he spends 300 years until returning to Ireland. his parentage combined warrior and visionary elements. Another characteristic is its frequent celebration of the beauty of nature. the most famous is the one with the goddess Sadb.2. who hunt. the Tara fian. In folklore the injury is caused by Fionn’s burning his thumb on the Salmon of Knowledge from the Boyne.D. institutional attributes. his son Oisín. who came to him in the form of a deer. fight. initially threatened by the youthful lover. Afterwards. in his turn.) Among his romances. Manannan’s daughter. yet he was also a poet. but eventually getting his bride back. Oísin is lured away to Tir-na-nOg by Niamh. Bran and Sceolang. Fionn was to some extent an outlaw. had led. In “The Pursuit of Diarmuid and Gráinne”. Most stories centre on the exploits of the mythical hero Fionn mac Cumhaill. and sage. evoked in vivid language. Oscar (Fionn’s grandson) and many of the Fianna are killed. he declares war on the Fianna. The Fionn Cycle (Fenian. Ossianic. Fionn possesses a gift of special insight which he can summon by biting his finger.The Cycle of Munster (the Finn Cycle) 4. the mother of Oísin. When Cormac’s son succeeds to the thrown. His father. Fenian Heroes and Tales Fionn mac Cumhaill is the leader of the Fianna under the High King Cormac mac Airt. As well as being endowed with physical courage. are said to be his cousins (Muirne’s sister having been turned into an animal during her pregnancy. and. 4. therefore. At the battle of Gabhra (Cath Gabhra). which he is cooking for Finnegas. and live an open-air nomadic life. As such. endowed with traditional. Munster) The Fionn Cycle contains a group of tales developed in Munster and Leinster and dating to the 3rd century A.
golden loops down over her shoulders. “I’ve travelled a great distance to find you. Finn and a handful of survivors went south to Lough Lene in Kerry. Oisin’s own son. Patrick preached the new doctrines to him but the old warrior scorned the newcomers and their rituals and in defiant response sand the praises of the Fianna. Many of their companions had been killed at Gowra. When Finn. hung down over the silk trapping of her horse. lustrous cloak. Her long. last of the Fianna. among them the bravest warrior of the Fianna. Her eyes were as clear and blue as the May sky above the forest and they sparkled like dew on the morning grass. The beauty of the countryside and the prospect of the chase revived their spirits a little as they followed the hounds through the woods. but this last battle had brought them total defeat and bitter losses. Around Lough Lene the woods were fresh and green and the early mists of a May morning were beginning to lift when Finn and his followers set out with their dogs to hunt. and Finn found his voice. Oisin. No one had seen a better animal. the last battle the Fianna fought. Suddenly a young hornless deer broke cover and bounded through the forest with the dogs in full cry at its heels. After the battle of Gowra. glinting with gold-embroidered stars. He had heard many stories about the adventures of the Fianna and he was interested in these old heroes whom the people spoke about as if they were gods. told his story. The Fianna followed them. They had all fought many battles in their time.” “I am called Niamh of the Golden Hair and my father is the king of Tir na n-Og. Oisin in the Land of Youth (From the Finn Cycle) Hundreds of years after Finn and his companions had died. They were stopped in their tracks by the sight of a lovely young woman galloping towards them on a supple. One day a feeble. Patrick doubted the old man’s word since Finn had been dead for longer than the span of any human life. Their story was written into the very landscape of Ireland. their code of honour and their way of life.3.Chapter 4 – The Cycle of Munster (the Finn Cycle) 4. His body was weak and wasted but his spirit was strong.” she said. “Who are you and where have you come from?” he asked. dozens marked their graves. Only once before had the Fianna seen their leader cry and that was at the death of his staghound Bran. So to convince the saint that his claim was true.” the girl replied. blind old man was brought to Patrick. They were dispirited because they knew their day was over. He said he was Oisin. had seen his favourite grandson lying dead on the field. Her horse was saddled and shod with gold and there was a silver wreath around his head. the son of Finn himself. nimble white horse. the Land of Youth. Oscar. She was so beautiful she seemed like a vision. a favourite haunt of theirs in happier times. The Celtic Paradigm in Modern Irish Writing 39 . hills and woods resounded with their legends. She wore a crown and her hair hung in shining. rejuvenated by the familiar excitement of the chase. rivers and valleys bore their names. he had turned his back to his troops and wept. “Tell us your name and the name of your kingdom. Saint Patrick came to Ireland bringing the Christian religion with him. the baule-hardened old veteran. moon-struck and silent. Her skin glowed white and pink and her mouth seemed as sweet as honeyed wine. The woman reined in her horse and came up to where Finn stood. Oisin.
” he cried out. Princess Niamh. You’re leaving me here heartbroken for I know we’ll never meet again!” Oisin stopped and embraced his father and said goodbye to all his friends. As they travelled across the sea. strength and power. a hundred swift bay horses. You will never fall ill or grow old there. plunging into the sea.” Oisin had been silent all this time. In my country you will never die. A young fawn rushed past. as much as you could ever want. A beautiful young woman on a bay horse galloped by on the crests of the waves. sorrowful shots. “You love one of my sons? Which of my sons do you love. The land thaws with honey and wine.Chapter 4 – The Cycle of Munster (the Finn Cycle) “Then tell us. So I decided to come and find him. “Reports of his handsome looks and sweet nature reached as far as the Land of Youth. He saw the defeat and sorrow on his father’s face and the sadness of his friends. And me for your wife. he let out three loud. and it will protect you from every danger. dazzled by the beautiful girl and when he heard her name him as the man she loved he trembled from head to toe. Oisin. “You are the most beautiful woman in the world and I would choose you above all others. my son. Niamh. “why are you leaving me? I will never see you again. “for I’ve never had a husband. You will get a hundred cows. A hundred young women will sing to you and a hundred of the bravest. “Go slowly. I will gladly marry you!” “Come away with me. And a hundred swords. “Oh. It is the most beautiful country under the sun. With tears streaming down his face he took a last look at them as they stood on the shore. a hundred keen hunting dogs.” she answered. “Come back with me to the Land of Youth. and a hundred sheep with golden wool. till we reach the shore!” Niamh said. painted summerhouses and stately palaces. a hundred calves.” “Oh. a crown that he has never given to anyone else. As well as all of this. In Tir na n-Og you will sit at feasts and games with plenty of music for you. Oisin!” Niamh whispered. Then the white horse shook its mane. “Oisin is the champion I’m talking about. You will get gold and jewels. but I wouldn’t look at any of them because I loved your son. I could never refuse you anything you ask and I will gladly go with you to the Land of Youth!” Oisin cried and he jumped up on the horse behind her. white-washed bawns and forts. courts and castles. gave three shrill neighs and leapt forward. They passed cities. He remembered his days together with them all in the excitement of the hunt and the heat of battle. you will get beauty. Oisin. plenty of wine. When Finn saw his son being borne away from him. why have you left a country like that and crossed the sea to come to us? Has your husband forsaken you or has some other tragedy brought you here?” “My husband didn’t leave me. a hundred silk tunics.” replied Niamh. Many men in my own country wanted to marry me. You will get a hundred of the most beautiful jewels you’ve ever seen and a hundred arrows. But he recovered himself and went over to the princess and took her hand in his. young warriors will obey your command. a white dog with scarlet ears racing after it. carrying a golden apple in 40 The Celtic Paradigm in Modern Irish Writing . more than you could imagine. Niamh? And tell me why your mind settled on him?” he asked.” Finn started in surprise. With Niamh cradled between his arms he took the reins in his hands and the horse started forwards. wonderful sight appeared to them on every side. Trees grow tall there and treed bend low with fruit. The King of the Ever Young will place a crown on your head. The waves opened before Niamh and Oisin and dosed behind them as they passed.
handsome and richly dressed with a gold-bladed sword in his hand. I’m not afraid of him! Either I’ll kill him or I’ll fight till he kills me. mounted on a white horse. a shining palace came into view. Then. the story you’ve told me is sad. she replied that they were insignificant compared to the inhabitants of the Land of Youth. When the feast was over. “The daughter of the king of the Land of Life is the queen. He was huge and ugly and he carried a load of deerskins on his back and an iron bar in his hand. The two women gave three triumphant cheers when they saw the giant felled. He looked into the face of his prisoner and straight away he knew that she had told her story to the visitors. What country are we in now and who is the king?” “This is the Land of Virtue and that is the palace of Fomor.” They turned the horse towards the white palace and when they arrived there they were welcomed by a woman almost as beautiful as Niamh herself. Oisin overpowered him in the end and cut off his head. as powerful as Fomor was. looking up at the pillars of clouds blotting out the sun until the wind dropped and the storm died down. Set amid the smooth rich plains was a majestic fortress that shone like a prism in the sun. so they said goodbye to her and that was the last they saw of her. The Celtic Paradigm in Modern Irish Writing 41 . Niamh and Oisin rode steadily through the tempest. bathed in sunshine. Ahead of them and visible from afar. With a loud. The queen of the Land of Virtue was sad to see them go. Suddenly the sky darkened. “I’ll go to the fortress and try to overcome the giant and set the queen free. When they saw that Oisin was badly injured and too exhausted to walk unaided. Oisin looked in awe at this handsome couple but when he asked Niamh who they were. But a prisoner she remains for no one wants to fight the giant. Behind her. spread out in all its splendour. “Dry your eyes.” “Niamh. The queen put ointments and herbs on his wounds and in a very short time Oisin had recovered his health and spirits. the wind rose and the sea was lit up by angry flashes of light. but she was free now to return home.” Oisin told her.” Niamh replied. even though your voice is music in my ears. She brought them to a room where thy sat on golden chairs and ate and drank of the best. For three days and three nights they struggled and fought but. and indeed they were sad to leave her. ahead of them. They buried the giant and raised his flag over the grave and caned his name in ogham script in stone. the queen told the story of her captivity and as tears coursed down her cheeks she told them that until the giant was overcome she could never return home. They mounted the white horse and he galloped away as boisterously as a March wind roaring across a mountain summit. “I’ll challenge the giant. She has put a geis on him that he may not marry her until a champion has challenged him to single combat.Chapter 4 – The Cycle of Munster (the Finn Cycle) her right hand. a giant. Then they feasted till they were full and slept till dawn in the feather beds that were prepared for them. He saw Oisin and Niamh but did not acknowledge their presence. angry shout he challenged Oisin to fight.” At that moment Fomor approached the castle. “That’s the most beautiful palace I have ever see!” Oisin exclaimed. marble facade shone in the sun. they took him gently between them and helped him back to the fortress. She was abducted from her own country by Fomor and he keeps her a prisoner here. they saw the most delightful country. rode a young prince.” Oisin said. Its delicate. The morning sun awoke them and Niamh told Oisin they must continue on their journey to Tir na n-Og.
“listen to me well. He began to get homesick for Ireland and longed to see Finn and his friends. who is to be married to my beloved daughter. This is Tir na n_og. The festivities lasted for ten days and ten nights. Everything you ever dreamt of is waiting for you here. and set out at once to find the Fianna. Oisin!” she said. “Our white horse knows the way. set out for Ireland. you will find only a crowd of monks and holy men. “and remember what I’m saying. You will not see Finn or the Fianna. he named her Plur na mBan. Oisin gave his daughter a name that suited her loving nature and her lovely face. He said goodbye to his children and as he stood by the white horse Niamh came up to him and kissed him. you will receive. Three hundred years went by. you will be lost for ever to the Land of Youth. “I told you the truth when I told you how beautiful it was. Niamh and Oisin lived happily in the Land of Youth and had three children.” Then Niamh began to sob and wail in great distress. “I can’t refuse you though I wish you had never asked.” Oisin thanked the king and queen and a wedding feast was prepared for Oisin and Niamh. Oisin! Here you will have a long and happy life and you will never grow old.” Oisin tried to console her but Niamh was inconsolable and pulled and clutched at her long hair in her distress. I tell you again.” Oisin mounted his horse and turning his back on the Land of Youth. Oisin. but she gave Oisin a most solemn warning. “This land is the most beautiful place I have ever see!” Oisin exclaimed. who crossed the sea to find you and bring you back here so that you could be together for ever. “You’re welcome to this happy country. the king took Oisin by the hand and welcomed him. The king consented but Niamh was perturbed by his request. if your foot as much as touches the ground. This is my queen and this is my daughter Niamh. “Oisin. so he asked Niamh and her father to allow his to return home. here is a last kiss for you! You will never come back to me or to the Land of Youth. Oisin arrived in Ireland in high spirits. If you dismount from the horse you will not be able to return to this happy country. “Oh. and they welcomed the couple to Tir na n-Og. Everything I promised you. Finn’s son.Chapter 4 – The Cycle of Munster (the Finn Cycle) Surrounding it were airy halls and summerhouses built with great artistry and inlaid with precious stones.” He turned to Oisin. Niamh!” he said.” Niamh replied. Oisin. The horse took him away from Tir na n_og as swiftly as it had brought Niamh and him there three hundred years before. Niamh named the boys Finn and Oscar after Oisin’s father and son. for the third time I warn you: do not set foot on the soil of Ireland or you can never come back to me again! Everything is changed there. I promise you that all I say is true for I am the king of Tir na n-Og. He’ll bring me back safely!” So Niamh consented. As Niamh and Oisin approached the fortress a troop of a hundred of the most famous champions came out to meet them. though to Oisin they seemed as short as three. Then he turned towards the crowd and said. “Have we arrived at the Land of Youth?” “Indeed we have.” she implored him. “I’m afraid that if you go you’ll never return. “This is Oisin. He 42 The Celtic Paradigm in Modern Irish Writing .” Oisin tried to comfort his wife. A huge glittering crowd then approached with the king and queen at their head. as strong and powerful a champion as he had ever been. When Oisin and Niamh met the royal party. the Golden-haired.” As Niamh spoke a hundred beautiful young women came to meet them. “Don’t be distressed. Niamh of the Golden Hair. the Flower of Women. dressed in silk and heavy gold brocade.
1994) Accounts of Fionn’s death vary. “The stories about him say that there never was anyone to match him in character. taking the marble slab in his hands. His powerful body withered and shrank. Oisin stood upright for a moment. chickweed and nettles. Again the leader shouted desperately to Oisin. Instead he saw a crowd of men and women approaching from the west. Some were down already. Oisin and Oscar have inspired many generation of writers. the tall young warrior. But the slab was so heavy and the exertion so great that the golden girth round the horse’s belly snapped and Oisin was pulled out of the saddle. OVER NINE WAVES. but they kept on staring at him. The cycle has been Christianized. When they saw Oisin approach on his horse one of them shouted out. his skin sagged into wrinkles and folds and the sight left his clouded eyes. But when he got there. They addressed him courteously. He had to jump to the ground to save himself and the horse bolted the instant its rider’s feet touched the ground. There was only a bare hill overgrown with ragwort. he raised it with all his strength and flung it away and the men underneath it were freed. Faber and Faber. astonished at his appearance and his great size. the crowd stopped too. the headquarters of the Fianna in the plains of Leinster. Oisin was heartbroken at the sight of that desolate place. the warriors lamenting the abeyance of heroic conduct in Christian Ireland. but in folk tradition he is still alive (sleeping in a cave). as the horrified crowd watched. “Come over here and help us! You are much stronger than we are!” Oisin came closer and saw that the men were trying to lift a vast marble flagstone. through Glenasmole. he lay at their feet. Then.4. The Celtic Paradigm in Modern Irish Writing 43 . the Valley of the Thrushes. He went from one of Finn’s haunts to another but they were all deserted. As he passed through Wicklow. and some stories present the meeting of Oísin and other survivors of the Fianna with St. He scoured the countryside but there was no trace of his companions anywhere. “We’ve heard of Finn and the Fianna. When Oisin told them he was looking for Finn MacCumhaill and asked of his whereabouts the people were even more surprised. Hopeless and helpless. Literary Treatments of Fenian Tales and Heroes The stories included in the Fionn Cycle as well as the Fenian heroes like Fionn. There are so many stories that we could not even start to tell them to you!” When Oisin heard this a tide of weariness and sadness washed over him and he realized that Finn and his companions were dead. He drew in his horse and. a bewildered blind old man. Straight away he set out for Almu. towering over the gathering.” they told him. “Come quickly and help us to lift the slab or all these men will be crushed to death!” Oisin looked down in disbelief at the crowd of men beneath him who were so puny and weak that they were unable to lift the flagstone. there was no trace of the strong. (from Marie Heaney. at the sight of Oisin. behaviour or build. ready to help Ireland in times of need. Patrick. 4.Chapter 4 – The Cycle of Munster (the Finn Cycle) travelled over the familiar terrain but saw no trace of any of his friends. The weight of the stone was so great that the men underneath could not support it and were being crushed by the load. he saw three hundred or more people crowding the glen. He leaned out of the saddle and. who had been stronger than all of them. shining white fort. sank slowly to the ground.
Chapter 4 – The Cycle of Munster (the Finn Cycle) 4. The title is taken from a popular ballad about Tim Finnegan. the fairy daughter of the seagod Manannan. Goethe translated parts of it. the poem relates Oisin’s threehundred years sojourn in the immortal islands of the Sidhe. dance to your partner Welt the flure yer trotters shake Wasn’t it the truth I told you. Patrick. Lot’s of fun at Finnegan’s wake. 3. Napoleon carried a copy into battle. Finn Maccool. with the love of the liquor he was born. the Dream of Ossian was based on it. from “Finnegan’s Wake” to Joyce’s “Finnegans Wake” Nevertheless. who dies in a fall from a ladder and is revived with a splash of whiskey at his wake. and one of Ingres' most romantic and moody paintings. the most famous literary treatment of Fionn himself is found in James Joyce’s Finnegans Wake (1939) Finnegans Wake is a modernist novel. an ancient Caledonian bard. 4. held traditionally to have converted Ireland to Christianity. Collected in the Highlands of Scotland. Yeats reworked the tale of “Oisin in the Land of Youth” in his first long narrative poem entitled The Wanderings of Oísin (1889). an’ to rise in the world he carried a hod. and Translated from the Gaelic or Erse Language (1760). dancing. 4. He had a tongue both rich and sweet. W. “The Wanderings of Oisin” W. whose poems he claimed to have discovered and then translated into English with the publication of: • Fragments of Ancient Poetry. 1. Ossianism The Scott James MacPherson is among the first to have revived the figure of Oisin under the guise of Ossian. 4. an Ancient Epic Poem. B. Yeats. Written in the form of a dialogue between the aged fenian hero and St. a drunken hodcarrier. • Fingal. 4. 4. and feasting in the company of Niamh. Now Tim had a sort of a tipplin’ way. One morning Tim was rather full. 44 The Celtic Paradigm in Modern Irish Writing .B. An’ to help him on with his work each day he’d a drop of the craythur ev’ry morn. FINNEGAN’S WAKE Tim Finnegan liv’d in Walkin Street a gentleman Irish mighty odd. written in a highly innovative ‘dream language’ combining multilingual puns with the stream of consciousness developed in Ulysses. spent hunting. Chorus: Whack fol de dah. in Six Books (1762) • Temora (1763) Ossianism had a massive cultural impact during the 18th and 19th centuries. 2.
see how he rises. “Whirl your liquor round like blazes. will inevitably return (‘Mister Finn. It also systematically reflects Giordano Bruno’s theory that everything in nature is realized through interaction with its opposite.Chapter 4 – The Cycle of Munster (the Finn Cycle) His head fell heavy which made him shake. I’m sure. Bedad he revives. It also connects to modern psychology. to which Joyce added a section called the ‘Ricorso’.” But Biddy gave her a belt in the gob. Shillelagh law did all engage.” said Paddy McGee. He fell from the ladder and broke his skull. did you ever see. Then Micky Maloney raised his head. orra whyi deed ye diie?’). then the war did soon enrage. And Mrs. Finnegan called for lunch. “Biddy. His friends assembled at the wake. Thanam o’n dhoul. Tim avourneen. When a noggin of whiskey flew at him. And a barrel of porter at his head. ‘Twas woman to woman and man to man. They rolled him up in a nice clean sheet And laid him out upon the bed. Then Biddy O’Connor took up the job. The pipes. the novel enacting the processes of the sleeping mind in keeping with Joyce’s description of it as the dream of Fionn lying in death beside the Liffey. And a row and a ruction soon began. you’re going to be Mister Finnagain!’ Its structure is governed by Giambattista Vico’s division of human history into three ages (divine. Arrah. heroic. “Such a neat clean corpse. Oh. emphasizing the Neapolitan philosopher’s cyclical conception. and human). do ye think I’m dead?” It further relates to Fionn mac Cumhaill who. and whiskey punch. First they brought in tay and cake.” says she. So they carried him home his corpse to wake. Miss Biddy O’Brien began to cry. And left her sprawling on the floor. Macool. Says. It missed and falling on the bed. why did you die?” “Ah. having passed away (‘Macool. tobacco. “you’re wrong. And Timothy rising from the bed. hould your gab. The main characters of the novel are: • Humphrey Chimpden Earwicker (HCE) (Father) • Ana Livia Plurabelle (ALP) (Mother) • Shem the Penman and Shaun the Post (Sons) The Celtic Paradigm in Modern Irish Writing 45 . The liquor scattered over Tim. With a gallon of whiskey at his feet.
The fall (bababadalgharagharaghtakmminorronnkonnbronntonnerronntuonnthunntrovarrhhounawskawntoohoohoordenenthurnuk!) of a once wallstrait oldparr is related early in bed and later on life down through all christian minstrelsy.] A way a lone a last a loved a long the Task Consider one of the following topics to develop into a full-length essay: 1. . Aged ALP prepares to return as her daughter Issy to catch his eye again. HCE perpetrates a sexual misdemeanour in the Phoenix Park. nor had topsawyer’s rocks by the stream Oconee exaggerated themselse to Laurens Country’s gorgios while they went doublin their mumper all the time. Not a peck of pa’s malt had Jhem or Shen brewed by archlight and rory end to the regginbrow was to be seen ringsome on the aquaface. Sir Tristram. The great fall of the offwall entailed at such short notice the pftjschute of Finnegan. [. Celtic Connections: from the Finn to the Arthurian cycle of tales. were sosie sesters wroth with thone nathandjoe. past Eve and Adam’s. fr’over the short sea. that the humptyhillhead of himself prumptly sends an unquiring one well to the west quest of his tumptytumtoes: and their upturnpikepoindandplace is at the knock out in the park where oranges have been laid to rust upon the green since devlinsfirst loved livvy. had a kidscad buttened a bland old isaac. though vennissoon after. Tim Finnegan and Finnegans Wake 46 The Celtic Paradigm in Modern Irish Writing . had passencore rearrived from North Armorica on this side the scraggy isthmus of Europe minor to wielderfight his penisolate war. is buried and revives. nor avoice from afire bellowsed mishe mishe to tauf-tauf thuartpeatrick. 2. The narrative line consists of a series of situations primarily relating to the sexual life of the Earwicker family. violer d’amores. In testimony of this cyclic conception. HCE grows old and impotent. from swerve of shore to bend of bay. not yet. . They appear under different personal and impersonal forms throughout the text. erse solid man. brings us by a commodius vicus of recirculation back to Howth Castle and Environs. and becomes the victim of a scadalmongering. ALP defends him in a letter written by Shem and carried by Shaun. Irish Heroes in Joycean Metamorphosis: Fion MacCumhail. though all’s fair in vanessy. the novel starts in the middle of a sentence and ends with its beginning: Finnegans Wake (1939) riverrun. also serving as underlying symbols for male and female in a world of flux. not yet.Chapter 4 – The Cycle of Munster (the Finn Cycle) • Issy (Daughter) These are not so much members of a particular family. but representatives of a kinship system repeating itself afresh in all times and places. The boys endlessly contend for Issy’s favours.
originally a vigorous ruler and a great warrior. and the king seized the psalter and threw it into the lake.1. having travelled much of Ireland. he slew one of the clerics with a spear and made a second cast at Ronan himself. bemoaning his fate. 5. Ronan went to Moira to make peace between Domnall and Congal Claen.The King (Historical) Cycle of Tales 5. Suibne. and at last he The Celtic Paradigm in Modern Irish Writing 47 . They are often concerned with kingship. He then laid hands on the saint and was dragging him away. Next day an otter from the lake restored the psalter to the saint unharmed. wishing that he might fly through the air like the shaft of his spear and that he might die of a spar cast like the cleric whom he had slain. BUILE SUIBHNE [THE MADNESS/FRENZY OF SWEENEY] Suibhne son of Colman was king of Dal nAraide. but he rushed naked from the house. The second spear broke against the saint’s bell. living in tree-tops. His weapons fell from his hands. They deal with persons and events of the early historical period from the 6th to the 8th centuries. is drive mad by the sound of battle. Thereafter. Then his people told him that the saint was establishing a church in his territory. He was seized with trembling and fled in a frenzy like a bird of the air.1. wishing that he might wander naked through the world as he had come naked into his presence. and the shaft flew into the air. mythology and magic continue to play an important part. and celebrating nature in haunting lyrical verse. dynastic conflicts and battles. where he spends may years naked or very sparsely clothed. Ronan was chanting the Office when Suibhne came up. He takes to the wilderness. he set out in anger to expel the cleric. after Suibne is killed by one of the servants. buries the madman in consecrated ground. Suibhne was terrified by the clamour. Moling welcomes him and. when the battle was joined. but without success. Ronan cursed Suibhne. Ronan was marking the boundaries of a church in that country. he arrives at a small religious community. His feet rarely touched the ground in his flight. Though history is present in the background of all stories. Buile Suibhne (Frenzy of Sweeney) The most famous tale in the cycle is “Buile Suibhne”. but when they sprinkled in on Suibhne. as consequence of a curse imposed on him by a cleric named Rónán.Chapter 5 – The King (Historical) Cycle of Tales Chapter 5 . which recounts the tribulations of the Mad King Sweeney. Ronan gave thanks to God and cursed the king. when a messenger arrived from Congal Claen to summon him to the battle of Moira. He and his clerics sprinkled holy water on the armies. the armies on both sides raised three mighty shouts. romance. His wife Eorann sought to restrain him and caught the border of his cloak. One day St. Finally. Suibhne departed with the messenger. The Historical (King) Cycle The Historical Cycle includes a group of early Irish tales composed between the 9th and 12th centuries. and Suibhne heard the sound of his bell. leaving Ronan sorrowful. leaving the cloak in her hands.1. where St.
. . for that valley is always a place of great delight to madmen. who had fled the field after the victory of Domnall. he would return at night. There Loingsechan came to seek him and found the footprints of Suibhne near the river where he came to eat watercress. Suibhne fled again and was for a long time travelling through Ireland till he came to Glenn Bolcain. For seven years. I do not smile. Mo Ling bade his cook give supper to Suibhne. It was there that the madmen used to abide when their year of frenzy was over. but Suibhne flew away like a bird and came to Tir Conaill. Mo Ling and Mongan the herdsman is recorded in a poem of twenty-six quatrains.] [. Domnall recognised him and lamented his misfortune. Sweeter to me once was the cry of wolves than the voice of a cleric within bleating and whining. I would rather drink water from my hand taken from the well by stealth. and then he returned to Glenn Bolcain. .]At last Suibhne came to the monastery of St. sweeter to me the noble chant of the hounds of Glenn Bolcain.] Green cress and a drink of clear water is my fare. and Suibhne would lie down to drink. [. Mo Ling made him welcome and bade him return from his wanderings every evening so that his history might be written.] Though I live from hill to hill on the mountain above the valley of yews. [. This is not the fate of the man by the wall. [. . For seven years since that Tuesday at Moira I have not slept for a moment. [The conversation of Suibhne. alas! That I was not left to lie with Congal Claen. and a sandy stream of clear water with green cress and long waving brooklime on its surface. Though sweet to you yonder in the church the smooth words of your students. Glenn Bolcain has four gaps to the wind and a lovely fragrant wood and clean-bordered wells and cool springs. grew jealous of this attention by his wife. And he uttered a lay: The man by the wall snores: I dare not sleep like that. Before his death he confessed his sins and received the body of Christ and was anointed. Though you like to drink your ale in taverns with honour. Suibhne wandered throughout Ireland. It happened that the victorious army of Domnall had encamped there after the battle. Mo ling. The cook would thrust her foot into some cowdung and fill the hole with milk. wherever he travelled during the day. for it was destined that his story should be written there and that he should receive a Christian burial. . .Chapter 5 – The King (Historical) Cycle of Tales settled upon a yew tree far from the battle field. where he perched on a tree near the church called Cill Riagain. .] 48 The Celtic Paradigm in Modern Irish Writing . . There he was discovered by a kinsman. [. Sweeter to me once than the voice of a lovely woman beside me was the voice of the mountain grouse at dawn. He slept one night in a hut and Suibhne came near and heard him snore. in which Suibhne says: Sweeter to me once that the sound of a bell beside me was the song of a blackbird on the mountain and the belling of the stag in a storm. and. . My face betrays it. Aongus sought to persuade Suibhne to join him. Aongus the Fat. and he slew Suibhne with a spear as he lay drinking the milk one evening. who was a herdsman. Truly I am Suibhne the Madman.] The cress of the well of Druim Cirb is my meal at terce. . But the cook’s husband.
49 . “ THE BLACKBIRD BY BELFAST LOCH The small bird hang lets a trill son. [. dear each well of clear water. and they went together to the door of the church. the half-said thing to them is dearest.Chapter 5 – The King (Historical) Cycle of Tales Then Suibhne swooned. in his Introduction to the Ancient Irish Poetry. Suibhne arose out of his swoon. and Mo Ling said: Here is the tomb of Suibhne. Like the Japanese.2. these poems occupy a unique position in the literature of the world. was given to no people so early and so fully as to the Celt. calls up before us by light and skilful touches. Give me. from bright tip of yellow bill The shrill chord by Loch Lee of blackbird goodness from yellow tree. The Celtic Paradigm in Modern Irish Writing THE SCRIBE IN THE WOODS Over me green branches A blackbird leads the loud Above my pen-lined booklet I hear a fluting bird-throng The cuckoo pipes a clear call Its dun cloak hid in deep dell: Praise to God for this That in woodland I write well. Early Irish Poetry The lyrical passages contained in the story and attributed to the mad King display similar characteristics with early Irish poems. the Celts were always quick to take an artistic hint. . If the King of the stars allows it. I pray to the chaste King of heaven over his grave and tomb. but rather a succession of pictures and images which the poet. arise and go with me. And Suibhne leaned against the doorpost and gave a great sigh. Summary by Miles Dillon 5. To seek out and watch and love Nature. and Mo Ling and his cleric brought each a stone for his monument.] Dear to me each cool stream on which the green cress grew. Many hundreds of Gaelic and Welsh poems testify to this fact. O heart. Indeed. and Mo Ling took him by the hand. in the following terms: “In nature poetry the Gaelic muse may vie with that of any other nation. for Suibhne used to visit them. like an impressionist. It is a characteristic of these poems that in none of them do we get an elaborate or sustained description of any scene or scenery. and his spirit went to heaven. in its tiniest phenomena as in its grandest. which are characterised by Kuno Meyer. thy hand. and he was buried with honour by Mo Ling. Sweet to me was the conversation of Suibhne: long shall I remember it. . and come from the tomb. Dear to me for the love of him is every place the holy madman frequented. His memory grieves my heart. they avoid the obvious and the commonplace.
A huge old tree encompasses it .Chapter 5 – The King (Historical) Cycle of Tales THE SHIELDING IN THE WOOD I have a shielding in the wood None knows it safe my God: An ash-tree on the higher side. culture. the note of the swan. and Peggy. Instead. Dermot Trellis. summons her to his room and seduces her. . tradition vs. .) The Suibne story continues to inspire Irish writers.1. little musicians of the wood. and figures of Irish legend like Finn MacCool and the mad King Sweeney. Along with these characters there is a more banal cast. A gentle chorus: Wild geese and ducks. shortly before summer’s end.1. Trellis falls in love with Sheila Lamont. Brian O'Nolan (Brian Ó Núalláin) (1911 –66) Brian O’Nolan is best known for his novels An Béal Bocht. he spends his time carousing with friends and smoking cigarettes (in bed. The “Suibhne” Motif in Irish Literature Through the story of his wanderings – physical and mental – Suibhne became the principal Irish exponent of the legend of the Wild Man. 5. 5. while wearing a single suit of clothes). notably Flan O’Brien in AtSwim-Two-Birds (1939) and Seamus Heaney in Sweeney Astray (1982) 5. The voice of the wind against the branchy wood Upon the deep-blue sky: Falls of the river.1.3. .3. and the Great Count O'Blather. . Swarms of bees and chafers. Through its overt religious symbolism. At Swim-TwoBirds and The Third Policeman written under the nom de plume Flann O'Brien.present. the story is historically rooted in the clash between pre-Christian and Christian customs and values. The student begins to write a novel about an Irish novelist. . The music of the dark torrent . past vs. Other pseudonyms he used were: John James Doe. the individual and the state. namely Antony and Sheila Lamont. The 50 The Celtic Paradigm in Modern Irish Writing . This seduction results in the birth of a child. John Furriskey. by extrapolation. who has a limited imagination and borrows characters from the existing pool of literary stereotypes: cowboys from American westerns. Delicious music . At Swim-Two Birds (1939) The novel is narrated by a college student who never goes to class.3. nature vs. . He also wrote many satirical columns in the Irish Times under the name Myles na gCopaleen. Another motif relates to the state of frenzy and the world of vision entailed by it (the frenzy unlocks the gifts of poetry ad seership. Many of the motifs attached to him are associated with rites of passage and the transition from one state to another. Paul Shanahan. Brother Barnabas. a Good Fairy and a pookah. modernity. and. a hazel-bush beyond. George Knowall. whose upbringing is controlled by the pookah.
its daemon. Nature of chuckles: Quiet. He then brought from his own pocket a box of the twenty denomination. The God-big Finn. yes. I said. Each should be allowed a private life. lighting one for each of us. It was undemocratic to compel characters to be uniformly good or bad or poor or rich. to write a book or to make a book. I said. I then tendered an explanation spontaneous and unsolicited concerning my own work. you’re the queer bloody man. dislike their narrative and convince Trellis’s child to write a novel about his novelist. self-determination and a decent standard of The Celtic Paradigm in Modern Irish Writing 51 . depending for their utility on a knowledge of the French language as spoken in medieval times. There are two ways to make big money. the novel was self-administered in private. he said. its sorrow and its joy. Psycho-analysis was mentioned . in which the author is to be tortured to death. in the hands of un unscrupulous writer. I took out my ‘butt’ or half-spent cigarette and showed it in the hollow of my hand. affording an insight as to its aesthetic. Witticisms were canvassed. In reply to an inquiry. meanwhile. What are you laughing at? I said. Nature of explanation offered: It was stated that while the novel and the play were both pleasing intellectual exercises. Under the cover of the bed-clothes I poked idly with a pencil at my navel. the predilections of publishers and the importance of being at all times occupied with literary activities of a spare-time or recreative character. its darkness. affecting a pathos in my voice. from AT SWIM-TWO-BIRDS (1939) I withdrew my elbow and fell back again as if exhausted by my effort.great authors living and dead. Brinsley was at the window. The novel. that stuff I gave you? Oh. that was the pig’s whiskers. You and your book and your porter. however. he said. By God. private. Just at this point.with. My dim room rang with the iron of fine words and the names of great Russian masters were articulated with fastidious intonation. Did you read that stuff about Finn. giving chuckles out. could be despotic. frequently inducing the reader to be outwitted in a shabby fashion and caused to experience a real concern for the fortunes of illusory characters. Brinsley turned from the window and asked me for a cigarette. That is all I have. and character of modern poetry. averted. a somewhat little touch. That was funny all right.Chapter 5 – The King (Historical) Cycle of Tales characters in the author’s proposed novel. My talk had been forced. he said. the novel was inferior to the play inasmuch as it lacked the outward accidents of illusion. The play was consumed in wholesome fashion by large masses in places of public resort. This I found a pleasing eulogy. couched in the accent of the lower or working-classes. its sun-twinkle clearness. It happened that this remark provoked between us a discussion on the subject of Literature . and At Swim-Two-Birds ends. the college student passes his exams. its argument. it was explained that a satisfactory novel should be a self-evident sham to which the reader could regulate at will the degree of his credulity. he said.
said Lamont. A wealth of references to existing works would acquaint the reader instantaneously with the nature of each character. contentment and better service. said Furriskey. It is bad living without a house. running with the red stag through fields. If the evil hag had not invoked Christ against me that I should perform leaps for her amusement. what’s this about jumps? Hopping around. Seamus Heaney (1939-) Heaney was born into a nationalist Irish Catholic family at Mossbawn. . That is all my bum. upstarts. . 5.3. It snowed on his tree that night. said Lamont. in a rural area thirty miles to the north-west of Belfast. It would be incorrect to say that it would lead to chaos. and he was constrained to the recital of these following verses.2. I would not have relapsed into madness. [direct speech and indirect speech] [. The modern novel should be largely a work of reference. you know.it is truth wolves for company. said Brinsley.now reading.put down in the book against him. it is my due. thimbleriggers and persons of inferior education from understanding contemporary literature. the snow being the worst of all the other snows he had endured since the feather grew on his body. Peerless Christ. The upshot is that your man becomes a bloody bird. it is a piteous life! A filling of green-tufted fine cresses a drink of cold water from a clear rile Stumbling out of the withered tree-tops walking the furze . I see. Sweeny arrived at nightfall at the shore of the widespread Loch Ree his resting-place being the fork of the tree of Tiobradan for that night. Terrible is my plight this night the pure air has pierced my body. This would make for self-respect. my cheek is green O Mighty God. said Sweeny. Conclusion of explanation. is about this fellow Sweeny that argued the toss with the clergy and came off second-best at the wind-up.usually said much better. Come here.Chapter 5 – The King (Historical) Cycle of Tales living. 52 The Celtic Paradigm in Modern Irish Writing . Characters should be interchangeable as between one book and another. said learned Shanahan in a learned explanatory manner. I explained to him my literary intentions in considerable detail . The entire corpus of existing literature should be regarded as a limbo from which discerning authors could draw their characters as required. now discoursing. would obviate tiresome explanations and would effectively preclude mountebanks. ] After a prolonged travel and a searching in the skies. lacerated feet. But taking precise typescript from beneath the book that was at my side. There was a curse .a malediction . Most authors spend their time saying what has been said before . man-shunning. creating only when they failed to find a suitable existing puppet. The story. oratio recta and oratio obliqua.
The Celtic Paradigm in Modern Irish Writing 53 . Heaney's work is deeply associated with the lessons of history. many of which seemed to have been ritually sacrificed to earth deities. 1975) I can feel the tug of the halter at the nape of her neck. Heaney evolved the “bog myth” to distance the sectarian killings in modern Ulster through their analogues of 2000 years ago. brain-firkin: her shaved head like a stubble of black corn. Glob’s “The Bog People” – which dealt with the discovery of well-preserved Iron Age bodies in the Danish bogs. her blindfold a soiled bandage. It blows her nipples to amber beads. the body of a young Danish woman accused of adultery and sacrificed to the land in an ancient fertility ritual prompts him meditate on tribal revenge and justice. I can see her drowned body in the bog. sometimes even prehistory. PUNISHMENT (from North.Chapter 5 – The King (Historical) Cycle of Tales His main collections of poetry are: Death of a Naturalist (1966) Door into the Dark (1969) Wintering Out (1972) North (1975) Field Work (1979) Sweeney Astray: A Version From the Irish (1983) Station Island (1984) The Haw Lantern (1987) Seeing Things (1991) The Midnight Verdict (1993) The Spirit Level (1996) Heaney's work is often set in rural Londonderry. the weighing stone. for example. the floating rods and boughs.V. finding its modern counterpart in the shaved and tarred heads of young Irish women humiliated by the I. Under the influence of P.R. the county of his childhood. Hints of sectarian violence can be found in many of his poems. In “Punishment”.A. even works that on the surface appear to deal with something else. the wind on her naked front. for fraternizing with British soldiers. Under which at first she was a barked sapling that is dug up oak-bone. Like the Troubles themselves. it shakes the frail rigging of her ribs.
Chapter 5 – The King (Historical) Cycle of Tales her noose a ring to store the memories of love. Little adulteress, before they punish. Nevertheless, if the bog myth distances contemporary violence through an objective correlative, it also aestheticises it through Heaney’s art. Being accused of having become an “anthropologist of ritual violence”, Heaney decided that investing poetry with the burden of political meaning meant to frustrate its flight. While he himself withdrew from the politically embittered North to Wicklow, in the Republic, his subsequent poems revel in the condition of “exile” as a necessary one for a poet who acknowledges the priority of his artistic vocation over the constraints of the political world. In “Exposure” the speaker is an “inner émigré”, who has given up history as a bad job: EXPOSURE It is December in Wicklow: Alders dripping, birches Inheriting the last light, The ash tree cold to look at. A comet that was lost Should be visible at sunset, Those million tons of light 54 The Celtic Paradigm in Modern Irish Writing
Chapter 5 – The King (Historical) Cycle of Tales. 5.3.2.1. Sweeney Astray (1983) In 1983 Heaney undertook a full-scale translation of “Buile Suibhne” as “Sweeney Astray”, finding in the figure of the ancient king an analogue for himself as an artist who has chosen to flee from the constraints of the tribe in order to find release into imaginative freedom. SWEENEY ASTRAY God of heaven! Why did I go battling out that famous Tuesday to end up changes into Mad Sweeney, The Celtic Paradigm in Modern Irish Writing 55
Chapter 5 – The King (Historical) Cycle of Tales roosting alone up in the ivy? From the well of Drum Cirb, watercress supplies my bite and sup at terce; its juices that have greened my chin are Sweeney’s markings and birth-stain. And the manhunt is an expiation. Mad Sweeney is on the run and sleeps curled beneath a rag under the shadow of Slieve leaguelong cut off from the happy time when I lived apart, an honoured name; long exiled from those rushy hillsides, far from my home among the reeds. I give thanks to the King above whose harshness only proves His love which was outraged by my offence and shaped my new shape for my sins a shape that flutters from the ivy to shiver under a winter sky, to go drenched in teems of rain and crouch under thunderstorms. Though I still have life, haunting deep in the yew glen, climbing mountain slopes, I would swoop places with Congal Claon, stretched on his back among the slain. My life is steady lamentation that the roof over my head has gone, that I go in rags, starved and mad, brought to this by the power of God. It was sheer madness to imagine any life outside Glen BolcainGlen Bolcain, my pillow and heart’s ease my Eden thick with apple trees. What does he know, the man at the wall, how Sweeney survived his downfall? Going stooped through the long grass. A sup of water. Watercress. Summering where herons stalk. Wintering out among wolf-packs. Plumed in twigs that green and fall. What does he know, the man at the wall? I who once camped among mad friends 56 The Celtic Paradigm in Modern Irish Writing
The Celtic Paradigm in Modern Irish Writing 57 . In 1995 Seamus Heaney was awarded the Nobel Prize for literature. Task Consider one of the following topics to develop into a full-length critical essay: 1. Exposure. that happy glen of winds and wind-borne echoes. “The Matter of Ireland” and Heaney’s Ars Poetica: Punishment vs.Chapter 5 – The King (Historical) Cycle of Tales in Bolcain. 3. At-Swim-Two-Birds and Sweeney Astray: Two Versions of Buile Sweeney. “Mad King Sweeney” and the “Buile” Motif in Irish Literature 2. live miserable Beyond the dreams of the man at the wall..
Berresford-Ellis. Welch. 2004. Mohor-Ivan. Kiberd. Declan. INVENTING IRELAND: The Literature of the Modern Nation. 4. (ed. 2. 3. 1994. DICTIONARY OF CELTIC MYTHOLOGY. Oxford UP. Robert (ed. LANDMARKS OF IRISH DRAMA.) MODERN IRISH POETRY. Mercier Press. EDP. Moody. 1993. Methuen. Constable.) THE OXFORD COMPANION TO IRISH LITERATURE. THEATRE AND BRIAN FRIEL’S REVISIONIST STAGE. 1998. AN ANTHOLOGY.Chapter 5 – The King (Historical) Cycle of Tales Minimal Bibliography: 1.) THE COURSE OF IRISH HISTORY. 1996. 7.W. Crotty. T. Vintage. Peter. Ioana REPRESENTATIONS OF IRISHNESS: CULTURE. Patrick (ed. 1996. 5. 1991. 6. Lagan Press. 58 The Celtic Paradigm in Modern Irish Writing .
.
Ioana Mohor-Ivan Irish Literature TOPICS Introduction: The Matter of Ireland Part One: Colonial themes and the politics of representation Conquests (1): The Anglo-Norman Legacy in Irish Culture Conquests (2): England’s “Other”. Inscribing and Re-inscribing Ireland’s Story Colonialism and the Nationalist Imaginary Part Two: Space and nation in literary representation The ‘Big House’ Theme in Irish Literature The ‘Pastoral’ in Irish Literature. The ‘City’ in Irish Literature Minimal Bibliography Annexes 2 .
throughout the Middle Ages. Penguin. M. Editura didactica si pedagogica. Yet. but a possible security threat as the Irish could be now used by the Catholic powers of the day (the Spaniards in particular) to attack England. M. they chose to remain within the Catholic Church. the Pale. Ireland was attacked with great brutality and colonised in the same way that America was at the time. Trevelyan. Trevelyan notes. Bucuresti. Within the new religious discourse. being called “Old English” in order to differentiate them from the fresher waves of Protestant conquerors. ruled by their Irish chiefs). at times. the exiled king of Leinster. Yet. sovereignity over it. The following is extracted from Ioana Mohor-Ivan. These first colonists and their descendants were largely absorbed in the Celtic atmosphere around them. once in Ireland. of equal importance and attraction. Later. asked the Norman lords of South Wales to help him regain his kingdom. even if the English captured and massacred them at Smerwick. As G. 1979. Ireland itself remained independent of English royal control. As a result of this first wave of English colonists. as both represented two new fields. The policy of real conquest and colonisation was undertaken by the English state during Elizabeth I’s and James I’s reigns. and tracts of mixed control in-between (with Anglo-Irish barons ruling over the native population). though the English kings called themselves ‘Lords of Ireland’ and claimed. the Normans turned into conquistadors. consisting in: the Pale (that region where English law was administered as in an English shire). many intermarrying with the native populations and adopting the local customs. 2004. and was largely prompted by England’s turn to Protestantism during the 16th century. where private fortunes could be made. public service rendered to the Queen. prompting the Queen to undertake its conquest. 2 G. Catholic Ireland was no longer a place to be ignored. and the cause of true religion upheld against the Pope and the Spaniards 2 . when Dermot. a three-fold division of the island was established. and subsequently trying to advance westwards. in practice no troops were effectively sent there to actually conquer and govern the island. 62-3 1 3 . A Short History of England. for. occupying and colonising a region around Dublin. the West (an area peopled by purely Celtic tribes. The fact that Ireland was becoming the danger point in Elizabeth’s dominions was confirmed in 1588 when the Pope himself planned to attack England by sending armed troops bearing his commission to Ireland. pp. after the Reformation.Ioana Mohor-Ivan Irish Literature INTRODUCTION – THE MATTER OF IRELAND1 The first contacts established between the English state and Ireland occurred at the end of the 12th century. Glimpses of Britain: a cultural studies perspective.
the Protestants in the north proclaimed William king and fortified Derry. This event has come to be called The Flight of the Earls. eventually only the landlords suffered this fate. It was rendered easier for Cromwell and his army because the Protestants over there. carrying with them their extreme version of Protestantism. when the Catholic King James II was deposed by the English Parliament in favour of the Protestant William of Orange. earl of Ulster. 6 Although the idea of driving the whole Catholic population beyond the Shannon was entertained. sending his troops to reconquer Ireland as the first step in the reconstitution of the British Empire. aiming to fulfil a three-fold objective: to pay off in Irish land the soldiers who had fought. aided by French money. in an atrocious way. 5 In 1641 Sir Phelim O’Neill led an insurrection against the Ulster Plantation. the largest part of the colonists establishing James I’s Plantation of Ulster in 1608 were Scots from the neighbouring coast. tended to rally round him as the champion of their race and creed 4 . at the end of the war Cromwell took full revenge on them. Another key-date in the history of Ireland’s colonisation is the year 1689. that confirmed once again for the English that Ireland did represent a security threat for their state. by trying to push the whole indigenous population to the west of the river Shannon. 4 G. Antrim and Derry. The British Isles. signifying the moment when the Gaelic rule comes to an end in Ireland. now styling themselves as ‘Old Protestants’ 7 to distinguish themselves from the Baptists and Quakers (the ‘New Protestants’) of the Cromwellian army. op. The real beneficiaries were the ‘New English’ planters of pre-1641. despite the efforts undertaken by the English state in order to persuade people to emigrate to Ireland. As the Catholic Irish registered their support on the King’s side. mainly in Ulster. exiling himself in Italy. leaving the rest of the army carry on. enduring In 1607 the last of the Northern earls. Hugh O’Neill. departed from Ireland. whatever their political allegiance. The Cromwellian conquest also led to the downfall of the ‘Old English’ interest in Ireland. troops and generals. 1989.Trevelyan. 7 Hugh Kearney. trying to complete the conquest of a land where already three-fourth of its population obeyed him. but is economically very poor 6 . as the best land the country possessed. In response to this action. A History of Four Nations. Cambridge UP. after the defeat of the rising of the Northern earls 3 . But. the guerrilla war in the West. to render the English hold secure against another rebellion like that of 1641 5 . and.. James II landed in Ireland. while the Irish resistance became racial and Catholic instead of Royalist.Ioana Mohor-Ivan Irish Literature The island was first subjugated military. The next important moment within the history of Anglo-Irish relationships occurred during the 17th century Civil Wars in England. 3 4 . cit. Ireland was colonised. The most important outcome of the Cromwellian policy was the fact that Ulster had now to face its own set of problems deriving from the large-scale settlements of Scots in Down. to Cannaught. and lastly to extirpate Catholicism. pp. a region that invokes a deep primitive Gaelic feeling. Cromwell went home. After the fall of Drogheda had broken the back of resistance in the East. 79-81. The subsequent land settlement completed the transference of the soil from Irish to British proprietors. A year later.M.
the defence of Limerick and its defeat has also been turned into a celebratory event by the Nationalist rhetoric. while. but it also saved Protestantism in Europe and enabled the British Empire to launch forth on its career of expansion overseas. op.Ioana Mohor-Ivan Irish Literature the famous Catholic siege of 169o until William landed in Ireland and released the town. It was the struggle of the Anglo-Scots against the Catholic Irish for the leadership of Ireland. cit. the hero of the Limerick siege. The penal code placed the Catholics in Ireland under every political and social disadvantage and pursued and persecuted their leaders. was forced to withstand a Protestant siege and finally surrender in 1691. 10 Hugh Kearney. and for some time even religious freedom. G.M. 8 9 5 . but enjoying the greatest political power and closely involved with affairs in England). of regiments from the continent represented the international issues at stake. At the same time. The outcome of that battle decided the future of Ireland for the next two centuries. in its turn. bringing the defeat of the native Irish and the final eclipse of the culture of the ‘Old English’. the decrees of the English Parliament were ruining the Irish Trade. while the Battle of Boyne is celebrated on the 12 July by Protestant Orange Lodge marches that commemorate the defeat of James II. upon two quarrels. The 17th century and its events provide the focus for the most politically charged folk festivals for both Protestants and Catholics alike. The restored English rule in Ireland reflected very little tolerance to any groups outside the Established Anglican Church. has entered the Catholic pantheon of heroes withstanding oppression. on both sides of the river. and the consequent domination of the world by the French monarchy 8 . the siege of Derry is commemorated by the ‘Apprentice Boys March’ 9 . Anglican intolerance refused political equality. The presence. the year that also witnessed the renaming of Derry to Londonderry (a victory has to be enunciated in different ways). op. at the same time. a Presbyterian culture in Ulster (socially dominant in Antrim and Down. but also the struggle of Britain and her European allies to prevent a Jacobite restoration in England. and preserving close links with Scotland). but not well represented elsewhere. A group of apprentice boys closed the gates of Derry against the wish of its governor and resisted James II’s siege until William’s troops arrived. to Presbyterians as well. and Patrick Sarsfield. In August and December. and the Catholic majority to be found in all the four provinces. ultimately merging the Gaelic and the ‘Old English’ cultures through its sense of a common Catholicism 10 .Trevelyan. halting the economical development of a country which was now freezing into a three-fold cultural pattern that was to persist throughout the next century: a Protestant land-owning Ascendancy in the East (smallest in number. The decisive battle was fought at the Boyne on the 12 July 1690. With equal intensity of recollection. as the moment when the brave and gallant defenders of Ireland were eventually defeated. The defeated Catholic forces retreated to Limerick which. cit.
a movement calling itself “The Volunteers”. in spite of the opposition of the Protestant Ascendancy. The ‘memories of ‘98’ became a heirloom of hatred. Yet. the initiative was not Catholic and Gaelic. led largely by landlords. a much more radical political society was formed in Dublin and Belfast with members of the newly-expanding Protestant urban middle-class. cherished in every cottage. This society of “The United Irishmen” sought to forge an alliance with leaders of the Catholic community in order to demand the widening of the franchise and to put an end to the political and civil disabilities of the Presbyterians and Catholics. prepared to defend the country against a French invasion. It was an act which also listed the support of the Catholic population who was hoping now for an improvement of their condition. which claimed to be non-sectarian and rationalist under the influence of French political thought. The rebellion of 1798 also led the British government conclude that a union of Ireland with Britain was a necessity. In 1798 the ’United Irishmen’ rose in revolt. the “Orange Order”. with the result that the gulf between the North and the South was enlarged. It also brought the Industrial Revolution to the North of Ireland. the American Independence War and the French Revolution. an exclusively Protestant society which was formalised with quasi-Masonic ritual in 1797 when lodges were formed. in 1795 the landlords placed themselves at the head of a “Church and King” society. In 1791. as the only method of permanently restoring order and justice. on condition that the English government abolished all Ireland’s commercial disabilities and granted the formal independence of its Parliament from British control. in effect only the Anglican interest was represented at Westminster as Irish Catholic MPs were not admitted. entering an alliance with the French forces with the aim of concerting a French invasion with an Irish insurrection. while the economic backwater of the South was left 6 . and the balance of power shifted within the Ascendancy in favour of the industrially-expanding North. as it operated underground. the Act of Union abolished the parliament in Dublin and secured the incorporation of Ireland within the British State. and sectarian hostility led to atrocious reprisals being taken against the insurrectionists and the native population. The Union had the result of bringing the complexity of Irish society and politics into the heart of Westminster. led by Wolfe Tone and Robert Emmett. and eventually republican.Ioana Mohor-Ivan Irish Literature At the end of the 18th century Ireland was affected by the two great revolutions that are part of the world history. and renewed by successive generations of nationalists. and also provided the outlet for Irish immigration to England. in the first instance. but Protestant and Liberal. hoping to unite the religions of Ireland in arms against England’s domination and establish a United Independent Ireland (in the fashion of The United States of America). Suppressed in 1794. the Society’s demands grew more radical. In 1800. which stirred up once again the factions involved. In reaction against ‘The United Irishmen’ society. But even if the act provided for Irish representation in the House of Commons and the House of Lords. The rebellion was put down by the British and the Orange Order loyalists.
and the labourers also survived as an important segment of the population. when the issue of the long-term future of AngloIrish relations came again to the fore. At the same time this event made possible for the Irish tenant farmers to consolidate and extend landholdings after the Famine. inspired by the ‘advanced’ nationalism of the Italian nationalistic movement of Mazzini. forming the basis of a very powerful pressure group in the years to come. By the mid-1860s. By 1847 large numbers of small farmers were obliged to emigrate to the United States of America. “Fenians” was the alternative. due to their contrasting experiences. social and cultural accommodations in the South. founded in 1858. transmitting family wealth from generation to generation through a set of practices termed “familism” 11 . popular name for the Irish Republican Brotherhood. the execution of some of its leaders in Manchester 12 helped the publicity of the Fenian cause within Catholic opinion. Daniel O’Connor. including the imposition and perpetuation of strict codes of behaviour between men and women. By contrast. they ceased to exert the same degree of influence that they had wielded before the Famine. was decimated by starvation and disease. A final outcome of the union was that the old animosities between the Anglican and Presbyterian Protestants died out in the North in an environment of industrialisation and revived Catholicism. general endorsement of celibacy outside marriage and postponement of marriage in farmer’s families until the chosen heir was allowed by the father to take possession of the farm. which was not reversed in subsequent decades. led the Fenians start bombing activity in the Autumn of 1865. forcing the British government to pass the Bill in 1828. the most numerous class at the time which also defined the characteristics of the people-nation. the Catholic South of small farming and labouring classes. This sudden drop in population. the Great Potato Famine that struck Ireland in 1846 enhanced once again the division between the Catholic and Protestant cultures. a social tragedy that had its greatest impact on the Catholic poor. “Familism” consisted of a number of procedures used to control access to marriage. also led to a complex series of economic. Its intention of establishing an Irish republic by force. While the North of the country was mostly spared by the failure of the potato crops (the main element of popular diet was oats). rose to fight for the Catholic emancipation. a distinct culture emerged in the later 19th century. a period of comparative political tranquillity ended abruptly with the advent of “Fenianism”.Ioana Mohor-Ivan Irish Literature in the hands of the Catholic urban and rural middle-class. It was from the ranks of the latter one that the charismatic leader. either by emigration or by death. while by 1851 statistics showed that Ireland had lost one quarter of its population. heavily dependent upon the potato. in the north more sexual permissiveness was allowed in rural society. 12 The so-called “Manchester Martyrs” 11 7 . Towards the middle of the 19th century. and even if the movement ultimately failed. As a result. As the numbers of the landless labourers and their families drastically declined. a secret revolutionary organisation. the culture of the Irish tenant farmers (marked by late marriage and strict sexual taboos).
Being founded in 1879 under the name of “The Irish Land League” by a Fenian. being concerned in the beginning with a campaign . and reprisals. This led to a complete reversal of the Irish opinion which turned its sympathies from the Irish parliamentary party and. refusing to send its members to occupy their places at Westminster. in a wave of national anger. for the government made the mistake of shooting the rebels. or the ‘troubles’ as the people euphemistically called it. with both sides illegally armed and the drilling of the Ulster Volunteers in the North answered by similar demonstrations in the south. such as the Gaelic League 13 and later. Meanwhile. It was a struggle characterised by guerrilla warfare. and of arresting and executing people who had no involvement in the rising. raids on police barracks. even the seriously injured ones. the shooting-up and burning-up of towns. and planned assassinations on the one side. ambushes. after the fall of Parnell’s parliamentary. the Orange Order opposition to an independent and united Ireland intensified and before the outbreak of the First World War Ireland was on the brinks of a civil war. When the war broke out. in 1908. the United Irish League. The outcome was the Easter rebellion of 1916.to resist landlord seizure of tenants’ land for non-payment of rents. which won the general elections in 1918. followed by the signing of a treaty five months later that conceded dominion status to the twenty counties that formed the Irish Free State. The national demand for self-government proved so deeply implanted in the mind of the Irish that it survived not only the fall and death of Parnell. while the six Protestant 13 an organisation founded in 1893 to promote the restoration of the Irish language. dominating the British politics until the beginning of the First World War. while the Fenian linked organisation. most Ulster Volunteers and Irish National Volunteers joined the British army. its followers reunited within a new shell organisation. one by one. The outcome of this measure was the Anglo-Irish war from early 1919 to July 1921. Eventually public opinion in America and in Britain demanded a truce. it was taken over by Charles Stewart Parnell who used its cause as platform to become the leader of a group of Irish MPs pressing for the Home Rule bill for Ireland. disapproving of Irish support for England. executions and terrorising on the other. It was not so much the rebellion of the Easter week that completed the change in the attitude of the Irish people generally as its aftermath. which was arranged in July 1921.the man and the question which had first given it power -. a party that united a number of smaller groups to campaign for Irish independence. In reaction to this growing nationalism. but the subsequent removal of the land grievance . decided that a new insurrection was to take place in Ireland before the end of the war. the Irish Republican Brotherhood. the Sinn Fein. gave its approval to Sinn Fein. and the political landscape was further complicated by the emergence of other groups struggling for hegemony. The victorious Sinn Fein pledged itself to the Irish republic and proceeded to put into operation a policy of passive resistance to continued British rule. 8 .in the wake of the agrarian crisis of 1879 . even if conscription was not applied in Ireland. Michael Davitt.Ioana Mohor-Ivan Irish Literature In the 1880s a first nationalist party emerged.
the enforcement of law and order and the drawing of electoral boundaries. cit. schools. a complex and subtle system of relationships came into existence in which both sides were taking great pains to avoid causing offence. soccer and rugby were appropriate games. Eire’s neutrality in the Second World War was the final proof of how far the paths of the two Irish governments had diverged 15 . while for the other Gaelic football and hurling were national sports. Mercier Press. with a Home Rule Parliament of their own. North and South. Nationalists continued to complain of discrimination in the distribution of houses and jobs. Events in the rest of Ireland during these years also helped to keep alive old issues in the north. 16 idem 14 9 . There were occasions when nationalist demonstrations were broken up by the police. In Northern Ireland. the new Irish constitution of 1937. pp 307-310. The act of 1920 had set up a state in which about one third of the population was bitterly hostile. enabling thus the unionists to appropriate loyalty and good citizenship to themselves and identify Catholicism with hostility to the state. 14 Northern Ireland had been brought into existence. but important social and economic changes occurred as well. The old issues survived into the post-war age as well. More than this. Due to the general benefits brought by the implantation of the British Welfare State in Northern Ireland. but its future was far from assured. Some took part in an attempt to overthrow it by force. In the Republic change was above all economic and social. Unionists retorted that Catholics were disloyal to the state and used occasional royal visits to reaffirm their loyalty to Britain. 16 Yet. A new government brought along the shift from conservatism to innovation. others adopted an attitude of non-cooperation. Northern Ireland. an articulate middle-class had risen within the Catholic community. in The Course of Irish History.McCracken. From Parnell to Pearse (1891-1921). the 1960s were years of change for both communities. and the policy of raising the partition question on every possible occasion heartened the nationalists but confirmed the unionists in their resolve that Ulster’s position within the United Kingdom and the Empire must remain unchanged. For one community. the cultures of the two communities were also divergent. with a minimum of social contact established between them: each had its own churches. 15 J. more prepared than its predecessors to acquiesce in the constitutional status quo. a legacy from the days of Fenianism.L. 1994. in The Course of Irish History. provided Catholics Donald McCartney. 1921-66. attempted ‘offensive’ operations to overthrow partition. newspapers and forms of recreation. paving the way for the expansion of education and beginning the erosion of the rural political and cultural domination. The dismantling of the Anglo-Irish Treaty after 1932.. A new campaign of violence was carried on from 1956 to 1962. From time to time.Ioana Mohor-Ivan Irish Literature counties of Ulster remained within the British Union. pp 316-322. op. IRA. In mixed rural areas. change was most obviously political.
Irish/Scot or AngloIrish. freedom and true religion. the holding without trial of suspected terrorists J. This body. as the sharp divergence between unionist and nationalist aspirations has remained. planter and Gael as that between oppressor and oppressed. Protestant history celebrates 17th century events as those which allowed the defence of civilisation. reorganised as the Provisional IRA and reverted to nationalist military traditions and with the first IRA victims the government lost control of its own Army who turned against nationalists. Catholic/Protestant. Northern Ireland is still an extremely parochial place where matters of life and death have forced people to fall back on their own resources and close ranks. Northern Ireland has remained a place where history and its versions play a central role in shaping the attitudes of the two groups involved in this intricate drama. as well as the establishment of a Protestant Ascendancy. A year later disorder had reached such a height with Protestant mobs launching savage attacks on Catholic areas of west Belfast that the Northern Irish government was obliged to request the British government to send in troops to restore order. pp342-347 passim. as each community has its different interpretation of more remote or more recent events that would legitimate its claims. A sign of the new mood of the catholic community was the growth of the Northern Ireland Civil Rights Association. while for rhetorical purposes the more recent history (from the 1920s onwards) is employed as a catalogue of grievances against the Catholics who have failed to accept the will of the majority and subverted the state using violent means. 19 the 1985 Anglo-Irish treaty. But the crisis deepened as in the 1970s IRA appeared on the scene of battle.H.Ioana Mohor-Ivan Irish Literature received a fair deal within it. the 1994 peace-process 17 18 10 . From 1972 to the present day all attempts to deal with the “Troubles” in Ireland 19 have offered only momentary respite from the embittered clash between the two communities. Republican/Unionist. op. did not challenge the existence of the Northern Ireland state. unlike previous organisations. On the other hand. in The Course of Irish History. From August 1968. founded in 1967.cit. marches and demonstrations in support of this objective were held in various towns. so that in 1972 the British government decided to suspend the Northern Ireland government and introduce direct rule from Westminster 18 . Nationalist history classically portrays an opposition between Britain and Ireland. entitling the Irish to a catalogue of grievances whose rhetorical force derives from the reciprocity principle: their moral advantage against the putative descendants of oppressors.. and where conflict is still based on an atavistic claim to territory on both sides. but the police and the Protestant right wing saw this development as a new attempt to undermine the state so that successive demonstrations were broken up by police and harassed by Protestant extremists. 1966-82. a place where identity has always been conceived in antithetical pairs. Ireland.White. the central events of this historical narrative being the successive invasions of Ireland in the 16th and 17th century. undertaken with great ferocity. The politics of internment 17 which was subsequently applied only helped to increase the level of violence. but demanded merely the ending of abuses within it.
Ioana Mohor-Ivan
Irish Literature
To this it adds a folk history, feelings handed down from generation to generation, always pointing to “the goodness of us” versus “the badness of them”, which is culturally ingrained and genetically transmitted, plus a personal history for everybody has his own memories of fathers and ancestors who have been cast as martyrs in this drama. As recent events have demonstrated, the peace-process proved to be only a fragile mutual cease-fire, the two communities continuing to step on each other’s feet persistently. The only hope for a true lasting peace would be for the reason of living to triumph over the law of the dead.
11
Ioana Mohor-Ivan
Irish Literature
CHAPTER 1 – Conquests:
THE ANGLO-NORMAN LEGACY IN IRISH CULTURE
After the death of the famous High King Brian Boru in 1014, Ireland was at almost constant civil war for two centuries. The various families which ruled Ireland's four provinces were constantly fighting with one another for control of all of Ireland. At that time Ireland was like a federal kingdom, with five provinces (Ulster, Leinster, Munster and Connaught along with Meath, which was the seat of the High King) each ruled by kings who were all supposed to be loyal to the High King of Ireland.
12
Ioana Mohor-Ivan
Irish Literature
1.1.
The Norman Invasion
1152 1155 1166 1169 1171 1199 1366 Dermot Mac Murrough, King of Leinster, abducts O’Rourke’s wife, Dervorgilla The Pope gives Ireland by papal Bull to Henry II Rory O’Conor and o’Rourke attack Dermot, forcing him to take refuge in Aquitaine. A Norman army, led by Richard FitzGilbert de Clare, Earl of Pembroke (Strongbow) lands in Ireland. Following Dermot’s death, Strongbow assumes the office of King of Leinster On John’s ascension to the English throne, the second phase of the Norman conquest is innitiated. The Statutes of Kilkenny acknowledge the Irish Revival of the 14th c.
In the mid-1100's, two competing Irish Kings, Dermot MacMurrough of Leinster and Rory O’Connor of Connacht, feuded over the high kingship of Ireland. Upon O’Connor’s victory, MacMurrough was sent into exile. He sought aid from Henry II, King of England, and invited the Anglo-Norman Earl of Pembroke, subsequently known as Strongbow, to invade part of Ireland and help him subdue his rival. Strongbow conquered much of the east, including Waterford, Wexford, and Dublin.Irish, resulting in the passage of the Statutes of Kilkenny in 1366.
1.2.
Norman Cultural Influences
o Within the Pale feudal estates are evolved. Gradually English civil government established in Ireland: exchequer, chancery, courts of justice, division into counties, parliament (Anglo-Irish only). During this time the great Old English (Anglo-Norman) families—Fitzgerald, de Burgh, Butler— form their power, and the Old Irish Kings—O’Connor, O’Brien, and O’Neill—still retain much of their ancient kingdoms. o Southern varieties of English are introduced within the Pale. These mediaeval varieties of Hiberno-English become the language of commerce and administration, and still survive in rural Wexford and the north of Dublin.
13
Ioana Mohor-Ivan Irish Literature o After the plantations of the 16th and 17th century.3. is a chanson de geste.1. northern dialects of English and Inglis (dialect of the Scottish lowlands) are introduced in Ireland.3. the age of Charlemagne and Louis the Pious. and made up of strophes of varying length linked by assonance . • 14 . followed by the latter’s subsequent marriage to Aoife. Chansons des geste: The Song of Dermot and the Earl Chansons de geste (Old French for "songs of heroic deeds“) are the epic poetry that appears at the dawn of French literature. forming the basis of modern Hiberno-English. 1. Anglo-Norman Literary Productions 1.the chansons de geste narrate legendary incidents (sometimes based on real events) in the history of France in the eighth and ninth centuries. nearly a hundred years before the emergence of the lyric poetry of the troubadours and the earliest verse romances. secretary to Dermot MacMurrough.apparently intended for oral performance by jongleurs . The Song records Dermot’s journey to enlist the Norman support for regaining his kingdom. and the victory of Strongbow. Dermot’s daughter. composed in the mid-thirteenth century. The earliest known examples date from the late eleventh and early twelfth centuries. and assigned to Morice Regan. Composed in Old French. with emphasis on their combats against the Moors and Saracens. • The Song of Dermot and the Earl.
on condition that you be my helper so that I do not lose at all: you I shall acknowledge as sire and lord. vus ward e saut. the valiant king. Your liege man I shall become henceforth all the days of my life. that wilfully would he help him as soon as he should be able. But I should wish in these matters to crave licence of the English king.1200-25) Quant dermod. Here I assure you loyally that I shall assuredly come to you. Par deuant li rei engleis. Bien ebel deuant la gent: ‘Icil deu ke meint en haut Reis henri.’ Then the king promised him. before the English king. Que fet me hunte le men demeine!(…) (When Dermot. hearken unto me. very courteously he saluted him fairly and finely before his men: ‘May God who dwells on high guard and save you. in the presence of the barons of your empire.Ioana Mohor-Ivan Irish Literature THE SONG OF DERMOT AND THE EARL (c. whence I was born. wherefore I cannot go from his territory without obtaining licence in this way. the powerful king of England. To you I come to make my claim. He had neither spouse nor wife. Al rei henri par deuant Esteit uenus a cele fiez. Of Ireland I was born a lord. good sire.(…) (The earl at this time was a bachelor. Mult le salue curteisement. Si entent del rei dermot Que sa fille doner lui uolt Par si que od lui uenist E sa terre lui conquist. but wrongfully my own people have cast me out of my kingdom. the king turned straight towards Wales and never ceased journeying there until he came to St. in Ireland a king. David’s) 15 . in the presence of your barons and lords. li reis vaillant. for he is the lord of my landed estate. When he hears from King Dermot that he was willing to give him his daughter on condition that he would come with him and subdue his land for him. King Henry. Femme naueit ne mullier. the earl replies before his men: ‘Rich king.) Li quens al hort iert bacheler. noble King Henry. before King Henry had come at this time. When they had concluded this accord.’ The king assured the earl that he would give him his daughter when he would come to his aid to Ireland with his barons. and give you also heart and courage and will to avenge my shame and my misfortune that my own people have brought upon me! Hear. of what country. E vu donge ensement Quer e curage e talent Ma hunte uenger e ma peine.
• • Modern treatments of Dermot and Dervorgilla’s story: • Augusta Gregory. known as Strongbow. She is famously known as the "Helen of Ireland" as her abduction from her husband Tigernán Ua Ruairc by Diarmait Mac Murchada in 1152 played some part in bringing the AngloNormans to Irish shores.B. and on Dervorgilla!” • 16 . The Dreaming of the Bones (1919): A rebel soldier who has taken part in the Easter Rising flees to Corcomroe Abbey. king of Meath. Unlike many other women. where he encounters the ghosts of Dermot and Dervorgilla. The soldier refuses. she is mentioned no less than five times in contemporary annals: her abduction by Diarmait in 1152 (Annals of Clonmacnoise). her retirement to Mellifont in 1186 (Annals of Ulster. who beg him to absolve them of their guilt. self-denial and good works. But the news of the casual slaughter of the Irish by the Normans prove that her acts of charity are but a futile attempt to allay her sense of guilt. although this is a role that has often been greatly exaggerated and often misinterpreted. and 60 ounces of gold during the consecration ceremony in 1157 (Annals of the Four Masters).Ioana Mohor-Ivan Irish Literature Historical characters: • Diarmait Mac Murchada (also known as Diarmait na nGall. (1108-1193) was a daughter of Murchad Ua Maeleachlainn. De Clare was a Cambro-Norman lord notable for beginning the Norman conquest of Ireland. Annals of the Four Masters). Dervorgilla (1907): 20 years after the events. her donation to the Cistercian abbey of Mellifont of altar cloths. was the son of Gilbert de Clare. anglicized as Dermot MacMurrough (died 1 May 1171) is often considered to have been the most notorious traitor in Irish history. 2nd Earl of Pembroke (1130 – 20 April 1176). Richard de Clare. "Dermot of the Foreigners"). Annals of Loch Ce). 1st Earl of Pembroke and Isabel de Beaumont. spending her declining years in pray. and her death in Mellifont in 1193 (Annals of Ulster. a gold chalice. her completion of the Nuns' Church at Clonmacnoise in 1167 (Annals of the Four Masters). W. Yeats. Anglicised as Dervorgilla. renewing the curse: “My curse upon all that brought in the Gall Upon Dermot’s call. Dervorgilla has retired to the Abbey of Mellinfont. Derbforgaill .
The Land of Cokaygne is not an isolated poem. snack time. For what is there in paradise But grass and flowers and green rice? (…) In Cokayne there is food and drink Without care. 1340) Fur in see bi west Spayngne Is a lond ihote Cokaygne.3. Italy. poetry and performance. They were mainly clerical students at the universities of France. and supper. drink. that describes a comical paradise full of food. 17 . British Library. London. At dinner. þe met is trie. þo3 Paradis be miri and bri3t. Cokaygn is of fairir si3t. What is þer in Paradis Bot grasse and flure and grene ris? (…)I Cokaigne is met and drink Wiþvte care. anxiety and labor. its fictional and parodic otherworld belongs to a tradition of poems dealing with an imaginary paradise where leisure rules and food is readily available. Cokaygne is yet a fairer sight. and loose women. such as the failure of the crusades and financial abuses. þer nis lond vnd' heuen riche Of wel.2. The food is excellent. russin. satirical Latin poetry in the twelfth and thirteenth centuries. • Classical: going back to Lucian's True History. hit iliche. The Land of Cockayne (c. how. a Greek work of the second century AD. and sopper. the drink is splendid. To none. Under God's heaven no other land Such wealth and goodness has in hand Though paradise be merry and bright.Ioana Mohor-Ivan Irish Literature 1. Germany. Goliardic poems: The Land of Cockayne • The Goliards were a group of clergy who wrote bibulous. of godnis. and swink. This poem survives in only one manuscript. expressing themselves through song. and England who protested the growing contradictions within the Church. Far in the sea to the west of Spain There is a land that we call Cokaygne. Probably compiled in Ireland in the early-mid 1300s. þe drink is clere. Harley MS 913.
a parody of the medieval vision and voyage tales. Influenced by goliardic satire. which invert the usual norms of religious life. which also mocks the conventions of heroic literature and the institutions of Church and State. an 'abbot of Cockaygne' who presides over drinking and gambling. 18 . Believed visited by Alexander the Great. Pieter Brugel the Elder. Goliardic: one Latin poem of the twelfth century (Carmina Burana 222) is spoken by an abbas Cucaniensis. though remote. The Land of Cockayne. and the descriptions of the two abbeys in Cockaygne.Ioana Mohor-Ivan • Irish Literature • Christian: descriptions of both Heaven and the garden of Eden (which was seen as a real. place on earth). the tale was composed in the 12th century. it often was placed far to the East. 1567 The fantastic descriptions of plenteous food may be compared to those in The Vision of MacConglinne.
They are a sort I dearly love . passionate and self-disciplined. All the blame they've ever had is undeserved. a history of Ireland from the creation of the world to the coming of the Normans in the twelfth century. • Geoffrey Keating (Seathrún Céitinn) (c. courtly love was a contradictory experience between erotic desire and spiritual attainment. in which women were held in high esteem. the 4th Earl of Desmond (1333-1398) was the first to adapt the courtly love tradition of the Norman French to the Irish. • • 19 . close to his birthplace. ." Gerald Fitzgerald. "a love at once illicit and morally elevating. human and transcendent. He draws on the older. the love of woman is exalted. In the poetry of courtly love. . Gerald's poem is a rebuttal of the fierce clerical misogyny that was prevalent in the Middle Ages: Woe to him who slanders women. humiliating and exalting. 1580-1644) was a renowned priest. • Courtly love was a medieval European conception of ennobling love which found its genesis in the ducal and princely courts in southern France at the end of the eleventh century. The Danta Gradha: O Woman Full of Wile The Danta Gradha is an Irish adaptation of the Courtly love poetry. . Scorning them is no right thing. In common with many of his educated Catholic contemporaries. Celtic tradition. It is thought that in his youth he studied at a bardic school in South Tipperary. Keating's most significant work.3. Foras Feasa ar Éirinn. His poem O Woman Full of Wile is one of the finest examples of the Irish Danta Gradha. he went abroad to pursue his philosophical and theological training as a priest. a redemptive force for both the lover and his beloved. was completed about 1634.3. poet. . In essence. prose-writer. of that I'm sure . Sweet their speech and neat their voices. and scholar.Ioana Mohor-Ivan Irish Literature 1.
Padraic Pearse 20 . Take thy mouth from my mouth. Every deed but the deed of the flesh And to lie in thy bed of sleep Would I do for thy love. O slender witch. Tho’ thou be sick for my love. Let our love be without act Forever.Ioana Mohor-Ivan Irish Literature O WOMAN FULL OF WILE O woman full of wile. See how my hair is grey! See how my body is powerless! See how my blood hath ebbed! For what is thy desire? Do not think me besotted: Bend not again thy head. Thy lovely round white breast. Keep from me thy hand: I am not a man of the flesh. Graver the matter so. That draw the desire of eyes. Thy grey eye bright as dew. Let us not be skin to skin: From heat cometh will. O woman full of wile! Trans. ‘Tis thy curling ringleted hair.
The native Irish. Under Elizabeth’s rule. Such policies resulted in several rebellions in the late 16th century by great Irish and Anglo-Irish aristocratic families. leading to his policy of “surrender and regrant” 1558 Accession of Elizabeth I 1580 The Munster rebellion is crushed by the English 1586 Plantation of Munster 1588 Defeat of Spanish Armada 1595 Hugh O’Neill’s rebellion 1599 Essex in Ireland as Lord Deputy 1601 Battle of Kinsale 1607 Flight of the Earls 1608 James I’s accession. making the Anglican Church the "official" Irish Church (now called "the Church of Ireland"). and so the division between Irish and English became also a division between Catholic and Protestant. enforcing strict Anglican rule. and many of the Anglo-Irish aristocracy. the last of the native Irish aristocracy--fled the country for the continent. Queen of Scots (1542-1587) restored Catholicism. as Mary. Plantation of Ulster 1641 Irish rebellion 1649 Cromwell begins his Irish campaign after the King’s execution 1654 Cromwellian Plantation The Reformation and the declaration by Henry VIII in 1534 that England would no longer acknowledge the Catholic Church led to the establishing of the Church of England or Anglican Church. thereby making England a Protestant nation. Plantations 1509 Henry VIII succeeds to the throne of England 1534 The English Reformation 1551 Henry VIII is declared King of Ireland. refused to follow this split from Rome. and Queen Elizabeth (1533-1603) then restored Protestantism. This "Flight of the Earls" becomes a paradigm in Irish thought for the abandonment of the country by the very leaders who needed to save it.Ioana Mohor-Ivan Irish Literature CHAPTER 2 – CONQUESTS: ENGLAND’S “OTHER”: INSCRIBING AND RE-INSCRIBING IRELAND’S STORY 2. This split created turmoil in both English and Irish politics throughout the 16th and 17th centuries. all of which were put down by the English. The Munster Plantation (colonised by English Anglicans in the second half of the 16th century) was followed at the beginning of the 17th century by the Ulster 21 .1. and suppressing the rights and privileges of Catholics. Finally in 1607 the Earls of Tyrone (Hugh O'Neill) and Tyrconnell (Rory O'Donnell). the Acts of Supremacy and Uniformity were passed.
Ioana Mohor-Ivan Irish Literature Plantation. Gradually these radical Protestants. These colonists came partly to escape England. where the official Anglican Church persecuted the more radical sects of Protestantism. when mainly Scottish Presbyterians flocked to the North of Ireland. along with native Irish Catholics and ruling British Anglicans. called "dissenters. 22 ." would present a third term in Anglo-Irish politics.
experience. • Produced in relation to the West. produced by scholars. English Narratives of Ireland 2. or novelists. one of its deepest and most recurring images of the Other. and finally representing it or speaking on its behalf. the type of structure he builds. being represented as the Other to the civilised image of the West. poets. .Ioana Mohor-Ivan Irish Literature 2. determined by this social context and contributing to its continuing existence. this location includes the kind of narrative voice he adopts. translated into his text.2. Colonial Discourse • Discourse (Michel Foucault): groupings of statements. travel writers. The Orient was thus produced as a repository of Western knowledge. literary and non-literary texts produced within the period and context of colonialism about the colonised society. the Orient was described in terms of the way it differed from it. containing the Other. themes. In Orientalism.2. Edward Said describes the discursive features of the 19thcentury body of knowledge on the Orient. not a society and culture functioning on its own terms: The Orient was almost an European invention . motifs that circulate in his text . Everyone who writes about the Orient must locate himself vis-à-vis the orient. • Colonial oppositions: The West Colonist Self Civilisation Modernity The Orient Colonised Other Barbarism Backwardness • • • 23 . utterances enacted within a social context. the kind of images. idea. Colonial discourse: language in which colonial thinking was expressed. .1. In addition the Orient has helped to define Europe (or the West) as its contrasting image.all of which adds up to deliberate ways of addressing the reader. personality.
The use of the 3rd person singular reduces the colonised to a single specimen. with a short Narrative of the State of the Kingdom from 1169. Inventing Ireland. John Derricke: English engraver who accompanied Sir Henry Sidney on campaigns against Hugh O’Neill in the 1570s.2. They are labelled as “backward”. etc. These rulers began to control the developing debate. a place whose peoples were. . Barbarians Anglo-Irish Chronicles: a body of political writings about Ireland produced during the 16th and 17th centuries. Moryson became in 1600 secretary to Sir Charles Blount. . 2. Later an identity was proposed for the natives which cast them as foils to the occupiers. corrupt. Ireland was soon patented as not-England. Othering Ireland “If Ireland had never existed. lord-deputy of Ireland. 9) 2.e. .2.1. in various ways. existing on a different time-scale). In 1617 he published an account of his travels and of his experiences in Ireland.Ioana Mohor-Ivan Discursive structures of colonial discourse: • • • • • • Irish Literature The colonised countries become objects of knowledge. Civilians vs. The use of ethno-graphic present freezes their society at the time of its observation. At the outset they had no justification other than superior force and cohesive organisation. • 24 . . p. • Fynes Moryson (1556-1630): English traveller and writer. “primitive” (i. and since it never existed in English eyes as anything more than a patch-work-quilt of warring fiefdoms. The colonised become stereotyped: the docile Hindu.Another part of the Itinerary was republished in 1735 with the title History of Ireland 1599-1603.” (Declan Kiberd.2. and it was to be their version of things which would enter universal history.2. commonly recycling prejudices and misconceptions that compared the Irish to other uncivilised races in different historical and geographical contexts. His detailed and skilfully composed woodcuts in The Image of Ireland with A Discovery of Woodkarne (1581) depict contemporary scenes in camp and battle. Vintage. the English would have invented it. 1996. weak. with illustrations of Irish plundering from an English standpoint. Negativity: idle. the very antitheses of their new rulers . the sneaky Arab. their leaders occupied the neighbouring island and called it Ireland. (where he had witnessed O'Neill's rebellion) in a voluminous work entitled An Itinerary. which were primarily concerned with justifications for the expropriation of the country by the English crown.
A View of the Present State of Ireland. Arthur Grey. In the early 1590s Spenser wrote a prose pamphlet titled. The text argued that Ireland would never be totally 'pacified' by the English until its indigenous language and customs had been destroyed. if necessary by violence.1612). Among his acquaintances in the area was the poet Walter Raleigh. also a fellow colonist. • 25 . From 1579 to 1580. probably in the service of the newly appointed lord deputy. a well-written account of the constitutional standing of Ireland.Ioana Mohor-Ivan Irish Literature (The feast of an Irish nobleman – from Derricke’s Image) • Sir John Davies (1569-1626) English poet and lawyer. he served with the English forces during the rebellions in Munster. the pamphlet remained in manuscript form until its publication in print in the mid-seventeenth century. Davies was very much committed to reform not just in the law but in religious affairs too. After the defeat of the rebels he was awarded lands in County Cork. Davies became in 1603 attorney general in Ireland. In 1610 he wrote the Discoverie of the True Causes why Ireland was never entirely subdued (pub. Spenser went to Ireland in the 1570s . aiming to banish the catholic clergy from Ireland and for enforcing church attendances. Edmund Spenser (1552-1599): One of the most famous English Renaissance poets and Poet Laureate. Due to its inflammatory content. He also became heavily involved in government efforts to establish the plantation of Ulster.
yet not able long to continue therewithal. they spoke like ghosts crying out of their graves. They looked anatomies of death. (. we might be drawn from this that we have in hand. nor be slain by the soldier. creeping forth upon their hands. EUDOXUS: What hear I? And is it possible that an Englishman brought up naturally in such sweet civility as England affords could find such liking in that barbarous rudeness that he should forget his own nature and forgo his own nation? How may this be. or what. may be the cause hereof? IRENIUS: Surely nothing but the first evil ordinance and institution of that commonwealth. I pray you. Yet sure in all that war there perished not many by the sword. for notwithstanding that the same was a most rich and plentiful country. namely the handling of abuses in the customs of Ireland. ) IRENIUS: . EUDOXUS: The end I assure me will be very short and much sooner than can be in so great a trouble (as it seemeth) hoped for. and their cattle from running abroad by this hard restraint. such as will never be made dutiful and obedient. for their legs could not bear them. nor brought to labour or civil conversation. they did eat of the dead carrions. ‘yea and more malicious to the English that the very Irish themselves. yet ere one year and a half they were brought to so wonderful wretchedness. . they would quickly consume themselves and devour one another.Ioana Mohor-Ivan Irish Literature From A VIEW ON THE PRESENT STATE OF IRELAND (1596) EUDOXUS: What is this that ye say of so many as remain English of them? Why are not they that were once English abiding English still? IRENIUS: No. that you would have thought they could have been able to stand long. But thereof now is here no fit place to speak. for that those which will afterwards remain without are stout and obstinate rebels. happy were they could find them. Although there should none of them fall by the sword. and being acquainted with spoil and outrages will ever after be ready for the like occasions. . for the most part of them are degenerated and grown almost Irish. Out of every corner of the woods and glens they came. and therefore needful to be cut off. The proof whereof I saw sufficiently ensampled in those late wars in Munster. And if they find a plot of water cress or shamrocks. lest by the occasion thereof offering matter of a long discourse. My reason is. so as there is no hope of their amendment or recovery. which they themselves had wrought. full of corn and cattle. yet thus being kept for manurance. having once tasted that licentious life. yea and one another soon after in so much as the very carcasses they spared not to scrape out of their graves. but all by the extremity of famine. . as that any stony heart would have rued the same. 26 . . that in short space there were none almost left and a most populous and plentiful country suddenly left void of man or beast. there they flocked as to a feast for the time.
The simianisation of the Irish was also informed by other discourses of the time that inscribed them as members of a second-order race in relation to the first-order English: the discourse of anthropology was spawning. uncivilised’. Towards the end of the 19th century. showing constant disrespect for the English law. debates on Darwinism placed the Irish closer to apes on the evolutionary ladder.Ioana Mohor-Ivan • English / Irish Polarities CIVILISATION PROTESTANTISM ORDER RESTRAINT REASON Irish Literature BARBARISM CATHOLICISM LAWLESSNESS VIOLENCE IRRATIONALITY This image of the ‘barbaric’. 27 . scientific anthropology was advancing the idea that the Irish mind was ineluctably criminal. religious violence or political risings in Ireland made the issue of the Anglo-Irish relation come to the fore. a period marked by the intensification of nationalist rebellions in Ireland. the notion of the Irish as a race of covert blacks. the Victorian press and the iconographic productions of the time that consistently presented the ‘Simianised terrorist’ or the ‘quaint Paddy’ as stereotypes of the Irish person. at some of its wildest extremities. ‘inferior’ Irish was to stuck in the English mind and to be retorted to whenever civil unrest.
.. Archbishop of Canterbury. the General of our gracious Empress As in good time he may . notably the Earl of Essex's attempted suppression of revolts in Ireland. .2. Fluellen. Henry V Also known as The Cronicle History of Henry the fifth. boasting of having seen a great deal of the world when he has probably been no further from his own country than some English barracks and camp. . some wild screech or oath of Gaelic origin at every third word: he has an unsurpassable gift of ‘blarney’ and cadges for tips and free drinks.from Ireland coming. by way of Hibernian seasoning. the other the braggart (also partial to a ‘dhrop of the besht’) who is likely to be s soldier or ex-soldier. . it is a play by William Shakespeare (thought to date from 1599) based on the life of King Henry V of England. he is rosy-cheeked. His face is one of simian bestiality. massive and whiskey-loving. The play is connected to the English military ventures in Ireland that were important at the time of the play's writing.2. (Fitz-simons 1983: 94) He [the Stage Irishman] has an atrocious Irish brogue. with an expression of diabolical archness written all over it. prior to the foundation of the Irish Literary Theatre of 1898 tend to fall into one or other of two categories . the first stage Irishman reflected a desire to stigmatise the Irish as savages or anathemise them as traitors. since the Chorus directly refers to Essex's military triumphs in the fifth act.one. The Stage Irishman • • • A term for stereotypical Irish characters on the English-language stage from the 17th century. and Henry himself all being prime examples. . (Maurice Bourgeois. crafty. It deals with the events immediately before and after the Battle of Agincourt during the Hundred Years' War. Later versions sought to provide amusement to English audiences by exaggerating the traits which differentiated the Irish from the English. . . . and never fails to utter. Bringing rebellion broachèd on his sword. in Styan 1991) William Shakespeare. Irishmen on the stage. .1. As a product of colonialism. his boisterousness and his pugnacy. 30-34) 28 . . .’ (V.Ioana Mohor-Ivan Irish Literature 2. How many would the peaceful city quit To welcome him! . q. The play can be seen as a glorification of nationalistic pride and conquest. . and (in all probability) inebriated buffoon who nonetheless has the gift of good humour and a nimble way with words. are his swagger. with the Chorus. His hair is of a fiery rea. the lazy. His main characteristics . blunders and bulls in speaking. makes perpetual jokes.2.
look you. The concavities of it is not sufficient. the trompet sound the retreat. in the way of argument.Ioana Mohor-Ivan Irish Literature The Irish Captain Macmorris is considered to be the prototype for the Stage Irishman. I beseech you now. of the Roman disciplines. upon my particular knowledge of his directions. la. as I may pick occasion: that sall I. you must come presently to the mines. in the disciplines of the pristine wars of the Romans. so Crish save ma. as partly touching or concerning the disciplines of the war. ‘tish ill done . that is the point. MACMORRIS It is no time to discourse. and I sall quit you with gud leve.by my hand. FLUELLEN It is Captain Macmorris. and friendly communication? . a few disputations with you. GOWER How now. as in the world. and the Dukes . ‘tish ill done! FLUELLEN Captain Macmorris. FLUELLEN By Cheshu. look you. is digt himself four yard under the countermines. look you. gud captens. . I will verify as much in his beard. and partly for the satisfaction. he is an ass.partly to satisfy my opinion. I would have blowed up the town. will you voutsafe me. Captain Fluellen. JAMY I say gud-day. He has no more directions in the true disciplines of the wars. ACT III. is it not? GOWER I think it be. and the King. in an hour. if there is not better directions. of my mind. ‘tish ill done. for. look you. ‘tish ill done! The work ish give over. By Cheshu. I’faith. FLUELLEN To the mines? Tell you the Duke. gud feith. and the wars. for. Captain Jamy. Gower following GOWER Captain Fluellen. and my father’s soul. and the Scots captain. Enter Captain Macmorris and Captain Jamy GOWER Here ‘a comes. I thin ‘a will plow up all. GOWER The Duke of Gloucester. look you. it is not so good to come to the mines. the mines is not according to the disciplines of the war. FLUELLEN Good-e’en to your worship. JAMY It sall be vary gud.it is not 29 . FLUELLEN Captain Jamy is a marvellous falorous gentleman. good Captain James. By my hand I swear. Captain Macmorris. a very valiant gentleman. the work ish ill done: it is give over. you may discuss unto the Duke. By Cheshu. marry. and of great expedition and knowledge in th’auchient wars. have you quit the mines? Have the pioneers given o’er? MACMORRIS By Chrish.as touching the direction of the military discipline. to whom the order of the siege is given. that is certain. bath. HENRY V. look you. and the weather. SCENE 2 Enter Fluellen. than is a puppy-dog. the Roman wars. is altogether directed by an Irishman. The Duke of Goucester would speak with you. with him. he will maintain his arguments as well as any military man in the world. O. th’athversary. so Crish save me! The day is hot. look you. la.
ere theise eyes of mine take themselves to slomber. be Chrish. and there ish nothing done. JAMY Ah. the town is beseeched. so Chrish sa’ me. ‘tis shame for us all: so God sa’ me. (Exeunt) • English / Irish Polarities KING MASTER KNOWLEDGE RESTRAINT ENGLISH SUPERIORITY BUFOON SERVANT IGNORANCE BOASTFULNESS HIBERNO ENGLISH INFERIORITY 30 . I think.Ioana Mohor-Ivan Irish Literature time to discourse. when there is more better opportunity to be required. if you take the matter otherwise than is meant. and in other particularities.and there is throats to be cut. and a knave. GOWER Gentlemen both. I will be so bold as to tell you. that’s a foul fault! (A parley is sounded) GOWER The town sounds a parley. peradventure I shall think you do not use me with that affability as in discretion you ought to use me. that is the breff and the long. by my hand . Captain Macmorris. la! JAMY By the mess. I know the disciplines of war. What ish my nation? Who talks of my nation? FLUELLEN Look you. FLUELLEN Captain Macmorris. Marry. and in the derivation of my birth. or ay’ll lig I’th’grund for it. look you. you will mistake each other. and there is an end. and the trumpet call us to the breach. under your correction. MACMORRIS I do not know you so good a man as myself. ‘tis shame to stand still. that sall I suerly do. both in the disciplines of war. and works to be done. look you. being as good a man as yourself. I will cut off your head. So Chrish save me. look you. and we talk. ay’ll de gud service. or go to death! And qy’ll pqy’t as valorously as I may. do nothing. ay. I wad full fain hear some question ‘tween you tway. and a rascal. and. and a bastard. FLUELLEN Captain Macmorris. it is shame. there is not many of your nation – MACMORRIS Of my nation? What ish my nation? Ish a villain.
• The Irish Trilogy (The Colleen Bawn.3. a United Irishmen rebel. Fanny. The Shaughraun) • The Colleen Bawn: The play is focused on the story of the beautiful but untutored country girl. farces (Forbidden Fruit). Dion Boucicault (1820-1890): playwright. The Comic Melodrama The comic melodrama transforms the stage Irishman into an intelligent and witty rustic who becomes an agent of mediation between Englishness and Irishness. colonel O’Grady. but is discovered there on the eve of her wedding to Shaun the Post. and producer. The Irish Melodrama In the 19th century. began his remarkable career in 1841 with the successful production of his own London Assurance and continued virtually unabated until his death in 1890. detective plays (Mercy Dodd or Presumptive Evidence). E. Re-writing Ireland’s Story A recurrent strategy of Anglo-Irish dramatists was to subvert the stereotype by enabling their Irish characters to defeat with comical aplomb the ruses of English tricksters who try to gull them. Arrah-na-Pogue. actor.2. The Shaughraun and Robert Emmet). American plays (The Octoroon). Arrah-na-Pogue: Beamish MacCoul.g. As a playwright.: George Farquhar (c. when Irish plays ( Arrah na Pogue.3. has returned from exile in France to organise an insurrection. Myles-naGoppaleen (Boucicault’s modified stage-Irishman) is an engaging rustic who foils the murder attempt and makes Cregan accept Eily as his bride.Ioana Mohor-Ivan Irish Literature 2. he embraced varied genres: historical romance (Louis XI). whom her gentleman lover (Cregan) wants to kill in order to avoid a misalliance. Beamish and his rival. Arrah-na-Pogue. He hides in the cottage of his foster-sister. domestic plays (Dot -an adaptation of Dicken's The Cricket in the Hearth-). 1677-1707): The Twin Rivals Thomas Sheridan (1719 –1788): The Brave Irishman Richard Brinsley Sheridan (1751-1816): The Rivals 2. To save his bride. rush to • 31 . Shaun takes the blame upon himself and is thus taken to Dublin to be sentenced to death by a court martial. He also wrote the acting version of Rip Van Winkle. Irish melodrama brought further changes to the cliché. Eily O’Connor. and also marry Fanny Power.
escape from Australia. the United Irishmen’s rebellion. Robert Ffolliott. and Protestant and Catholic. more importantly. 32 . loyalty and wit. Fenianism. ‘selfreliance’. attempting to construct an Irishness marked by such qualities as ‘manliness’. Conn the Shaughraun.Ioana Mohor-Ivan Irish Literature Dublin to save Shaun’s life and a benevolent Secretary of State settles their differences and grants Shaun a last-minute reprieve. and Molineaux marrying Robert’s sister. emerging as more than stereotypical drunken sots to take an active. economic and political conflicts of their world. Myles na Copaleen. Whitbread: Wolfe Tone (1898). ‘combativeness’. Conn the Shaughraun Though they still wear some of the traditional traits of the dramatic type. English/Irish. and. The Ulster Hero (1903) Given the power of the heroic myth. a good-hearted wanderer. ethnic and social cleavages between themselves and the other ranks of nationalist Ireland. Endowed with bravery. the patriotism of the title characters transgresses any religious. rich and poor become one in their affection for their country and in pledging all their efforts against England. ‘antagonism’ towards the British rule. Shaun the Post. Plays: D. Conn takes his place and is apparently killed.) In this. ‘patriotism’. with Conn turning well and alive. A pardon for the Fenians arrives in time to secure the happy ending. at times courageous part in the social. has helped an ex-Fenian rebel. Claire. intellectual and peasant. With the help of Harvey Duff. being cast as comic rustics who display a propensity for banter and blarney and still ‘put their lips to the jug’ with some regularity. • The Shaughraun: The play is a political melodrama in which Boucicault’s sympathetic version of the stage-Irishman has advanced to the title role. Robert is arrested by the English Captain Molineaux. it reverts to the myth of the national hero. traitor and police spy. W. Boucicault: Robert Emmett (1884) J. When Duff and the villain Kinchela stage an escape for the prisoner in order to shoot him on the run. The Historical Melodrama It celebrates heroic events in the nationalist version of Irish history (e. they overcome all obstacles / adversaries and finally become agents of reconciliation between opposing parties: landlord/peasant.g. Boucicault’s Stage Irishmen are far removed from the extreme silhouette of the figure of ridicule.
because evil is entirely projected upon stage villains. SHAUGHRAUN COMEDY SERVANT BENIGN CLEVER WIT PEASANT LOYALTY MEDIATION RUSTIC PASTORAL HISTORICAL HERO TRAGEDY MASTER ALTRUISTIC INTELLIGENT ELOQUENCE ARISTOCRAT NATIONALISM INDEPENDENCE MARTIAL CIVILISATION 33 . highlighting thus the latter’s status as martyred victims of both tyranny from without and treachery from within. typically featuring native informers operating under the direction of reprehensible British officers.Ioana Mohor-Ivan Irish Literature Tensions between England and Ireland intensify. who. Their function is to account for the failure of the heroes’ enterprises solely in terms of someone else’s moral failings. in contradistinction to the comic melodrama. become increasingly politicised.
Like the Troubles themselves.) was born into a nationalist Irish Catholic family at Mossbawn. in a rural area thirty miles to the north-west of Belfast. His work is often set in rural Londonderry. 34 . we ‘deem’ or we ‘allow’ when we suppose and some cherished archaisms are correct Shakespearean. Contemporary Revisions of Historical Narratives a) Seamus Heaney: Traditions. is grass-roots stuff with us. for example. even works that on the surface appear to deal with something else. Nor to speak of the furled consonants of the lowlanders shuttling obstinately between bawn and mossland. beds us down into the British Isles. Seamus Heaney (1939 .2. We are to be proud of our Elizabethan English: ‘varsity’. In 1995 he was awarded the Nobel Prize for literature TRADITIONS I Our guttural muse was bulled long ago by the alliterative tradition. sometimes even prehistory.Ioana Mohor-Ivan Irish Literature 2. her uvula grows vestigial. that ‘most sovereign mistress’.3. Heaney's work is deeply associated with the lessons of history. forgotten like the coccyx or a Brigid’s Cross yellowing in some outhouse while custom. Hints of sectarian violence can be found in many of his poems. the county of his childhood.
Ioana Mohor-Ivan III Irish Literature MacMorris. Given the persistence of this ambiguity in colonial writings. though so much later. 35 . re-constructing him in accordance to a post-colonial agenda. a recurring theme for Friel.’ said Bloom. the wandering Bloom replied. his grandparents were illiterate peasants from County Donegal whose first language was Irish. Friel helped found the Field Day Theatre Company which is committed to the search for "a middle ground between the country's entrenched positions" to help the Irish explore new identities for themselves. gallivanting round the Globe.): born in a Catholic family. Brian Friel attempts to dismantle traditional representations of the Ulster chieftain. Many of his plays are set in fictional Ballybeg. Vilified in Anglo-Irish chronicles as traitor and rebel. Making History employs intertextuality in order to question the mechanics of historical definition through which previous texts like Peter Lombard’s De Regno Hiberniae Commentarius (1632). as anatomies of death: ‘What ish my nation?’ And sensibly. Making History (1988) dramatizes the writing of Irish history as well as the historical events themselves before and after the Battle of Kinsale (1601). or Shakespeare’s Henry V that transformed him into a “stage Irishman” have fixed men and events in their “official” readings.’ b) Brian Friel: Making History Brian Friel (1929 . Donegal. Thus his own family exemplifies the divisions between traditional and modern Ulster and Ireland. the Anglo-Irish Chronicles who viewed him as an Irish barbarian. whinged to courtier and groundling who had heard of us as going very bare of learning. Though his father was a teacher. Brian Friel is one of Ireland's most prominent playwrights. Ireland. is another influence that features strongly in Friel's life and work. County Tyrone in Northern Ireland. Earl of Tyrone. ‘Ireland. as wild as hares. This figure has accrued contradictory meanings from the late 16th-century onwards. In 1980. Its main hero is the historical persona of Hugh O'Neill. ‘a remote part of Donegal‘. ‘I was born here. in Omagh. which promoted O’Neill as the leader of a European counter-Reformation. he was construed as a mythic hero by the nationalist discourse. where he moved in 1969. the leader of the last Gaelic rebellion against the Tudor re-conquest of Ireland.
LOMBARD: Will I lie.15-16) O’NEILL: This is my last battle. I’m an old man. I start with your birth and your noble genealogy and I look briefly at those formative years when you were fostered with the O’Quinns and the O’Hagans and received your early education from the bards and the poets.your life -that it contains within it one ‘true’ interpretation just waiting to be mined.wait. the drunk. Hugh? O’NEILL: I need the truth. . LOMBARD: Battle? What battle? O’NEILL: That [book]. We then look at the years when you consolidated your position as the pre-eminent Gaelic ruler in the country. Peter. LOMBARD: What’s that? O’NEILL: I spent nine years in England with Leicester and Sidney. .I’m not pleading. 1989 LOMBARD: I don’t believe that a period of history . I have all the material here. . the statesman. FABER AND FABER. [. LOMBARD: What are you talking about? O’NEILL: That thing there. and that leads to those early intimations you must have had of an emerging nation state. But I’m telling you that I’m going to fight you on that and I’m going to win. the soured. ] LOMBARD: Hold on now -wait -wait.a given space of time . I’m not whingeing . That is a solemn promise.in a florid lie. bitter émigré . the lecher.that’s what you said yourself. I have no position.wait . That’s all that’s left.I’ll rewrite the whole thing in any way you want. Just tell me one thing.Ioana Mohor-Ivan Irish Literature MAKING HISTORY . no money. the liar. And now we come to the first of the key events: that September when all the people of Ulster came together at the crowning stone at Tullyhogue outside Dungannon.my life . Can I be fairer than that? Now.in . no power. Record the whole life .] (pp. I then move O’NEILL: England. LOMBARD: Your history? O’NEILL: Your history. [. ] LOMBARD: Let me explain what my outline is.or any detail in it . No. But I do believe that it may contain within it several possible narratives: the life of Hugh O’Neill can be told in many different ways. Peter. And those ways are determined by the needs and the demands and the expectations of different people and different eras.put it all in. LOMBARD: You did indeed. Peter. May I? Please? And if you object to it . Is this book some kind of a malign scheme? Am I doing something reprehensible? O’NEILL: you are going to embalm me in . The schemer. . the leader. . the patriot. What do they want to hear? How do they want it told? [. and the golden slipper is thrown over your head and 36 . .
That’s why the great O’Neill is here . O’NEILL: You’re not listening to me now.you make it sound like a lap of honour. I then move on to that special relationship between yourself and Hugh O’Donnell. And suddenly the nation state was becoming a reality.hiding from the English. skulking round the countryside . and the True Bell of St Patrick peals out across the land.my countryside! . O’NEILL: They routed us in less than an hour.in Rome. O’NEILL: The very next month I begged Elizabeth for pardon. [.] Those are the 37 . O’NEILL: And the six years after Kinsale . and you are proclaimed .here . LOMBARD: But an occasion of enormous symbolic importance for your people . the second key event: the Nine Years War between yourself and England culminating in the legendary battle of Kinsale and the crushing of the most magnificent Gaelic army ever assembled. And then when I could endure that humiliation no longer.I’ve named it ‘The Flight of the Earls’. We disgraced ourselves at Kinsale. hasn’t it? That tragic but magnificent exodus of the Gaelic aristocracy O’NEILL: Peter LOMBARD: When the leaders of the ancient civilisation took boat from Rathmullan that September evening and set sail for Europe O’NEILL: As we pulled out from Rathmullan the McSwineys stoned us from the shore! LOMBARD: Then their journey across Europe when every crowned head welcomed and fêted them. But the telling of it can still be a triumph. Here. . the uniting of the whole Ulster into one great dynasty that finally inspired all the Gaelic chieftains to come together under your leadership. Because we ran away. The O’Neill. O’NEILL: That was a political ploy.at rest . [. LOMBARD: And again that’s not the point.six hundred and thirty continuous years of O’Neill hegemony.before the Flight of the Earls aren’t they going to be recorded? When I lived like a criminal. .that has to be said. Mountjoy routed us. LOMBARD: It may have been that. I ran away! If these were ‘my people’ then to hell with my people! The Flight of the Earls . from the Old English. and the white staff in placed in your right arm. In Rome. Isn’t that the point of Kinsale? LOMBARD: You lost a battle . LOMBARD: And then I come to my third and final key point. too. and I’m calling this section . . too. the patient forging of the links with Spain and Rome. And then the final coming to rest. Right. . .Ioana Mohor-Ivan Irish Literature fastened to your foot. O’NEILL: Kinsale was a disgrace. . We ran away like rats. but most assiduously hiding from my brother Gaels who couldn’t wait to strip me of every blade of grass I ever owned.I’m rather proud of the title . ] Now. We ran away just as we ran away at Kinsale. from the Upstarts. That has a ring to it. Peter. We were going to look after our own skins! That’s why we ‘took boat’ from Rathmullan.
.just what is your point. This isn’t the time for a critical assessment of your ‘ploys’ and your ‘disgraces’ and your ‘betrayal’ . And those stories are true stories.took the haphazard events in Christ’s life and shaped them into a story. Hugh. . . No. People think they want to know the ‘fact’. no. And your point .that’s the stuff of another history for another time. they think they believe in some sort of empirical truth. for heaven’s sake. Peter? [. I’m simply talking about making a pattern. . There us no way you can make unpalatable facts palatable. And we believe them. And that’s what this will be: the events of your life categorised and classified and then structured as you would structure any story.] LOMBARD: That’s exactly what my point is. And I’m offering them Hugh O’Neill as a national hero. So I’m offering Gaelic Ireland two things.we are talking about a colonised people on the brink of extinction. about lying. Ireland is reduced as it has never been reduced before . Now is the time for a heroic literature. into four complementary stories.Ioana Mohor-Ivan Irish Literature facts. A hero and the story of a hero [. We call them gospel.](pp 63-67) 38 . but what they really want is a story. I’m not talking about falsifying. And that narrative will be as true and as objective as I can make it with the help of the Holy Spirit. And that cohesion will be a narrative that people will read and be satisfied by. Would it be profane to suggest that that was the method the Four Evangelists used? . Now is the time for a hero. don’t we? (He laughs suddenly and heartily) Would you look at that man! Why are you so miserable about? This of this [book]as an act of pietas. That’s what I’m doing with all this stuff offering a cohesion to that random catalogue of deliberate achievement and sheer accident that constitutes your life. I’m offering them this narrative that has the elements of myth.
1776 American Declaration of Independence 1789 Fall of Bastille. Protestant identitary tropes 39 . Each facet of the complex process linked to the development of a colonial identity is correspondingly expressed in the culture of the given group: History: Nationalist vs. loyal to Britain. The siege of Derry (The Apprenticeboys March). retained links with Scotland. 1690 William III lands at Carrickfergus.) Largely deprived of leadership and religiously. 1690-91The siege of Limmerick (Patrick Sarsfield). Catholic majority: spread throughout the four provinces and including the Old English (via a common Catholicism. 1695 Penal Laws restrict Catholic rights. Colonial Identities Cultural identity: a group sharing a relatively common way of life Colonial identity: a cultural identity shaped by the new environment of colonialism 1689 James II lands at Kinsale. 1800 Act of Union 1803 Rising of Robert Emmet 1829 Catholic Emancipation (Daniel O’Connell) 1845-49The Great Potato Famine Cultural groups: Protestant Ascendancy: elite group. 1715 &1745 Jacobite risings in Scotland.1. 1795 Foundation of Orange Order. they have the least influence. landowners.Ioana Mohor-Ivan Irish Literature CHAPTER 3 – COLONIALISM AND THE NATIONALIST IMAGINARY 3. Unionist versions Literature: Nationalist vs. Ulster Presbyterians: politically and economically disabled. Battle of the Boyne (12 July). 1798 United Irishmen’s Rebellion helped by French troops (Wolfe Tone). 1791 United Irishmen founded in Belfast. Scots Presbyterians are also disabled. politically and economically disabled by the Penal Acts.
a sorrowful mother summoning her sons to protect and defend her homestead. a beautiful maiden queen in search for a redeemer for her occupied nation. in terms of gender. has not escaped being culturally cast as “other” and “female” in both colonial and countercolonial contexts. the colonized have attempted to “produce a reverse discourse of overdetermined masculity”[3]. in which the land becomes a “mother forced into penury by foreign invaders”[4]. and ultimately at the mercy of the masculine forces competing for domination over them”[2]. Banbha and Fodla). in the context of a colonized Ireland.2. the colonial project has often been metaphorically constructed as the attempt “of the male colonizer to subdue and penetrate the female territory of the colonized people”[1].Ioana Mohor-Ivan Irish Literature 3.2. as in the popular tradition of Cailleach Beara (the Old Woman of Beara. each time with a new husband. “seductive. Very often. the western imagination has translated the conquered territories of India or Africa. into images of exotic women. the two main feminine figurations for Ireland were: the Spéar-bhean (literally meaning a ‘sky-woman’). where the Gaelic culture and the clan system were inevitably broken. The Spear-Bhean and the 18th century “aisling” Nevertheless. or with the landscape itself. at times. one of the great peninsulas of the South-West Irish coast). the divine race of Irish myth -. As such. Nationalist Literary Tropes: Woman as Nation If the colonial discourse is based on a binary model of thought predicated upon the basic opposition established between self and other. the Irish folklore rescripts the narrative of the legitimacy theme by turning the Old Woman of Beara into a shape-shifting hag who displays youthful loveliness to the rightful king. seducible. though placed in the paradoxical position of being at once Western and a colony. Babh and Macha). 3. a queen who supposedly lived seven lifetimes. native Irish poetry of grows increasingly political in character. Celtic Matriarchs Yet both figures claim their ancestry in the distant Gaelic tradition. Ireland. in the principal discourses of Irish nationalism. After the Williamite War and the enactment of the Penal Laws. 3. Starting with the mythic Danu – the mother goddess of the Tuatha de Danaan. with sexual potency. for example. If early Irish literary texts of the vision type present future kings of Ireland having their claims to the land legitimated through prophetic encounters with one such sovereignty goddess.2. In response to this colonial feminization. or as the Sean Bhean Bocht (the ‘Poor Old Woman). war and death (Mórrigan. though hiding its 40 . where Celtic mythology features a number of formidable divine matriarchs who stand.1. the nature and identity of the true king become problematic. some of the attributes of this archetypal female agency are further embodied across a range of goddesses associated with the sovereignty and prosperity of the land (Eriu. requiring her sons to fight the oppressors in order to restore her former possessions. as female personifications of Ireland.2.
And other tidings which. They burst into laughter. all lonely as she was News of the return of HIM to the place which is his by kingly descent. In the bondage of fetters they put me without much respite. her speech not more with age. lubberly clown. News of the destruction of the bands who expelled him.the way I came I know not That dwelling of dwellings. As she hears my voice she weeps through wounded pride. Through margins of a morass. Oh. The streams run down plenteously from her glowing cheeks. her blue eyes tinged with green. She is the Brightness of Brightness I saw upon a lonely path. trim.Ioana Mohor-Ivan Irish Literature expectation of political deliverance “in what seemed like harmless love songs” [11] which rework the conventions of the Gaelic vision tale. 41 . And the maiden went off in a flash to the fairy mansion of Luachair. The ruddy and white appeared in her glowing cheeks. Which was fashioned at her creation in the world above. While to my maiden clung a clumsy. I will not put in my lays.a troop of wizards And a band of maidens. A tale of knowledge she told me. That robbed the earth of its brilliancy by their full sweeping. Melody of melody. She sends me with a guide for my safe conduct from the mansion. through sheer fear. Plaiting of plaiting in every hair of her yellow locks. Thus the eighteenthcentury aisling (vision) poem repeatedly looked outside the country for liberation and the true sovereign. How it will became her to be united to an awkward. with plaited locks. I rush in mad race running with a bounding heart. mockingly . folly of follies for me to go up close to her! By the captive I was bound fast a captive. An ornament brighter than glass on her swelling breast. through meads. While the fairest thrice over of all the Scotic race Was waiting to receive her as his beauteous bride. 1709) BRIGHTNESS MOST BRIGHT (GILE NA GILE) The brightness of Brightness I saw in a lonely path. in words the sincerest. through a barren moorland. I reach the strong mansion .” [12] • Aogan O Rathaille (c. who would only recover her happiness when a young liberator would come to her defence. evoking the former sovereignty goddess into the image of “a willing [and] defenceless spéirbhean [sic] or ‘sky-woman’. 1675-1729): Gile na Gile (Brightness Most Bright) (c. As I implored the Son of Mary of aid me. Crystal of crystal. I told her then. sorry churl. reared by wizard sorcery. she bounded from me.
in my bosom faints To think of you. . MY DARK ROSALEEN O my Dark Rosaleen. . Do not sigh. my saint of saints. Over hills and through dales Have I roamed for your sake. Red lightning lightened through my blood. All yesterday I sailed with sails On river and on lake. from the royal Pope Upon the ocean green. love! The heart . My life of life. My life. There’s wine . My Dark Rosaleen. . To see your bright face clouded so. My Dark Rosaleen! All day long in unrest To and fro do I move The very soul within my breast Is wasted for you. Like to the mournful moon. and identified both with the sovereignty of Ireland and with the Blessed Virgin. shall give you hope. . . at its highest flood I dashed across unseen. pain and woe. my saint of saints. My Dark Rosaleen! My own Rosaleen! Oh! There was lightning in my blood. a cluster of associations that will be carried over by subsequent invocations of Ireland under a female aspect [13]. my love. My Dark Rosaleen! My own Rosaleen! To hear your sweet and sad complaints. do not weep! The priests are on the ocean green. For there was lightning in my blood. Shall give you health. My Dark Rosaleen! Woe and pain. my Queen. And Spanish ale shall give you hope. and help. . Such associations inform James Clarence Mangan’s (1803-49) My Dark Rosaleen (1846). My Dark Rosaleen! My own Rosaleen! Shall glad your heart. The Erne . They march along the Deep.Ioana Mohor-Ivan Irish Literature In a late eighteenth-century text composed by the blind poet Liam O hIfearnain this female persona of Ireland is specifically named Caitlin ni Uallachain (Cathleen ni Houlihan). and hope. 42 . Are my lot night and noon.
in your emerald bowers. Ere you shall fade. My Dark Rosaleen! Irish Literature 43 . ‘Tis you shall reign and reign alone. . ‘Tis you shall reign. My Dark Rosaleen! My fond Rosaleen! Would give me life and soul anew. . ere you can die. I could plough the high hills. . I could scale the blue air. My Dark Rosaleen! My fond Rosaleen! You’ll think of me through daylight’s hours. . beamy smile from you Would float like light between My toils and me. My Dark Rosaleen! My own Rosaleen! The Judgement Hour must first be nigh. ere you shall die. will I rear your throne Again in golden sheen. My Dark Rosaleen! Over dews. The earth shall rock beneath your tread. You’ll pray for me. I could kneel all night in prayer. Your holy delicate white hands Shall girdle me with steel. And gun-peal and slogan cry. my true. Oh. At home . shall reign alone. To heal your many ills! And one . Wake many a glen serene. My virgin flower. And flames wrap hill and wood. a soul anew. my own. . My Dark Rosaleen! O! the Erne shall run red With redundance of blood. From morning’s dawn till e’en. Ere you can fade. A second life. My Dark Rosaleen.Ioana Mohor-Ivan But yet . over sands Will I fly for your weal. My Dark Rosaleen! My own Rosaleen! ‘Tis you shall have the golden throne. . my flower of flowers. my flower of flowers.
‘twill take root there. No more St. And he asaid.and nineteenth-centuries blend the traditions of the Old Woman of Beara with those of the goddesses of war and death. and how does she stand?” She’s the most distressful country that iver yet was seen. and throw it on the sod. praise God. which stand for the darker side of the Celtic matriarch. Kali-like. Richard Kearney has suggested that the Sean Bhean Bocht has been turned into an emblem of Irish nationalism because it is closely linked to its sacrificial mythology in which the blood sacrifice of the heroes is needed to free and redeem Ireland. I’ll stick to wearin’ o’ the green. Patrick’s Day we’ll keep. And never fear. I wear in my caubeen. The “sean bhean bhocht” and the popular ballad In their turn. the popular ballads of the late eighteenth. For there’s a cruel law agin the wearin’ o’ the green! I met wid Napper Tandy. and.3. “How’s poor Ould Ireland. Their favourite trope becomes thus the Sean Bhean Bocht. But till that day. Let it remind us of the blood that Ireland has shed. tho’ under foot ‘tis trod! When law can stop the blades of grass from growing’ as they grow. Then pull the shamrock from your hat. at the same time in which these heroic sacrificial martyrs are rewarded by being “remembered for ever” [14]. his colour can’t be seen. An’ if the color we must wear is England’s cruel red.2. this nationalist sacrificial mythology can be further tied to pagan concepts of “seasonal rejuvenation” and the sacrificial aspects of Christianity in the Crucifixion and tradition of martyrdom [15]. THE WEARIN’ OF THE GREEN Oh. requires the sacrifice of successive generations of sons in the hope that the recurring heroic failures to eject the invader will finally prove successful. Moreover. 44 .Ioana Mohor-Ivan Irish Literature 3. an idealised persona of the land who suffers historic wrongs. And when the leaves in summer-time their color dare not show. Then I will change the color. Paddy dear! an’ did ye hear the news that’s goin’ round? The shamrock is by law forbid to grow on Irish ground. too. and he took me by the hand. For they’re hangin’ men and women there for wearin’ o’ the green.
She looks at Michael as she passes. sexual and pure) in order to create its dynamic tension. starts to bemoan that she has been set wandering by “too many strangers in the house. Bridget is standing at a table undoing a parcel. epitomizes this tradition. Cathleen Ni Houlihan William Butler Yeats’s Cathleen Ni Houlihan.B.e. YEATS CATHLEEN NI HOOLIHAN (1902) PERSONS IN THE PLAY: PETER GILLANE MICHAEL GILLANE (his son. Michael: There she is. in 1798. [.] I’d sooner a stranger not to come to the house the night before the wedding. the time of the historical French landing at Killala. W. It might be some poor woman heard we were making ready for the wedding. The play makes use of what Valente calls the double-woman trope (i.4. the play written in 1902. the play is set in the cottage of the Gillane family. Mesmerized by her words.2. and came to look for her share. Michael. . Located with naturalistic precision in 1798. as the son leaves. and. but she has her cloak over her face. Peter is sitting at one side of the fire. I wonder? Michael: I don’t think it’s one of the neighbours. Patrick at the other. constituting a mythic nexus for personifications of Ireland. Peter: I may as well put the money out of sight. ] Bridget: Do you see anything? Michael: I see an old woman coming up the path. Michael decides to forsake his family and bride in order to go off to fight in the brewing insurrection. . [. father! [An old woman passes the window slowly. the combination of the Spéar-bhean and the Sean Bhean Bocht who is both young and old. There’s no use leaving it out for every stranger to look at. the old woman offers no doubt as to what his fate will be. .Ioana Mohor-Ivan Irish Literature 3. An old woman arrives who.” who took from her “four beautiful green fields”[17] and then tells of the sacrifices young men have made for her across the ages. . going to be married) PATRICK GILLANE (a lad of 12. Michael’s brother) BRIDGET GILLANE (Peter’s wife) DELIA CAHEL (engaged to Michael) THE POOR OLD WOMAN NEIGHBOURS Interior of a cottage close to Killala. taken for a beggar at first. Bridget: Maybe it’s the same woman Patrick saw a while ago. Bridget: Who is it. mother and bride. which signalled the beginning of the United Irishmen Rebellion. where the eldest son.] 45 . is about to be married the next day.
] Old Woman: God save all here! Peter: God save you kindly. Michael stands aside to make way for her. indeed. ma’am? Old Woman: I have not. Old Woman: That is true for you. You have plenty to do. They are coming to help me. [.] Bridget: What was it put you astray? Old Woman: Too many strangers in the house Bridget: Indeed you look as if you had had your share of trouble. [She gets up. With all the lovers that brought me their love. Michael: What way will you do that.] I must be going to meet my friends. the hope of putting the strangers out of my house. . Old Woman: You have good shelter here. It is not silver I want. [Michael watches her curiously from the door. Peter comes over to the table. I am not afraid. he must give me himself. ma’am? Old Woman: I have good friends that will help me. [. [. Old Woman: That is not that I want. . and it is long I am on the road since I first went wondering. there are few have travelled so far as myself Peter: it is a pity.Ioana Mohor-Ivan Irish Literature [The old woman comes in. indeed. If they are put down to-day. Bridget: What was it put the trouble on you? Old Woman: My land was taken from me. Peter[offering the shilling]: Here is something for you. Old Woman: I have had trouble. and I must be there to welcome them. Michael: What hopes have you to hold to? Old Woman: The hope of getting my beautiful fields back again. they will get the upper-hand to-morrow. it is the girl coming into the house you have to welcome. . Peter: You are welcome to whatever shelter we have. It is seldom I have any rest. I never set out the bed for any. indeed. it is food and drink you have to bring to the house. . Peter: What is it you would be asking for? Old Woman: If anyone would give me help. They are gathering to help me now. Peter: Was it much land they took from you? Old Woman: My four beautiful green fields. Michael: Are you lonely going the roads. I must call the neighbours together to welcome them.] Peter: Have you travelled far to-day? Old Woman: I have travelled far. Michael: I will go with you Bridget: It is not her friends you have to go and welcome. he must give me all. Old Woman [warming her hands]: There’s a hard wind outside. Bridget: Sit down there by the fire and welcome. .] 46 . . Michael. for any person to have no place of their own. very far. ma’am? Old Woman: I have my thoughts and I have my hopes. Michael: Have you no man of your own.] Bridget[to the old woman]: Will you have a drink of milk? Old Woman: It is not food or drink that I want.
and there are some that call me Cathleen ny Hoolihan. . no.] Michael: I do not know what that song means. singing. [She sings. ] [Michael breaks away from Delia and goes towards the neighbours at the door. . I remember I heard it in a song. [. [Michael and the neighbours go out.][She goes out. Old Woman: Come over to me. The people shall hear them for ever. and she had the walk of a queen. I heard one on the wind this morning. . but tell me something I can do for you. THE END 47 . Peter: I think I knew someone of that name once.] Michael: Come. at all? Bridget: You did not tell us your name yet. No. I wonder? It must have been someone I knew when I was a boy. Old Woman [who is standing in the doorway]: They are wondering that there were songs made for me. . . there have been many songs made for me. we must follow her.] Peter [laying his hand on Patrick’s arm]: Did you see an old woman going down the path? Patrick: I did not.] They shall be remembered for ever. Who was it. ma’am.Ioana Mohor-Ivan Irish Literature Peter[to Bridget]: Who is she. They shall be alive for ever. . Her voice is heard outside.] [. Old Woman: Some call me The Poor Old Woman. do you think. we have no time to lose. They shall be speaking for ever. but I saw a young girl. Michael. [.
while Neary is a natonalist mystic who smashes his head against the buttocks of Cuchullain’s statue in Dublin. The trope is thus deconstructed in a series of texts that include James Joyce’s short-story “A Mother” (included in his Dubliners." [21]. Bailengangaire (1985) 48 . and 'quite exceptionally anthropoid for an Irish girl‘. 1905). “A Mother” (1905) An inexperienced Dublin impresario named Mr. delaying the start of that evening’s entertainment. the Irish mistress of the title character of his novel Murphy (1938). This effectively re-inscribes the woman as devoid of agency”[23]. any feminine national icons. A burlesque novel which presents the story of an impecunious Irishman living in London. and the woman-nation equation has carried over into the post-colonial imagination. Holohan arranges with Mrs. Kearney for her daughter Kathleen to accompany on the piano the singers at a series of four concerts. or contemporary plays like Brian Friel’s Dancing at Lughnasa (1990) and Tom Murphy’s Bailengangaire (1985). As Fleming remarks. Finally. it focuses on Mommo. without ever ending it. Mary and Dolly. Moving between Ireland and England. where such traditional feminine figures of the nation have been reduced “to a metaphor for national identity and a powerful interpellative figure in the nationalist struggle for the state”[22]. who tries to recount to her granddaughters. but also for the writers who attempt to reproduce such symbolic figures of women in their work. Set in a rotting thatched cottage. Samuel Beckett’s Miss Counihan. with a bed placed centre stage. the insatiable Miss Counihan. the story of a long-ago laughing competition. won by her husband coincided with the death of the couple’s son. actually displace them outside history into the realm of myth. with the painful recognition that the laughing contest.3. Deconstructing the Woman-Nation trope While essentially a colonial by-product.Ioana Mohor-Ivan Irish Literature 3. “while seeming to empower women. the figure of Cathleen has "congealed into republican rhetoric. James Joyce. Mrs. When the first three concerts are sparsely attended. Murphy (1938) Tom Murphy. the novel is caustically satirical at the expense of the Irish Free State: the astrologer Murphy consults is famous 'throughout civilised world and Irish Free State'. Samuel Beckett. the senile grandmother. Kearney refuses to let Kathleen play during the second half of the concert because she has not been paid the entire promised fee. Kearney demands payment for all the performances before the fourth show. Mrs. The smoldering rivalries between the two sisters act as a catalyst that force Mommo to finish her story. among the posse of Irish people who pursue the protagonist. No wonder then that Cathleen has become an extremely problematic symbol not only in contemporary Irish literary and cultural studies. his former mistress. is high-breasted and high-buttocked.
” 1767-1722: Lord Townsend establishes a resident Lord Lieutenant-ship in Ireland. had become firmly established as the great land-owning families throughout. The confidence of the Ascendancy was manifested towards the end of the 18th century by its adoption of a nationalist Irish. 249] flourishing among this class who increasingly felt that their fortunes were linked with those of their adoptive country.g. initiated largely due to British concern over the revolutions in France and America 1782-1800“Grattan's Parliament”: under leadership of Henry Grattan. and Dublin.Ioana Mohor-Ivan Irish Literature CHAPTER 4 – PROTESTANT LITERARY TROPES: THE ‘BIG HOUSE’ THEME IN IRISH LITERATURE • 1704: The Sacramental Test Act. English trade laws restrict Irish export & trade industries. the authority “to make laws and statutes of sufficient force and validity to bind the kingdom and people of Ireland. 1782 “The Constitution of 1782”: a series of concessions to the Irish Parliament. The Protestant Ascendancy begins. during the 18th century. the Irish Parliament in Dublin (the only independent Parliament in any British colony in the entire empire). such as George Berkeley. combined with the crisis in America. The Protestant Ascendancy Protestant Ascendancy is a term used to refer to the Anglican (not radical Protestant) descendants of English colonists. and for the defense of. penal laws reduce Catholic landowners. the splendor of Georgian Dublin reaches its height • • • • • 4. 1720: The Declaratory Act gave to the British Parliament legislative jurisdiction over Irish affairs. the center of the Protestant power. a national volunteer army formed by. the formation of Henry Grattan’s Patriot Party in 1760). the Protestant Ascendancy. the Irish Parliament holds its greatest legislative independence. Jonathan Swift or Oliver Goldsmith. turned into a true capital. the eastern half of Ireland. Irish economic revival follows. As English and Anglo-Irish aristocracy settle in Ireland. leads to removal of most restrictions on Irish trade. as direct representative of Royal English power in Irish government 1778: First Protestant Volunteer Force forms. including repeal of Declaratory Act. making political office and membership in municipal corporations available only to those who receive communion according to the Church of Ireland (excluding both Roman Catholics and Protestant dissidents). though still exclusively Protestant. Their threat. political and economic power over the land. Among the achievements of this ruling class are: Trinity College established as their seat of learning. and were determined to sustain their social.1. came to stand for “a cast of Irish mind” [Foster. upon which they were 49 . Eighteenth-century Anglo-Irish intellectuals. who. identity. (e. particularly.
essayist 50 . playwright o Jonathan Swift (1667 –1745): satirist. poet. often making rents uncollectable. while another 2. 4.Ioana Mohor-Ivan Irish Literature economically dependant. 1829: The eventual arrival of ‘Catholic emancipation’ (a relief act enabling Catholics to enter parliament. who identified them with what they saw as the continuing domination of Britain over Ireland. a feeling solidified by various resentments against their constitutional and career dependence upon England 20 .2. The popular perception of the Ascendancy became one of an absentee landlord shipping food to England while the population starved. many stately homes of the old landed class were burned down by the Irish Republican Army. 1845-9: The Great Famine (subsequent failures of the potato crop for three out of four years resulted in the death of as many as 1. 1918-1923: During the Anglo-Irish War and the subsequent Irish Civil War. and widespread emigration of the ruling class to the new centre of power in London. largely to the United States) magnified the festering sense of native grievance.000.abolished the Irish Parliament. the dominant pattern of Irish political life will show the gradual decline of the Protestant Ascendancy against the emboldening of the growing Catholic middle and lower classes. Many decent landlords genuinely cared for their tenants and felt responsible for their fate: that care was often returned with a 20 Prominent Ascendancy writers include: o Edmund Burke (1729-97): political philosopher o George Berkeley (1685-1753): empiricist o Oliver Goldsmith (?1730-74): novelist. At around the same time. A series of Land Acts allowed tenants to take ownership of the land.passed partly in response to a perception that the 1798 rebellion and the subsequent bloodshed had been provoked by the misrule of the Ascendancy .000. Following the 1801 Act of Union. Ever since the time of Jonathan Swift there had been a pressure on the AngloIrish to throw in their lot with the natives…Over the century and a half which followed it became more and more clear that a strange reciprocity bound members of the ascendancy to those peasants with whom they shared the Irish predicament. 1880s-1900s: The ‘Land War’ saw a mass mobilisation of tenant farmers against the landlord class. the political power of the Ascendancy passed to a largely Catholic and middle class Irish nationalist movement. which led to the phenomenon of the absentee landlord. when England took direct control over the island. 1850-80: The emergence of secret and open societies such as the Tenant League or the Land League challenged the economic position of many landlords. belong to any corporation and hold higher offices in state) meant that the Ascendancy now faced competition from prosperous Catholics in parliament and the various professions.000 Irish from disease and starvation. Landmarks of Historical Decline 1801: The Act of Union . This was followed by economic decline in Ireland.000 had to emigrate. poet.
family continuities and apparently unlegislated harmony of environmental and human relationships” [5. While the Irish Big Houses are increasingly valued today for their architectural significance and have been recognized as an important part of Irish heritage. Goldsmith. 52]. the Anglo-Irish had to work up their own set of representations.1. with its serenity. 24] and.67) 4. when the Big House reached its heyday.3. and use of classical orders.3. which “provides the focus for a mythology of the social order which is one of the most established in national ideology . ix]. In so doing. they turned to the space of the Big House in order to provide themselves with their own myth of rootedness. according to Jacqueline Genet. made up of literary figures and intellectuals like Swift. invaded Ireland and helped thus the first wave of English colonizers to establish themselves in the area known as the Irish Pale. discipline and restraint. The first one.Ioana Mohor-Ivan Irish Literature mixture of affection and awe. that 51 . and [plotting] its eventual disintegration and decomposition” [12. contain “the myth of the Anglo-Irish Ascendancy” by offering “an explanation of that class. a whole new class of Anglo-Irish landlords vied to outdo one another in the building of lavish countryside estates and gardens designed in newly-popular Palladian style. Cutural Myth Feeling themselves entitled to candidate for the appellation of Irishness. by the eighteenth-century. totally oblivious to the harsh realities outside the demesne walls. characterized by grace. which. whose writings witnessed to similar elements of classicism. understated decorative elements. pointed to an idyll of social and political harmony where the affinity between paternalistic Protestant landlords and childlike Catholic peasants expressed itself in what John Corner and Sylvia Harvey term as its “aristocratic”. The “Big House”: from cultural construct to literary theme As a historical structure. 158]. they are also cultural constructs. investing it with the sense of a cultural continuum able to preserve the values of that eighteenth-century spiritual élite. when Richard of Clare. As the English military. 4. This mythical space became then the fictional frame within which the Anglo-Irish. the Big House made its appearance into the Irish landscape during the last decades of the twelfth century. The second one mythologised the “Big House” as an “Apollonian ideal of civilization and order” [6. its style and manners. the defensive aspects of the high-walled Anglo-Norman tower-houses were gradually lost [16. Others were negligent and some cruelly exploitative: but these attitudes served only to emphasize the kindness of the better sort…When the doom of the big house was sealed by the Land Acts. This myth was sustained by two aspects. known as Strongbow. Shaw was not the only commentator to wonder whether the lot of landless labourer would prove happier under peasant proprietors than it had under paternalistic landlords… (Kiberd:1996.that of the country house. administrative and political domination extended throughout the subsequent centuries. [setting] out its relations with its environment and culture. Burke or Berkeley.
forever Irish in England” [14. “it was not until it was on the verge of total disappearance that the Big House became a major theme in Irish literature. tried to invent an ideal self which could live “on the hyphen between ‘Anglo’ and ‘Irish’”[14. 368].Ioana Mohor-Ivan Irish Literature group labeled by Declan Kiberd as “a hyphenated people. built in 1672 by Richard Edgeworth. It had small windows. former members of the Royal Irish Constabulary. its economic. But the famines of the nineteenth-century and the subsequent Land Acts which conceded large parts of Anglo-Irish domains to the tenantry “spelled the end of the great estates and of the families who owned them” [16. [2. 116] Curiously enough. who felt that the new Ireland was unlikely to provide a satisfactory home for themselves or their offspring. as Guy Fehlman notices. The decline was even more dramatic in the first decades of the twentieth-century. forever English in Ireland. Until then. low wainscoted rooms and heavy cornices. thus recorded by Terence Brown in his historical account of the social changes undergone by postrevolutionary Ireland: The period 1911-26 saw indeed a striking decline of about one-third in the Protestant population of the south of Ireland as a whole which must be accounted for not only by the lamentable losses endured by Protestant Ireland in the Great War but by the large numbers of landed families. the inventor and father of Maria Edgeworth. social. The house was much enlarged and modernised after 1770 by Richard Lovell Edgeworth. 16]. civil servants and Protestant small farmers. Protestant professional men.) 52 . political and legal implications in Irish life had been too overwhelming to be transferred to fiction” [9. 367]. 27]. (Edgeworthstown House.
among other works whose fictional representations of this figurative space evoke elegiac nostalgia for the lost days of Ascendancy grandeur and spirit. or Joyce Cary’s Castle Corner (1938). is generally considered to inaugurate not only the conventions of the Big House fiction – summarized by Kersti Tarien Powell in terms of “the dilapidated house. the Land League. Literary Theme As setting. the irresponsible absentee landlords. and reflecting the anxieties and uncertainties of this Protestant landowning class in their decline. Maria Edgeworth’s Castle Rackrent. . referring to the big houses of the ascendancy. ANGLO-IRISH LITERATURE: term used to describe Irish writing in English.3. in Neill Corcoran’s opinion. 32]. Conventions: .the decaying house and declining gentry family. 53 . often absentee.the rise of a predatory middle class seeking to wrest power from landowners. and the rise of the (frequently militant. the demise of the Big House world. it has become a “significant sub-genre in Irish writing”[4. the Famine. from the early 19th century. and the growth of modern militant Irish nationalism. the rise and fall of the gentrified family. . through Catholic Emancipation. THE “BIG HOUSE”: A recurrent theme in Anglo-Irish Literature. which helps to distinguish this tradition from English literature and literature in Gaelic (applied mostly to Protestant Ascendancy writers). Primarily related to the Anglo-Irish novelistic tradition. published in 1800. theme or character.Ioana Mohor-Ivan Irish Literature 4.2. and therefore threatening) peasant class” [20.the improvident. 115] – but also to anticipate the social phenomenon related to the dramatic dislocation of the Ascendancy class. It appears mainly in the novel. Elizabeth Bowen’s The Last September (1929). landlord. but also in poetry. the theme is present in Somerville and Ross’s The Big House at Inver (1925). drama and memoir. to the founding of the Irish State. the Big House resurfaces as a recurrent and popular motif in Irish literature to the extent that.
. time out of mind. To look at me. out of friendship for the family.afterward.) Sir Tallyhoo only never gave a gate upon it. My real name is Thady Quirk. I think it my duty to say a few words. by it. he fell down in a sort of fit. Having. but the heir who attended the funeral was against that. in the first place. seeing how large a stake depended upon it. they say. The family of the Rackrents is. upon whose estate. though come Holantide next I’ve had it these seven years. but I wash my hands of his doings. in the morning. On coming into the estate. I remember to hear them calling me ‘old Thady’ and now I’m come to “poor Thady”. gains possession of the estate by loans and litigation. as I never put my arms into the sleeves. From CASTLE RACKRENT Monday Morning. one of the most ancient in the kingdom. until Thady’s own son. (. .a rescue was apprehended from the mob. not a man could stand after supper but Sir Patrick himself. and was carried off: they sat it out. praised be Heaven! I and mine have lived rent-free. Never did any gentleman live and die more beloved in the country by rich and poor.3. . that he should. narrates the eccentricities and excesses of three generations of landowning Rackrents. voluntarily undertaken to publish the Memoirs of the Rackrent Family. you would hardly think “poor Thady” was the father of attorney Quirk. . upon one condition. though in the family I have always been known by no ther than “honest Thady” . and little 54 . I am proud to say. they are as good as new. take and bear the surname and arms of Rackrent. for the estate came straight into the family. But I ought to bless that day. landed estate. His funeral was such a one as was never known before or since in the country! (.) Sir Patrick died that night: just as the company rose to drink his health with three cheers. at last. but thought better of it afterwards. Jason. it holds on by a single button round my neck. which Sir Patrick O’Shaughlin at the time took sadly to heart.2. and having better than fifteen hundred a year. “Big House” Novels Maria Edgeworth (1767-1849): Castle Rackrent (1800) o Thady Quirk. when the body was seized for debt . to be sure. on inquiry. by act of parliament. Now it was that the world was to see what was in Sir Patrick. to find that it was all over with poor Sir Patrick. it being his maxim that a car was the best gate. the law must take its course. and were surprised. Poor gentleman! He lost a fine hunter and his life. true and loyal to the family. (. which is very handy. all in one day’s hunt.)But who’d have thought it? Just as all was going on right. . for I wear a long great coat winter and summer. deceased. through his own town they were passing. he is a high gentleman and never minds what poor Thady says.Ioana Mohor-Ivan Irish Literature 4. an old steward. looks down upon honest Thady. who could sit out the best man in Ireland. cloak fashion. concerning myself. for the fear of consequences. .1. and as I have lived so will I die. he gave the finest entertainment ever was heard of in the country. let alone the three kingdoms itself. in the time of Sir Murtagh. seeing that those villains who came to serve acted under the disguise of the law: so.
It was whispered (but none but the enemis of the family believe it). (…) He had the saving. wants to make her way up the social scale in the village of Lismoyle by marrying her pretty cousin Francie Fitzpatrick to Christopher Dysart. His fastidious dislike of doing a thing indifferently was probably a form of conceit: it brought about him a kind of deadlock. you might give me a cup o’tay first!” Charlotte had many tones of voice. but the moment the law was taken of him. not perhaps being aware that her own accent scarcely admitted of being strengthened. It was the same with everything else. marries the infatuated Lambert. his tentative essays in painting died an early death. refused to pay a shilling of the debts. and. that this was all a sham seizure to get quit of the debts. till I tell her to her face that I know her plots and her thricks? ‘Tis to say that to her I came here. Her plan fails on both fronts when Francie falls in love with a member of the garrison in town. when he jilts her. there was an end of honour to be sure. but for the honour of the house. Sommerville and Ross [Edith Somerville (1858-1949)and Violet Martin (1862-1915)]: The Real Charlotte (1894) • Charlotte. At the same time. in which he was countenanced by all the best gentlemen of property. and to tell her ‘twas she lent money to Peter Joyce that was grazing my farm. hearty voice which she felt accorded best with the theory of herself that she had built up in Lady Dysart’s mind. . and when she wished to be playful she affected a vigorous brogue. in the next place. and others of his acquaintance. son and heir of the local ascendancy family in Bruff Castle. “I’ll head a forlorn hope to the bottom of the lake for you.Ioana Mohor-Ivan Irish Literature gain had the creditors for their pains. He had no confidence in anything about himself except his critical ability. they had the curses of the country: and Sir Murtagh Rackrent. the way he’s go bankrupt on me. the new heir. and he did not satisfy that. THE REAL CHARLOTTE “Well. according with the many facets of her character. on account of this affront to the body. which he had bound himself to pay in honour. This refinement of humour was probably wasted on Lady Dysart. she said. using prospects of property as the main enticement. Sir Murtagh alleging in all companies. and welcome. (…) Where’s Charlotte Mullen. and she’s to have my farm and my house that my grandfather built. and refused it to him secondly. or perhaps fatal power of seeing his own handiwork with as unflattering an eye as he saw other people’s. an intelligent but plain-looking middle-class Protestant of 40. that he all along meant to pay his father’s debts of honour. Charlotte tries to win the Dysart’s land agent Roddy Lambert for herself. First and foremost. in the bluff. thinking to even herself with the rest of the gentry . . your ladyship”. 55 .
she felt. to Gerald. She could not hope to explain that her youth seemed to her rather theatrical and that she was only young in that way because people expected it.Ioana Mohor-Ivan Irish Literature Elizabeth Bowen (1899-1973): The Last September (1929) o Set in the Naylors’ big house. His intentions burned on the dark an almost invisible trail. in some ideal no-place. .were explanation possible to so courteous. by the time she was his age. For to explain this . ironical and unfriendly a listener . . . She could not conceive of her country emotionally . be disloyal to herself.awakening. She could not hope to assure him she was enjoying anything he had missed. from sleep or preoccupation . (…) He had seemed amazed at her being young when he wasn’t. he might well have been a murderer he seemed so inspired. (…) And she could not try to explain . how after every return . to an illusion both were called upon to maintain. locked in misery between Holyhead and Kingstown .as sometimes when she was seasick. . (…) It must be because of Ireland he was in such a hurry . .to be enclosed in a nonentity. THE LAST SEPTEMBER She shut her eyes and tried . She had never refused a role . even. perfect and clear as a bubble. that she was now convinced and anxious but intended to be quite certain. .would.she and those home surroundings further penetrated each other mutually in the discovery of a lack. . that she had once been happy. it explores their niece Lois Farquahar’s emotional and sexual awakening against the background of the Anglo-Irish War in 1920. 56 . Danielstown. .
poet. Found certainty upon the dreaming air. there that slow man. scholar. A dance-like glory that those walls begot. Back turned upon the brightness of the sun And all that sensuality of the shade A moment’s memory to that laurelled head. When nettles wave upon a shapeless mound And saplings root among the broken stone. Yeats (1865-1939) : Coole Park 1929. 57 . Coole Park and Ballylee 1931 COOLE PARK I meditate upon a swallow’s flight. There one that ruffled in a many pose For all his timid heart. A sycamore and lime-tree lost in night Although that western cloud is luminous. There Hyde before he had beaten into prose That noble blade the Muses buckled on. And yet a woman’s powerful character Could keep a Swallow to its first intent. That seemed to whirl upon a compass-point.3. and those Impetuous men. They came like swallows and like swallows went. traveller. Found pride established in humility. John Synge. take your stand When all those rooms and passages are gone. Shawe-Taylor and Hugh Lane. And dedicate . The intellectual sweetness of those lines That cut through time or cross it withershins. And half a dozen in formation there. Upon an aged woman and her house. Here.Ioana Mohor-Ivan Irish Literature 4. Thoughts long knitted into a single thought.2.2.B.eyes bent upon the ground. A scene well Set and excellent company. Great works constructed there in nature’s spite For scholars and for poets after us. Poetry W. That meditative man.
We were the last romantics . a last inheritor Where none has reigned that lacked a name and fame Or out of folly into folly came. Run underground.all that great glory spent Like some poor Arab tribesman and his tent.chose for theme Traditional sanctity and loveliness. A spot whereon the founders lived and died Seemed once more dear than life. a sound From somebody that toils from chair to chair. and there to finish up Spread to a lake and drop into a hole. Great rooms where travelled men and children found Content or joy. that high horse riderless. Sound of a stick upon the floor. rise in a rocky place In Coole demesne. it sails into the sight And in the morning’s gone.Ioana Mohor-Ivan Irish Literature COOLE AND BALLYLEE Under my window-ledge the waters race Otters below and moor-hens on the top. 58 . Beloved books that famous hands have bound. And every bride’s ambition satisfied. And. So arrogantly pure. Old marble heads. like the soul. Another emblem there! That stormy white But seems a concentration on the sky. Or gardens rich in memory glorified Marriages. whatever most can bless The mind of man or elevate a rhyme. Whatever’s written in what poets name The book of the people. old pictures everywhere. ancestral trees. But all is changes. For Nature’s pulled her tragic buskin on And all rant’s a mirror of my mood: At sudden thunder of the mounting swan I turned about and looked where branches break The glittering reaches of the flooded lake. Run for a mile undimmed in Heaven’s face Then darkening through ‘dark’ Raftery’s ‘cellar’ drop. What’s water but the generated soul? Upon the border of that lake’s a wood Now all dry sticks under a wintry sun. no man knows why. And is so lovely that it sets to right What knowledge or its lack had set awry. alliances and families. a child might think It can be murdered with a spot of ink. And in a copse of beeches there I stood. Though mounted in that saddle Homer rode Where the swan drifts upon a darkening flood. Where fashion or mere fantasy decrees We shift about .
comfortable rooms described as “containing the vestigial of generations” [21. the house is attacked by the Irregulars for favouring the Free State government and burnt to the ground. while at home. eventually burning the house down.3. The ghost of the stablehand and his bride now re-enact the peddler’s conception.B. with its impressive Georgian architecture and large.2. whom the family attempted to defend against the Black and Tans. But. as the ghosts live through their passion and their suffering once more. which span the years 1918 and 1923. 139] and the beliefs that underpin St Leger Alcock’s quasi-feudal utopianism. To his horror the hoof-beats start again. and in an attempt to exorcise guilt and remorse. sent to fight in the Great War under the English flag. are both killed on the front. the individual members of the family as well as the house and the myths sustaining it are “besieged” by history: the two sons. Yeats: Purgatory (1938) o An old peddler and his 16-year-old son return to the ruined big house where the father was conceived. hating his father who had kept him ignorant and made him coarse.3. At the age of 16 the peddler. Betrayed from within. W. The old man relates how his mother married a drunken stable-hand who wasted her inheritance. the period which witnessed to the fall of the old order and the inevitable decline of the Big House in Irish life and culture.Ioana Mohor-Ivan Irish Literature 4. Drama Lennox Robbinson (1886-1958): The Big House (1926). 59 . turn against their Protestant neighbours. At the beginning of the play. (Killycregs in Twilight (1937) o The Big House offers four scenes from the recent life of a Big House family. he stabs his own son with the knife he used on his father. the villagers. the myths of the Ascendancy sustain both the appearance of the house. which makes him revel in the privileged position of Ballydonal as symbol of the Anglo-Irish culture in the community and in his own role as paterfamilias to the surrounding peasant villagers. the Alcocks of Ballydonal House in County Cork. through the course of the play. killed him on the night of the fire.
And he squandered everything she had. . being dead. Or came from London every spring To look at the may-blossom in the park.) OLD MAN. if upon themselves.) Listen to the hoof-beats! Listen. Looked at him and married him. they know at last The consequence of those transgressions Whether upon others or upon themselves. to kill a house Where great men grew up. OLD MAN. Great people lived and died in this house. Had loved the house. died. But now she knows it all. . and long ago Men that had fought at Aughrim and the Boyne. There is no help but in themselves And in the mercy of God. had loved all The intricate passages of the house. OLD MAN. because She died in giving birth to me. I have had enough! Talk to the jackdaws. if talk you must. Some that had gone on Government work To London or to India came home to die. . Upon others. Captains and Governors. colonels. But there are some That do not care what’s gone. Re-live Their transgressions. drink and women. BOY. . BOY. and that not once But many times. members of Parliament. (. She never knew the worst. what’s left: The souls in Purgatory that come back To habitations and familiar spots. ( . Magistrates.Ioana Mohor-Ivan Irish Literature PURGATORY OLD MAN. married. Your wits are out again. They had loved the trees that he cut down To pay what he had lost at cards Or spent on horses. others may bring help. For when the consequence is at an end The dream must end. listen! 60 . I here declare a capital offence. But he killed the house. Stop! Sit there upon that stone. That is the house where I was born.
And if he touch he must beget And you must bear his murderer. (..) BOY.there -there . What if I killed you? You killed my grand-dad. . I cannot hear a sound. . And that I could not talk and see! You have been rummaging in the pack. How quickly it returns . Beat! Beat! This night is the anniversary Of my mother’s wedding night.] (. .) OLD MAN. That beast there would know nothing. . .Ioana Mohor-Ivan Irish Literature BOY.there[He stabs again and again.) 61 . . My father is riding from the public-house. But you are in the light because I finished all that consequence. A whiskey-bottle under his arm.) OLD MAN: Do not let him touch you! It is not true that drunken men cannot beget. OLD MAN.beat -! Her mind cannot hold up that dream. [He stabs the boy. the window is dark again.. Deaf! Both deaf! If I should throw A stick or a stone they would not hear. Begot and passed pollution on.. I killed that lad because had he grown up He would have struck a woman’s fancy. being nothing.] ( . .) Dear mother.. . (.. The window grows dark.. If I should kill a man under the window He would not even turn his head.beat . Or of the night wherein I was begotten. (. [A window is lit showing a young girl.] My father and my son on the same jack-knife! That finishes .) Hoof-beats! Dear God. And that’s proof my wits are out. ( . Now I am young and you are old. And she must animate that dead night Not once but many times! ( . Because you were young and he was old. My bag of money between your fingers. Twice a murderer and all for nothing.) Come back! Come back! And so you thought to slip away.
Over the years. Stands there staring beyond at that black veil lips quivering to half-heard words. . who has oppressed his children in his need for absolute authority. he all but said of loved ones. Dying on. . Empty for the moment. Never but the one matter. Umbrellas round a grave. Streaming black canopies. District Justice O’Donnell. Move on to other matters. . is aware of the decline and is the only one to experience a sense of loss. The dead and gone. That place beneath. . Beyond that black beyond. . So stands there facing blank wall. Rain bubbling in the black mud. To other matters. . . (…) Grey light. Rain pelting. . Eamon. .): Aristocrats (1979) o Friel’s play permutes a Catholic family into a big house setting. . Gone. . Whose? Fade. Ghost graves. The wedding of the youngest daughter Claire to a small local greengrocer coincides with the death of the patriarch of the family. Brian Friel (1929 . The dying and the going. Seen from above. Ghost nights. . (…) Thirty thousand nights of ghosts beyond. as the play moves slowly and lyrically towards an extended scene of Chekhovian leavetaking where the members of the family say goodbye to each other and to their past. Years of nights. he all but said which loved one? . Down one after another. now “dead and gone”. Treating of other matters. . Pictures of . . in order to chronicle its disintegration at a reunion in Ballybeg Hall. . . Black ditch beneath.Ioana Mohor-Ivan Irish Literature Samuel Beckett (1906-1989): A Piece of Monologue (1979) o The lonely speaker’s memories recall familiar pictures of the Protestant Ascendancy. Try to move on. A PIECE OF MONOLOGUE Covered with pictures once. Gone. Torn to shreds and scattered. . married into the family. No more no less. . Coffin out of frame. . he all but said ghost loved ones. Ghost light. Ghost rooms. Which . Ghost . . 62 . Waiting on the rip words.
variously seen as Romantic Golden Age or peasant community has been discursively used to signify the nation. the native representational range for Irishness has mainly nurtured on the pastoral. it attempts a failed insurrection in 1867. leading to his split with catholic clergy and condemnation by British public. soon to become the Home Rule League. 5. 1870 the Home Government Association. a splinter group from O'Connell's repeal association. THE PASTORAL MODE: Archetypal human response to the countryside. is founded by Isaac Butt 1875 Charles Stewart Parnell enters parliament. the Gaelic league is founded by Douglas Hyde • • • • • 5. or as rural simplicity and morality to be contrasted to the present urban existence. a secret insurrectionary group. he soon assumes leadership of the Home Rule League from Butt 1886 the first Home Rule bill is defeated in parliament 1889 Parnell is named co-respondent in O’Shea divorce petition.2. attempt a failed insurrection 1858 the Irish Republican Brotherhood.e. expressed in legends. under the leadership of James Stephens. If the Anglophone view has invariably constructed the Irish identity as the negative term of the basic opposition established between barbarism and civilisation.Ioana Mohor-Ivan Irish Literature CHAPTER 5 – THE PASTORAL IN IRISH LITERATURE 5. Irish independence is translated in terms of the country’s distinctive cultural inheritance (i. viewed either as a mythic Golden Age. POLITICAL NATIONALISM • • 1848 the Young Irelanders.1. Celtic). CULTURAL NATIONALISM: main premises The essential. Language bears the gifts of the past into the present and supplies a living link with a racial spirituality. spiritual life of a people subsists in its culture. 1893 the second Home Rule bill is defeated in parliament. literature and songs. 63 . is formed out of the Fenian Movement. and rural Ireland.3.
Matthew Arnold and the Celtic Revival. containing "Balder Dead. the Englishman’s work sets out to provide a list of attributes pertaining to the Celtic race. 23 Quoted from J. Kelleher. Essays in Criticism. On Translating Homer (1861 and 1862). Indeed. bravery in defeat.V. 197. Cairns and S. 22 Quoted from D. 210. God and the Bible (1875)." Merope (1858). having ineffectualness and selfwill for its defect 23 . is just hat the Celt has least turn for . 46-47.2. "Dover Beach. containing "Thyrsis. consequently. paying thus the Celtic world the first valuable compliment it had received from an English source in several hundred years 21 . in Perspectives in Criticism. had advanced the notion of the Celt as the producer of civility and culture within the mutually interdependent Indo-European family of races. emerging in the second half of the 19th century. He also wrote some works on the state of education in mainland Europe.Ioana Mohor-Ivan Irish Literature 5." "The Weary Titan. 2nd Series (1855). 1971. pp. op. as in material civilisation he has been ineffectual. so has the Celt been ineffectual in politics 24 . indifference to fact.." "Rugby Chapel. .4. CELTICISM: Cultural discourse on the Irish identity. Matthew Arnold developed this view in the context of British cultural imperialism. influenced by Matthew Arnold’s lectures collected and published as On the Study of Celtic Literature (1876) 5. it lacks the capacity for political self-government: the skillful and resolute application of means to ends which is needed both to make progress in material civilisation and also to form powerful states. Richards. power." and "The Scholar Gypsy. Literature and Dogma (1873). New Poems (1867)." in prose.4. Last Essays on Church and Religion (1877)." "A Southern Night. Poems (1853). edited by Harry Levin. 24 Ibid. On the Study of Celtic Literature (1867). p. because. . Irish Essays (1882)." and his masterpiece. sensitivity to verbal and musical magic. Kelleher. and Discourses in America (1885). 2nd Series (1888).4.1. but his intention is far from being that of outlining these virtues as the basis of a separate Celtic culture and. Matthew Arnold (1822 – 1888): poet and cultural critic. Careful to put a politically independent future for the Celts beyond the bounds of possibility. drawing on contemporary philological discourses. Arnold argues that it is not in the outward and visible world of material life that the Celtic genius of Wales and Ireland can at this day hope to count for much 22 . Culture and Anarchy (1869). 21 64 . 5. Essays in Celtic Literature (1868). emphasising the qualities of melancholy. which.. On the Study of Celtic Literature (1876) is influenced by the thesis propounded by Ernest Renan in his Poésie des Races Celtique. His principal writings are: in poetry." Poems. op. Chicago. containing "Sohrab and Rustum. John V. other-worldliness. cit. Mixed Essays (1879). cit. p.
cit.Ioana Mohor-Ivan Irish Literature Arnold’s aim is ultimately that of getting his fellow Englishmen accept that an invigorated British culture may stem only of the blending of the positive aspects of Saxon common sense and steadfastness 25 with Celtic sensibility..by the needs of the “masculine” Saxons. . Richards.3 Celt / Saxon dichotomies: ENGLISH Saxon material reasoned realist objective scientific modern masculine IRISH Celt spiritual emotional idealist visionary mystic primitive feminine The Oxford Companion to Irish Literature. p. 47. . p. London: Faber and Faber.. As Cairns and Richards note. and Spenser’s dichotomy between the English order and the Irish lawlessness was re-written as that between Saxon pragmatism and Celtic spirituality: 5. op. and the Celt is peculiarly disposed to feel the spell of the feminine idiosyncrasy 28 . we may use German faithfulness to Nature to give us science and to free us from insolence and self-will. the importance of Arnold’s study resides with the fact that the critic managed to produce a context for the cultural incorporation of the Celts which flattered them into accepting a subsidiary position for themselves vis-àvis the English 27 . 48. 1985. Oxford: Oxford U. have something feminine in them. 26 Quoted from D. Celtic Revivals: Essays in Modern Irish Literature. we may use the Celtic quickness of perception to give us delicacy and to free us from hardness and Philistinism 26 . 29 Consequently.P.. the recognition of the values of their cultural products being a ‘healing measure’ in Anglo-Irish relations on the cultural plane. one major outcome of the English critic’s study was that of introducing the ‘Celtic’ idea as a differentiating fact between Ireland and England. 25 65 . its nervous exaltation. 49. 28 Ibid.. 27 Ibid. edited by Robert Welch. p.4. p. According to Seamus Deane. 1996. 29 Seamus Deane. managing to give this word a political resonance it has not yet entirely lost. the centrality of the Celts within the British culture was guaranteed through this resort to the categories of sexuality . due to the fact that the sensibility of the Celtic nature. which would provide the only antidote to what he calls the Philistinism of modern economic society: . 21. it was accepted that the Celtic spirit was utterly different from the Saxon one. Cairns and S. More than this.
. These social changes found a counterpart in the distinct culture which this class evolved in response to these novel social and economic factors. antagonistic to the Anglo-Saxon. . general endorsement of celibacy outside marriage and postponement of marriage in farmers’ families until the chosen heir was allowed by the father to take possession of the farm [ .. seen as masculine. Cairns and Richards note: . and. cit. were spared in the main by the failure of the potato crops. a social tragedy that had its greatest impact on the Catholic poor. while by 1851 statistics showed that Ireland had lost one quarter of its population. Cairns and S.1. pressure on them to observe strict chastity and not. Consequently the Gaeltacht people of the rural west were turned into the ideal of Irishness. Cambridge U..5. during the latter half of the 19th century. By 1847 large numbers of small farmers were obliged to emigrate to the United States. Cambridge. While the northern rural areas. warrior-like. . this Gaelic idea of Irishness soon came to fuse with the other important discourse shaping rural Ireland. becoming endowed with every virtue known to Gaelic civilisation. the Famine enhanced once more the differences between the Irish Catholic south and the mainly Scots Presbyterian north. Richards. According to Hugh Kearney (The British Isles: A History of Four Nations. warrior-like.P. 1989). social and cultural accommodations with the new circumstances brought by the simplification of rural social relations. who became the most numerous class in the land. namely familism 30 . antagonistic to the Anglo-Saxon. ]the spread of matchmaking as a preliminary to marriage. pressure on ‘surplus’ sons and daughters to emigrate. o Institutions like the Gaelic Athletic Association (founded in 1884 as a powerful rural network emphasising physical training). due to their contrasting experiences. caused by the decline in number and importance of the landless labourers. FAMILISM: The Great Potato Famine which had struck Ireland in 1846. were the main element of popular diet was oats. the Irish countryside underwent a complex series of economic. 5.5. and the rise in prominence of the tenant farmers. marked by a series of practices and procedures. 30 31 66 . and. o On the other hand. the southern ones of small farming and labouring classes. including the imposition and perpetuation of strict codes of behaviour between men and women. heavily dependant on the potato.Ioana Mohor-Ivan Irish Literature 5. op. extend and transmit family holdings from generation to generation. were decimated by starvation and disease. had led to a sudden drop in population among the rural Catholic class 31 . which the tenant-farmers used in order to consolidate. or the Gaelic League (established nine years later and mainly dedicated to the revival of the Gaelic language) promoted a definition of Irishness based on the Gael. Chapters 3 and 4. either by emigration or by death. . collectively termed familism. a number of procedures to control access to marriage. “GAEL”-ICISM: o Cultural discourse emerging in opposition to Celtism o Promoted by the members of the Gaelic League o Irish identity based on the “Gael”: masculine. Among these practices. consequently. as a consequence. See D.
35 Declan Kiberd. cit. GAEL / SAXON DICHOTOMIES: IRISH Gael Irish language Brehon law Gaelic football Catholic moral manly rural ENGLISH Saxon English language* English law* soccer* Protestant corrupt effeminate urban D. 32 The codes of belief and behaviour upon which familism rested. . Inventing Ireland. such as the assumed spirituality and anti-materialism of the Irish.Ioana Mohor-Ivan Irish Literature through following their own desires. but any valued cultural possessions of the English were shown to have their Gaelic equivalents 35 . and unquestioned patriarchal authority 33 . 1996. Foster. shows how this definition of Irishness mainly aimed at projecting the country as not-England. 42-43. hence the merging of the two provided the additional marks of identity to the Gaelic Irishness. In this view. 151.2. 1989. . * These categories are presented in Kiberd’s study as instances of “national parallelism” 32 33 67 . . the rural definition of Irishness deployed linguistic. Thus. Inventing Ireland: The Literature of the Modern Nation. Richards.5. Modern Ireland: 1600-1972. but also as a code for anti-Englishness 34 . religious and moral categories not only as criteria of national identity. p. anything English could not be but a corrupting influence on the Gaelic mentality. where anything English was ipso facto not for the Irish [.. ]. 34 R. particularly the regulation of sexuality. F. . 5.. to risk the transmission of the farm under unfavourable circumstances through a mésalliance . London: Penguin Books. Declan Kiberd in his study of modern Irish literature and culture. 449. p. while retaining what were perceived as positive characteristics of Celticism. p. were also discursively controlled by Catholicism. 60. London: Vintage. Ibid. pp. op. Cairns and S.
5.6. which served as the stage for many new Irish writers and playwrights of the time. dramatist. Yeats (1865-1939) Poet. as distinct from English culture. B. Main representatives: 5.6. The movement also encouraged the creation of works written in the spirit of Irish culture. After the establishment of the Irish Free State. They have the spade over which man has leant from the beginning. in part. as distinct from English culture. becoming thus the primary driving force behind the Irish Literary Revival – a movement which stimulated new appreciation of traditional Irish literature. who have steeped everything in the heart: to whom everything is a symbol. mystic and public figure. W. encouraging the creation of works written in the spirit of Irish culture. pain and death has cropped up unchanged for centuries. Introduction to “Fairy and Folk Tales of the Irish Peasantry”(1888) These folk-tales are full of simplicity and musical occurences. which is prose and a ‘parvenue’. for they are the literature of a class for whom every incident in the old rut of birth. love.Yeats was also co-founder of the Abbey Theatre. 68 . THE IRISH LITERARY REVIVAL o The Irish Literary Revival stimulated new appreciation of traditional Irish literature. He was awarded the Nobel Prize in Literature in 1923 for what the Nobel Committee described as "his always inspired poetry. another great symbol of the literary revival.Ioana Mohor-Ivan Irish Literature 5.1. Yeats was appointed to the first Irish Senate Seanad Éireann in 1922 and re-appointed in 1925.6. Yeats was born to an Anglo-Irish Protestant family. which in a highly artistic form gives expression to the spirit of a whole nation". which served as the stage for many new Irish writers and playwrights of the time.1. o It was influenced by both celticism and gaelicism. The people of the cities have the machine. but turned into a committed Irish nationalist.1. This was. due to the political need for an individual Irish identity. An important symbol of the literary revival became the Abbey Theatre.
Douglas Hyde (1860-1949) (Irish: Dubhghlas de hÍde) Hyde was an Anglo-Irish scholar of the Irish language and founder of the Gaelic League. We hope to find in Ireland an uncorrupted and imaginative audience. 5. Her home at Coole Park. He also served as the first President of Ireland from 1938 to 1945.3.6.6. He also wrote one-act plays in the Irish language which were staged by the Irish Literary Theatre and then by the Abbey. The Necessity for De-Anglicising Ireland. County Galway served as an important meeting place for the leading Revival figures and her early work as a member of the board of the Abbey was at least as important for the theatre's development as her creative writings were. which whatever be their degree of excellence. will be written with a high ambition. and wrote numerous short works for both companies.1. We sill show that Ireland is not the home of buffoonery and easy sentiment. 5. and without which no new movement in art or literature can succeed. she co-founded the Irish Literary Theatre and the Abbey Theatre.1. and that freedom of expression which is not found in the theatre in England. and so to build up a Celtic and Irish school of dramatic literature. literature and even in dress. 69 . However. as it has been represented.2. She also produced a number of books of retellings of stories from Irish mythology. Lady Gregory is mainly remembered for her driving force of the Irish Literary Revival. Isabella Augusta. and believe that our desire to bring upon the stage the deeper thoughts and emotions of Ireland will ensure for us a tolerant welcome. Lady Gregory (1852-1932): With William Butler Yeats and others. trained to listen by its passion for oratory. argued that Ireland should follow her own traditions in language.Ioana Mohor-Ivan Irish Literature from Manifesto for the establishing of the Irish Literary Theatre (1897) We propose to have performed in the spring of every year certain Celtic and Irish plays. but the home of an ancient idealism. His famous pamphlet.
nevertheless protesting as a matter of sentiment that they hate the country which at every hand’s turn they rush to imitate. with Rory O’Moore. everything that is English. that connected it with the Christianisers of Europe.(…. music. then the school of Europe and the torch of learning. cut off from the past. and even to some extent with the men of ’98. the sword of the Norman. we mean it.) I shall endeavour to show that this failure of the Irish people in recent times has been largely brought about by the race diverging during this century from the right path. the wile of the Saxon were unable to perform. and hastening to adopt. It has lost all that they had . that the Ireland of today is the descendant of the Ireland of the seventh century. and is. that connected it with Brian Boru and the heroes of Clontarf. but rather to show the folly of neglecting what is Irish. I should also like to call attention to the illogical position of men who drop their language to speak English. still going on. it finds itself deprived and striped of its Celtic characteristics. I shall attempt to show that with the bulk of the people this change took place quite recently..language.) What we must endeavour to never forget is this. in fact. of men who read English books.Ioana Mohor-Ivan Irish Literature from THE NECESSITY FOR DE-ANGLICISING IRELAND (1892) When we speak of ‘The necessity for De-Anglicising the Irish Nation’. simply because it is English. and just at the moment when the Celtic race is presumably about to largely recover possession of its own country. yet scarcely in touch with the present.) What the battleaxe of the Dane. pell-mell. and indiscriminately. (. . . much more recently than most people imagine. genius and ideas. . traditions. not as a protest against imitating what is best in the English people. It has lost since the beginning of this century almost all that connected it with the era of Cuchullain and of Ossian. of men who translate their euphonious Irish names in English monosyllables. we have accomplished ourselves. for that would be absurd. We have at last broken the continuity of Irish life. 70 . . and know nothing about Gaelic literature. and ceasing to be Irish without becoming English. with the Wild Geese.(. with the O’Neills and O’Donnells.
When Bartley’s body is returned. Maurya. poet. however. Synge's writings are mainly concerned with the world of the Irish-speaking peasants of rural Ireland (Gaeltacht) and with what he saw as the essential paganism of their world view. Once she is gone. prose writer. from the tinkers to the clergy. who has lost her husband and five of her six fishermen sons to the sea. and where a country loses its humour. a form of cancer that was untreatable at the time and died just weeks short of his 38th birthday. and they live in ‘the last cottage at the head of a long glen in County Wicklow’. as Baudelaire’s mind was morbid. and collector of folklore. Michael Dara. Riders to the Sea (1904): a one-act play which tells of an old woman. from the Preface to “The Tinker’s Wedding”: Of the things which nourish the imagination humour is one of the most needful. 71 . Michael is hatching plans for Dan’s legacy and Nora’s thoughts are taking on an unexpected dark complexion. while Dan and Michael compliment each other over whiskey. but then she leaves the Tramp alone in order to call to a young neighbouring sheep farmer.7. the old woman transcends her agony by accepting her loss. J.M.Ioana Mohor-Ivan Irish Literature 5. I do not think that these country people.1. 5. and it is dangerous to limit or destroy it. have still a life. 5. Baudelaire calls laughter the greatest sign of the Satanic element in man. as the people in every country have been laughed at in their own comedies. and who earnestly begs the last – Bartley – not to undertake a treacherous crossing to sell a pig on the mainland. Synge (1871 – 1909) Dramatist. He shares his suspicions and his schemes with the Tramp and assumes his sham death-pose before Nora and Michael enter. as some towns in Ireland are doing.1. dripping in a sailcloth.2. soothing her with fine words to win her over to a life on the road. a sheep farmer many years her elder. Dan shams his death because he suspects Nora to be ‘a bad wife’. there will be morbidity of mind.7. They leave together. when the old man rises up and banishes his wife from the house.1. The Tramp takes up her cause. Synge was a key figure in the Irish Literary Revival and was one of the cofounders of the Abbey Theatre.7. In the Shadow of the Glen (1902): Nora Burke is married to Dan.1. Although he came from a middle-class Protestant background. 7. the whole people. He suffered from Hodgkin's disease. Dan Burke sits up. who have so much humour themselves. and a view of life that are rich and genial and humorous. A passing Tramp begs shelter from the wet night and the woman lets him in. Plays: 5. In the greater part of Ireland. will mind being laughed at without malice.
(CATHLEEN stops her wheel with a sudden movement. oil-skins.NORA (a younger daughter). then wipes her hands. the way she won’t know of them at all. with nets. and come in before we’d done. Herself does say prayers half through the night. MAURYA comes from the inner room. Nora. if she’s able.) Shall I open it now? CATHLEEN: Maybe she’d wake up on us. for she’ll be getting her death.) It’s a long time we’ll be. ‘with no son living. BARTLEY (her son).) CATHLEEN (spinning the wheel rapidly): What is it you have? NORA: The young priest is after bringing them. and puts it down in the pot-oven by the fire.) CATHLEEN (looking out anxiously): Did you ask him would he stop Bartley going this day with the horses to the Galway fair? NORA: ‘I won’t stop him. CATHLEEN goes up a few steps and hides the bundle in the turf-loft. a young girl. ‘If it’s Michael’s they are’ says he. (Cottage kitchen. CATHLEEN: How would they be Michael’s.’ CATHLEEN: Is the sea bad by the white rocks.) 72 . ‘you can tell herself he’s got a clean burial by the grace of God.’ says he. God help us. ‘but let you not be afraid. finishes kneading cake. CATHLEEN: Give me the ladder. There’s a great roaring in the west. and leans out to listen. a girl of about twenty. (She goes ever to the table with the bundle. Cathleen. CATHLEEN (her daughter). She’ll be coming in a minute.’ says he. and if they’re not his. and begins to spin at the wheel. An island off the West of Ireland.MEN and WOMEN. ‘with crying and lamenting. (NORA comes in softly. NORA (goes to the inner door and listens): She’s moving about on the bed.(They put the ladder against the gable of the chimney. Nora? NORA: Middling bad. and the two of us crying.) NORA (in a low voice): Where is she? CATHLEEN: She’s lying down. and it’s worse it’ll be getting when the tide’s turned to the wind.Ioana Mohor-Ivan Irish Literature RIDERS TO THE SEA CHARACTERS: MAURYA (an old woman). let no one say a word about them.’(The door which NORA half closed is blown open by a gust of wind. some time herself will be looking by the sea. (Coming to the table. It’s a shirt and a plain stocking were got off a drowned man in Donegal. spinning wheel. and takes a bundle from under her shawl. SCENE. etc.) NORA: We’re to find out if it’s Michael’s they are. and I’ll put them up in the turf-loft. some new boards standing by the wall. puts her head in at the door. and may be sleeping. How would he go the length of that way to the far north? NORA: The young priest says he’s known the like of it. Nora. and the Almighty God won’t leave her destitute. God help her.’ says he. and maybe when the tide turns she’ll be going down to see would he be floating from the east.
(NORA picks up the turf and puts it round the pot-oven.. were lost in the great wind. . and Shawn. for his body is after being found in the far north. and in by that door. I was sitting here with Bartley.with fine clothes on him. and I could say nothing. for I won’t live after them. and he’s got a clean burial by the grace of God. but they’re gone now the lot of them. Bartley came first on the red mare. NORA: Didn’t the young priest say the Almighty God wouldn’t leave her destitute with no son living? MAURYA (in a low voice. the girls start as if they heard something through the door that is half open behind them. and carried up the two of them on the one plank. though it was a hard birth I had with every one of them and they coming to the world . . as if to hide something from her eyes.) The Son of God spare us. He went by quickly.Ioana Mohor-Ivan Irish Literature MARYA (looking up at CATHLEEN and speaking querulously): Isn’t it turf enough you have for this day and evening? CATHLEEN: There’s a cake baking at the fire for a short space (throwing down the turf) and Bartley will want it when the tide turns if he goes to Connemara. . . and ‘the blessing of God on you. Cathleen? Did you hear a noise in the north-east? CATHLEEN (in a whisper): There’s some one after crying out by the seashore. (She puts up her hands. but clearly): It’s little the like of him knows of the sea . There was Patch after was drowned out of a curagh that turned over. It wasn’t Michael you seen.’ but something choked the words in my throat. and I tried to say ‘God speed you. and his own father again. lying on my two knees. .) NORA (in a whisper): Did you hear that. and new shoes on his feet.(She pauses for a moment. MAURYA (continues without hearing anything): There was Sheamus and his father. and I stood there saying a prayer to myself. and let you call in Eamon and make me a good coffin out of the white boards. and not a stick or sign was seen of them when the sun went up.. I looked up the. . at the grey pony. It’s destroyed. Nora! CATHLEEN: What is it you seen.) (. MAURYA: I seen Michael himself.’ says he. Bartley will be lost now.six fine men. and he riding and galloping.and some of them were found and some of them were not found.. surely. and I crying. and 73 . Then Bartley came along. were lost in a dark night. I’ve had a husband. and he a baby.) MAURYA: I went down to the spring well.. CATHLEEN (begins to keen): It’s destroyed we are from this day. and there was Michael upon it . CATHLEEN (speaking softly): You did not. and he riding on the red mare with the grey pony behind him. There were Stephen. mother. MAURYA (a little defiantly): I’m after seeing him this day.. and found after in the Bay of Gregory of the Golden Mouth. and six sons in this house . and a husband’s father.
two blind beggars have been led to believe that they are beautiful by the lies of the townsfolk. it’s hard set his own mother would be to say what man was it. . and there were men coming after them. . laid on a plank. NORA looks out. God rest his soul. MAURYA stands up slowly and takes them in her hands. 74 .1. and four women coming in. crossing themselves on the threshold. and must hire themselves out for manual labour to survive. for when a man is nine days in the sea. and not saying a word. (She pauses again with her hand stretched out towards the door. when in fact they are old and ugly. CATHLEEN: It is Michael.4.and leaving a track to the door.7. and they holding a thing in the half of a red sail.7. Blindness descends on them once more.it was a dry day. (Two younger WOMEN come in and pull out the table. and he was washed out . CATHLEEN (in a whisper to the women who have come in): Is it Bartley it is? ONE OF THE WOMEN: It is surely. Molly. The Well of the Saints ( 1905): Martin and Mary Doul. but she viciously rejects him. for they’re after sending us a bit of his clothes from the far north. A saint restores their sight with water drawn from a well in a ‘place across a bit of the sea. having ‘seen’ the ill-will of those around them. with a bit of sail over it.1. (She reaches out and hands MAURYA the clothes that belonged to Michael. and lay it on the table.) MAURYA (half in a dream. where there is an island’. Then men carry in the body of Bartley. and when he is found there how could he be here in this place? MAURYA: There does be a power of young men floating round in the sea. and water dripping out of it . and they crossing themselves.) CATHLEEN (to the women.Ioana Mohor-Ivan Irish Literature I seen two women. God spare him. and what way would they know if it was Michael they had. and three women. decided to embrace a life on the roads. and Timmy sends him away.) NORA: They’re carrying a thing among them and there’s water dripping out of it and leaving a track by the big stones. Nora . Martin goes to work for Timmy the smith and tries to seduce his betrothed. They are now able-bodied.3. I looked out then. or Michael. and kneeling down in front of the stage with red petticoats over their heads. . 5. The couple refuse the cure this time. or what is it at all? CATHLEEN: Michael is after being found in the far north. the saint goes to restore their sight a second time. and the wind blowing. or another man like him. to CATHLEEN): Is it Patch. . It opens softly and old women begin to come in. as they are doing so): What way was he drowned? ONE OF THE WOMEN: The grey pony knocked him into the sea. The Tinker’s Wedding (1906) 5.
I just riz the loy and let fall the edge of it on the ridge of his skull. Mayo village and wins the hearts of the local women by boasting that he has killed his father. the servile son. and never a day’s work but drawing a cork an odd time. still a great deal more that is behind it is perfectly serious when looked at in a certain light. and Pegeen Mike is left to lament her loss of ‘the only playboy of the western world’. a pathetic. for doing the like of that. or rinsing out a shiny tumbler for a decent man. His prowess at the local sports confirms him in the role of a hero and as fitting mate for Pegeen Mike. . . disdainful of the gullible Mayo peasants. then. a widower who owns the country pub where Christy stays. several sides to ‘The Playboy’. has been transformed into a figure of power and dignity by this rite of passage. Escaping from their clutches. . Pegeen [with blank amazement]: Is it killed your father? Christie [subsiding] With the help of God I did. and never let a grunt or groan from him at all. Tuesday was a week. despite his offer to ‘slay his da’ a second time. but although parts of it are. Glory be to God! Michael [with great respect] That was a hanging crime. the way I couldn’t put up with him at all. and I stalking around. Christy. FROM THE PLAYBOY OF THE WESTERN WORLD (1907) . not a play with a ‘purpose’ in the modern sense of the world.5. 1) Christie [twisting round on her with a sharp cry of horror]: Don’t strike me. . . . Shawn Keogh. . . and he getting old and crusty. Christy woos Pegeen Mike away from her cousin. in place of my old dogs and cats. and the two leave the stage. Irish Literature The Playboy of the Western World (1907): it tells how Christy Mahon arrives in a Co. 2) Christie: . [He takes the 75 . the community turn upon their hero. You should have had good reasons for doing the like of that.] Christie: I did not.Well. or wiping a glass. Christie [in a very reasonable tone]: He was a dirty man. it may be hinted. Jimmy: Oh. There are. he tames his father.Ioana Mohor-Ivan 5. and that the Holy Immaculate Mother may intercede for his soul. Pegeen: And you shot him dead? [. The play was condemned by nationalists as a travesty of western Irish life which evoked a peasantry of alcoholics and ineffectual fantasists rather than a people ready to assume the responsibilities of self-government. When the supposedly murdered father enters the scene. mister honey. and he went down at my feet like an empty sack. priest-fearing peasant. by his fine talk and athletic feats.1. I killed my poor father.7. this’d be a fine place to be my whole life talking out with swearing Christians. daughter of Michael James (Flaherty). God forgive him. smoking my pipe and drinking my fill. or are meant to be extravagant comedy. surely. Philly [retreating with Jimmy]: There’s a daring fellow.
.] 3) Christie [impressively]: With that sun came out between the cloud and the hill. and I gave a lep to the east. but what’s a squabble in your back yard. the way I’ll go romancing through a romping lifetime from this hour to the dawning of the Judgement Day. for you’ve turned me a likely gaffer in the end of all. and I after doing it this time in the face of all? Pegeen: I’ll say. And won’t there be crying out in Mayo the day I’ll stretch upon the rope. Deirdre (1910) 76 . with his mighty talk. if I’ve had to face the gallows. laid him stretched out. then sits down in front of it and begins washing his face]. [He raises the chicken bone to his Adam’s apple.’ says he. and the blow of a loy. I was handsome. ‘God have mercy on your soul. .[.]If I can wring a neck among you. surely! 4) Christie [to Pegeen]: And what is it you’ll say to me. Susan: That’s a grand story. Christie [flattered and confident. for. raising the loy. and I hit a blow on the ridge of his skull. the way I’ll have a soft lovely skin on me and won’t be the like of the clumsy young fellows do be ploughing all times in the earth and dung. would twist a squint across an angel’s brow. God bless you! You’re the lad. a strange man is a marvel. [.1. lifting a scythe. I tell you.Ioana Mohor-Ivan Irish Literature looking-glass from the wall and puts it on the back of a chair.7. Didn’t I know rightly. I’ll have a royal judgement looking on the trembling jury in the courts of law.] Girls [together]: Well.6. and he split to the knob of his gullet. That’s your kind. Honor: He tells it lovely. I’ll have a gay march down. [His voice rising and growing stronger]. is it? Then let the lot of you be wary. and it shining green on my face. . and I’ll be growing fine from this day. [. and they rhyming songs and ballads on the terror of my fate? 5) Christie: Ten thousand blessings upon all that’s here. .] Christie: You’re blowing for to torture me. though it was the divil’s own mirror we had beyond. waving bone]: He gave a drive with the scythe. . ‘Or on your own. with ladies in their silks and satins snivelling in their lacy kerchiefs. . have taught me that there’s a gap between a gallous story and a dirty deed. 5. Then I turned around with back to the north. you’re a marvel! Oh. and shed the blood of some of you before I die.’ says I.
Ioana Mohor-Ivan Irish Literature 5. The Land embodied a theme of intimate and recognisable social significance in its real setting. o A play focusing on peasant characters. It was this latter version of the peasant play which became the popular genre of the Irish theatre after the Independence. shame and poverty. set at the end of the Land Wars. while the relatively dull and unenterprising Sally Cosgar and Cornelius Duras remained behind to marry and succeed their parents. dealt with the generational conflicts between Murtagh Cosgar and his son. untouched by modern forms of life. conflicts between fathers and sons. and though love was presented as a disruptive force. the traditional subjects and style of the peasant play remained in the limelight of the Abbey stage helped by successive playwrights like George Shiels. a metaphor for progress which is set into violent contrast to the traditional notions of law and order based on colonialist conditions marked by the Irish tolerance for lawlessness and contempt for the informer. Colum’s Broken Soil (1903). While the pastoral idyll became the focus of satire in plays such as Denis Johnston’s The Moon in the Yellow River (1931). Mat left behind the land for which his father had fought so hard to keep intact. driving Mairie into a loveless marriage in order to save her family. an instinctive artist and wanderer brings his daughters endless worry. emigration. or John B Keane. Shiel’s The Rugged Path (1940) introduced the audience into a peasant cottage setting provided with electric light and a radio. Bryan MacMahon. The Land (1905). Theatre as a means for the selfexpression of a rural society had followed the social changes underwent by the class representing it.8. C. Murray changed the peasant play’s focus on the seamy side of the farmers’ lives: agrarian disputes. Where Synge exploited the image of the Irish tramp as a symbol of imagination and freedom. THE PEASANT PLAY: o A dramatic subgenre established during the 20th century on the Abbey stage. the peasants had been discovered as a kind of primordial rural society.) Rural Ireland started to display gloomier contours once Padraic Colum. depicting their lives. Con Hourican. o Characteristic features: peasant cottage setting. Like the previous play. in the beginning of the dramatic movement. Tom Coffey. John Murphy. the fight for landownership. Lennox Robinson and T. Moreover. Mat. habits and ownership of lands. Pressed by the ambitious school-teacher Ellen Douras to seek his fortune by emigrating to America such as all of his elder brothers had attempted. habits and customs in a manner true to life. The members of the Tansey family become the microcosm within which the play explores the two contrasting 77 . over the value of the old rural way of life. If. the unhappiness of matches made to conform to the dictates of familism. it raised the question of the worth of the fields won after the Land War in the changing conditions of the countryside where the fittest chose emigration. as landowners and citizens of an independent nation they could no longer play this role. it was not improper. revised as The Fiddler’s House (1907) showed his audiences the real cost involved in having one in the family. peasant life themes (rural marriage.
The Field (1965) treats a similar theme like that of Shiel’s The Rugged Path. While the older generation are afraid to accuse them partly because of their fear of retribution and partly because of the old prejudice against informing. “Economic Development 1958-1985” in Kieran A. But. having left fifteen years ago for America. but for the values of rural existence and even the flaw in his character. 78 . The play’s nostalgic stance towards rurality as an embodiment of what T. in The Field the villagers do not inform. The play. helping thus Curly learn the lesson and remain by the farm. John Murphy’s The Country Boy (1959) picked up the thread of the story from where The Land had left it by focussing on the figure of the returned emigrant. Cork and Dublin: Mercier. 1986. is finally revealed as a virtue: it is the test of Curly’s resolution. the homecomer who.Ioana Mohor-Ivan Irish Literature attitudes related to rural violence. Where Colum’s play looked at the causes leading to the rural exodus. and the picture of the rural world is harsh and joyless. Whitaker calls a sort of Paradise Lost 36 ensures the happy ending whereby exposure to his forsaken roots in the country prompt Eddie undergo a recognition crises with a purging effect that enables him to reconcile with his situation and admit its truth in front of his family. with the action being set in motion by a dispute over land and money. 10. justice is not done. Kennedy (ed. Ireland in Transition. one of the characters protests against the political establishment for their neglect of this human tragedy. Murphy’s The Country Boy treats emigration as an individual and not a social problem. making a strong case for the joys of sex and the evil of its suppression. the younger ones decide to give evidence against the Dolis. Keane’s Many Young Men of Twenty (1961) is an angry response to the same phenomenon which reached some of its highest rates at the end of the fifties. for he must prove mature and self-willed enough not to be afraid of his father’s anger before he can take over the farm. In other plays like The Year of the Hiker (1963) and Big Maggie (1969) Keane addressed the theme of the sexual repression with deep roots in the cultural and religious definitions of rurality.K. Nevertheless. 36 T. set in a country pub where the emigrants gather for a last drink before their departure. the voice of an unyielding past is obstinate in his intention not to turn over the control of the farm to his son. the old Maher does not stand for the abuse of patriarchy. unlike in Shield where the farmers eventually testify against the murderer. the simple rural virtues of the native place are set in contrast to the flimsiness of Eddie’s and Julia’s make-believe: the first trying to hide his story of failure under an air of snobbery and a trunk filled with the American homecomer’s symbols of prosperity. Moreover. Whitaker. embarking thus on the “rugged path” of change and confrontation. his contrariness. exemplified by the wild Dolises from the mountains who terrorise the local farmers and kill an old man for two pounds. the latter disguising her lower-class origin and proletarian status under the mask of the tourist. followed by “The Bull” McCabe’s murder of his rival and his terrorising of his neighbours against informing. always comparing Ireland to America in a condescending manner. returns home for a vacation with his American wife Julia to find his younger brother Curly planning to emigrate for much the same reasons like his own: their father. having left his parents’ farm and established himself in a non-farming society could be contrasted to the peasants.).K. Eddie Maher. p.
and a bitter alcoholic father) collapses. It tells the story of Francis 'Francie' Brady. a schoolboy who retreats into a violent fantasy world as his troubled home life (with a suicidal mother. 5.9. He has also written a children's book (The Adventures of Shay Mouse) and several radio plays broadcast by the RTÉ and the BBC Radio 4.1.Ioana Mohor-Ivan Irish Literature 5. His novels include The Butcher Boy (1992) and Breakfast onPluto (1998). frequently abused both verbally and physically by the husband. both shortlisted for the Booker Prize. 79 . Becoming obsessed with the sanctimonious Mrs. The Butcher Boy (1992) Written in a hybrid of first-person narrative and stream of consciousness.1. and adapted into films by the Irish director Neil Jordan.) Patrick McCabe is a writer of mostly dark and violent novels of contemporary. often small-town. with the butcher’s bolt gun he has taken from the abattoir where he works.9.1. Patrick McCabe (1950 . the novel is set in a small town in Ireland in the late 1950s. THE BLACK PASTORAL ‘Black pastoral’: works which self-consciously invert the earlier idealizations of life in the west of Ireland by presenting it as brutal and unidyllic (Nicholas Grene) 5. with little punctuation and no separation of dialogue and thought. Nudgent who once claimed that the Brady family were ‘a bunch of pigs’. Ireland.9. Francie eventually kills her.
they institute legal. 1919-1921 “Anglo-Irish War”: armed conflict between British forces and Irish Nationalists 1921 The Anglo-Irish treaty establishes two self-governing areas. begins guerilla warfare campaign against British soldiers. most Irish police resign. Fermanagh. the Irish Republican Army forms. led by James Connolly. when World War I begins. In response. replaced by British recruits referred to as “the Black and Tans. and Tyrone) and Southern Ireland (called the Irish Free State) 1922-23 Civil War in Irish Free State between supporters of the treaty (“Nationals” or “Free State” troops). De Valera takes over presidency of Sinn Fein from Griffith. and the Irish Free State begins its rule. Political context: • • 1905 Sinn Fein ("ourselves alone"). led by Griffith and Michael Collins. bitter. Down. 1916 The Easter Rising: Catholic insurgents seize central areas of Dublin. and cruel on all sides. In Northern Ireland. the Ulster Volunteers (Protestant military force) and then the Irish Volunteers (Catholic military force--soon to become the Irish Republican Army) form. led by de Valera (“Irregulars”). Londonderry. but Connolly had managed to connect the plight of urban workers with that of the rural tenants in opposition to British rule. to increasing public and international outrage. political. fighting lasts for one week before insurgents are forced to surrender. establishes new provisional government. is formed by Arthur Griffith 1912-1913 The Home Rule bill is passed in the House of Commons. stage a series of effective strikes in the cities. and proclaim a provisional government. and opposition. Northern Ireland (the six counties of Antrim. 1918 Sinn Fein wins the parliamentary elections. covert. Armagh. the Protestant majority succeeds in suppressing the armed rebellions of the Catholic minority. • • • • • • • 80 .” The fighting is fierce.Ioana Mohor-Ivan Irish Literature CHAPTER 6 – THE CITY IN IRISH LITERATURE 6. Armed struggle ends in 1923.1. the strikes are violently put down. A bitter hatred and pattern of violence is established in the North that remains to this day. 1913 The labor movement. and police restrictions assuring Protestant control of virtually every level of government. Civil War seems imminent. all but one of the leaders (Eamon de Valera) are executed. a radical nationalist group. and both Nationalists and Unionists agree to suspend the conflict.
Ioana Mohor-Ivan Irish Literature (The Declaration of Independence drafted by Patrick Pearse in 1916) 81 .
THE “ALIEN” CITY Belfast Unionist Industry Protestant Materialist Entrepreneurial Decadent English THE “HEROIC” CITY Dublin Nationalist Revolution Catholic Idealist Sacrificial Moral Irish 82 . an oppositional “un-Irishness” became crystallised in the materialist. may be seen as an attempt to fix the two categories of rural versus urban Ireland into a taxonomic relationship assigning priority to the countryside over the city.Ioana Mohor-Ivan Irish Literature 6. On the one hand. the only large industrial centre in the island and the home of a large ScotsIrish Presbyterian minority stern in displaying its Unionist sense of identity. stamped in public memory as an exemplar of heroic nationalism associated with the 1916 Easter Rising. metonymically represented through the same space of the city. the northern Belfast. the antithesis was internalised in the opposing stances towards the two different political territories. as it was concocted both at the political and cultural level at the end of the 19th century.2. modern. became fatally marked off as Ireland’s “Other”. was perceived as intrinsic to Irishness. republican Dublin. While rural Ireland was discursively used to represent the national essence. industrialist and party-biased values of England and the city alike. Perceptions of the urban space: The definition of “Irishness”. On the other hand. With independence and the division of the country at the birth of the state.
too.Ioana Mohor-Ivan Irish Literature 6. 83 . too. has been changed in his turn. Or lingered awhile and said Polite meaningless words. Transformed utterly: A terrible beauty is born. young and beautiful. So daring and sweet his thought. And thought before I had done Of a mocking take or a gibe To please a companion Around the fire at the club Being certain that they and I But lived where motley is worn: All changed. changed utterly: A terrible beauty is born.1. She rode to harriers? This man had kept a school. Her nights in argument Until her voice grew shrill. So sensitive his nature seemed. I have passed with a nod of the head Or polite meaningless words. He might have won fame in the end. The “heroic city” 6. Yeats’s Easter 1916. vainglorious lout. He.3.3. has resigned his part In the casual comedy. He had done most bitter wrong To some who are near my heart. This other his helper and friend Was coming into his force.B. I HAVE met them at close of day Coming with vivid faces From counter or desk among grey Eighteenth-century houses. This other man I had dreamed A drunken. That woman’s days were spent In ignorant good-will. He. And rode our winged horse. W. Yet I number him in the song. What voice more sweet than hers When.
The rider. Too long a sacrifice Can make a stone of the heart. Are changed. What is it but nightfall? No. And a horse plashes within it. We know their dream. The horse that comes from the road. O when may it suffice? That is Heaven’s part. And what if excess of love Bewildered them till they died? I write it out in a verse MacDonagh and MacBride And Connolly and Pearse Now and in time to be. enough To know they dreamed and are dead. changed utterly: A terrible beauty is born. Wherever green is worn. Was it needless death after all? For England may keep faith For all that is done and said. A shadow of cloud on the stream Changes minute by minute. And hens to moor-cocks call.Ioana Mohor-Ivan Irish Literature Hearts with one purpose alone Through summer and winter seem Enchanted to a stone To trouble the living stream. 84 . no. not night but death. the birds that range From cloud to tumbling cloud. Minute by minute they change. A horse-hoof slides on the brim. The long-legged moor-hens dive. our part To murmur name upon name. As a mother names her child When sleep at last has come On limbs that had run wild. Minute by minute they live: The stone’s in the midst of all.
unimportant people will be shown struggling to steer the course of their lives through the chaotic and violent background of the national struggle. trying to jump off. but also unnecessary because Minnie is killed by mistake. Minnie removes it. Post-Revolutionary Revisionism Playwrights like Sean O’Casey. though they too are responsible for their fate: due to their own pettiness. In their place. and. cowardice. planted by the real gunman. but mostly by allowing themselves to be governed by illusion. Hero-worshipping has proved a dangerous illusion: Minnie has died for a shadow. the 1919-21 War of Independence and the Civil War of 1922-23) with the aim of revising cherished loci of the republican tradition. 137) aimed at redrawing the nationalist map of the “heroic” Dublin.3. Denis Johnston and Brendan Behan engaged in “a postrevolutionary theatrical revisionism” (Grene: 2002. so Donal Davoren accepts the persona of a gunman in hiding in order to secure her admiration. but is herself arrested by the Black and Tans. On his stage such heroes will no longer hold the lime-light. With the one notable exception provided by O’Casey’s Dublin trilogy (staged at the Abbey).3. 231). or vanity. selfishness. especially its much revered myth of the hero-martyr. such plays were also to find alternative venues of production.Ioana Mohor-Ivan Irish Literature 6. provided by the small art-house theatres of Dublin. Once he becomes a “shadow” of a gunman the engine of the play is set in motion: Minnie falls in love with an imaginary hero and not a real person. but. 6. Trying to save her hero’s life when a suitcase full of bombs. o In The Shadow of A Gunman Minnie Powell is attracted to the idea of a ‘gunman’. the hero of the nationalist myth. Most of these characters will be eventually drawn into the maelstrom and crushed by the impersonal forces of international hatred (Edwards: 1979. by contrary. she is shot in the confusion. emphasising thus their imaginary status. 85 . Moreover.2. her death was not only pointless. which makes her sacrifice futile. and killed when trying to escape. The Dublin Trilogy o The Shadow of A Gunman (1923) o Juno and the Paycock (1924) o The Plough and the Stars (1926) O’Casey’s Dublin trilogy engages with the episodes of recent nationalist history (the 1916 Easter Rising. and lets herself be governed by an illusion which will eventually destroy her.1. the ordinary. Minnie has glorified the gun and the gun finally kills her. they will be either peripheral to the action or cast as mere shadows. when the lorry taking her away for questioning is ambushed by the IRA. are discovered in Davoren’s room.2. Sean O’Casey (1880-1964). Once shadows are believed in they are no longer insubstantial but acquire an ominous physicality which will prove fatal for the dreamer.
an’ the rattle of machine guns. Davoren: I remember the time when you yourself believed in nothing but the gun. who. their De Profundis is ‘The Soldier’s Son’. Seumas: Ay. is silhouetted outside the window of the public house where most of his tenement dwellers are gathered. their Hail Marys and Paternosters are burstin’ bombs burstin’ bombs. The country is gone mad. The voice preaches the sanctity of hate and the redemption of bloodshed. Johnny. . . Mary. the promise of new life in her unborn grandchild. Nevertheless. where were you when me darlin’ son was riddled with bullets? Sacred Heart o’ Jesus.Ioana Mohor-Ivan Irish Literature Seumas: I wish to God it was all over. an’ give us Thine own eternal love! o In The Plough and the Stars the shadow is the Speaker. will be forced to leave the home. In the same way in which the material expectations aroused by the will be contrasted to the family’s being irrevocably reduced into debt and poverty. as well as by her morally-outraged father. when there wasn’t a gun in the country. 83).an’ it’s all for ‘the glory o’ God an’ the honour o’ Ireland’. left pregnant and deserted by her lover. take away our hearts o’ stone. maker of heaven an’ earth . have pity on us all! Blessed Virgin. will be executed by his former comrades. with the imagined rise and real fall of the Boyles paralleling the disparity between revolutionary ideal and embittering actuality. in the second act. bringin’ you into the world to carry you to your craddle. despite Johnny’s death. while Juno’s departure at the end of the play may be seen to carry with it. in fact. But this legacy is also a metaphor for the newly won national sovereignty (Innes: 1990. I believe in the gun almighty. 101). their Mass is a burnin’ building’. Mother o’ God. Juno: . left to face the terrible reality that. “th’ whole whorl’s … in a terr … ible state of … chassis” (O’Casey: 1985. What was the pain I suffered. I’ve a different opinion now when there’s nothin’ but guns in the country o In Juno and the Paycock The Boyles also believe in a shadow: the legacy which they are to inherit is actually an illusion. an’ their Creed is. arising from the misinterpretation of a relative’s will. the son crippled by a bullet during the Easter Rising. Instead of counting their beads now they’re countin’ bullets. petrol is their holy water. nationalist idealism will be juxtaposed against the fate of the Boyles’ children: Johnny. to the pains I’ll suffer carryin’ you out o’ the world to bring you to you grave! Mother o’ God. the words being culled by O’Casey from a 86 . and give us hearts o’ flesh! Take away this murdherin’ hate. no such emblematic hope will be afforded to Jack Boyle.
When war comes to Ireland she must welcome it as she would welcome the Angel of God! CAPT.3.Ioana Mohor-Ivan Irish Literature number of Pearse’s actual writings. its voluptuous vision of death turns into terrifying actuality. metonymically rendered through the urban experience of his contemporary Dublin. Heroism has come back to the earth. and the nation that regards it as the final horror has lost its manhood. mundane activities. . LANGDON [catching up the Tri-colour]. the play aims to juxtapose the complexities and complacencies of the Irish Free State. Denis Johnston (1901-1984) • • • • • • • • • The Old Lady Says 'No!' (1929) The Moon in the Yellow River (1931) A Bride for the Unicorn (1933) Storm Song (1934) Blind Man's Buff (1936) (with Ernst Toller) The Golden Cuckoo (1939) The Dreaming Dust (1940) A Fourth for Bridge (1948) The Scythe and the Sunset (1958) The same gap between illusion and reality lies at the centre of Denis Johnston’s The Old Lady Says ‘No!’. but once believed in. .2. which. following its rejection by the Abbey. concretise the dialectic between vibrant life and the ‘heroic death’ preached by the Speaker. . and of the by-standers like Bessie Burgess and Nora’s unborn child exhibit the distance between the emotive rhetoric of nationalism and what it leads to in terms of its human cost. the voice is insubstantial for the existence of the pub-denizens. As shadow.There are many things more horrible that bloodshed and slavery is one of them! . The real deaths which occur onstage. VOICE: Bloodshed is a cleansing and sanctifying thing. Using an expressionistic technique of collage. . engaged in comical. . but first produced in 1929 at the Gate Theatre. . BRENNAN [catching up The Plough and the Stars] Imprisonment for th’ independence of Ireland! LIEUT. Brennan and Langan. Wounds for th’ Independence of Ireland! CLITHEROE: Death for th’ Independence of Ireland! THE THREE [together]: So help us God! 6. The old heart of the earth needed to be warmed with the red wine of the battlefields. rousing words is juxtaposed the informal life of the pub. against the revolutionary imaginings of a Robert Emmet. a play written in 1926. The play begins thus as a sentimental re-creation of Ireland’s heroic past – with a playlet staging Robert Emmet’s unsuccessful rising of 1803 and his love for Sarah 87 . nevertheless. Against these awesome.2. both of the warriors like Clitheroe.
Flinging away his sword. a two-fold shadow facing a de-glorified society achieved with so much human blood. instead of delivering the famous historical speech from the dock. a Gaelicspeaking English aristocrat and also a convert to Irish nationalism. The new I. It saves everything but blood. 124).R. But. . 150). once a Republican sanctuary.He had every class of comfort until one day he discovered he was an Irishman. The song which celebrates Michael Collins sums up the political dilemma entailed in the split between the Laughing Boy’s ideal of a free Ireland and the reality of the partially fulfilled republican project. now a brothel.2. 6. questioning his identity and threatening him. gets hold of a revolver which goes off and a young man whom he has shot apparently dies interminably. a former IRA member who runs the place.”(Behan: 1962. 421). Let my epitaph be written” (Johnston: 1988. Johnston’s image of the mythical heromartyr is emblematically that of a somnambulist and an actor. As Pat. is written in the context of the renewed IRA border campaigns in the 1950s. 14-5) The absurdity of this situation sets the note for Behan’s mockery of the Irish political fanaticism. The other death Emmet has to confront in the play is the historical gratuitous slaughter of Lord Kilwarden for which the bitter figure of Grattan blames the hero’s followers. and struggling to give coherence to the bewildering scenes he encounters. before lying down in his previous state of concussion. Grattan accuses Emmet of prolonging the cult of bloodshed endemic in Irish history: “Oh. remained one for years . ‘Emmet’. Emmet comes to see that he is but a playactor. Emmet is forced to face the unintended violent consequences of his romantic ideals. The Hostage (1958) Richard's Cork Leg (1972) Brendan Behan’s The Hostage. revised and enabling alternatives. At one point the crowd becomes menacing. he adds: “There now. significantly.3. And blood is the cheapest thing the good god has made” (Johnston: 1988. The Hostage is set in an old house. it is an easy thing to draw a sword and raise a barricade.Ioana Mohor-Ivan Irish Literature Curran. questioning the revolution for what its history did to make Irish politics a muddle. the legacy of which materialised in the obstinate movement to continue “the quixotic struggle for Ireland’s total liberation from English control” (Murray: 2000. But the actor in the play is knocked out and has a nightmare about being the real Emmet wandering round 1920s Dublin. and.A campaign is seen as part of Monsewer’s lunacy which makes him plan “battles fought long ago 88 . towards the end of the play. he “forgives the strumpet city Dublin. . excited.3.. says: “He was born an Englishman. Brendan Behan (Breandán Ó Beacháin) (1923 . metonymy for Ireland” (Murray: 2000. it saves waiting. which is owned by Monsewer.1964) • • • The Quare Fellow (1954) An Giall (1958). 375). free to rebel and repudiate the tradition of violence that history has assigned to him. As with the ‘murder’ of the young man. performed in 1958 as An Giall at the Pike Theatre. It saves working. This is a recognition that words can alter the shape of history and a plea to abandon traditional pieties in favour of new.
but his death comes accidentally. Leslie." They conduct a guerilla war against the Ulster police (Royal Ulster Constabulary). bombs erupt in Omagh. Catholics. 1970-71 The I. and the British army.4. Provisional I.R. culminating in death of Bobby Sands after a 66-day strike. 1979 Provisional I.Ioana Mohor-Ivan Irish Literature against enemies long since dead” (Behan: 1962.1.R. 108) 6. killing 29 and injuring hundreds more . extremists of both sides (Unionist and Republican) intensify fighting in August. as Minnie was probably shot by the Auxiliaries. Three months after the Agreement is ratified.R. kill 5 and injure 80 in Christmas bombing in London. Nobody meant to kill him. and the Irish Republic. the Irish servant-girl. and Behan leaves the question open to any of the two alternatives: “It’s no one’s fault. 1969 Great Britain pushes for reform in Northern Ireland. being shot in the confusion of a police raid. kills 19 and wounds 130 in Belfast bombings on 21 July (Bloody Friday). nobody knows who has killed Leslie: probably the IRA. setting up provisions for cease-fire and joint government of Northern Ireland among Protestants. 1998 Easter Agreement signed on April 10. resumes activities with renewed vigor.A. the Ulster volunteer army (UVA). and assassinate Lord Mountbatten in the Republic. Political Context • • 1968 Riots in Londonderry in October between Catholics demanding increased civil rights and Protestants seeking to maintain their political superiority.A. and government transferred directly to London.A. Northern Ireland. and British troops are deployed to restore order.4. kill 18 British soldiers in Co. at the end of the play. Leslie’s fate seems sealed. 1985 The Anglo-Irish agreement is signed between Great Britain and Eire in effort to work out Northern Ireland conflict. • • • • • • • 89 . As in Minnie’s case. while he also engineers a scheme to get hold of a British hostage in order to forestall the execution of an IRA man in Belfast. 1981 Series of hunger strikes in Maze prison by Catholic prisoners to protest living conditions.A. firmly establishing itself in the Catholic districts of Londonderry and Belfast and titling itself the "Provisional I.”(Behan: 1962. the Northern Ireland constitution is suspended. 1983 Provisional I. since the IRA youth has been hanged.A. but in both cases the odds speak also for the other side. Nevertheless.R. 6). Down.the single greatest loss of life since "the troubles" began. gradually gets the affection of its occupiers and develops a romantic relationship with Teresa. The “Troubles” and the Northern City 6. 1972 British soldiers kill 13 Catholic civilians on 30 January (Bloody Sunday) in Londonderry. the English soldier who ends up in the brothel.R.
As such. developing into what D. an insoluble conflict emerged once the sense of difference translated now “on one side into a sense of superiority and on the other into a sense of grievance” (Murray: 2000. IRA martyr) 90 . Maxwell considers to represent a subgenre of modern Irish drama (Maxwell: 1990). (Belfast murals: Ulster Freedom Fighters and the Red Hand of Ulster vs. S. Johnston or Behan as one dramatic option through which the present turmoil may be artistically framed.2. both Protestant and Catholic playwrights often find a common ground in aligning themselves to the postrevolutionary theatrical revisionism of O’Casey. With the actuality of violence. This inevitably led to a revival of Irish nationalism in ways which harked back to the early decades of the century in its persistent belief in the unfinished nature of the Irish revolution. Bobby Sands.4. Staging the Troubles Since 1970 dozens of plays dealing with various aspects of the troubles in Ulster have been written.Ioana Mohor-Ivan Irish Literature 6. 187).
and Michael represent a cross-section of the Catholic population of Derry. . [ . three demonstrators take refuge in the Mayor’s Parlour in Derry’s Guildhall. . Lily. . Come down and pay me for the six weeks you owe me.1. The Freedom of the City (1973) Although set in 1979. And when I look back there’s Johnny the Tumbler standing there with his fists in the air and him shouting. When an unauthorised civil-rights march is dispersed by CS gas. Parallel to this. And I’m just after telling him ‘The streets is ours and nobody’s going to move us’ when I turn round and Jesus. 1972.Ioana Mohor-Ivan Irish Literature 6. . ] I was at the back of the crowd. is shouting up from the road. And that’s what we must show them . . Dr Dodds.so 91 . . the play recalls Bloody Sunday in Derry. . And above us Dickie Devine’s groping under the bed for his trombone and he doesn’t know that Annie pawned it on Wednesday for the wanes’ bus fares and he’s going to beat the tar out of her when she tells him.] a decent job.you know the window cleaner . and they’ll come to respect what we’re campaigning for. the milkman.2.that we’re responsible and respectable.4. In opposition to the abstract and inflexible figures which represent the official world. . Brian Friel. Mary and Joseph there’s this big Saracen right behind me. like O’Casey humble innocents. And down the passage aul Andy Boyle’s lying in bed because he has no coat. ‘I know you’re there. disciplined.’ And the chairman’s sitting at the fire. In the public world outside. who. [. [. I took to my heels. MICHAEL: It was a good. are caught in the crossfire of powerful partisan forces. a tribunal examines the events and exonerates the security forces. LILY: At this minute Mickey Teague. beside wee Johnny Duffy . a sociologist. lectures the audience directly on the subculture of poverty. as confused. while intermittent scenes provide brief comment on the influence of the media and the clergy. like a wee thin saint with his finger in his mouth and the comics up to his nose and hoping to God I’ll remember to bring him home five fags. responsible march.and I’m telling him what the speakers is saying ‘cos he hears hardly anything now since he fell off the ladder last time. ‘The streets is ours and nobody’s going to move us. Skinner. Of course.Johnny the Tumbler . And below us Celia Cunningham’s about half-full now and crying about the sweepstake ticket she bought and lost when she was fifteen. a decent town to bring up your children in. and the ensuing Widgery Report that exonerated the British soldiers of guilt. frightened but also high-spirited human beings. In another strand. Friel turns to the naturalist mode to delineate his central trio in fundamentally humanistic terms.] fair play. and when they try to leave the building with hands above their heads they are shot dead by British soldiers. rumour and romantic nationalism inflate the trio into armed terrorists and freedom fighters. a decent place to live. lily Doherty. .
.the majority . LILY: And in the silence before my body disintegrated in a purple convulsion. even a small unimportant happening been isolated. Isn’t that stupid? You and him [Michael] and everybody else marching and protesting about sensible things like politics and stuff and me in the middle of you all. . and became aware that there were hundreds. . Because you know your children are caught in the same morass. . . LILY: . not because I was dying. an event. SKINNER: .stirring in our sleep. and you heard each other. thousands.Ioana Mohor-Ivan Irish Literature that no matter what our religion is. And then the Guildhall Square exploded and I knew a terrible mistake had been made. and that to match their seriousness would demand a total dedication. a solemnity as formal as theirs.it’s for him I go all the civil rights marches. Isn’t that the stupidest thing you ever heard? MICHAEL: I knew they weren’t going to shoot. and assessed and articulated. . . I thought I glimpsed a tiny truth: that life had eluded me because never once in my forty-three years had an experience. It’s about us . Shooting belonged to a totally different order of things. SKINNER: And as we stood on the Guildhall steps. Because you exist on a state subsistence that’s about enough to keep you alive but too small to fire your guts. It has nothing to do with doctors and accountants and teachers and dignity and boy scout honour.the poor . two thoughts raced through my mind: how seriously they took us and how unpardonably casual we were about them. That’s all it’s all about. Lilly. marching for Declan. but that this terrible mistake be recognized and acknowledged. no matter what our politics is. . 92 . we have the same chances and the same opportunities as the next fella. and in a vague groping way you were outraged.Because you live with eleven kids and a sick husband in two rooms that aren’t fit for animals. Because for the first time in your life you grumbled and someone else grumbled and someone else. millions of us all over the world. And I became very agitated.
Ioana Mohor-Ivan
Irish Literature
6.4.3. Writing the “Troubles” 6.4.3.1. Bernard MacLaverty (1942-)
Novelist and short-story writer, Bernard MacLaverty was born and lived in Belfast until 1975 when he moved to Scotland, where, for some years, he became writer-inresidence at the University of Aberdeen. He has published extensively and has also adapted his fiction for other media (radio, television, cinema.) Published works: Secrets & Other Stories (1977) Lamb (1980) A Time to Dance & Other Stories (1982) Cal (1983) The Great Profundo & Other Stories (1987) Walking the Dog & Other Stories (1994) Grace Notes (1997) The Anatomy School (2001) Matters of Life & Death & Other Stories (2006)
Cal (1983) focuses on the psychological torment and political victimhood of Cal
McCluskey, a young working-class Catholic living in a Protestant housing estate in Northern Ireland during the “Troubles”. He the local IRA commander, Skeffington, Cal broods relentlessly on his shame and abjection. His torment deepens when he and his father are burned out of their home by Loyalist paramilitaries, after which Cal moves to an abandoned cottage on the Morton farm, where he is employed as a labourer. Here his tortured affair with Marcella develops in secret, though any hope of them building a new life together is soon shattered when Cal sees Crilly planting a bomb in the library where Marcella works. The novel’s climax is swift and sudden. After Crilly and Skeffington are apprehended by the police, Cal informs the authorities about the bomb and then returns to Marcella to await passively his own arrest on Christmas Eve. MacLaverty adapted Cal for the screen in 1984. The film starred Helen Mirren and John Lynch.
93
Ioana Mohor-Ivan
Irish Literature
Minimal Bibliography
Bradshaw, Brenna, Andrew Hadfield and Willy Maley (eds.), REPRESENTING IRELAND: LITERATURE AND THE ORIGINS OF CONFLICT, Cambridge: Cambridge UP, 1993. Brady, Ciaran, Mary O’Dowd and Brian Walker (eds.), ULSTER: AN ILLUSTRATED HISTORY, foreword by J. C. Beckett, London: B .T. Batsford, 1989. Brophy, James D. and Raymond J. Porter, CONTEMPORARY IRISH WRITING, Boston: Iona College Press, Twayne Publishers, 1983. Brown, Terence IRELAND’S LITERATURE, Mercier Press, 1992. Cairns, David and Shaun Richards, WRITING IRELAND: COLONIALISM, NATIONALISM AND CULTURE, Manchester, Manchester UP, 1988. Crotty, Patrick (ed.) MODERN IRISH POETRY. AN ANTHOLOGY, Lagan Press, 1993. Deane, Seamus, A SHORT HISTORY OF IRISH LITERATURE, London et al.: Hutchinson; Notre Dame: University of Notre Dame Press, 1986. Deane, Seamus, CELTIC REVIVALS: ESSAYS IN MODERN IRISH LITERATURE, 1880-1980, London: Faber and Faber, 1985. Foster, John Wilson, COLONIAL CONSEQUENCES: ESSAYS IN LITERATURE AND CULTURE, Mullingar: The Lilliput Press, 1991. IRISH
Gibbons, Luke, TRANSFORMATIONS IN IRISH CULTURE, Cork: Cork University Press; Field Day, 1996. Grene, Nicholas, THE POLITICS OF IRISH DRAMA: PLAYS IN CONTEXT FROM BOUCICAULT TO FRIEL, Cambridge: Cambridge UP, 2002. Kenneally, Michael (ed.), IRISH LITERATURE AND CULTURE, Gerrards Cross: Colin Smythe, 1992 Kiberd, Declan INVENTING IRELAND: The Literature of the Modern Nation, Vintage, 1998. LANDMARKS OF IRISH DRAMA, Methuen, 1996. Mohor-Ivan, Ioana REPRESENTATIONS OF IRISHNESS: CULTURE, THEATRE AND BRIAN FRIEL’S REVISIONIST STAGE, EDP, 2004. Moody, T.W. (ed.) THE COURSE OF IRISH HISTORY, Mercier Press, 1994. NATIONALISM, COLONIALISM AND LITERATURE, with an introduction by Seamus Deane, Minneapolis: University of Minnesota Press, 1990. Vance, Norman, IRISH LITERATURE: A SOCIAL HISTORY, Oxford: Basil Blackwell, 1990. Welch, Robert (ed.) THE OXFORD COMPANION TO IRISH LITERATURE, Oxford UP, 1996.
94
Ioana Mohor-Ivan
Irish Literature
ANNEX 1 INDIVIDUAL AUTHORS & TEXTS (Recommended for individual research)
1. “The Land of Cockayne” 2. Geoffrey Keating, “O Woman Full of Wile” 3. Edmund Spenser, “A View on the Present State of Ireland” 4. William Shakespeare, “Henry V” 5. Dion Boucicault, “The Irish Trilogy” (Arrah-na Pogue, The Colleen Bawn, the Shaughraun) 6. “The Quiet Man” (directed by Boris Ford) 7. Brian Friel, “Making History” 8. Seamus Heaney, “Traditions”, “Ocean’s Love to Ireland” 9. James Clarence Mangan, “My Dark Rosaleen” 10. W. B. Yeats, “Kathleen Ni Houlihan” 11. James Joyce, “A Mother” (from “The Dubliners”) 12. Samuel Beckett, “Murphy” 13. Dancing at Lughnasa (film or play) 14. Thomas Murphy, “Bailegangaire” 15. Maria Edgeworth, “Castle Rackrent” 16. Lennox Robinson, “Killycregs in Twilight” 17. W.B. Yeats, “Purgatory” 18. Jennifer Johnston, “How Many Miles to Babylon?”, “The Invisible Worm” (tranl. into Romanian as “Casa de vara”) 19. Elizabeth Bowen, “The Last September” 20. “The Last September” (film) 21. “The Real Charlotte” (BBC series) 22. “High Spirits” (film, directed by Neil Jordan) 23. J.M. Synge, “In the Shadow of the Glen”, “Riders to the Sea”, “The Well of the Saints”, “The Playboy of the Western World” 24. “The Field” (film)
95
directed by Neil Jordan) 27. “Cal” (film) 33. “Easter 1916” Irish Literature 28. Patrick McCabe. “The Butcher Boy” (film. Martin McDonagh. Juno and the Paycock. “The Dublin Trilogy” (In the Shadow of a Gunman. W. Sean O’Casey.Yeats. Bernard MacLaverty. “In Bruges” (film) 96 . The Plough and the Stars) 29. Denis Johnston. “The Butcher Boy” 26. “The Freedom of the City” 31. “Cal” 32.Ioana Mohor-Ivan 25. “The Old Lady Says ‘No’!” 30. Brian Friel.B.
as v." never as j." s with slender vowels (e." a (short)." never as in "church. g with broad vowels (a. like h. o. as in "threw." never as s." th. i). as in "car." d with broad vowels (a. as in "full. i). u)." u (short). u) is broad ch voiced. c with broad vowels (a. as in German "Ich. as in ale." never as z. u). s with broad vowels (a. t with slender vowels (e. u)." never as in "church." never as s." t with broad vowels (a. mh and bh intervocalic with broad vowels." g with slender vowels (e. u). u). as in "tin. i). í (long). as in "note." never as j. as in "done. as in "give. as in "king. o." d with slender vowels (e. o. u). as w. i). as in "go. ú (long). as in "aught." ch with broad vowels (a. as in German "Buch. o. mh and bh intervocalic with slender vowels. o. ch with slender vowels (e. as in "thy. gh with slender vowels (e. as s." i (short). i). ó (long). as in "hot. as in "feel. as in "pool. as in French "dieu. i)." o (short). as in it.Ioana Mohor-Ivan Irish Literature ANNEX 2 Pronunciation Guide á (long). as in "bet." é (long). i) is slender ch voiced. o. gh with broad vowels (a. as in "shine. o. e (short)." c with slender vowels (e." The remaining consonants are pronounced almost as in English 97 .
Williamite War begins.I. Direct Rule imposed in N. heads rebellion Flight of the Earls Plantation of Ulster Irish Catholic Rebellions Cromwellian campaigns and Plantation James II lands at Kinsale. 6000 BC c. Anglo-Irish Agreement IRA and Loyalist ceasefires 98 . Irish Citizen Army The Easter Rising Anglo-Irish War Irish Free State established. Battle of the Boyne Penal Laws restrict Catholic rights United Irishmen founded in Belfast Foundation of Orange Order United Irishmen’s Rebellion Act of Union Rising of Robert Emmet Catholic Emancipation (Daniel O’Connell) First year of the Great Famine Young Ireland Rising Irish Republican Brotherhood founded Fenian Rebellion. Civil War begins De Valera’s Constitution Irish Free State declares itself a republic Beginning of the “Troubles” “Bloody Sunday” in Derry. Earl of Tyrone. Parnell elected leader of the Irish Parliamentary Party Gael League founded Opening season of the Irish Literary Theatre Ulster Volunteers. 400 BC 432 AD 795 1006 1169 1541 1586 1595-1601 1607 1609 1641-1646 1649-1654 1689 1690 1695 1791 1795 1798 1800 1803 1829 1845 1848 1858 1867 1879 1800 1893 1899 1913 1916 1919-1921 1922 1937 1948 1968 1972 1985 1994 probable date of first human settlements in Ireland possible date of arrival of Celts traditional date of the beginning of St Patrick’s mission first raids of Viking invasion Brian Boraime recognised as high king Norman invasion begins Declaration Act.Ioana Mohor-Ivan ANNEX 3 Irish Literature Brief Chronology of Historical Events c. Irish Volunteers. Manchester Martyrs Michael Davitt founds the Land League. Henry VIII is declared King of Ireland Plantation of Munster Hugh O’Neill. | https://www.scribd.com/document/216454956/Irish-Literature-2014-Ioana-Mohor | CC-MAIN-2018-51 | refinedweb | 59,317 | 78.14 |
I get asked all the time about the different security measures used to control what container processes on a system can do. Most of these I covered in previous articles on Opensource.com:
- Are Docker containers really secure?
- Bringing new security features to Docker
- Docker security in the future
Almost all of the above articles are about controlling what a privileged process on a system can do in a container. For example: How do I run root in a container and not allow it to break out?
User namespace is all about running privileged processes in containers, such that if they break out, they would no-longer be privileged outside the container. For example, in the container my UID is 0 (zero), but outside of the container my UID is 5000. Due to problems with the lack of file system support, user namespace has not been the panacea it is cracked up to be. Until now.
OpenShift is Red Hat's container platform, built on Kubernetes, Red Hat Enterprise Linux, and OCI containers, and it has a great security feature: By default, no containers are allowed to run as root. An admin can override this, otherwise all user containers run without ever being root. This is particularly important in multi-tenant OpenShift Kubernetes clusters, where a single cluster may be serving multiple applications and multiple development teams. It is not always practical or even advisable for administrators to run separate clusters for each. Sadly one of the biggest complaints about OpenShift is that users can not easily run all of the community container images available at docker.io. This is because the vast majority of container images in the world today require root.
Why do all these images require root?
If you actually examine the reasons to be root, on a system, they are quite limited.
Modify the host system:
- One major reason for being root on the system is to change the default settings on the system, like modifying the kernel's configuration.
- In Fedora, CentOS, and Red Hat Enterprise Linux, we have the concept of system containers, which are privileged containers that can be installed on a system using the
atomiccommand. They can run fully privileged and are allowed to modify the system as well as the kernel. In the case of system containers we are using the container image as a content delivery system, not really looking for container separation. System containers are more for the core operating system host services as opposed to the users app services that most containers run.
- In application containers, we almost never want the processes inside the container to modify the kernel. This is definitely not required by default.
Unix/Linux tradition:
- Operating system software vendors and developers have known for a long time running processes as root is dangerous, so the kernel added lots of Linux capabilities to allow a process to start as root and then drop privileges as quickly as possible. Most of the UID/GID capabilities allow a processes like a web service to start as root, then become non-root. This is done to bind to ports below 1024 (more on this later).
- Container runtimes can start applications as non-root to begin with. Truth be known, so can systemd, but most software that has been built over the past 20 years assumes it is starting as root and dropping privileges.
Bind to ports < 1024
- Way back in the 1960s and 1970s when there were few computers, the inability of unprivileged users to bind to network ports < 1024 was considered a security feature. Because only an admin could do this, you could trust the applications listening on these ports. Ports > 1024 could be bound by any user on the system so they could not be trusted. The security benefits of this are largely gone, but we still live with this restriction.
- The biggest problem with this restriction is the web services where people love to have their web servers listening on port 80. This means the main reason apache or nginx start out running as root is so that they can bind to port 80 and then become non-root.
- Container runtimes, using port forwarding, can solve this problem. You can set up a container to listen on any network port, and then have the container runtime map that port to port 80 on the host.
In this command, the podman runtime would run an
apache_unpriv container on your machine listening on port 80 on the host, while the Apache process inside the container was never root, started as the
apache user, and told to listen on port 8080.
podman run -d -p 80:8080 -u apache apache_unpriv
Alternatively:
docker run -d -p 80:8080 -u apache apache_unpriv
Installing software into a container image
- When Docker introduced building containers with
docker build, the content in the containers was just standard packaged software for distributions. The software usually came via rpm packages or Debian packages. Well, distributions package software to be installed by root. A package expects to be able to do things like manipulate the
/etc/passwdfile by adding users, and to put down content on the file system with different UID/GIDs. A lot of the software also expects to be started via the init system (systemd) and start as root and then drop privileges after it starts.
- Sadly, five years into the container revolution, this is still the status quo. A few years ago, I attempted to get the package to know when it is being installed by a non-root user and to have a different configuration. But I dropped the ball on this. We need to have packagers and package management systems start to understand the difference, and then we could make nice containers that run without requiring root.
- One thing we could do now to fix this issue is to separate the build systems from the installing systems. One of my issues with #nobigfatdaemons is that the Docker daemon led to the containers running with the same privs for running a container as it did for building a container image.
- If we change the system or use different tools, say Buildah, for building a container with looser constraints and CRI-O/Kubernetes/OpenShift for running the containers in production, then we can build with elevated privileges, but then run the containers with much tighter constraints,or hopefully as a non-root user.
Bottom line
Almost all software you are running in your containers does not require root. Your web applications, databases, load balancers, number crunchers, etc. do not need to be run as root ever. When we get people to start building container images that do not require root at all, and others to base their images off of non-privileged container images, we would see a giant leap in container security.
There is still a lot of educating needing to be done around running root inside of containers. Without education, smart administrators can make bad decisions.
5 Comments | https://opensource.com/article/18/3/just-say-no-root-containers?rate=PAV9KN9D8KTht4_e-mn16e74kltVFDffitApFiH8E9M | CC-MAIN-2022-21 | refinedweb | 1,168 | 58.82 |
#include <rpl_commit_stage_manager.h>
Append a linked list of threads to the queue.
Fetch the entire queue for a stage.
Fetch the entire queue for a stage.
It is a wrapper over fetch_and_empty() and acquires queue lock before fetching and emptying the queue threads.
Fetch the entire queue for a stage.
It is a wrapper over fetch_and_empty(). The caller must acquire queue lock before calling this function.
Fetch the first thread of the queue.
Get number of elements in the queue.
Remove first member from the queue.
Pointer to the first thread in the queue, or nullptr if the queue is empty.
Pointer to the location holding the end of the queue.
This is either
&first, or a pointer to the
next_to_commit of the last thread that is enqueued.
Lock for protecting the queue.
size of the queue | https://dev.mysql.com/doc/dev/mysql-server/latest/classCommit__stage__manager_1_1Mutex__queue.html | CC-MAIN-2022-21 | refinedweb | 137 | 87.62 |
Posts1,768
Joined
Last visited
Days Won158
Content Type
Profiles
Forums
Store
Showcase
Product
ScrollTrigger Demos
Downloads
Posts posted by Rodrigo
Hi Tiago,
I looked at your site using firebug and as far as i can see now (i didn't gave a good look to your js code) is that you're getting an event propagation problem.
What i saw is the separators display going bezerk between list and none, background position doing the same stuff between 20px 20px and 20px -20px.
Maybe you could put some console.log or alerts inside the tween to see when things are happening, in order to check if the problem is with your code or tweenmax.js. Also use the uncompressed version for development and in the final version you reference to the compressed version, in case there is a bug with tweenmax.js is going to be easier to find.
Also try using the className method instead of tweening a bunch of properties:
TweenLite.to(myElement, 1, {css:{className:"class2"}});
I hope this can help,
Cheers,
Rodrigo.
1
Hi Tiago,
Using JQuery you can get the document total height like this:
var max = $(document).height();
And then you can trigger the following tween to scroll to the bottom of the page:
TweenLite.to(window, 2, {scrollTo:{y:max}, ease:Power2.easeOut});
Of course if you're using another DOM element be sure to use it instead of window.
Now in pure javascript it would go like this:
var body = document.body, html = document.documentElement; var totHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); function scrollWindow() { TweenLite.to(window, 2, {scrollTo:{y:totHeight}, ease:Power2.easeOut}); }
I hope this helps a little,
Cheers,
Rodrigo.
2
Hi and welcome to the forums,
Mhh... as far as I can say the only advice will be to create one timeline and then add the respective tween to it, instead of run two timeines, for the rest your code looks good, at least to me
.
var tl1 = new TimelineLite(); tl1.insert( TweenLite.to(elem, 1, {css:{left:number}}) ); tl1.insert( TweenLite.to(elem, 1, {css:{rigth:number}}) );
Now in terms of tweening right and left on the same tween, as far as I know, that can't be done because in my experience GSAP renders the css attributes in the order that they are declared, so if you put this:
TweenLite.to(elem, 1, {css:{left:'100px', right:'100px'}});
That is going to tween your element to the left position, but not the right position, and if you invert them is going to tween the right position but not the left , so separate tweens are needed, but maybe someone with greater knowledge could give you more advice in this matter.
Anyway I hope I can help a little with this,
Cheers,
Rodrigo.
Hi Jon and welcome to the forums.
First GSAP JS does not support css3 properties yet, Jack (Greensock developer) is currently working on it. But he got a workaround which you can see here:
And based on that post another user came up with this:
You can also find more info about transform Matrix on IE8 here:
I believe that there might be your problem. Any way it would help to see the code of your tween/timeline to find out more.
Hope i can help a little.
Cheers,
Rodrigo.
Hi, says other thing.
Since i started with this tutorial i found a lot of things about parallax and because of that i will make a second tutorial which i haven't started yet, but as soon as my schedule allows me to i will write it.
I hope you enjoy it,
Cheers,
Rodrigo.
2
Hi Barry,
No problemo...
I got a little intrigued by your problem so i looked up for some information and i found this regarding the @font-face rule and IE8:
I also read in StackOverflow that in the @font-face rule, the recommendation is to use quotation marks in the font-family property.
And finally take a look at this:
Cheers,
Rodrigo.
1
Hi Barry,
Glad to hear you find out where is the problem, but it's a strange behavior to say the least. Question, have you tried changing the tween effect?, i mean try something like this:
TweenLite.to($('#headerText'), 1, {css:{autoAlpha:0.5}});
in order to see if the style changing is what is causing the trouble or if maybe something else.
And like Jamie said try using the uncompressed code in order to pinpoint the problem.
And another suggestion, try a web safe color to see if that could be causing trouble.
Cheers,
Rodrigo.
Hi,
Here is a simple example of background change layering the different elements, meaning there are three background images and a div with text in front of them. The background images are changed with a crossfade tween:
Cheers,
Rodrigo.
1
Hi,
There's a lot going on in your code, and like Jamie says IE8 has a major collapse with preventDefault() so my suggestion will be to try this:
if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue = false; };
Cheers,
Rodrigo.
Hi Moolood,
Sorry, i thought i knew what your problem is because i once ran into some trouble with som jquery ajax calls, php and images, in which i kept loading the image data instead of the image, which got resolved using the data uri scheme, but i'm not sure if is the same problem.
Maybe this can help a little:
Hope i can help,
Cheers,
Rodrigo.
Hi and welcome to the forum!!
The most simple way is to use repeat property, but for that you have to use TimelineMax, since repeat is not a property of TimelineLite. Take a look at the api reference.
You said that the idea is to repeat that timeline 7 times, so it would be something like this:
function forward(){ var tl = new TimelineMax({repeat:6}); tl.to(one, 0.75, {css:{rotation:".16rad" },ease:Linear.easeNone} ); ..... tl.to(two, 0.14, {css:{rotation:"0 rad" },ease:Linear.easeNone}); }
Keep in mind that the code above will play the tween 7 times, since it will play one time and repeat six times.
Hope this can help,
Cheers,
Rodrigo.
3
Hi Stef,
You are most welcome, anyway i have something else to clarify this point a little more.
Let's go to the expression breakdown:
progress = (1 / (end - start)) * (position - start)
First part
Let's say that your tween starts when the scroll bar is 100 px from the left edge of the screen, and ends when the scroll bar reaches the right edge. Asume that this position is at 2100 px. So in a very simple term your tween is going to extend for 2000 pixels, is like saying that is going to last let's say 10 seconds. So considering thath almost every programming language uses miliseconds your tween will last 10000 miliseconds, and each milisecond can be considered a progress or update unit of your tween. In the case of updating your tween with the scroll you have to consider each pixel that is scrolled a progress or update unit.
Since the progress of the tween has to be set in base of a number that goes between 0 and 1 you have to divide the total progress of your tween -that's 1- between the total progress or update units, in this case pixels. Since our tween is going to last 2000 pixels you have to divide 1 between 2000. And that's how you get the single progress or update unit.
(1 / (2100 - 100)) ==>progress unit ( 0,0005 )
Second Part
Now your tween is progressing as the user scrolls to the right of the screen and reversing as the user scrolls to the left, right? We have the total amount of pixels on which the tween extends and now we need to know where the scroll bar is right now so we can tell the tween "hey buddy, you have to be here now". For that we need the actual position of the scroll bar. Since the $(window).scroll() function triggers every time the window moves we can ask for the scroll bar position.
Let's say that the scroll bar is actually at 1200 pixels. Since our tween started at 100 pixels, this means that our tween has progressed 1100 pixels, so we can obtain this number like this:
(position - start) ==>actual position ( 1100 )
Summarizing
progress = (1 / (end - start)) * (position - start)
At the beginning of time this is quite simple:
progress = (1 / (2100 - 100)) * (0 - 100) = (0,0005) * (-100) = -0,05
This is smaller than 0 therefore our tween goes nowhere.
progress = (1 / (2100 - 100)) * (100 - 100) = (0,0005) * (0) = 0
Our tween is at the very beginning nothing happens, yet...
progress = (1 / (2100 - 100)) * (1200 - 100) = (0,0005) * (1100) = 0,55
Our tween is a little past the half point.
I hope this helps a little more.
Cheers,
Rodrigo.
2
Well, first of all...great that you reply to a beginners question
No problemo my friend, here to help
.
I see what your doing..but i don't understand what the 'between 0 and 1 ' is doing in your var progress...1 / ( end - start ) . Where does the '1' comes from ?
There are two public method called "progress" and "totalProgress" for both TweenMax and TimelineMax; i'll just quote some of the api reference:progress(value:Number):*Gets or sets the tween's progress which is a value between 0 and 1 indicating the position of the virtual playhead (excluding repeats) where 0 is at the beginning, 0.5 is halfway complete, and 1 is complete.
Take a good look at the documentation in the site here
You have to consider at which point the tween will begin and at which point it will end, therefore those two points are key to set the progress of your tween. In terms of the mathematical expression itself it goes a little like this: you need a number that is linked to the actual position in the X axis which you get from the scrollLeft method. Since you want your tween to begin at certain point when the user scrolls, you need a 0 at that point (remember the API?) and your tween is going to extend from that point to an end point where the tween is over even if the user keeps scrolling, right?. Since you need to tell TweenMax to set the progress with a number between 0 and 1, you have to divide 1 by the amount of pixels that your tween is going to last and then multiply that by the current position relative to the start point.
i did look at your example rodrigo..but i like to understand stuff ..not just copy it and implement...
That's great, like i said take a look at the docs here and to the JQuery API in order to understand a little more. Any way you caught me a little short of time in order to explain a little more, but i will try to get something in the next days in order to clarify a little more this subject.
Cheers and Good luck!!!
Rodrigo.
Hi Stef,
Maybe this could help a little, it's not the complete job but it could help you for a start.
Just like Carl said, in JQuery with scrollLeft you can get (and set if you want) the horizontal scroll position of any element, including window; and the scroll event is going to helpp you trigger a handler that is going to give you the current left position, pretty much like this:
$(window).scroll(function() { var position = $(this).scrollLeft(); $("div#log1").html(position); });
So any time you scroll in the horizontal the variable position is going to get the horizontal scroll value so you can use it.
And with some simple math you can get the position and transform it into something usefull by creating a number that goes between 0 and 1 so you can set the progress of your tween. Something like this:
$(window).scroll(function() { var position = $(this).scrollLeft(); var start = 400; var end = 800; var progress = (1 / (end - start)) * (posicion - start)); if(posicion >= start && posicion <= end) { $("div#log1").html(posicion); $("div#log2").html(progress); } });
You can see it working here.
Hope i can help a little.
Good luck and cheers,
Rodrigo.
1
First of all thanks to you Carl, without your input it would have taken a lot of time for me to see where the problem was, so again thanks to you. As i said the only problem with the first example was the delay time, it was as simple as changing this:
TweenMax.fromTo(fondo1, 0.7, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:0.05});
to this:
TweenMax.fromTo(fondo1, 0.7, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:j*0.05});
As Carl said in his first response:In my loop all the tiles have the same tween except the delay is based on what column they live in.
And the code posted by Carl works an does the trick very good, so if any one else is interested in doing something like this could use either one of the codes, Carl's or mine.
As for your tutorial Carl just one word: AWESOME!!!
Thank you again,
Rodrigo.
Hi,
This post has been extremely helpful and for that i thank treeloy and the admin.
Using the code given here i have created my own grid but there is something i want to achieve but reducing the amount of code involved.
I uploaded the examples here in order to explain myself correctly.
The code of the first example is as follows:
FIRST FRAME
import com.greensock.*; this.stop(); var cont1:MovieClip = new MovieClip(); var delay:Number = 0; btn1.addEventListener(MouseEvent.CLICK, btn1ck); function btn1ck(e:MouseEvent):void{ gotoAndPlay("2"); }
SECOND FRAME
this.stop(); addChild(cont1); cont1.x = 600; cont1.y = 5; TweenMax.to(cont1, 0.5, {x:5}); for (var i:Number = 0; i < 7; i++) { for (var j:Number = 0; j < 9; j++) { var fondo1:MovieClip = new cuadro(); fondo1.x = 25 + fondo1.width * j; fondo1.y = 25 + fondo1.height * i; cont1.addChild(fondo1); fondo1.alpha = 0; TweenMax.fromTo(fondo1, 0.7, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:0.05}); } } btn2.addEventListener(MouseEvent.CLICK, btn2ck); function btn2ck(e:MouseEvent):void{ gotoAndPlay("1"); removeChild(cont1); }
AS you can see what i achieve is a well defined grid that expands an moves from right to left, then the idea is to continue from center to the left of the screen in order for the grid to disappear.
But what i want to achieve is what happens in the second example because in the first one all the grid components expand at the same time while in the second example they do it in sequence.
The point is that the second example is made with quite an amount of code that could and it would probably cause problems in the future. Here is the code of the second example:
FIRST FRAME
import com.greensock.*; this.stop(); var cont1:MovieClip = new MovieClip(); var delay:Number = 0; var delay2:Number = 0; var delay3:Number = 0; var delay4:Number = 0; var delay5:Number = 0; var delay6:Number = 0; var delay7:Number = 0; btn1.addEventListener(MouseEvent.CLICK, btn1ck); function btn1ck(e:MouseEvent):void{ gotoAndPlay("2"); }
SECOND FRAME
addChild(cont1); cont1.x = 600; cont1.y = 5; TweenMax.to(cont1, 0.5, {x:5}); for (var i:Number = 0; i < 9; i++){ var fondo1:MovieClip = new cuadro(); cont1.addChild(fondo1); fondo1.x = 25 + fondo1.width * i; fondo1.y = 25; fondo1.alpha = 0; TweenMax.fromTo(fondo1, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay}); delay += 0.05; } for (var j:Number = 0; j < 9; j++){ var fondo2:MovieClip = new cuadro(); cont1.addChild(fondo2); fondo2.x = 25 + fondo2.width * j; fondo2.y = 75; fondo2.alpha = 0; TweenMax.fromTo(fondo2, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay2}); delay2 += 0.05; } for (var k:Number = 0; k < 9; k++){ var fondo3:MovieClip = new cuadro(); cont1.addChild(fondo3); fondo3.x = 25 + fondo3.width * k; fondo3.y = 125; fondo3.alpha = 0; TweenMax.fromTo(fondo3, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay3}); delay3 += 0.05; } for (var l:Number = 0; l < 9; l++){ var fondo4:MovieClip = new cuadro(); cont1.addChild(fondo4); fondo4.x = 25 + fondo4.width * l; fondo4.y = 175; fondo4.alpha = 0; TweenMax.fromTo(fondo4, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay4}); delay4 += 0.05; } for (var ñ:Number = 0; ñ < 9; ñ++){ var fondo5:MovieClip = new cuadro(); cont1.addChild(fondo5); fondo5.x = 25 + fondo5.width * ñ; fondo5.y = 225; fondo5.alpha = 0; TweenMax.fromTo(fondo5, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay5}); delay5 += 0.05; } for (var ij:Number = 0; ij < 9; ij++){ var fondo6:MovieClip = new cuadro(); cont1.addChild(fondo6); fondo6.x = 25 + fondo6.width * ij; fondo6.y = 275; fondo6.alpha = 0; TweenMax.fromTo(fondo6, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay6}); delay6 += 0.05; } for (var ik:Number = 0; ik < 9; ik++){ var fondo7:MovieClip = new cuadro(); cont1.addChild(fondo7); fondo7.x = 25 + fondo7.width * ik; fondo7.y = 325; fondo7.alpha = 0; TweenMax.fromTo(fondo7, 0.5, {autoAlpha:0, scaleX:0.1, scaleY:0.1}, {autoAlpha:1, scaleX:1, scaleY:1, delay:delay7}); delay7 += 0.05; } btn2.addEventListener(MouseEvent.CLICK, btn2ck); function btn2ck(e:MouseEvent):void{ gotoAndPlay("1"); removeChild(cont1); }
As i said in the beginning what i want is what happens in the second example but i want to reduce the amount of code involved, but i haven't been able to make it happen from the code of the first example.
Any help will be extremely helpful.
Thank you,
Rodrigo.
scrollTo Plugin Doubt
in GSAP
Posted
Hi Jack,
Maybe this is a dumb question, but for this version of the scrollTo plugin how does the syntax goes?, is it necessary to declare a variable or not? because with the code below I'm not getting anywhere:
I looked at the code of the plugin but my knowledge of javascript is not even close enough to know how this works
Cheers,
Rodrigo. | https://staging.greensock.com/profile/9252-rodrigo/content/page/71/?type=forums_topic_post | CC-MAIN-2021-49 | refinedweb | 3,112 | 74.39 |
Definition of C++ Formatter
C++ formatter is basically a tool or software available in the market to format/ beautify the C++ source code in the desired format. C++ formatter software provides many coding style schemes which help in formatting with the proper indentation of the source code in various styles or according to the specific requirements of the programmer. These code formatters are also known as beautifier tools in the market. Formatting of source code is must as it helps in the easy understanding and improves the bug hunting which in turn saves a lot of time and money.
Need of C++ Formatters in Source Code
Let us understand the need of C++ formatters with the help of an example:
Code:
#include <iostream>
using namespace std;
intmain()
{
int num1, num2, add;
cout<< "Enter the first integer";
cin>> num1;
cout<< "Enter the second integer";
cin>> num2;
add = num1 + num2;
// Printing the addition result
cout<< "The result is " <<add ;
return 0;
}
The above code is the simple addition of 2 integer numbers. But the way it is written makes it very uneasy or difficult to understand. There is a need for proper indentation, required spaces in the code. Code after ‘{‘ should be written should be indented properly in order to show that the required block of code is a part of it. It should be formatted as given below:
#include <iostream>
using namespace std;
intmain() {
int num1, num2, add;
cout<< "Enter the first integer";
cin>> num1;
cout<< "Enter the second integer";
cin>> num2;
add = num1 + num2;
// Printing the addition result
cout<< "The result is " << add;
return 0;
}
In real time projects, the code is very lengthy and hence has many functions, methods, specific blocks, loops, nested loops, etc. starting and ending multiple times in the code. Moreover, there are specific teams of developers, testers, and maintenance people working on it accessing the same code. So the code should be written in such a way that it would be clear and easily understandable by everyone.
Types of C++ Formatters
There are a lot of formatters / beautifiers available in the market. Let us understand some of the commonly used formatters in detail:
1. Clang-Format
Clang-format is one of the most popular and commonly used open-source formatters used to format C, C++, and Objective C source code. It automatically formats the C++ code and helps in a better understanding of code. It is programmed in C++ and Python language. In order to format the source code automatically according to Electron C++, we need to run the following command:
clang-format -i file_path.cc
Users can also perform the formatting of code according to the specific requirements (other than the one available by default) by inserting the style in ‘.clang-format’ file or using the option -style = “{key:value, ….}”.
2. Artistic Styler
Artistic Styler is a well known formatter and beautifier used to indent the source code of C, C++, CLI, and Java language. In order to address the issue of many formatters for inserting the spaces in place of tabs (inability to distinguish between tabs and spaces in source code), Artistic Style was developed in April 2013. It is written in C++ language and has the ability to re-indent and re-format the source of various languages properly. It can be used by the programmers/ testers directly as a command line or it can also be included in the existing program’s library. This beautifier is available for Windows, Linux, and Mac as well.
3. PrettyPrinter
Pretty Printers and beautifiers are an essential tool while coding in programming languages like C++. It accepts the source code file and generates the other equivalent code file with proper format and the indentation according to the respective syntax and control statements. The main purpose of PrettyPrinter is the proper indentation of code which helps in revealing the nesting of functions, loops with their proper opening and closing braces. Long lines can be folded in smaller ones using the respective functions which helps in the good readability of code. It helps in revealing many syntactical errors to the programmer.
4. Jindent
Jindent is one of the most powerful and commonly used tools used to beautify the source code of Java, C, and C++ language. It automatically indents the code according to the syntax and correct coding conventions which helps in finding the bugs in the code and saves time. One of the cool features of Jindent is that it provides the plugin for almost all popular IDE’s like Visual Studio, Eclipse, Netbeans, etc so that it can be used easily by the programmers/ testers working on them. It allows its invocation from the shell scripts. Jindent provides support for all the Operating systems is it Windows, Mac, or Linux. It is developed in pure Java language and one needs to have a Java Runtime Environment to work properly on it. Jindent is very user friendly as it provides the GUI so that the user can perform actions like formatting settings, changing the environment variables, etc very easily.
5. Highlighter
It is also one of the most commonly used formatters used to format the source code of C++, Perl, HTML, and some other languages as well. It is very user-friendly and hence pretty simple to use. Users just need to copy the source code in the desired text field, choose the C++ language, and Style dropdown to have the required formatting. It provides other interesting features as well like one can also choose to see the line numbers on the left side of code, can directly insert the source code in the HTML page without adding any external CSS and JavaScript file to it.
Conclusion – C++ Formatter
The above description clearly explains the various formatters/beautifiers available in the market used to format the source code of C++ programs. Proper formatting and indentation is a must while working on real time projects as it helps in a clear understanding of code, finding the bugs and hidden errors easily especially the syntactical ones. It helps the maintenance team also to maintain the code properly and proceed further accordingly.
Recommended Articles
This is a guide to C++ Formatter. Here we also discuss the definition and need of c++ formatters along with various types and example. You may also have a look at the following articles to learn more – | https://www.educba.com/c-plus-plus-formatter/?source=leftnav | CC-MAIN-2021-21 | refinedweb | 1,062 | 57.3 |
Up to [cvs.NetBSD.org] / src / lib / libc / gen
Request diff between arbitrary revisions
Default branch: MAIN
Revision 1.13 / (download) - annotate - [select for diffs], Sun May 1 02:49:54 2011 UTC (3 years,.12: +10 -8 lines
Diff to previous 1.12 (colored)
nice should always return EPERM, not EACCES
Revision 1.12 / (download) - annotate - [select for diffs], Thu Aug 7 16:42:53 2003 UTC .11: +3 -7 lines
Diff to previous 1.11 (colored)
Move UCB-licensed code from 4-clause to 3-clause licence. Patches provided by Joel Baker in PR 22280, verified by myself.
Revision 1.9.6.1 / (download) - annotate - [select for diffs], Fri Jun 21 18:18:10 2002 UTC (12 years, 4 months ago) by nathanw
Branch: nathanw_sa
CVS Tags: nathanw_sa_end
Changes since 1.9: +5 -3 lines
Diff to previous 1.9 (colored) next main 1.10 (colored)
Catch up to -current.
Revision 1.9.8.2 / (download) - annotate - [select for diffs], Tue Jun 11 01:55:52 2002 UTC (12.8.1: +5 -6 lines
Diff to previous 1.9.8.1 (colored) to branchpoint 1.9 (colored) next main 1.10 (colored)
Pull up revision 1.11 (requested by kleink in ticket #236): Take into consideration that setpriority() silently fits the given priority into its interval, so we really need to use getpriority() to retrieve the correct return value; noted by Matthias Drochner.
Revision 1.11 / (download) - annotate - [select for diffs], Mon Jun 10 18:32:01 2002 UTC (12 years, 4 months ago) by kleink
Branch: MAIN
CVS Tags: nathanw_sa_before_merge, nathanw_sa_base, fvdl_fs64_base
Changes since 1.10: +5 -6 lines
Diff to previous 1.10 (colored)
Take into consideration that setpriority() silently fits the given priority into its interval, so we really need to use getpriority() to retrieve the correct return value; noted by Matthias Drochner.
Revision 1.9.8.1 / (download) - annotate - [select for diffs], Tue Jun 4 11:42:02 2002 UTC (12 years, 4 months ago) by lukem
Branch: netbsd-1-6
Changes since 1.9: +7 -4 lines
Diff to previous 1.9 (colored)
Pull up revision 1.10 (requested by kleink in ticket #150): As documented, return the new priority if successful; from Matthias Drochner in PR lib/17156.
Revision 1.10 / (download) - annotate - [select for diffs], Tue Jun 4 10:58:12 2002 UTC (12 years, 4 months ago) by kleink
Branch: MAIN
Changes since 1.9: +7 -4 lines
Diff to previous 1.9 (colored)
As documented, return the new priority if successful; from Matthias Drochner in PR lib/17156.
Revision 1.9 / (download) - annotate - [select for diffs], Sat Jan 22 22:19:11 2000 UTC (14 years, 9 months ago) by mycroft
Branch: MAIN
CVS Tags: netbsd-1-6: netbsd-1-6, nathanw_sa
Changes since 1.8: +3 -3 lines
Diff to previous 1.8 (colored)
Delint. Remove trailing ; from uses of __weak_alias(). The macro inserts this if needed.
Revision 1.8 / (download) - annotate - [select for diffs], Tue Jun 9 06:58:41 1998 UTC (16 years, 4 months ago) by mike)
include <errno.h> instead of declaring errno locally
Revision 1.7 / (download) - annotate - [select for diffs], Mon Jul 21 14:07:20 1997 UTC (17:46:05 1997 UTC (17 years, 3 months ago) by christos
Branch: MAIN
Changes since 1.5: +3 -2 lines
Diff to previous 1.5 (colored)
Fix RCSID's
Revision 1.5.4.1 / (download) - annotate - [select for diffs], Thu Sep 19 20:03:21 1996 UTC (18 years, 1 month ago) by jtc
Branch: ivory_soap2
Changes since 1.5: +7 -2 lines
Diff to previous 1.5 (colored) next main 1.6 (colored)
snapshot namespace cleanup: gen
Revision 1.4.4.1 / (download) - annotate - [select for diffs], Tue May 2 19:34:53 1995 UTC (19 years, 5 months ago) by jtc
Branch: ivory_soap
Changes since 1.4: +2 -1 lines
Diff to previous 1.4 (colored) next main 1.5 (colored)
#include "namespace.h"
Revision 1.5 / (download) - annotate - [select for diffs], Mon Feb 27 04:35:24 1995 UTC (19, keeping local changes. Fix up Id format, etc.
Revision 1.1.1.2 / (download) - annotate - [select for diffs] (vendor branch), Sat Feb 25 09:12:16 1995 UTC (19 years, 7 months ago) by cgd
Branch: WFJ-920714, CSRG
CVS Tags: lite-2, lite-1
Changes since 1.1.1.1: +4 -3 lines
Diff to previous 1.1.1.1 (colored)
from lite, with minor name rearrangement to fit.
Revision 1.4 / (download) - annotate - [select for diffs], Mon Sep 27 02:40:38 1993 UTC (21 years -1 lines
Diff to previous 1.3 (colored)
#include <sys/types.h>, for magnum changes.
Revision 1.3 / (download) - annotate - [select for diffs], Thu Aug 26 00:44:51 1993 UTC (21:51 1993 UTC (21 (21. | http://cvsweb.netbsd.org/bsdweb.cgi/src/lib/libc/gen/nice.c | CC-MAIN-2014-42 | refinedweb | 805 | 76.22 |
This adds support for testing host PCI device hotplug/unplug in libvirt drivers. This requires that the host have a usable IOMMU & hardware virt, and that the device in question can be reset safely. Since the TCK can't assume there are any host PCI devices that can be safely messed around with, the person running the test suite must first list one or more devices in the config file. If no devices are listed, the test will automatically skip all parts, rather than failing. * conf/default.cfg: Config entry to specify PCI devices that the TCK can mess around with * lib/Sys/Virt/TCK.pm: API for getting a host PCI device from the config * scripts/domain/250-pci-host-hotplug.t: Test case for PCI device hotplug/unplug. --- conf/default.cfg | 15 ++++ lib/Sys/Virt/TCK.pm | 18 +++++ scripts/domain/250-pci-host-hotplug.t | 117 +++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 0 deletions(-) create mode 100644 scripts/domain/250-pci-host-hotplug.t diff --git a/conf/default.cfg b/conf/default.cfg index f9c2b5c..5b85cbc 100644 --- a/conf/default.cfg +++ b/conf/default.cfg @@ -112,3 +112,18 @@ host_usb_devices = ( # } # Can list more than one USB device if many are available ) + + +# Host PCI devices that the test suite can safely mess around with +# without risk of breaking the host OS. Using a NIC device is the +# most reliable option. Definitely don't try listing a VGA device. +host_pci_devices = ( +# Slot is only required entry, all others default to 0 +# { +# domain = 0000 +# bus = 00 +# slot = 07 +# function = 0 +# } +# Can list more than one PCI device if many are available +) diff --git a/lib/Sys/Virt/TCK.pm b/lib/Sys/Virt/TCK.pm index ce03935..f101937 100644 --- a/lib/Sys/Virt/TCK.pm +++ b/lib/Sys/Virt/TCK.pm @@ -787,4 +787,22 @@ sub get_host_usb_device { return ($bus, $device, $vendor, $product); } +sub get_host_pci_device { + my $self = shift; + my $devindex = @_ ? shift : 0; + + my $devs = $self->config("host_pci_devices", []); + + if ($devindex > $#{$devs}) { + return (); + } + + my $domain = $self->config("host_pci_devices/[$devindex]/domain", 0); + my $bus = $self->config("host_pci_devices/[$devindex]/bus", 0); + my $slot = $self->config("host_pci_devices/[$devindex]/slot"); + my $function = $self->config("host_pci_devices/[$devindex]/function", 0); + + return ($domain, $bus, $slot, $function); +} + 1; diff --git a/scripts/domain/250-pci-host-hotplug.t b/scripts/domain/250-pci-host-hotplug.t new file mode 100644 index 0000000..9ccd036 --- /dev/null +++ b/scripts/domain/250-pci-host-hotplug.t @@ -0,0 +1,117 @@ +# -*- perl -*- +# +# Copyright (C) 2009 Red Hat +# Copyright (C) 2009 Daniel P. Berrange +# +# This program is free software; You can redistribute it and/or modify +# it under the GNU General Public License as published by the Free +# Software Foundation; either version 2, or (at your option) any +# later version +# +# The file "LICENSE" distributed along with this file provides full +# details of the terms and conditions +# + +=pod + +=head1 NAME + +domain/250-pci-host-hotplug.t - verify hot plug & unplug of a host PCI device + +=head1 DESCRIPTION + +The test case validates that it is possible to hotplug a pci +host device to a running domain, and then unplug it again. +This requires that the TCK configuration file have at least +one host PCI device listed. + +This first searches for the node device, then detachs it from +the host OS. Next it performs a reset. Then does the hotplug +and unplug, before finally reattaching to the host. + +=cut + +use strict; +use warnings; + +use Test::More tests => 10; + +use Sys::Virt::TCK; +use Test::Exception; + +my $tck = Sys::Virt::TCK->new(); +my $conn = eval { $tck->setup(); }; +BAIL_OUT "failed to setup test harness: $@" if $@; +END { + $tck->cleanup if $tck; +} + + +my $xml = $tck->generic_domain("tck")->as_xml; + +diag "Creating a new transient domain"; +my $dom; +ok_domain(sub { $dom = $conn->create_domain($xml) }, "created transient domain object"); + + +my ($domain, $bus, $slot, $function) = $tck->get_host_pci_device(); + +SKIP: { + # Must have one item be non-zero + unless ($domain || $bus || $slot || $function) { + skip "No host pci device available in configuration file", 9; + } + + my $nodedev; + my @devs = $conn->list_node_devices("pci"); + foreach my $dev (@devs) { + my $thisxml = $dev->get_xml_description(); + + my $xp = XML::XPath->new(xml => $thisxml); + + #warn $thisxml; + my $ndomain = $xp->find("string(/device/capability[\\n" . + " <source>\n" . + " <address domain='$domain' bus='$bus' slot='$slot' function='$function'/>\n" . + " </source>\n" . + "</hostdev>\n"; + + my $initialxml = $dom->get_xml_description; + + diag "Attaching the new dev $devxml"; + lives_ok(sub { $dom->attach_device($devxml); }, "PCI dev has been attached"); + + my $newxml = $dom->get_xml_description; + ok($newxml =~ m|<hostdev|, "new XML has extra PCI dev present"); + + diag "Detaching the new dev $devxml"; + lives_ok(sub { $dom->detach_device($devxml); }, "PCI dev has been detached"); + + lives_ok(sub { $nodedev->reset() }, "reset the host PCI device"); + lives_ok(sub { $nodedev->reattach() }, "reattached device to host OS"); + + my $finalxml = $dom->get_xml_description; + + is($initialxml, $finalxml, "final XML has removed the disk") +} + -- 1.6.5.2 | https://www.redhat.com/archives/libvir-list/2010-March/msg00168.html | CC-MAIN-2015-48 | refinedweb | 786 | 52.7 |
Get the highlights in your inbox every week.
Teach kids Python by building an interactive game | Opensource.com
Teach kids Python by building an interactive game
Open source tools can help anyone get started learning Python in an easy and fun way—making games.
Opensource.com
Subscribe now
Python.
The Jupyter project is a browser-based Python console, initially designed for data scientists to play with data.
I have a Jupyter Notebook designed to teach you how to make a simple interactive game, which you can download from here. In order to open the file, you will need to install the latest Jupyter project, JupyterLab.
Prerequisites:
- Running a recent version of Python (instructions for Linux, Mac, and Windows)
- Running a recent version of Git (instructions here)
We will briefly configure a virtual environment to create a separate space for the needed libraries. (You can learn more about how virtual environments work here.)
$ git clone
$ cd penguin-bit-by-bit
$ python -m venv venv
$ source ./venv/bin/activate
$ pip install -r requirements.txt
$ jupyter lab .
The last command should open JupyterLab in your default browser at the address. Choose the dynamic_penguin.ipynb file in the left-hand column, and we can get started!
The event loop that will run the gameJupyter runs an event loop internally, which is a process that manages the running of further asynchronous operations. The event loop used in Jupyter is asyncio, and PursuedPyBear runs its own event loop.
We can integrate the two using another library, Twisted, like glue. This sounds complicated, but thankfully, the complexity is hidden behind libraries, which will do all the hard work for us.
The following cell in Jupyter takes care of the first half—integrating Twisted with the asyncio event loop.
The
__file__ = None is needed to integrate PursuedPyBear with Jupyter.
from twisted.internet import asyncioreactor
asyncioreactor.install()
__file__ = None
Next, we need a "setup" function. A setup function is a common term for the configuration of key game elements. However, our function will only put the game "scene" in a global variable. Think of it like us defining the table on which we will play our game.
The following cell in Jupyter Notebook will do the trick.
def setup(scene):
global SCENE
SCENE = scene
Now we need to integrate PursuedPyBear's event loop with Twisted. We use the
txppb module for that:
import txppb
d = txppb.run(setup)
d.addBoth(print)
The
print at the end helps us if the game crashes because of a bug—it will print out a traceback to the Jupyter output.
This will show an empty window, ready for the game elements.
This is where we start taking advantage of Jupyter—traditionally, the whole game needs to be written before we start playing. We buck convention, however, and start playing the game immediately!
Making the game interesting with interaction
It is not a very interesting game, though. It has nothing and just sits there. If we want something, we better add it.
In video game programming, the things moving on the screen are called "sprites." In PursuedPyBear, sprites are represented by classes. A sprite will automatically use an image named the same as the class. I got a little penguin image from Kenney, a collection of free and open source video game assets.
import ppb
class Penguin(ppb.Sprite):
pass
Now let's put the penguin riiiiiight in the middle.
SCENE.add(Penguin(pos=(0,0)))
It carefully sits there in the middle. This is marginally more interesting than having nothing. That's good—this is exactly what we want. In incremental game development, every step should be only marginally more interesting.
Adding movement to our penguin game with ppb
But penguins are not meant to sit still! The penguin should move around. We will have the player control the penguin with the arrow keys. First, let's map the keys to vectors:
from ppb import keycodes
DIRECTIONS = {keycodes.Left: ppb.Vector(-1,0), keycodes.Right: ppb.Vector(1,0),
keycodes.Up: ppb.Vector(0, 1), keycodes.Down: ppb.Vector(0, -1)}
Now we will use a utility library. The
set_in_class function sets the method in the class. Python's ability to add functions to classes retroactively is really coming in handy!
from mzutil import set_in_class
Penguin.direction = ppb.Vector(0, 0)
@set_in_class(Penguin)
def on_update(self, update_event, signal):
self.position += update_event.time_delta * self.direction
The code for
set_in_class is not long, but it does use some non-trivial Python tricks. We will put the full utility library at the end of the article for review, and for the sake of flow, we will skip it for now.
Back to the penguin!
Oh, um, well.
The penguin is diligently moving…at zero speed, precisely nowhere. Let's manually set the direction to see what happens.
Penguin.direction = DIRECTIONS[keycodes.Up]/4
The direction is up, but a little slow. This gives enough time to set the penguin's direction back to zero manually. Let's do that now!
Penguin.direction = ppb.Vector(0, 0)
Adding interactivity to our penguin game
Phew, that was exciting—but not what we wanted. We want the penguin to respond to keypresses. Controlling it from the code is what gamers refer to as "cheating."
Let's set it to set the direction to the keypress, and back to zero when the key is released.
@set_in_class(Penguin)
def on_key_pressed(self, key_event, signal):
self.direction = DIRECTIONS.get(key_event.key, ppb.Vector(0, 0))
@set_in_class(Penguin)
def on_key_released(self, key_event, signal):
if key_event.key in DIRECTIONS:
self.direction = ppb.Vector(0, 0)
The Penguin is a bit bored, isn't it? Maybe we should give it an orange ball to play with.
class OrangeBall(ppb.Sprite):
pass
Again, I made sure to have an image called
orangeball.png. Now let's put the ball on the left side of the screen.
SCENE.add(OrangeBall(pos=(-4, 0)))
Try as it might, the penguin cannot kick the ball. Let's have the ball move away from the penguin when it approaches.
First, let's define what it means to "kick" the ball. Kicking the ball means deciding where it is going to be in one second, and then setting its state to "moving."
At first, we will just move it by having the first update move it to the target position.
OrangeBall.is_moving = False
@set_in_class(OrangeBall)
def kick(self, direction):
self.target_position = self.position + direction
self.original_position = self.position
self.time_passed = 0
self.is_moving = True
@set_in_class(OrangeBall)
def on_update(self, update_event, signal):
if self.is_moving:
self.position = self.target_position
self.is_moving = False
Now, let's kick it!
ball, = SCENE.get(kind=OrangeBall)
ball.kick(ppb.Vector(1, 1))
But this just teleports the ball; it immediately changes the position. In real life, the ball goes between the intermediate points. When it's moving, it will interpolate between where it is and where it needs to go.
Naively, we would use linear interpolation. But a cool video game trick is to use an "easing" function. Here, we use the common "smooth step."
from mzutil import smooth_step
@set_in_class(OrangeBall)
def maybe_move(self, update_event, signal):
if not self.is_moving:
return False
self.time_passed += update_event.time_delta
if self.time_passed >= 1:
self.position = self.target_position
self.is_moving = False
return False
t = smooth_step(self.time_passed)
self.position = (1-t) * self.original_position + t * self.target_position
return True
OrangeBall.on_update = OrangeBall.maybe_move
Now, let's try kicking it again.
ball, = SCENE.get(kind=OrangeBall)
ball.kick(ppb.Vector(1, -1))
But really, the penguin should be kicking the ball. When the ball sees that it is colliding with the penguin, it will kick itself in the opposite direction. If the penguin has gotten right on top of it, the ball will choose a random direction.
The update function now calls
maybe_move and will only check collision if we are not moving right now.
from mzutil import collide
import random
OrangeBall.x_offset = OrangeBall.y_offset = 0.25
@set_in_class(OrangeBall)
def on_update(self, update_event,signal):
if self.maybe_move(update_event, signal):
return
penguin, = update_event.scene.get(kind=Penguin)
if not collide(penguin, self):
return
try:
direction = (self.position - penguin.position).normalize()
except ZeroDivisionError:
direction = ppb.Vector(random.uniform(-1, 1), random.uniform(-1, 1)).normalize()
self.kick(direction)
But just kicking a ball around is not that much fun. Let's add a target.
class Target(ppb.Sprite):
pass
Let's put the target at the right of the screen.
SCENE.add(Target(pos=(4, 0)))
Rewarding our penguin
Now, we will want a reward for the penguin when it kicks the ball into the target. How about a fish?
class Fish(ppb.Sprite):
pass
When the target gets the ball, it should remove it and create a new ball at the other end of the screen. Then, it will cause a fish to appear.
@set_in_class(Target)
def on_update(self, update_event, signal):
for ball in update_event.scene.get(kind=OrangeBall):
if not collide(ball, self):
continue
update_event.scene.remove(ball)
update_event.scene.add(OrangeBall(pos=(-4, random.uniform(-3, 3))))
update_event.scene.add(Fish(pos=(random.uniform(-4, -3),
random.uniform(-3, 3))))
We want to have the penguin eat the fish. When the fish sees the penguin, it should vanish.
Fish.x_offset = 0.05
Fish.y_offset = 0.2
@set_in_class(Fish)
def on_update(self, update_event,signal):
penguin, = update_event.scene.get(kind=Penguin)
if collide(penguin, self):
update_event.scene.remove(self)
It works!
Iterative game design is fun for penguins and people alike!
This has all the makings of a game: the player-controlled penguin kicks the ball into the target, gets a fish, eats the fish, and kicks a new ball. This would work as a "grinding level" part of a game, or we could add obstacles to make the penguin's life harder.
Whether you are an experienced programmer, or just getting started, programming video games is fun. PursuedPyBear with Jupyter brings all the joy of classic 2D games with the interactive programming capabilities of the classic environments like Logo and Smalltalk. Time to enjoy a little retro 80s!
Appendix
Here is the full source code of our utility library. It provides some interesting concepts to make the game board work. For more on how it does that, read about collision detection, setattr. and the __name__ attribute.
def set_in_class(klass):
def retval(func):
setattr(klass, func.__name__, func)
return func
return retval
def smooth_step(t):
return t * t * (3 - 2 * t)
_WHICH_OFFSET = dict(
top='y_offset',
bottom='y_offset',
left='x_offset',
right='x_offset'
)
_WHICH_SIGN = dict(top=1, bottom=-1, left=-1, right=1)
def _effective_side(sprite, direction):
return (getattr(sprite, direction) -
_WHICH_SIGN[direction] *
getattr(sprite, _WHICH_OFFSET[direction], 0))
def _extreme_side(sprite1, sprite2, direction):
sign = -_WHICH_SIGN[direction]
return sign * max(sign * _effective_side(sprite1, direction),
sign * _effective_side(sprite2, direction))
def collide(sprite1, sprite2):
return (_extreme_side(sprite1, sprite2, 'bottom') <
_extreme_side(sprite1, sprite2, 'top')
and
_extreme_side(sprite1, sprite2, 'left') <
_extreme_side(sprite1, sprite2, 'right'))
9 Comments
Very nice, Moshe!
This is such a great article! Thanks for writing it
Yep I am agree with you. Making game is the best and fun way to learn programming.
This is a great idea! I've always thought that introductions to programming should be cantered around the thing that makes most people want to learn: game design. This certainly isn't the first platform to take this approach, but it's one of the first ones I've seen do it right. Too many "introductory" coding tools and courses fall flat due to excessively hand-holding gimics that alienate experienced coders and form a barrier to learning more "real" languages. This doesn't seem to do any of that; it just smooths over some of coding's more complicated or tedious aspects and leads directly into a very popular, mainstream language.
That's basically how I learned programming: After learning the basic fundamentals (thanks to Khan Academy), I started making simple games. My projects grew more complex as I refined my skills and researched the specific commands I needed.
After building a (very) rudimentary and limited 3D engine, I realized that i had outgrown Khan Academy's editor and decided to move on to more advanced languages like Java and C++. It wasn't until my freshman year of college (after years of coding) that I started to branch out and try things other than game development.
Thanks for writing this.
My child 10 years old already goes to IT school, I think this is a promising education in our country
1234
My friends told me about Qweetly.com. I’ve gone there to read various templates of A-winning academic papers. They were absolutely free.
Very useful information! | https://opensource.com/article/20/5/python-games | CC-MAIN-2020-29 | refinedweb | 2,105 | 59.5 |
This tutorial depends on step-6.
In this program, we will mainly consider two aspects:
Besides these topics, again a variety of improvements and tricks will be shown.
There has probably never been a non-trivial finite element program that worked right from the start. It is therefore necessary to find ways to verify whether a computed solution is correct or not. Usually, this is done by choosing the set-up of a simulation in such a way that we know the exact continuous solution and evaluate the difference between continuous and computed discrete solution. If this difference converges to zero with the right order of convergence, this is already a good indication of correctness, although there may be other sources of error persisting which have only a small contribution to the total error or are of higher order. In the context of finite element simulations, this technique is often called the Method of Manufactured Solution.
In this example, we will not go into the theories of systematic software verification which is a very complicated problem. Rather we will demonstrate the tools which deal.II can offer in this respect. This is basically centered around the functionality of a single function, VectorTools::integrate_difference(). This function computes the difference between a given continuous function and a finite element field in various norms on each cell. Of course, like with any other integral, we can only evaluate these norms using quadrature formulas; the choice of the right quadrature formula is therefore crucial to the accurate evaluation of the error. This holds in particular for the \(L_\infty\) norm, where we evaluate the maximal deviation of numerical and exact solution only at the quadrature points; one should then not try to use a quadrature rule whose evaluation occurs only at points where super-convergence might occur, such as the Gauss points of the lowest-order Gauss quadrature formula for which the integrals in the assembly of the matrix is correct (e.g., for linear elements, do not use the QGauss(2) quadrature formula). In fact, this is generally good advice also for the other norms: if your quadrature points are fortuitously chosen at locations where the error happens to be particularly small due to superconvergence, the computed error will look like it is much smaller than it really is and may even suggest a higher convergence order. Consequently, we will choose a different quadrature formula for the integration of these error norms than for the assembly of the linear system.
The function VectorTools::integrate_difference() evaluates the desired norm on each cell \(K\) of the triangulation and returns a vector which holds these values for each cell. From the local values, we can then obtain the global error. For example, if the vector \((e_i)\) contains the local \(L_2\) norms, then
\[ E = \| {\mathbf e} \| = \left( \sum_i e_i^2 \right)^{1/2} \]
is the global \(L_2\) error.
In the program, we will show how to evaluate and use these quantities, and we will monitor their values under mesh refinement. Of course, we have to choose the problem at hand such that we can explicitly state the solution and its derivatives, but since we want to evaluate the correctness of the program, this is only reasonable. If we know that the program produces the correct solution for one (or, if one wants to be really sure: many) specifically chosen right hand sides, we can be rather confident that it will also compute the correct solution for problems where we don't know the exact values.
In addition to simply computing these quantities, we will show how to generate nicely formatted tables from the data generated by this program that automatically computes convergence rates etc. In addition, we will compare different strategies for mesh refinement.
The second, totally unrelated, subject of this example program is the use of non-homogeneous boundary conditions. These are included into the variational form using boundary integrals which we have to evaluate numerically when assembling the right hand side vector.
Before we go into programming, let's have a brief look at the mathematical formulation. The equation that we want to solve here is the Helmholtz equation "with the nice sign":
\[ -\Delta u + \alpha u = f, \]
on the square \([-1,1]^2\) with \(\alpha=1\), augmented by boundary conditions
\[ u = g_1 \]
on some part \(\Gamma_1\) of the boundary \(\Gamma\), and
\[ {\mathbf n}\cdot \nabla u = g_2 \]
on the rest \(\Gamma_2 = \Gamma \backslash \Gamma_1\). In our particular testcase, we will use \(\Gamma_1=\Gamma \cap\{\{x=1\} \cup \{y=1\}\}\). (We say that this equation has the "nice sign" because the operator \(-\Delta + \alpha I\) with the identity \(I\) is a positive definite operator; the equation with the "bad sign" is \(-\Delta u - \alpha u\) and results from modeling time-harmonic processes. The operator is not necessarily positive definite, and this leads to all sorts of issues we need not discuss here.)
Because we want to verify the convergence of our numerical solution \(u_h\), we want a setup so that we know the exact solution \(u\). This is where the Method of Manufactured Solutions comes in. To this end, let us choose a function
\[ \bar u(x) = \sum_{i=1}^3 \exp\left(-\frac{|x-x_i|^2}{\sigma^2}\right) \]
where the centers \(x_i\) of the exponentials are \(x_1=(-\frac 12,\frac 12)\), \(x_2=(-\frac 12,-\frac 12)\), and \(x_3=(\frac 12,-\frac 12)\), and the half width is set to \(\sigma=\frac {1}{8}\). The method of manufactured solution then says: choose
\begin{align*} f &= -\Delta \bar u + \bar u, \\ g_1 &= \bar u|_{\Gamma_1}, \\ g_2 &= {\mathbf n}\cdot \nabla\bar u|_{\Gamma_2}. \end{align*}
With this particular choice, we infer that of course the solution of the original problem happens to be \(u=\bar u\). In other words, by choosing the right hand sides of the equation and the boundary conditions in a particular way, we have manufactured ourselves a problem to which we know the solution. This allows us then to compute the error of our numerical solution. In the code below, we represent \(\bar u\) by the
Solution class, and other classes will be used to denote \(\bar u|_{\Gamma_1}\) and \({\mathbf n}\cdot \nabla\bar u|_{\Gamma_2}\).
Using the above definitions, we can state the weak formulation of the equation, which reads: find \(u\in H^1_g=\{v\in H^1: v|_{\Gamma_1}=g_1\}\) such that
\[ {(\nabla u, \nabla v)}_\Omega + {(u,v)}_\Omega = {(f,v)}_\Omega + {(g_2,v)}_{\Gamma_2} \]
for all test functions \(v\in H^1_0=\{v\in H^1: v|_{\Gamma_1}=0\}\). The boundary term \({(g_2,v)}_{\Gamma_2}\) has appeared by integration by parts and using \(\partial_n u=g_2\) on \(\Gamma_2\) and \(v=0\) on \(\Gamma_1\). The cell matrices and vectors which we use to build the global matrices and right hand side vectors in the discrete formulation therefore look like this:
\begin{eqnarray*} A_{ij}^K &=& \left(\nabla \varphi_i, \nabla \varphi_j\right)_K +\left(\varphi_i, \varphi_j\right)_K, \\ f_i^K &=& \left(f,\varphi_i\right)_K +\left(g_2, \varphi_i\right)_{\partial K\cap \Gamma_2}. \end{eqnarray*}
Since the generation of the domain integrals has been shown in previous examples several times, only the generation of the contour integral is of interest here. It basically works along the following lines: for domain integrals we have the
FEValues class that provides values and gradients of the shape values, as well as Jacobian determinants and other information and specified quadrature points in the cell; likewise, there is a class
FEFaceValues that performs these tasks for integrations on faces of cells. One provides it with a quadrature formula for a manifold with dimension one less than the dimension of the domain is, and the cell and the number of its face on which we want to perform the integration. The class will then compute the values, gradients, normal vectors, weights, etc. at the quadrature points on this face, which we can then use in the same way as for the domain integrals. The details of how this is done are shown in the following program.
Besides the mathematical topics outlined above, we also want to use this program to illustrate one aspect of good programming practice, namely the use of namespaces. In programming the deal.II library, we have take great care not to use names for classes and global functions that are overly generic, say
f(), sz(), rhs() etc. Furthermore, we have put everything into namespace
dealii. But when one writes application programs that aren't meant for others to use, one doesn't always pay this much attention. If you follow the programming style of step-1 through step-6, these functions then end up in the global namespace where, unfortunately, a lot of other stuff also lives (basically everything the C language provides, along with everything you get from the operating system through header files). To make things a bit worse, the designers of the C language were also not always careful in avoiding generic names; for example, the symbols
j1, jn are defined in C header files (they denote Bessel functions).
To avoid the problems that result if names of different functions or variables collide (often with confusing error messages), it is good practice to put everything you do into a namespace. Following this style, we will open a namespace
Step7 at the top of the program, import the deal.II namespace into it, put everything that's specific to this program (with the exception of
main(), which must be in the global namespace) into it, and only close it at the bottom of the file. In other words, the structure of the program is of the kind
We will follow this scheme throughout the remainder of the deal.II tutorial.
These first include files have all been treated in previous examples, so we won't explain what is in them again.
In this example, we will not use the numeration scheme which is used per default by the DoFHandler class, but will renumber them using the Cuthill-McKee algorithm. As has already been explained in step-2, the necessary functions are declared in the following file :
Then we will show a little trick how we can make sure that objects are not deleted while they are still in use. For this purpose, deal.II has the SmartPointer helper class, which is declared in this file :
Next, we will want to use the function VectorTools::integrate_difference() mentioned in the introduction, and we are going to use a ConvergenceTable that collects all important data during a run and prints it at the end as a table. These comes from the following two files:
And finally, we need to use the FEFaceValues class, which is declared in the same file as the FEValues class:
The last step before we go on with the actual implementation is to open a namespace
Step7 into which we will put everything, as discussed at the end of the introduction, and to import the members of namespace
dealii into it:
Before implementing the classes that actually solve something, we first declare and define some function classes that represent right hand side and solution classes. Since we want to compare the numerically obtained solution to the exact continuous one, we need a function object that represents the continuous solution. On the other hand, we need the right hand side function, and that one of course shares some characteristics with the solution. In order to reduce dependencies which arise if we have to change something in both classes at the same time, we move the common characteristics of both functions into a base class.
The common characteristics for solution (as explained in the introduction, we choose a sum of three exponentials) and right hand side, are these: the number of exponentials, their centers, and their half width. We declare them in the following class. Since the number of exponentials is a compile-time constant we use a fixed-length
std::array to store the center points:
The variables which denote the centers and the width of the exponentials have just been declared, now we still need to assign values to them. Here, we can show another small piece of template sorcery, namely how we can assign different values to these variables depending on the dimension. We will only use the 2d case in the program, but we show the 1d case for exposition of a useful technique.
First we assign values to the centers for the 1d case, where we place the centers equidistantly at -1/3, 0, and 1/3. The
template <> header for this definition indicates an explicit specialization. This means, that the variable belongs to a template, but that instead of providing the compiler with a template from which it can specialize a concrete variable by substituting
dim with some concrete value, we provide a specialization ourselves, in this case for
dim=1. If the compiler then sees a reference to this variable in a place where the template argument equals one, it knows that it doesn't have to generate the variable from a template by substituting
dim, but can immediately use the following definition:
Likewise, we can provide an explicit specialization for
dim=2. We place the centers for the 2d case as follows:
There remains to assign a value to the half-width of the exponentials. We would like to use the same value for all dimensions. In this case, we simply provide the compiler with a template from which it can generate a concrete instantiation by substituting
dim with a concrete value:
After declaring and defining the characteristics of solution and right hand side, we can declare the classes representing these two. They both represent continuous functions, so they are derived from the Function<dim> base class, and they also inherit the characteristics defined in the SolutionBase class.
The actual classes are declared in the following. Note that in order to compute the error of the numerical solution against the continuous one in the L2 and H1 (semi-)norms, we have to provide value and gradient of the exact solution. This is more than we have done in previous examples, where all we provided was the value at one or a list of points. Fortunately, the Function class also has virtual functions for the gradient, so we can simply overload the respective virtual member functions in the Function base class. Note that the gradient of a function in
dim space dimensions is a vector of size
dim, i.e. a tensor of rank 1 and dimension
dim. As for so many other things, the library provides a suitable class for this. One new thing about this class is that it explicitly uses the Tensor objects, which previously appeared as intermediate terms in step-3 and step-4. A tensor is a generalization of scalars (rank zero tensors), vectors (rank one tensors), and matrices (rank two tensors), as well as higher dimensional objects. The Tensor class requires two template arguments: the tensor rank and tensor dimension. For example, here we use tensors of rank one (vectors) with dimension
dim (so they have
dim entries.) While this is a bit less flexible than using Vector, the compiler can generate faster code when the length of the vector is known at compile time. Additionally, specifying a Tensor of rank one and dimension
dim guarantees that the tensor will have the right shape (since it is built into the type of the object itself), so the compiler can catch most size-related mistakes for us.
Like in step-4, for compatibility with some compilers we explicitly declare the default constructor:
The actual definition of the values and gradients of the exact solution class is according to their mathematical definition and does not need much explanation.
The only thing that is worth mentioning is that if we access elements of a base class that is template dependent (in this case the elements of SolutionBase<dim>), then the C++ language forces us to write
this->source_centers, and similarly for other members of the base class. C++ does not require the
this-> qualification if the base class is not template dependent. The reason why this is necessary is complicated; C++ books will explain under the phrase two-stage (name) lookup, and there is also a lengthy description in the deal.II FAQs.
Likewise, this is the computation of the gradient of the solution. In order to accumulate the gradient from the contributions of the exponentials, we allocate an object
return_value that denotes the mathematical quantity of a tensor of rank
1 and dimension
dim. Its default constructor sets it to the vector containing only zeroes, so we need not explicitly care for its initialization.
Note that we could as well have taken the type of the object to be Point<dim> instead of Tensor<1,dim>. Tensors of rank 1 and points are almost exchangeable, and have only very slightly different mathematical meanings. In fact, the Point<dim> class is derived from the Tensor<1,dim> class, which makes up for their mutual exchange ability. Their main difference is in what they logically mean: points are points in space, such as the location at which we want to evaluate a function (see the type of the first argument of this function for example). On the other hand, tensors of rank 1 share the same transformation properties, for example that they need to be rotated in a certain way when we change the coordinate system; however, they do not share the same connotation that points have and are only objects in a more abstract space than the one spanned by the coordinate directions. (In fact, gradients live in `reciprocal' space, since the dimension of their components is not that of a length, but of one over length).
For the gradient, note that its direction is along (x-x_i), so we add up multiples of this distance vector, where the factor is given by the exponentials.
Besides the function that represents the exact solution, we also need a function which we can use as right hand side when assembling the linear system of discretized equations. This is accomplished using the following class and the following definition of its function. Note that here we only need the value of the function, not its gradients or higher derivatives.
The value of the right hand side is given by the negative Laplacian of the solution plus the solution itself, since we wanted to solve Helmholtz's equation:
The first contribution is the Laplacian:
And the second is the solution itself:
Then we need the class that does all the work. Except for its name, its interface is mostly the same as in previous examples.
One of the differences is that we will use this class in several modes: for different finite elements, as well as for adaptive and global refinement. The decision whether global or adaptive refinement shall be used is communicated to the constructor of this class through an enumeration type declared at the top of the class. The constructor then takes a finite element object and the refinement mode as arguments.
The rest of the member functions are as before except for the
process_solution function: After the solution has been computed, we perform some analysis on it, such as computing the error in various norms. To enable some output, it requires the number of the refinement cycle, and consequently gets it as an argument.
Now for the data elements of this class. Among the variables that we have already used in previous examples, only the finite element object differs: The finite elements which the objects of this class operate on are passed to the constructor of this class. It has to store a pointer to the finite element for the member functions to use. Now, for the present class there is no big deal in that, but since we want to show techniques rather than solutions in these programs, we will here point out a problem that often occurs – and of course the right solution as well.
Consider the following situation that occurs in all the example programs: we have a triangulation object, and we have a finite element object, and we also have an object of type DoFHandler that uses both of the first two. These three objects all have a lifetime that is rather long compared to most other objects: they are basically set at the beginning of the program or an outer loop, and they are destroyed at the very end. The question is: can we guarantee that the two objects which the DoFHandler uses, live at least as long as they are in use? This means that the DoFHandler must have some kind of knowledge on the destruction of the other objects.
We will show here how the library managed to find out that there are still active references to an object and the object is still alive from the point of view of a using object. Basically, the method is along the following line: all objects that are subject to such potentially dangerous pointers are derived from a class called Subscriptor. For example, the Triangulation, DoFHandler, and a base class of the FiniteElement class are derived from Subscriptor. This latter class does not offer much functionality, but it has a built-in counter which we can subscribe to, thus the name of the class. Whenever we initialize a pointer to that object, we can increase its use counter, and when we move away our pointer or do not need it any more, we decrease the counter again. This way, we can always check how many objects still use that object. Additionally, the class requires to know about a pointer that it can use to tell the subscribing object about its invalidation.
If an object of a class that is derived from the Subscriptor class is destroyed, it also has to call the destructor of the Subscriptor class. In this destructor, we tell all the subscribing objects about the invalidation of the object using the stored pointers. The same happens when the object appears on the right hand side of a move expression, i.e., it will no longer contain valid content after the operation. The subscribing class is expected to check the value stored in its corresponding pointer before trying to access the object subscribed to.
This is exactly what the SmartPointer class is doing. It basically acts just like a pointer, i.e. it can be dereferenced, can be assigned to and from other pointers, and so on. On top of that it uses the mechanism described above to find out if the pointer this class is representing is dangling when we try to dereference it. In that case an exception is thrown.
In the present example program, we want to protect the finite element object from the situation that for some reason the finite element pointed to is destroyed while still in use. We therefore use a SmartPointer to the finite element object; since the finite element object is actually never changed in our computations, we pass a const FiniteElement<dim> as template argument to the SmartPointer class. Note that the pointer so declared is assigned at construction time of the solve object, and destroyed upon destruction, so the lock on the destruction of the finite element object extends throughout the lifetime of this HelmholtzProblem object.
The second to last variable stores the refinement mode passed to the constructor. Since it is only set in the constructor, we can declare this variable constant, to avoid that someone sets it involuntarily (e.g. in an `if'-statement where == was written as = by chance).
For each refinement level some data (like the number of cells, or the L2 error of the numerical solution) will be generated and later printed. The TableHandler can be used to collect all this data and to output it at the end of the run as a table in a simple text or in LaTeX format. Here we don't only use the TableHandler but we use the derived class ConvergenceTable that additionally evaluates rates of convergence:
In the constructor of this class, we only set the variables passed as arguments, and associate the DoF handler object with the triangulation (which is empty at present, however).
This is no different than before:
The following function sets up the degrees of freedom, sizes of matrices and vectors, etc. Most of its functionality has been showed in previous examples, the only difference being the renumbering step immediately after first distributing degrees of freedom.
Renumbering the degrees of freedom is not overly difficult, as long as you use one of the algorithms included in the library. It requires only a single line of code. Some more information on this can be found in step-2.
Note, however, that when you renumber the degrees of freedom, you must do so immediately after distributing them, since such things as hanging nodes, the sparsity pattern etc. depend on the absolute numbers which are altered by renumbering.
The reason why we introduce renumbering here is that it is a relatively cheap operation but often has a beneficial effect: While the CG iteration itself is independent of the actual ordering of degrees of freedom, we will use SSOR as a preconditioner. SSOR goes through all degrees of freedom and does some operations that depend on what happened before; the SSOR operation is therefore not independent of the numbering of degrees of freedom, and it is known that its performance improves by using renumbering techniques. A little experiment shows that indeed, for example, the number of CG iterations for the fifth refinement cycle of adaptive refinement with the Q1 program used here is 40 without, but 36 with renumbering. Similar savings can generally be observed for all the computations in this program.
Assembling the system of equations for the problem at hand is mostly as for the example programs before. However, some things have changed anyway, so we comment on this function fairly extensively.
At the top of the function you will find the usual assortment of variable declarations. Compared to previous programs, of importance is only that we expect to solve problems also with bi-quadratic elements and therefore have to use sufficiently accurate quadrature formula. In addition, we need to compute integrals over faces, i.e.
dim-1 dimensional objects. The declaration of a face quadrature formula is then straightforward:
Then we need objects which can evaluate the values, gradients, etc of the shape functions at the quadrature points. While it seems that it should be feasible to do it with one object for both domain and face integrals, there is a subtle difference since the weights in the domain integrals include the measure of the cell in the domain, while the face integral quadrature requires the measure of the face in a lower-dimensional manifold. Internally these two classes are rooted in a common base class which does most of the work and offers the same interface to both domain and interface integrals.
For the domain integrals in the bilinear form for Helmholtz's equation, we need to compute the values and gradients, as well as the weights at the quadrature points. Furthermore, we need the quadrature points on the real cell (rather than on the unit cell) to evaluate the right hand side function. The object we use to get at this information is the FEValues class discussed previously.
For the face integrals, we only need the values of the shape functions, as well as the weights. We also need the normal vectors and quadrature points on the real cell since we want to determine the Neumann values from the exact solution object (see below). The class that gives us this information is called FEFaceValues:
Then we need some objects already known from previous examples: An object denoting the right hand side function, its values at the quadrature points on a cell, the cell matrix and right hand side, and the indices of the degrees of freedom on a cell.
Note that the operations we will do with the right hand side object are only querying data, never changing the object. We can therefore declare it
const:
Finally we define an object denoting the exact solution function. We will use it to compute the Neumann values at the boundary from it. Usually, one would of course do so using a separate object, in particular since the exact solution is generally unknown while the Neumann values are prescribed. We will, however, be a little bit lazy and use what we already have in information. Real-life programs would to go other ways here, of course.
Now for the main loop over all cells. This is mostly unchanged from previous examples, so we only comment on the things that have changed.
The first thing that has changed is the bilinear form. It now contains the additional term from the Helmholtz equation:
Then there is that second term on the right hand side, the contour integral. First we have to find out whether the intersection of the faces of this cell with the boundary part Gamma2 is nonzero. To this end, we loop over all faces and check whether its boundary indicator equals
1, which is the value that we have assigned to that portions of the boundary composing Gamma2 in the
run() function further below. (The default value of boundary indicators is
0, so faces can only have an indicator equal to
1 if we have explicitly set it.)
If we came into here, then we have found an external face belonging to Gamma2. Next, we have to compute the values of the shape functions and the other quantities which we will need for the computation of the contour integral. This is done using the
reinit function which we already know from the FEValue class:
And we can then perform the integration by using a loop over all quadrature points.
On each quadrature point, we first compute the value of the normal derivative. We do so using the gradient of the exact solution and the normal vector to the face at the present quadrature point obtained from the
fe_face_values object. This is then used to compute the additional contribution of this face to the right hand side:
Now that we have the contributions of the present cell, we can transfer it to the global matrix and right hand side vector, as in the examples before:
Likewise, elimination and treatment of boundary values has been shown previously.
We note, however that now the boundary indicator for which we interpolate boundary values (denoted by the second parameter to
interpolate_boundary_values) does not represent the whole boundary any more. Rather, it is that portion of the boundary which we have not assigned another indicator (see below). The degrees of freedom at the boundary that do not belong to Gamma1 are therefore excluded from the interpolation of boundary values, just as we want.
Solving the system of equations is done in the same way as before:
Now for the function doing grid refinement. Depending on the refinement mode passed to the constructor, we do global or adaptive refinement.
Global refinement is simple, so there is not much to comment on. In case of adaptive refinement, we use the same functions and classes as in the previous example program. Note that one could treat Neumann boundaries differently than Dirichlet boundaries, and one should in fact do so here since we have Neumann boundary conditions on part of the boundaries, but since we don't have a function here that describes the Neumann values (we only construct these values from the exact solution when assembling the matrix), we omit this detail even though doing this in a strictly correct way would not be hard to add.
At the end of the switch, we have a default case that looks slightly strange: an
Assert statement with a
false condition. Since the
Assert macro raises an error whenever the condition is false, this means that whenever we hit this statement the program will be aborted. This in intentional: Right now we have only implemented two refinement strategies (global and adaptive), but someone might want to add a third strategy (for example adaptivity with a different refinement criterion) and add a third member to the enumeration that determines the refinement mode. If it weren't for the default case of the switch statement, this function would simply run to its end without doing anything. This is most likely not what was intended. One of the defensive programming techniques that you will find all over the deal.II library is therefore to always have default cases that abort, to make sure that values not considered when listing the cases in the switch statement are eventually caught, and forcing programmers to add code to handle them. We will use this same technique in other places further down as well.
Finally we want to process the solution after it has been computed. For this, we integrate the error in various (semi-)norms, and we generate tables that will later be used to display the convergence against the continuous solution in a nice format.
Our first task is to compute error norms. In order to integrate the difference between computed numerical solution and the continuous solution (described by the Solution class defined at the top of this file), we first need a vector that will hold the norm of the error on each cell. Since accuracy with 16 digits is not so important for these quantities, we save some memory by using
float instead of
double values.
The next step is to use a function from the library which computes the error in the L2 norm on each cell. We have to pass it the DoF handler object, the vector holding the nodal values of the numerical solution, the continuous solution as a function object, the vector into which it shall place the norm of the error on each cell, a quadrature rule by which this norm shall be computed, and the type of norm to be used. Here, we use a Gauss formula with three points in each space direction, and compute the L2 norm.
Finally, we want to get the global L2 norm. This can of course be obtained by summing the squares of the norms on each cell, and taking the square root of that value. This is equivalent to taking the l2 (lower case
l) norm of the vector of norms on each cell:
By same procedure we get the H1 semi-norm. We re-use the
difference_per_cell vector since it is no longer used after computing the
L2_error variable above. The global \(H^1\) semi-norm error is then computed by taking the sum of squares of the errors on each individual cell, and then the square root of it – an operation that is conveniently performed by VectorTools::compute_global_error.
Finally, we compute the maximum norm. Of course, we can't actually compute the true maximum, but only the maximum at the quadrature points. Since this depends quite sensitively on the quadrature rule being used, and since we would like to avoid false results due to super-convergence effects at some points, we use a special quadrature rule that is obtained by iterating the trapezoidal rule by the degree of the finite element times two plus one in each space direction. Note that the constructor of the QIterated class takes a one-dimensional quadrature rule and a number that tells it how often it shall use this rule in each space direction.
Using this special quadrature rule, we can then try to find the maximal error on each cell. Finally, we compute the global L infinity error from the L infinity errors on each cell with a call to VectorTools::compute_global_error.
After all these errors have been computed, we finally write some output. In addition, we add the important data to the TableHandler by specifying the key of the column and the value. Note that it is not necessary to define column keys beforehand – it is sufficient to just add values, and columns will be introduced into the table in the order values are added the first time.
As in previous example programs, the
run function controls the flow of execution. The basic layout is as in previous examples: an outer loop over successively refined grids, and in this loop first problem setup, assembling the linear system, solution, and post-processing.
The first task in the main loop is creation and refinement of grids. This is as in previous examples, with the only difference that we want to have part of the boundary marked as Neumann type, rather than Dirichlet.
For this, we will use the following convention: Faces belonging to Gamma1 will have the boundary indicator
0 (which is the default, so we don't have to set it explicitly), and faces belonging to Gamma2 will use
1 as boundary indicator. To set these values, we loop over all cells, then over all faces of a given cell, check whether it is part of the boundary that we want to denote by Gamma2, and if so set its boundary indicator to
1. For the present program, we consider the left and bottom boundaries as Gamma2. We determine whether a face is part of that boundary by asking whether the x or y coordinates (i.e. vector components 0 and 1) of the midpoint of a face equals -1, up to some small wiggle room that we have to give since it is instable to compare floating point numbers that are subject to round off in intermediate computations.
It is worth noting that we have to loop over all cells here, not only the active ones. The reason is that upon refinement, newly created faces inherit the boundary indicator of their parent face. If we now only set the boundary indicator for active faces, coarsen some cells and refine them later on, they will again have the boundary indicator of the parent cell which we have not modified, instead of the one we intended. Consequently, we have to change the boundary indicators of faces of all cells on Gamma2, whether they are active or not. Alternatively, we could of course have done this job on the coarsest mesh (i.e. before the first refinement step) and refined the mesh only after that.
The next steps are already known from previous examples. This is mostly the basic set-up of every finite element program:
The last step in this chain of function calls is usually the evaluation of the computed solution for the quantities one is interested in. This is done in the following function. Since the function generates output that indicates the number of the present refinement step, we pass this number as an argument.
After the last iteration we output the solution on the finest grid. This is done using the following sequence of statements which we have already discussed in previous examples. The first step is to generate a suitable filename (called
vtk_filename here, since we want to output data in VTK format; we add the prefix to distinguish the filename from that used for other output files further down below). Here, we augment the name by the mesh refinement algorithm, and as above we make sure that we abort the program if another refinement method is added and not handled by the following switch statement:
We augment the filename by a postfix denoting the finite element which we have used in the computation. To this end, the finite element base class stores the maximal polynomial degree of shape functions in each coordinate variable as a variable
degree, and we use for the switch statement (note that the polynomial degree of bilinear shape functions is really 2, since they contain the term
x*y; however, the polynomial degree in each coordinate variable is still only 1). We again use the same defensive programming technique to safeguard against the case that the polynomial degree has an unexpected value, using the
Assert (false, ExcNotImplemented()) idiom in the default branch of the switch statement:
Once we have the base name for the output file, we add an extension appropriate for VTK output, open a file, and add the solution vector to the object that will do the actual output:
Now building the intermediate format as before is the next step. We introduce one more feature of deal.II here. The background is the following: in some of the runs of this function, we have used biquadratic finite elements. However, since almost all output formats only support bilinear data, the data is written only bilinear, and information is consequently lost. Of course, we can't change the format in which graphic programs accept their inputs, but we can write the data differently such that we more closely resemble the information available in the quadratic approximation. We can, for example, write each cell as four sub-cells with bilinear data each, such that we have nine data points for each cell in the triangulation. The graphic programs will, of course, display this data still only bilinear, but at least we have given some more of the information we have.
In order to allow writing more than one sub-cell per actual cell, the
build_patches function accepts a parameter (the default is
1, which is why you haven't seen this parameter in previous examples). This parameter denotes into how many sub-cells per space direction each cell shall be subdivided for output. For example, if you give
2, this leads to 4 cells in 2D and 8 cells in 3D. For quadratic elements, two sub-cells per space direction is obviously the right choice, so this is what we choose. In general, for elements of polynomial order
q, we use
q subdivisions, and the order of the elements is determined in the same way as above.
With the intermediate format so generated, we can then actually write the graphical output:
After graphical output, we would also like to generate tables from the error computations we have done in
process_solution. There, we have filled a table object with the number of cells for each refinement step as well as the errors in different norms.
For a nicer textual output of this data, one may want to set the precision with which the values will be written upon output. We use 3 digits for this, which is usually sufficient for error norms. By default, data is written in fixed point notation. However, for columns one would like to see in scientific notation another function call sets the
scientific_flag to
true, leading to floating point representation of numbers.
For the output of a table into a LaTeX file, the default captions of the columns are the keys given as argument to the
add_value functions. To have TeX captions that differ from the default ones you can specify them by the following function calls. Note, that `\' is reduced to `\' by the compiler such that the real TeX caption is, e.g., ` \(L^\infty\)-error'.
Finally, the default LaTeX format for each column of the table is `c' (centered). To specify a different (e.g. `right') one, the following function may be used:
After this, we can finally write the table to the standard output stream
std::cout (after one extra empty line, to make things look prettier). Note, that the output in text format is quite simple and that captions may not be printed directly above the specific columns.
The table can also be written into a LaTeX file. The (nicely) formatted table can be viewed at after calling `latex filename' and e.g. `xdvi filename', where filename is the name of the file to which we will write output now. We construct the file name in the same way as before, but with a different prefix "error":
In case of global refinement, it might be of interest to also output the convergence rates. This may be done by the functionality the ConvergenceTable offers over the regular TableHandler. However, we do it only for global refinement, since for adaptive refinement the determination of something like an order of convergence is somewhat more involved. While we are at it, we also show a few other things that can be done with tables.
The first thing is that one can group individual columns together to form so-called super columns. Essentially, the columns remain the same, but the ones that were grouped together will get a caption running across all columns in a group. For example, let's merge the "cycle" and "cells" columns into a super column named "n cells":
Next, it isn't necessary to always output all columns, or in the order in which they were originally added during the run. Selecting and re-ordering the columns works as follows (note that this includes super columns):
For everything that happened to the ConvergenceTable until this point, it would have been sufficient to use a simple TableHandler. Indeed, the ConvergenceTable is derived from the TableHandler but it offers the additional functionality of automatically evaluating convergence rates. For example, here is how we can let the table compute reduction and convergence rates (convergence rates are the binary logarithm of the reduction rate):
Each of these function calls produces an additional column that is merged with the original column (in our example the `L2' and the `H1' column) to a supercolumn.
Finally, we want to write this convergence chart again, first to the screen and then, in LaTeX format, to disk. The filename is again constructed as above.
The final step before going to
main() is then to close the namespace
Step7 into which we have put everything we needed for this program:
The main function is mostly as before. The only difference is that we solve three times, once for Q1 and adaptive refinement, once for Q1 elements and global refinement, and once for Q2 elements and global refinement.
Since we instantiate several template classes below for two space dimensions, we make this more generic by declaring a constant at the beginning of the function denoting the number of space dimensions. If you want to run the program in 1d or 2d, you will then only have to change this one instance, rather than all uses below:
Now for the three calls to the main class. Each call is blocked into curly braces in order to destroy the respective objects (i.e. the finite element and the HelmholtzProblem object) at the end of the block and before we go to the next run. This avoids conflicts with variable names, and also makes sure that memory is released immediately after one of the three runs has finished, and not only at the end of the
try block.
The program generates two kinds of output. The first are the output files
solution-adaptive-q1.vtk,
solution-global-q1.vtk, and
solution-global-q2.vtk. We show the latter in a 3d view here:
Secondly, the program writes tables not only to disk, but also to the screen while running. The output looks like the following (recall that columns labeled as "<code>H1</code>" actually show the \(H^1\) semi-norm of the error, not the full \(H^1\) norm):
One can see the error reduction upon grid refinement, and for the cases where global refinement was performed, also the convergence rates can be seen. The linear and quadratic convergence rates of Q1 and Q2 elements in the \(H^1\) semi-norm can clearly be seen, as are the quadratic and cubic rates in the \(L_2\) norm.
Finally, the program also generated LaTeX versions of the tables (not shown here).
Go ahead and run the program with higher order elements (Q3, Q4, ...). You will notice that assertions in several parts of the code will trigger (for example in the generation of the filename for the data output). You might have to address these, but it should not be very hard to get the program to work!
Is Q1 or Q2 better? What about adaptive versus global refinement? A (somewhat unfair but typical) metric to compare them, is to look at the error as a function of the number of unknowns.
To see this, create a plot in log-log style with the number of unknowns on the x axis and the L2 error on the y axis. You can add reference lines for \(h^2=N^{-1}\) and \(h^3=N^{-3/2}\) and check that global and adaptive refinement follow those.
Note that changing the half width of the peaks influences if adaptive or global refinement is more efficient (if the solution is very smooth, local refinement does not give any advantage over global refinement). Verify this.
Finally, a more fair comparison would be to plot runtime (switch to release mode first!) instead of number of unknowns on the x axis. Picking a better linear solver might be appropriate though. | https://dealii.org/developer/doxygen/deal.II/step_7.html | CC-MAIN-2020-16 | refinedweb | 8,194 | 55.17 |
Hello Aspose Support.
Paragraph: space before and after
Hello Aspose Support.
Hi Michał,
Thanks for your inquiry. Please note that MS Word document is flow document and does not contain any information about its layout into lines and pages. Therefore, technically there is no “Page” concept in Word document. Pages are created by Microsoft Word on the fly.
Aspose.Words uses our own Rendering Engine to layout documents into pages. The Aspose.Words.Layout namespace provides
classes that allow to access information such as on what page and where
on a page particular document elements are positioned, when the document
is formatted into pages. Please read about LayoutCollector and
LayoutEnumerator from here:
Please check DocumentLayoutHelper project in Aspose.Words for .NET examples repository at GitHub. Please let us know if we can be of any further assistance.
Please manually create your expected Word document using Microsoft Word and attach it here for our reference. We will investigate how you want your final Word output be generated like. We will then provide you more information on this along with code. | https://forum.aspose.com/t/docx-gt-pdf-conversion-adding-space-at-the-end-of-each-line/55338 | CC-MAIN-2022-40 | refinedweb | 179 | 50.33 |
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site.
return (new Random().nextInt(2) == 0 ? "alive" : "dead");
Quote from sirolf2009
you don't, unless they have a properties file.
in that case you just op the file with notepad and change some numbers
Quote from ZShadow4899
A properties file is something set up by the mod owner so as players can configure the mod he made, if he didnt add a properties file then there is no way to make/get one, srry dude.
Quote from dQz3r
they're not properties files, they are config files found in the config folder in .minecraft.
yes there is a config file for iron chest mod, and u can change the id numbers
[url=""][IMG][/IMG]
Minecraft mods are AWESOME!!!!!!!!!!!!!!
in that case you just op the file with notepad and change some numbers
How do I get a properties file
java.lang.IllegalArgumentException: Slot 200 is already occupied by [email protected] when adding [email protected] an idea how to fix this
yes there is a config file for iron chest mod, and u can change the id numbers
Here's a helpful video i found to help with conflicting item ids
[url=""][IMG][/IMG]
Minecraft mods are AWESOME!!!!!!!!!!!!!!
use this video I tried doing what this guy did and it worked C: | http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/mods-discussion/1375116-how-to-change-mod-item-ids?cookieTest=1 | CC-MAIN-2016-44 | refinedweb | 229 | 74.83 |
From: Greg Colvin (gcolvin_at_[hidden])
Date: 2001-08-17 18:14:09
From: "Mark Rodgers" <mark.rodgers_at_[hidden]>
> > Wouldn't std::mem_fun be a different function that boost::mem_fun?
>
> Yes.
>
> > If so, where is the conflict?
>
> There is already boost::mem_fun in functional.hpp. Peter is proposing
> another boost::mem_fun.
Aha. I was think the conflict was with the standard library.
It does seem wrong to have to functions with the same name in
the same namespace. Is there anyway to unify these headers
so that there is only one boost::mem_fun?
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/2001/08/16060.php | CC-MAIN-2021-49 | refinedweb | 114 | 72.02 |
>
> .
>
This part sounds like a good idea for tricky postal codes.
>
> Would anyone like to see this added to the SDK at some point in the future?
>
I think the more validators we can add, that bring value, the better.
> For contribution like this what should the namespace be? mx.validators or
> org.apache.flex.mx.validators or something else?
>
I've been using org.apache.flex.spark... for the validators I put in my
whiteboard area. I think its still up for discussion whether we want to
eventually change the namespace, we talked about it briefly but I don't
think its something we want to do in the 4.x.x branch just so we don't add
an additional barrier to switching from Adobe Flex to Apache Flex.
>
> Any interest in a similar spark version?
>
Yes, I was wondering why you went MX as opposed to Spark. I guess a lot of
people are still using MX components, I haven't written in MX since Spark
was released. :D
--
Omar Gonzalez
s9tpepper@apache.org
Apache Flex PPMC Member | http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201203.mbox/%3CCAEFz_vtzpicCnf__akzHb2g8dwuChW7ynwkwMJ=+ckXA7L2G6g@mail.gmail.com%3E | CC-MAIN-2016-50 | refinedweb | 181 | 77.23 |
Difference Between PHP vs C#
PHP is the Programming language used in the development of a website, recursive acronym for “PHP: Hypertext Preprocessor”. PHP is used in a server-side scripting language, provides lots of features for a developer to use in web development applications. C# is object-oriented, modern, general-purpose, programming language developed by Microsoft. It is approved by the European Computer Manufacturers Association (ECMA) and the International Standards Organization (ISO).
Let us study about PHP and C# in detail:
- PHP was developed by Rasmus Lerdorf, it’s first released was in 1995. Enterprise applications can be developed using PHP, It can handle session tracking, database read-write operation, dynamic content. PHP is integrated with a number of popular databases Postgre SQL, including MySQL, Oracle, Informix, Sybase, and Microsoft SQL Server.
- PHP supports a large number of protocols such as IMAP, POP3, and LDAP. PHP4 added support for Java and distributed object architectures (COM and CORBA), making n-tier development a possibility for the first time. Php is easy to learn because its syntax is like to C, Anybody who knows C can easily learn PHP.
- C# was developed by Anders Hejlsberg and his team . C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.
- PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them. PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to the user. Database Operations add, delete, modify elements within your database through PHP. Access cookies variables and set cookies. Using PHP, you can restrict users to access some pages of your website. It can encrypt data.
Benefits of C# language.
- It is object-oriented.
- It is easy to learn.
- It is a modern, general-purpose programming language
- It is component oriented.
- It is a structured language.
- It can be compiled on a variety of computer platforms.
- It produces efficient programs.
- It is a part of.Net Framework.
- Strong Programming Features of C#
Characteristics of PHP
Five important characteristics make PHP’s practical nature possible −
- Security
- Simplicity
- Efficiency
- Familiarity
- Flexibility
Following is the list of few important features of C# −
- Automatic Garbage Collection
- Standard Library
- Conditional Compilation
- Boolean Conditions
- LINQ and Lambda Expressions
- Assembly Versioning
- Properties and Events
- Delegates and Events Management
- Easy-to-use Generics
- Indexers
- Simple Multithreading
- Integration with Windows
“Hello World” Script in PHP
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
It will produce following result −Hello, World!
HelloWorld Example In #C
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Head To Head Comparison Between PHP vs C#
Below is the top difference between PHP vs C#
Key Difference Between PHP vs C#
Both PHP vs C# performance are popular choices in the market; let us discuss some of the major Differences Between PHP vs C#:
To run PHP application we need an environment for it, There are following tools required for PHP Application 1.Web Server – many web server are available like Apache, XXamp, IIS. 2 Database required too for PHP application to interact with database PHP support all kind of database like Oracle, Sybase, MySQL. PHP parse also required to parse php script and produce output in HTML formate.
IDE – Integrated Development Environment provided Microsoft for C# are the following 1. Visual Studio, 2.Visual C#, 3. Visual Web Developer, these tools are required to work with C# applications.
4.5 (2,745 ratings)
View Course
Variables categorization in php is less compared to c# there total 8 type of variable present in php
Example- Integer type declaration $var= 100; , variable start with $ in php.
Variable categorization is wide in case of c# compared to php, at the top level, it has value type, reference type, pointer type variable, its declaration does not start with $, Example – int a=10;
PHP has while loop, for loop, do while loop, foreach loop.
C# has while loop, for loop, do while loop, nested loop.
Array Declaration in Php.
<?php
$numbers = array( 1, 2, 3,);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
Output
Value is 1
Value is 2
Value is 3
Value is one
Value is two
Value is three
Array in C#
using System;
namespace ArrayApplication {
class MyArrayDemo {
static void Main(string[] args) {
int [] n = new int[5]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 5; i++ ) {
n[ i ] = i + 100;
}
for (j = 0; j < 5; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
Output
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105
Php does not have structure like features .
C# support structure and union.
PHP vs C# Comparison Table
Below is the topmost Comparison between PHP vs C#
Conclusion – PHP vs C#
PHP vs C# performance having its own importance at their places, which one has to choose it depends on project requirement. As in case of web development PHP developer can easily developed the web application within limited time, MYSQL database embedded with PHP servers which is used to developed php web application so for small site no need to worry for connection with external database this is fast way to developed web application and force us to use php in this case, While C# can be used in web application along with desktop applications also .So we can choose anyone as per project requirement.
Recommended Article
This has a been a guide to the top differences between PHP vs C# performance. Here we also discuss the PHP vs C# key differences with infographics, and comparison table. You may also have a look at the following PHP vs C# articles to learn more –
hopmeow says
thankyou so much | https://www.educba.com/php-vs-c-sharp/ | CC-MAIN-2020-05 | refinedweb | 1,021 | 53.71 |
M5Atom Matrix and micropython
The Problem
I just flashed a vanilla micropython for esp32 on the M5Atom matrix. There seems to be an issue with network. I can connect to it, enter REPL and play with micropython. However if I try to turn the RF part on, the chip reboots. The reason being a power-on reboot.
An example is:
import network # Ok
wlan = network.wlan(network.STA_IF) # Ok
wlan.active(True) # Reboot on the matrix
I also have an M5Atom Lite and I have no problem using either the WiFi or the Bluetooth modules with micropython
The question
Is my M5Atom Matrix faulty, or is there a problem with micropython?
- lukasmaximus M5Stack last edited by
let me test with mine and get back to you
- robalstona last edited by
I use micropython for esp32 generic
Wifi and repl s working on my atom lite and matrix.
I just tried with another cable: the microcontroller works with a very short cable or from a powered hub. Basically it reboots because of a brown-out due to a power consumption that is at the limit of what a plain usb port can deliver. | https://forum.m5stack.com/topic/1673/m5atom-matrix-and-micropython/4 | CC-MAIN-2020-50 | refinedweb | 192 | 71.34 |
table of contents
NAME¶
perror - print a system error message
SYNOPSIS¶
#include <stdio.h>
void perror(const char *s);
#include <errno.h>
const char * const sys_errlist[];
int sys_nerr;
int errno; /* Not really declared this way; see errno(3) */
sys_errlist, sys_nerr:
From glibc 2.19 to 2.31:
_DEFAULT_SOURCE
Glibc 2.19 and earlier:
_BSD_SOURCE
DESCRIPTION¶
The.
VERSIONS¶
Since glibc version 2.32, the declarations of sys_errlist and sys_nerr are no longer exposed by <stdio.h>.
ATTRIBUTES¶
For an explanation of the terms used in this section, see attributes(7).
CONFORMING TO¶
perror(), errno: POSIX.1-2001, POSIX.1-2008, C89, C99, 4.3BSD.
The externals sys_nerr and sys_errlist derive from BSD, but are not specified in POSIX.1.
NOTES¶
The externals sys_nerr and sys_errlist are defined by glibc, but in <stdio.h>.
SEE ALSO¶
err(3), errno(3), error(3), strerror(3)
COLOPHON¶
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.debian.org/unstable/manpages-dev/sys_nerr.3.en.html | CC-MAIN-2021-49 | refinedweb | 177 | 70.19 |
The new age ushered in by high-speed networks (even the not so fast Internet) has brought about the requirement of new technology to cater to a lot of high scale distributed applications. Everything today has to be fast and reliable even if the applications are distributed with one located in Mars and the other on Neptune, and support the basic principle of completeness at the transactional level. Microsoft has addressed this in a wonderful way with its Windows DNA, 3 Tier Concepts. Ever got irritated when people told they want the latest hot browser interface for your application and not your Classical GUI which you really sweated out to get it running? All this changes with the 3 Tier Concept introduced by Windows DNA.
Windows 2000 (NT 4.0 with its service packs) provides you with MTS, IIS, MSMQ. Microsoft Transaction Server (MTS) provides you with the ability to write services (or packages as they are called) which support transactions by taking part in transactions supported by the Transaction Manager in MTS. MTS allows you to provide object pooling and load balancing. Therefore applications avail great benefit in the way they can be scaled as it would no longer mean that when your applications have to handle a higher load than anticipated it does not necessarily mean scratching your application from start to get that extra push. Rather it would mean putting a few extra processors, a little bit more RAM and may be a few extra processors to get that load balancing and a little bit more business for the Hardware folks.
Your application packages now support the basic two layers: Database Access Layer to interact with your data store, and the business layer to provide the essential business services. A change at the Data base layer does not necessarily mean a change in the business layer - at least not in Business Services Exposed API. Your third layer is your Presentation layer and may be your Classical GUI, or the browser Interface, or even some new interface that some one may ask in the next few years.
Now what happens in the distributed approach is that it is quite possible that all the servers that participate in your transaction are not available at the same time! An example may be the user filled in a request form about his email account details. These details that you have stored in a remote SQL server which may be down. Why not just accept the request and keep it in some kind of message store and then later forward to your SQL server application for it to process the request. The user need not get an "SQL server is down" message, why should he even know? Here enters Microsoft Message Queue, which systemizes this requirement of store and forward message requests to destinations when available.
MSMQ is supported on Windows 2000, Windows NT with Option Pack 4+, Windows 95 and Windows 98. (Note MSMQ can communicate with IBM Queues defined by the MQSeries.) and C API. This tutorial however uses COM API and Visual C++ as the COM API is much simpler to use.
MSMQ was originally code named as Falcon. MSMQ enables applications to reliably communicate with each other even in unreliable distributed environments in an efficient yet reliable way where intermediate servers need not be essentially available at all times.
Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues. The following illustration shows how a queue can hold the messages used by both sending and receiving applications.
MSMQ also provides Journaling for requests that occur, that can enable greatly in creating in data recovery and system audits.
MSMQ deploys the Store and Forward Mechanism in which messages are not exchanged directly between applications but rather through a message store known as a message queue. This allows applications at each end to be not necessarily available at the same time. MSMQ is not a technology that is brand new, but it is a sincere attempt to standardize and make available the same for Microsoft Platform..
MSMQ supports the following type of Queues
These Queues can be viewed and located by everyone.
These Queues can be viewed and located by only the applications, which are aware of the complete path of the Queue.
These Queues can participate in Transactions and allow in Transactional Support. They have a heavy I/O overhead; they are guaranteed and are recoverable. MSMQ API when used under MTS (Microsoft's Transaction Server for logical transactions) can become part of the current Transaction. In this context messages are transmitted together or not at all, and if sent the messages will be provided in the same sequence as they are transmitted. This discussion is outside the purview of the current discussion and will be discussed in further tutorials.
Quite often we (VC Developers) tend to get irritated seeing the VB Developers calling COM functions just by creating objects and calling their member functions. Whereas VC developers struggle using the CreateDispatch and slogging out the other details. However it is not all that bad because of VC's Native COM Support whereby you don't have to do the CreateDispatch calls with a GUID all by yourself. VC would internally do it all for you. It would declare the Interfaces and instantiate all the objects using CreateDispatch just when you want to create the objects.
CreateDispatch
This Native COM Support is possible by the use of the #import directive. This directive allows you to import information from a COM module (like a COM DLL or a type library).
#import
The #import syntax is described as
#import <filename> [attributes]
The #import directive causes the compiler to generate two files: a .TLH and a .TLI file (in your debug directory). These files contain the Interface declarations and member function implementations. It is quite similar to the pre-compiled header (PCH) that standard VC applications create.
In our sample I have used the no_namespace attribute so that the compile does not generate the namespace for the type library that we intend to use, but uses the namespace of the original interface definition. Further it is quite useful to check out the contents of the generated files by the compiler for additional information.
no_namespace
The class CMSMQApiWrapper is an MSMQ API Wrapper which should suffice for most common use. This wrapper however doesn’t wrap the Event notification for message arrivals in queues, but this is demonstrated in the sample Application using the CMSMQEventNotifier class.
CMSMQApiWrapper
CMSMQEventNotifier
The MSMQ API Wrapper imports the mqoa.dll which contains the message queuing interfaces using the #import "mqoa.dll" no_namespace directive. The constructor of the CMSMQApiWrapper initializes the OLE environment by a call to OleInitialize.
#import "mqoa.dll" no_namespace
OleInitialize
//Creating A Queue [Public/Private]
int CreateQueue(LPCTSTR pszPathQueue,LPCTSTR pszQueueLabel,BOOL bPublic);
int CreatePublicQueue(LPCTSTR pszPathQueue,LPCTSTR pszQueueLabel);
int CreatePrivateQueue(LPCTSTR pszPathQueue,LPCTSTR pszQueueLabel);
The above member functions facilitate in the creation of Queues. A private Queue is defined by preceding the Queue with the Private$ path.
A Queue using the above API is created by instantiating an IMSMQQueueInfoPtr object and setting its PathName and Label property and calling the create method.
IMSMQQueueInfoPtr
PathName
Label
//Locating A Public Queue by Label
int LocatePublicQueue(LPCTSTR pszPathQueue,IMSMQQueueInfoPtr &qinfo);
The above member functions facilitate in the Location of Public Queues.
A Queue can be located using the above API by creating a MSMQQuery object and using its LookUp function given the Label. This on success will return a MSMQQueuesInfo Object which can be looped to get the queues matching the given Query.
MSMQQuery
LookUp
MSMQQueuesInfo
//Deleting A Queue
int DeletePublicQueue(LPCTSTR pszQueueLabel);
The above member functions facilitate in the deletion of Public Queues.
A Queue using the above API is deleted by first Locating the Queue by Label, which accepts an IMSMQQueueInfo pointer. On Success the Delete method is called on the IMSMQQueueInfo object.
IMSMQQueueInfo
//Synchronously Purging A Queue
int SynchronousPurgePublicQueue(LPCTSTR pszQueueLabel);
This method allows you to purge a Public Queue, by first Locating the Public Queue by Label, it then Opens the Queue with Receive Access, and then finally receives all the messages in the Queue, thereby Purging all the messages in the Queue.
// Sending A Message [String other data types and persistent objects for files)
// Sending A String Message is currentlu supported
// Other Data types, files and even persistent objects can be sent
// using MSMQ
int SendStringMessage(LPCTSTR pszQueueLabel,CString szLabel,CString szMessage);
This method allows you to send sends a string message using a Variant of type VT_BSTR and a given Label to the specified MSMQ Queue. This is done by first locating the Queue and opening it with Send Access. Then an object of the type IMSMQMessage is instantiated and its Body, Label properties are set and the message is sent using the Send function for the message.
IPersistStream
VT_BSTR
IMSMQMessage
// Reading A Message[String other data types and persistent objects for files)
// Reading A String Message is currentlu supported
// Other Data types , files and even persistent objects can be read
// using MSMQ
// Requesting Events Notification For A Queue is implemented in the
// CMSMQEventNotifier class
int ReadStringMessage(LPCTSTR pszQueueLabel, CString &szLabel, CString &szMessage);
This method allows you to retrieve retrieves a string message using a Variant of type VT_BSTR and the Label that was sent to the specified MSMQ Queue. This is done by first locating the Queue and opening it with Receive Access. Then an object of the type IMSMQMessage is instantiated and its Body, Label properties are retrieved from the message queue pointer.
Messages can be retrieved asynchronously from an application using the MSMQEvent object. The MSMQEvent object enables the creation of a connection point to a sink interface in the application. This is demonstrated in the sample application where events are picked up at the message queue server for further processing.
MSMQEvent
// Retrieving and Setting Queue Properties
int SetAuthenticationLevelOfQueue (LPCTSTR pszQueueLabel,int iAuthenticationLevel);
This function sets the Authentication Level of the Queue.
int SetPriorityLevelOfQueue(LPCTSTR pszQueueLabel,int iPriorityLevel);
This function sets the Priority Level of the Queue.
int SetJournalingLevelOfQueue(LPCTSTR pszQueueLabel,int iJournalingLevel);
This function sets the Journaling Level of the Queue.
int SetMaximumSizeOfQueueJournal(LPCTSTR pszQueueLabel,long lMaximumSize);
This function sets the maximum size of the Queue Journal.
int SetLabelOfQueue(LPCTSTR pszQueueLabel,CString szLabel);
This function sets the Label of the Queue.
int SetPrivacyLevelOfQueue(LPCTSTR pszQueueLabel,int iPrivacyLevel);
This function sets the Privacy Level of the Queue.
int SetMaximumSizeOfQueue(LPCTSTR pszQueueLabel,long lMaximumSize);
This function sets the maximum size of the Queue.
The above functions Wrappers set the respective properties for the Queue and call its update function after locating the Queue.
int RetrieveAuthenticationLevelOfQueue(LPCTSTR pszQueueLabel,int &iAuthenticationLevel);
This function retrieves the Authentication Level of the Queue.
int RetrievePriorityLevelOfQueue(LPCTSTR pszQueueLabel,int &iPriorityLevel);
This function retrieves the Priority Level of the Queue.
int RetrieveFormatNameOfQueue(LPCTSTR pszQueueLabel,CString &szFormatName);
This function retrieves the Format Name of the Queue.
int RetrieveTransactionLevelOfQueue(LPCTSTR pszQueueLabel,int &iTransactionLevel);
This function retrieves the Transactional Level of the Queue.
int RetrieveReadLevelOfQueue(LPCTSTR pszQueueLabel,int &iReadLevel);
This function retrieves the Read Level of the Queue.
int RetrieveJournalingLevelOfQueue(LPCTSTR pszQueueLabel,int &iJournalingLevel);
This function retrieves the Journaling Level of the Queue.
int RetrieveMaximumSizeOfQueueJournal(LPCTSTR pszQueueLabel,long &lMaximumSize);
This function retrieves the Maximum Size of the Queue Journal.
int RetrieveLabelOfQueue(LPCTSTR pszQueuePath,CString &szLabel);
This function retrieves the label of the Queue.
int RetrievePrivacyLevelOfQueue(LPCTSTR pszQueueLabel,int &iPrivacyLevel);
This function retrieves the Privacy Level of the Queue.
int RetrieveMaximumSizeOfQueue(LPCTSTR pszQueueLabel,long &lMaximumSize);
This function retrieves the Maximum Size of the Queue.
int RetrievePathNameOfQueue(LPCTSTR pszQueueLabel,CString &szPathName);
This function retrieves the Path Name of the Queue.
The above functions Wrappers retrieve the respective properties for the Queue and call its Refresh function after locating the Queue.
The purpose of this application is to function as a Graphical User Interface Based Registry system as well as to provide a similar WEB interface using Active Server Pages. This system will accept the following details from the user while registering:
On registering a message it is placed on the InboundRequests Queue on the MSMQ Machine. A Target Application implementing MSMQEvents provides the Message Processing by adding this information to a database and sending a response email. The user at a later point of time on providing his Email Address can request for all details registered by him to be sent to him by email. It uses an email SMTP component developed by P J Naughter available here.
InboundRequests
MSMQEvents
Shown above is the screen from the MFC GUI Sample Application to register the user. This puts a message into the InboundRequests Queue after creating the Queue if it does not exist.
Shown above is a dialog from the MFC GUI Sample Application for the user to request his/her details. This puts a message into the InboundRequests Queue after creating the Queue if it does not exist.
This test application would require MSMQ to be installed on all the clients, the sample however writes on the local machine Queue and so you would have to do the routing or you could modify the test application to write on the remote Queue. If the remote machine is down MSMQ will ensure your message reaches the destination.
Shown above is the screen from the ASP based Web Page to register the user. This puts a message into the InboundRequests Queue after creating the Queue if it does not exist.
Shown above is the screen from the ASP based Web Page for the user to request his/her details. This puts a message into the InboundRequests Queue after creating the Queue if it does not exist.
The Active Server Pages does not require MSMQ Software to be setup on each client page. The Register and Request user details page call a server side script embedded in srvmsgsend.asp file. The script creates a queue on the server if it does not exist and then places a message on the Queue.
The server side script is as follows:
<%
on Error resume next
set queueinfo = CreateObject ("MSMQ.MSMQQueueInfo")
queueinfo.PathName = ".\InboundRequests"
queueinfo.Create
set queue = queueinfo.Open ( 2, 0 )
If queue.IsOpen Then
Set message = CreateObject("MSMQ.MSMQMessage")
message.Body = CStr (Request.QueryString ( "Body" ))
message.Label = CStr (Request.QueryString ( "Label" ))
message.Send queue
Response.Write "Message has been sent, you will be notified ASAP."
End If
queue.Close
%>
The MSMQReceiver is the test application, which manages events for the MSMQ Queue. It enables notification for the given Queue and on arrival of messages in to the Queue it processes the information by registering or retrieving the user information from an Access MDB and then mailing the registration users to the user.
MSMQReceiver
It implements a CMSMQEventCmdTarget class derived from CCmdTarget MFC's magic class for OLE Automation. This implements the Arrived method as the entry point for message arrivals, which could be customized, for your applications.
CMSMQEventCmdTarget
CCmdTarget
The EnableNotification method of the class opens the Queue and calls its EnableNotification method. advised about the Dispatch interface to the CMSMQEventCmdTarget class.
EnableNotification
ConectionPointContainer
IID_IMSMQSinkEvent
The DisableNotification method of the class closes the Queue and removes the connection to the sink. unadvised about the Dispatch interface to the CMSMQEventCmdTarget class.
DisableNotification
The code to implement the same is relatively simpler than the above description.
Having understood the functioning and the basic design of the MSMQ, you may now better understand what queuing could offer in your next new generation applications. The web should now be showing more assured and guaranteed message based queuing applications which could offer more security and reliability without a compromise on the performance. You can now go ahead and explore the entire MSMQ and MTS based DNA three tiers Applications. It would be ideal as time goes for application to start communicating with each other using these robust features and standard document formats like XML.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Anonymous wrote:It's my understanding that a company called Level8 developed the message queuing technology for both Microsoft (MSMQ) and IBM (MQSeries), and it is the basis of Level8's Geneva Message Queuing system. The previous poster's complaint of theft seems a bit exaggerated.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/481/The-Microsoft-Message-Queue?msg=738551 | CC-MAIN-2019-22 | refinedweb | 2,760 | 52.7 |
Working with Xcode, I'm looking to re-export a symbol (a function specifically) from a mach-o bundle binary, where the symbol is originally defined in a dylib.
I've tried the -sub_library linker switch but that doesn't seem to re-export the dylib symbols, probably because I'm not building a dylib myself(?)
And the reexport-l / reexport_library switches seem to be unsupported in Xcode's linker.
Any ideas?
This might be what you're looking for, if I understood you correctly. I'll be using libpthread as the hypothetical dylib containing functions you want to re-export.
mybundle.c:
#include <pthread.h> #include <stdio.h> void *foo(void *ctx) { puts((char *)ctx); return 0; }
mybundle.exp:
_foo _pthread_create _pthread_join
Compile the bundle, dynamically linking to libpthread.dylib:
josh$ gcc -bundle -lpthread -Wl,-exported_symbols_list,mybundle.exp -o mybundle.so mybundle.c
myloader.c:
#include <dlfcn.h> #include <pthread.h> // merely for type definitions #include <assert.h> #include <stdio.h> int main() { void *(*foo)(void *ctx); /* the following cannot be declared globally without changing their names, as they are already (and unnecessarily) declared in <pthread.h> */ int (*pthread_create)(pthread_t *thrd, const pthread_attr_t *attr, void *(*proc)(void *), void *arg); int (*pthread_join)(pthread_t thrd, void **val); void *bundle; assert(bundle = dlopen("mybundle.so", RTLD_NOW)); assert(foo = dlsym(bundle, "foo")); assert(pthread_create = dlsym(bundle, "pthread_create")); assert(pthread_join = dlsym(bundle, "pthread_join")); pthread_t myThrd; pthread_create(&myThrd, 0, foo, "in another thread"); pthread_join(myThrd, 0); return 0; }
Compile the loader:
josh$ gcc myloader.c -o myloader
Run:
josh$ ./myloader in another thread
Observe that myloader is in no way linked to pthread, yet pthread functions are loaded and available at runtime through the bundle. | http://www.dlxedu.com/askdetail/3/39a90f9d24ce6adc6c44ad4c2e63911b.html | CC-MAIN-2018-51 | refinedweb | 280 | 51.14 |
Hi Alec,
What I meant by multi threads here is that if the users want to use the subs in a threaded
envioronment, then Axis c++ lib should support that.
I do not want the transport (or any other part of Axis C++) to use threads. However, for
those
who wish to use the multiple stubs in threads, we have to make sure that Axis C++ lib is thread
safe.
I am *totally* in sync with you regarding the trouble that we bring into the code if we
try to
make Axis C++ code multithreaded.
However we could refrain from using static globles etc..
Thansk,
Samisa...
--- Aleksander Slominski <aslom@cs.indiana.edu> wrote:
> hi,
>
> i am not sure by what you mean when you talk about multi-thread
> transport and performance. it is much more efficient to avoid
> synchronization required for multiple threads and simply attach
> transport state to stub/skeleton. the only multi-thread re-use i would
> worry is for sockets when doing HTTP keep-alive. otherwise performance
> decreases, code complexity increases, and you have host of lovely bugs
> typical in concurrent programming emerge ...
>
> so i would aim for good design, ease of understanding, simplicity, and
> performance in this order - multi-threading adds so much complexity that
> it must be really really required to go this route and anyway i think
> most of XML parsers are not multi-thread safe and that is where are
> typical SOAP stack bottlenecks (CPU bound) not in network (IO bound) ...
>
> just my .02PLN
>
> alek
>
> Samisa Abeysinghe wrote:
>
> >Hi John,
> > I believe that if we could get rid of the static globles then this new transport
as well as
> the
> >LibWWW transport would be thread safe. (However it is a *belief*, we have to practically
try
> and
> >see)
> > If we could get LibWWW working with threads, then that is the best, as it supports
many
> >transports - not only HTTP - and we do not have to bother about transport specific
stuff such
> as
> >chunking etc.
> >
> > I would try and see if we could get rid of static globles and if that would free
us from
> >threading problems.
> >
> >Reagrds,
> >Samisa...
> >
> >--- John Hawkins <HAWKINSJ@uk.ibm.com> wrote:
> >
> >
> >
> >>
> >>
> >>Wow !!!
> >>
> >>The old code was really slow !
> >>Your code is really fast :-)
> >>
> >>We do get other things with libwww though don't we?
> >>
> >>
> >>If your code is better than the current code 9(and we can make it thread
> >>safe and have the same function) then let's use it and ditch the original
> >>one?
> >>
> >>
> >>
> >>John Hawkins
> >>
> >>
> >>
> >>
> >>
> >> Samisa Abeysinghe
> >> <samisa_abeysingh
> >> e@yahoo.com> To
> >> Apache AXIS C Developers List
> >> 17/09/2004 09:39 <axis-c-dev@ws.apache.org>
> >> cc
> >>
> >> Please respond to Subject
> >> "Apache AXIS C Analysis of Axis C++ client
> >> Developers List" transport
> >>
> >>
> >>
> >>
> >>
> >>
> >>
> >>
> >>
> >>
> >>Hi All,
> >> Since I was under the impression that the current Axis transport lib
> >>implementation is much
> >>slower than LibWWW based implementation I did some measurers on the speed
> >>with echo string method
> >>of base sample.
> >> The original Axis transport lib was much slower and hence I implemented
> >>a new socket based Axis
> >>transport lib with the logic similar to current Axis transport. The results
> >>are interesting. The
> >>original Axis transport implementation is too slow, and not only that, it
> >>cannot send messages
> >>lager than 48800 (strage number), if I try to the client segfaults. The new
> >>transport lib as well
> >>as the LibWWW based transport can send much larger messages (I tested upto
> >>2621440 characters)
> >> The other interesting thing is that the new trasport that I implemented
> >>are faster than LibWWW
> >>based implementation.
> >> Please have a look at the attached HTML file for results.
> >>
> >> At the moment, the Call class creates a new transport object for each
> >>and every invcation. I
> >>made the code to reuse the same transport and the code became still faster.
> >>
> >> However, testing for thread safety, both LibWWW and the new transport
> >>failed, only the old
> >>trasport work with threads. I am doubtful of this, because in the new
> >>transport I have very
> >>similar logic to that of the old (but not the same) I doubt the old
> >>transport pretends to be
> >>thread safe as it is too slow. We have to remove the globle variables from
> >>the code and see if
> >>this thread safety problems would persist. We must look into thread safety
> >>as an immediate high
> >>priority issue.
> >>
> >> As the code is frozen at the moment for 1.3 I did not commit the new
> >>trasport. It works for
> >>chunks as well, however it would have to be tested more to be used in
> >>production envioronments.
> >>Hence, even if I put it in cvs, I would like it to be seperate from the
> >>original Axis transport
> >>lib. I have removed all cyclic couplings in this new code and hence it
> >>would be easier to
> >>maintain.
> >>
> >> I have given below the client code that I used for this testing (with
> >>base.wsdl generated
> >>code)
> >>
> >>Thanks,
> >>Samisa...
> >>
> >>#include <string>
> >>#include <iostream>
> >>#include <time.h>
> >>#include <stdio.h>
> >>#include <sys/types.h>
> >>#include <sys/timeb.h>
> >>
> >>#ifdef WIN32
> >>#else
> >>#include <sys/times.h>
> >>#include <unistd.h>
> >>#endif
> >>
> >>
> >>#include <axis/AxisGenException.h>
> >>#include "./gen_src/InteropTestPortType.h"
> >>
> >>using namespace std;
> >>
> >>#define STRING_TO_SEND "HelloWorld"
> >>
> >>static void
> >>usage (char *programName, char *defaultURL)
> >>{
> >> cout << "\nUsage:\n"
> >> << programName << " [-? | service_url] " << endl
> >> << " -? Show this help.\n"
> >> << " service_url URL of the service.\n"
> >> << " Default service URL is assumed to be " << defaultURL
> >> <<
> >> "\n Could use to
> >>test with Axis Java."
> >> << endl;
> >>}
> >>
> >>
> >>int
> >>main (int argc, char *argv[])
> >>{
> >> int length = 10;
> >> char endpoint[256];
> >>
> >> // Set default service URL
> >> sprintf (endpoint, "");
> >> // Could use to test with Axis
> >>Java
> >>
> >> try
> >> {
> >>
> >> if (argc > 1)
> >> {
> >> // Watch for special case help request
> >> if (!strncmp (argv[1], "-", 1)) // Check for - only so
> >>that it works for
> >> //-?, -h or --help; -anything
> >> {
> >> usage (argv[0], endpoint);
> >> return 2;
> >> }
> >> length = atoi(argv[1]);
> >> }
>
=== message truncated ===
__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - Send 10MB messages! | http://mail-archives.us.apache.org/mod_mbox/axis-c-dev/200409.mbox/%3C20040920031450.44003.qmail@web40609.mail.yahoo.com%3E | CC-MAIN-2019-26 | refinedweb | 979 | 71.55 |
Using NetBeans 5.5 Web Services Client to consume Web Services in Visual Web Pack
–
Sanjay Dhamankar
–
Initail version: 08-31-06
–
Revised : 01-28-07
For detailed functional specifications refer to “NetBeans 5.5 Web Services Consumption in Visual Web
Pack Specification”.
Web Services :
According to the W3C a
Web service
is a software system designed to support interoperable machine-
to-machine interaction over a network. There are two types of web services supported by IDE.
JAX-WS web service clients (Java EE 5). For consuming JAX-WS web services, there is one type of web
service client, the IDE-generated static stub. The IDE generates the stub and other artifacts, packages
them in the archive, and deploys them. Since JAX-WS does not work with deployment descriptors, but
uses annotations within the Java code instead, a J2EE container-generated static stub, which implies the
use of deployment descriptors, would be superfluous.
JAX-RPC web service clients (J2EE 1.4). For consuming JAX-RPC web services, there are two types of web
service clients:
•
J2EE Container-generated static stub. This type is based on JSR-109, which enhances JSR-101 by
defining the packaging of web services into standard J2EE modules, including a new deployment
descriptor, and defining web services that are implemented as session beans or servlets. This is
the recommended and portable (via J2EE 1.4 specification) type. When one chooses this type, the
IDE adds deployment information in the deployment descriptors and the container does the
generation of the stub and other artifacts.
•
IDE-generated static stub. This type is based on JSR-101, which defines the mapping of WSDL to
Java and vice versa. It also defines a client API to invoke a remote web service and a runtime
environment on the server to host a web service. This type is not portable. When one chooses
this type, the IDE generates the stub and other artifacts, packages them in the archive, and
deploys them.
Since the WSDL file governs the interface to the web service, one may not add new operations to web
services that are created from a WSDL file, because these operations will not be reflected back in the
WSDL file. Click
here
for creating web services using Netbeans 5.5 as this document will describe only
web service consumption.
Consume the web service
1.
Either open an existing or create a new Visual Web Application project. If you are creating a
new JSF Application, the dialog may look as follows:
2.
To consume web services you need to create the web service client. Expand the “Web
Application” node (from the “Projects” tab). “Web Service Client...” is available under most of the
menus which contain “New”. Here are two of the many menus where the “Web Service Client...”
menu is available.
This depends on the deployment server chosen at the time of project creation.
If Sun App Server is chosen then the JAX-WS client is shown.
If TomCat is chosen then the JAX-RPC client is shown.
2. Specify either the Net Beans project where the web service is created, or a local WSDL file or URL of
the WSDL file. For URL, specify the proxy settings if you are behind the firewall. Typically, an error such
as the following is displayed in the Web Service Client wizard when the proxy settings for retrieving a
WSDL file have not been set correctly:
Download failed. I/O exception: (Check the proxy settings.)
Do the following to check and set the proxy:
•
Click Proxy Settings in the Web Service Client wizard.
•
In the HTTP Proxy Settings window, set the proxy host and port number.
•
The changes take effect when you click OK.
3. Specify the location for the client. Leave the project as default, specify the package name (remember
this as we might need to import this in the backing bean), Client type (default for JAX-WS) J2EE
Container-generated static stub (for JAX-RPC) (see above)
4. Click Finish.
5. Import the package specified in the dialog above in the backing bean (SessionsBean1.java) by
manually typing the import statement (in future this manual procedure may be eliminated). The
statement looks like “import my.travelWS.TravelService;”. Note that here the package name is
“my.travelWS”. See the code in the red ellipse in the diagram below. Here is sample code which will be
generated when the user drags and drops the web service method “
getCarRental
” in the “.java” file.
(e.g. Page1.java) T
he user still needs to type the “import” statement by hand.
Please note that the
// TODO part needs to reflect what the user intends to do with these web service methods and must be
modified manually.
:
try {
my.travelWS.TravelWS service = new my.travelWS.TravelWS();
my.travelWS.TravelService port = service.getTravelServicePort();
// TODO initialize WS operation arguments here
java.lang.Integer tripId = null;
// TODO process result here
my.travelWS.CarRentalDTO result = port.getCarRental(tripId);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
6. Now you have access to the web service client code from the Visual Web Pack backing bean actions.
Look at the code in the blue ellipse. Here's an example with the TravelWS.wsdl shipped with Visual
Web Pack. You get all the features of IDE such as code completion etc. when you are using the Web
Services.
NOTE: Following sections have been marked as “
[VisualWebPack_NB6]
”
meaning these feature are not implemented in shortfin but will be
implemented in future releases / updates.
Adding a Method Node to a Web Form by drag and drop
[VisualWebPack_NB6]
The user can drag and drop a non-void method on a Web Form. When a method is dropped on a Web
Form, a data provider instance for the method is added in the backing bean. Since the data provider is
for a method, it needs to be associated with a client instance when it gets created in the backing bean.
There are three possible ways for a data provider to be associated with a client instance:
•
There is no client instance added in the project yet when a method is dropped. In this case, a
client instance will automatically be created and the data provider instance will be associated
with it
•
There is exact one client instance is in the project. Then the data provider instance will be
associated with this client instance.
•
There are more than one client instance in the project. A dialog will popup to ask user to select a
client instance when a method is dropped.
Once the methods are dropped in the Web Form, they are ready to be bound to the data provider
bindable components using either the “Bind to Data...” or “Property Bindings...” dialog from the
components.
Binding the Drop Down List to a Web Service Method
[VisualWebPack_NB6]
User could drag and drop a web service method such as “getPersons()” to Drop Down List. When user deploys
the application, the Drop Down List displays a list of traveler names.
1.
Open the “Projects” window and expand Web Service References > TravelWS > TravelWS > Travel
Service Port. The following figure shows the TravelWS web service methods.
2.
Drag the
getPersons
method from the Projects window and drop it on the Drop Down List.
The value in the Drop Down List changes from item 1 to abc. The
"abc"
text indicates that the
display field is bound to a
String
object.
3.
Right-click the Drop Down List and choose Bind to Data.
The Bind to Data dialog box opens.
4.
In the Bind to Data Provider tab, set the following three values, as shown in Figure 5.
Drop-down list:
travelWSGetPersons1 (Page 1)
Value field:
personId
Display field:
name
5.
Click OK.
Binding the Table to the Web Service Method
[VisualWebPack_NB6]
This section describes how to bind the Table component to the
getTripsByPerson
method of the TravelWS
web service. When the application is deployed it displays master-detail data from a database. When user selects
a person from the Drop Down List, the application displays the trip records for that person in the table.
The following figure shows the layout of the table user designs in the next steps.
1.
From the Projects window, drag the Web Service References > TravelWS > TravelWS > Travel Service
Port >
getTripsByPerson
method and drop it on the Table in the Visual Designer.
The value fields of the TravelWS data provider appear as the column names in the Table.
Note: If the
Choose Target
dialog box opens, choose
table1
and click OK.
1.
Right-click anywhere in the Table and choose Table Layout from the pop-up menu.
2.
In the Table Layout dialog box, move tripid and personid from the Selected List to the Available List by
selecting each one and clicking the < button.
3.
Move depDate to the top of the Selected list by selecting it and clicking the
Up
button.
4.
Change the Header Text for depDate to
Departure Date
.
Note that user could drop a converter on the depDate column in the table and set it to show the date only.
For more information, see the
Using Converters
tutorial.
The following figure shows the Table Layout dialog box with the changes user made so far.
5.
Select depCity and change the Header Text to
Departure City
.
6.
Select destCity and change the Header Text to
Destination City
.
7.
Select tripType and change the Header Text to
Trip Type
.
8.
Click the Options tab and change the Title to
Trips
.
9.
Click OK to apply the changes and close the Table Layout dialog box.
Populating the Table from the Drop Down List
[VisualWebPack_NB6]
1.
In the Visual Designer, double-click the Drop Down List.
The Java Editor opens with the insertion point in the
nameDropDown_processValueChange
method.
2.
Open the Code Clips tab of the Palette and scroll to the Database and Web Services node.
3.
Drag
TravelWS: DropDown Process Value Change
from the Code Clips Palette and drop it
in the
nameDropDown_processValueChange
method.
This code clip gets the selected person id from the Drop Down List, and then sets the id to the data
provider for the Table.
4.
Drag the
TravelWS: Get the First Person ID
code clip from the Code Clips Palette and
drop it right before the end closing bracket in the Java Editor. Note that the statement that includes the
Rowkey
class contains a syntax error because the file does not yet include an import statement for that
class. User has to add the import statement in the next step.
The
Get the First Person ID
code gets the id of the first person from the travelWSGetPerson1
data provider.
5.
Right-click anywhere in the Java Editor and choose Fix Imports.
Fix Imports automatically adds import statements that are needed by user's code and removes unused
import statements. Fix Imports does not remove any fully qualified class names user may have in user's
code.
6.
Scroll up to the
init
method and then drag the
TravelWS: Select the First Person
code
clip from the Code Clips Palette and drop it after the comment
Creator-managed Component
Initialization
. Enter Control-Shift-F to automatically reformat the code. The result is similar to
the following code sample. The
Select the First Person
code is shown in
bold
.
init
Method With Select the First Person code
public void init() {
// Perform initialization inherited from our superclass
super.init();
// Perform application initialization that must complete
// *before* managed components are initialized
// TODO - add your own initialization code here
Creator-managed Component Initialization/
// Perform application initialization that must complete
// *after* managed components are initialized
// TODO - add your own initialization code here
// Initialize the drop down to initialize the first person
// and the data provider to get the trips for the first person
Integer firstPerson = getFirstPersonId();
nameDropDown.setSelected( firstPerson );
travelWSGetTripsByPerson1.setPersonId( firstPerson );
}
This code clip initializes the Drop Down List with the first name from the travelWSGetPersons1 data
provider. The code also retrieves the trips for the first person from the travelWSGetTripsByPerson1 data
provider. When a different person is selected, the contents of the Trips table change | https://www.techylib.com/el/view/cabbagepatchtexas/using_netbeans_5.5_web_services_client_to_consume_web | CC-MAIN-2017-30 | refinedweb | 2,014 | 64.61 |
The QFontEngineInfo class describes a specific font provided by a font engine plugin. More...
#include <QFontEngineInfo>
This class is under development and is subject to change.
This class was introduced in Qt 4.3.
The QFontEngineInfo class describes a specific font provided by a font engine plugin.
QFontEngineInfo is used to describe a request of a font to a font engine plugin as well as to describe the actual fonts a plugin provides.
See also QAbstractFontEngine and QFontEnginePlugin.
the family name of the font
Access functions:
the pixel size of the font
A pixel size of 0 represents a freely scalable font.
Access functions:
the style of the font
Access functions:
the weight of the font
The value should be from the QFont::Weight enumeration.
Access functions:
the writing systems supported by the font
An empty list means that any writing system is supported.
Access functions:
Constructs a new empty QFontEngineInfo.
Constructs a new QFontEngineInfo with the specified family. The resulting object represents a freely scalable font with normal weight and style.
Creates a new font engine info object with the same attributes as other.
Destroys this QFontEngineInfo object.
Assigns other to this font engine info object, and returns a reference to this. | http://doc.qt.nokia.com/4.6-snapshot/qfontengineinfo.html | crawl-003 | refinedweb | 203 | 57.87 |
Am 07.04.2016 um 20:15 schrieb Richard Henderson: > On 04/07/2016 08:53 AM, Sergey Fedorov wrote: >> +/* Enable TCI assertions only when debugging TCG (and without NDEBUG >> defined). >> + * Without assertions, the interpreter runs much faster. */ >> +#if defined(CONFIG_DEBUG_TCG) >> +# define tci_assert(cond) assert(cond) >> +#else >> +# define tci_assert(cond) ((void)0) >> #endif >> > > Please just use tcg_debug_assert. > > > r~ Hi Richard, that's a good suggestion, but maybe a little late for 2.6-rc2. I already sent a pull request an hour ago after Michael had added his tested-by. My first priority is fixing the build regression in 2.6. I can try to prepare a new patch, wait for reviews and send a pull request, but I am afraid this might not be finished in time for 2.6. Regards Stefan | https://lists.gnu.org/archive/html/qemu-devel/2016-04/msg01293.html | CC-MAIN-2018-05 | refinedweb | 133 | 71.55 |
or later. Oracle Text is such a cartridge, adding support for reading, writing, and searching text documents stored within the database.
A simple mechanism for adding style (fonts, colors, spacing, and so on) to Web documents. can be indexed and searched by the Oracle Text search engine.
The interface method in which the user enters in commands at the command interpreter prompt.
The programming interfaces enabling Web servers to run.
Oracle XML DB uses the Document Location Hint to determine which XML schemas are relevant to processing the instance document. It assumes that the Document Location Hint will map directly to the URL used when registering the XML schema with the database. When the XML schema includes elements defined in multiple namespaces, an entry must occur in the
schemaLocation attribute for each of the XML schemas. Each entry consists of the namespace declaration and the Document Location Hint. The entries are separated from each other by one or more whitespace characters. If the primary XML schema does not declare a target namespace, then the instance document also needs to include a
noNamespaceSchemaLocation attribute that provides the Document Location Hint for the primary XML schema.).
XSL consists of two W3C recommendations: XSL Transformations for transforming one XML document into another and XSL Formatting Objects for specifying the presentation of an XML document. XSL is a language for expressing stylesheets. It consists of two parts:
A language for transforming XML documents (XSLT), and
An XML vocabulary for specifying formatting semantics (XSLFO). name-based access will normally use the Oracle XML DB hierarchical index. application protocol used for transporting HTML files across the Internet between Web servers and browsers.
The use of Secure Sockets Layer (SSL) as a sub-layer under the regular HTTP application layer. Developed by Netscape. aid in the development of software run from a single user interface. JDeveloper is an IDE for Java development, because it includes an editor, compiler, debugger, syntax checker, help system, and so on, to permit Java software development through a single user interface.
The collection of complex datatypes and their access in Oracle. These include text, video, time-series, and spatial data.
The protocol used by CORBA to exchange messages on a TCP/IP network such as the Internet.
A high-level programming language developed and maintained by Sun Microsystems where applications run in a virtual machine known as a JVM. The JVM is responsible for all interfaces to the operating system. This architecture permits developers to create Java applications that can run on any operating system or platform that has a JVM.. JVM of the server..
Oracle., with the following attribute syntax:
xmlns:xsl="".. name.
W3C recommendation that enables you to describe the processing relations between XML resources.
The Oracle procedural database language that extends SQL. It is used to create programs that can be run within the database.
An entity that may be granted access control privileges to an Oracle XML DB resource. Oracle XML DB supports as principals:
Database users.
Database roles. A database role can be understood as a group, for example, the DBA role represents the DBA group of all the users granted the DBA role.
Users and roles imported from an LDAP server are also supported as a part of the database general authentication model.
The opening part of an XML document containing the XML declaration and any DTD or other declarations needed to process the document.
The set of database objects, in any schema, that are mapped to path names. There is one root to the repository ("/") which contains a set of resources, each with a path name.
The name of a resource within its parent folder. Resource names must be unique (potentially subject to case-insensitivity) within a folder. Resource names are always in the UTF-8 character set (
NVARCHAR2).
The element that encloses all the other elements in an XML document and is between the optional prolog and epilog. An XML document is only permitted to have one root element.
The definition of the structure and data types within a database. It can also be used to refer to an XML document that support the XML Schema W3C recommendation.
The process used to modify XML schemas that are registered with Oracle XML DB. Oracle XML DB provides the PL/SQL procedure
DBMS_XMLSCHEMA.CopyEvolve(). This copies existing XML instance documents to temporary tables, drops and re-registers the XML schema with Oracle XML DB, and copies the XML instance documents to the new
XMLType tables....
The native SQL function that returns as a single XML document the results of a passed-in
SYS_XMLGEN SQL query. This can also be used to instantiate an
XMLType.
The native SQL function that returns as an XML document the results of a passed-in SQL query. This can also be used to instantiate an
XMLType.
A single piece of XML markup that delimits the start or end of an element. Tags start with
< and end with
>. In XML, there are start-tags (
<name>), end-tags (
</name>), and empty tags (
<name/>).
TransX Utility is a Java API that simplifies the loading of translated seed data and messages into a database. the OTN XML site on the World Wide Web. W3C recommendation that describes the use of the
xml:base attribute, which can be inserted in an XML document to specify a base
URI other than the base URI of the document or external entity. The
URIs in the document are resolved by means of the given base.
The set of libraries, components, and utilities that provide software developers with the standards-based functionality to XML-enable their applications. In the case of the Oracle Java components of XDK, the kit contains an XML parser, an XSLT processor, the XML Class Generator, the JavaBeans, and the XSQL Servlet. the use of.
Allows Oracle XML DB protocol servers to recognize that an XML document inserted into Oracle XML DB repository is an instance of a registered XML schema. This means that the content of the instance document is automatically stored in the default table defined by that XML schema. Defined by the W3C XML Schema working group and based on adding attributes that identify the target XML schema to the root element of the instance document. These attributes are defined by the XMLSchema-instance namespace.
Used to identify an instance document as a member of the class defined by a particular XML schema. You must declare the XMLSchema-instance namespace by adding a namespace declaration to the root element of the instance document. For example:
xmlns:xsi=.
When using Oracle XML DB, you must first register your XML schema. You can then use the XML schema URLs while creating
XMLType tables, columns, and views.
This Oracle utility can generate an XML document (string or DOM) given a SQL query or a JDBC ResultSet object. within a table or view.
Oracle XML DB provides a way to wrap existing relational and object-relational data in XML format. This is especially useful if, for example, your legacy data is not in XML but you have.
Can be used when the
XMLType is stored in structured storage (object-relational) using an XML schema. Queries using XPath can potentially be rewritten directly to underlying object-relational columns. XPath query rewrite is used for XPaths in SQL functions such as
existsNode(),
extract(),
extractValue(), and
updateXML(). It enables the XPath to be evaluated against the XML document without constructing the XML document in memory..
Oracle's XSLT Virtual Machine is the software implementation of a "CPU" designed to run compiled XSLT code. The concept of virtual machine assumes a compiler compiling XSLT stylesheets to a program of byte-codes, or machine instructions for the "XSLT CPU".
The designation used by the Oracle Servlet providing the ability to produce dynamic XML documents from one or more SQL queries and optionally transform the document in the server using an XSL stylesheet.
See XML SQL Utility. | http://docs.oracle.com/cd/B13789_01/appdev.101/b10794/glossary.htm | CC-MAIN-2015-35 | refinedweb | 1,324 | 55.64 |
Practical ASP.NET
View components let you create reusable chunks of business logic coupled with a UI in multiple places in your application ... and then let you share that logic across multiple projects. Here's how to invoke them and share them.
In an earlier column I decide to look at one of the more interesting new features in ASP.NET Core: view components. View components look very like a mini-Controller class and View except that you invoke view components from a View in order to add HTML to the View. Effectively, they bundle business logic and UI into a single reusable package.
In that previous article, I showed how to create the class and View that make up a view component. In this article, I'll show how to use that view component both from a View and from within an Action method. I'll also walk through how to share a view component among multiple projects.
Invoking Your View Component
In a View, you can invoke a view component one of two ways: use a View's Component property or add a Tag Helper to the View.
For my money, the simplest method is to simply call the InvokeAsync method from the View's Component property, passing the name of your view component and its parameters. You must use the await keyword here to ensure that your Task object is resolved before your View finishes processing. If you omit the await keyword Razor will shove the string representation of the Task object returned by the InvokeAsync method into your page.
So, to call my CustomerAddress component passing A123 as the customer id, I'd use this code in a standard View:
@await Component.InvokeAsync("CustomerAddress", "A123")
The only real downside to this method is that you don't get any IntelliSense support for entering the view component's name or parameters.
Invoking IntelliSense for View Components
If you'd prefer getting some IntelliSense support, then you'll want to use a Tag Helper to invoke your view component. With a Tag Helper, you add a tag to your View that shares your view component's name. The name for that tag must be your view component's name converted to lowercase and with hyphens before any uppercase letters (what's called kebob style). The tag name also needs the prefix vc: added to it. A view component called CustomerAddress class, therefore, is represented by a tag called vc:customer-address.
Any parameters that you want to pass to the InvokeAsync method must be provided through attributes on your new tag. The attribute name must match the parameter name, again converted to kebob format. To invoke my CustomerAddress view component as a Tag Helper, passing A123 to the CustomerId parameter, I'd add an element like this to a View:
<vc:customer-address
This will only work, however, if you've told your project about your view component through an addTagHelper directive, even if your view component is in the same project as the View that's using it. You can put that in the Views using your tag or add it to the _ViewImports.cshtml file in your project's Views folder to use your view component in any View. The addTagHelper directive accepts two parameters: the name of your view component with or without the wildcard character (*), and the view component's namespace. An addTagHelper in the _ViewImports file like the following example lets you use any Tag Helper in the CustomerManagement namespace in any View:
@using SalesOrder
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, CustomerManagement
With the addTagHelper in place, IntelliSense will, in a View, prompt you through typing in the tag name and providing the parameter attributes.
View Components in Controller Methods
As a bonus, you can also invoke view components in Action methods. Typically, you'll want to do this in Action methods that return HTML to JSON calls. The Controller class's ViewComponent helper accepts the name of your view component and an anonymous object. The names of the properties on your anonymous object must match the names of your InvokeAsync method's parameters. This example invokes the CustomerAddress view component, passing A123 to a parameter called CustomerId:
public IActionResult Index() {
return ViewComponent("CustomerAddress", new { CustomerId = "A123"});
}
Rather than passing the name of your view component, you can pass its Type object, giving you some IntelliSense support, as in this example:
return ViewComponent(typeof(CustomerAddressViewComponent), new { CustomerId = "A123"});
You must use the actual name of your view component class with this syntax. If you've used the ViewComponent attribute to name your view component (as I showed in my previous article), then you must use the name of the class here.
Sharing Across Projects
Not only can you reuse a view component within a single project, you can share a view component's class across multiple projects (but only the view component's class file, not its related View). It's the responsibility of the project using the view component to provide a View in one of the appropriate folders.
To support this, instead of defining your view component in an ASP.NET Core project, define the class in a Class Library project. Your Class Library project will need some ASP.NET Core libraries to support the ASP.NET Core classes and interfaces used in your view component. For the case study that I used in writing this article, I added the Microsoft.AspNetCore.All NuGet package to my Class Library project, which is probably more libraries than I needed.
To use your view component class in an ASP.NET Core project, first add a reference to the Class Library containing your view component. After that, you can just use the Component.InvokeAsync method in your Views or Action methods. If you want to use the Tag Helper syntax in your Views, you'll also need to add a addTagHelper directive that references your Class Library's namespace.
Really, my only complaint with view components is that they don't make quite as tidy a package as Web Parts did in the original version of ASP.NET. On the other hand, this is the first piece of ASP.NET technology that supports any kind of sharing across projects. Since that sharing improves consistency and reduces my workload, I'm a happy cam | https://visualstudiomagazine.com/articles/2018/02/01/invoking-view-components.aspx | CC-MAIN-2019-43 | refinedweb | 1,059 | 60.65 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
A Thesis Submitted to the College of Graduate Studies and Research in Partial Fulfillment of the Requirements for the Degree of Master of Science in the Department of Mechanical Engineering University of Saskatchewan Saskatoon, Saskatchewan
By Zeping Wei
PERMISSION TO USE
In presenting this thesis in partial fulfillment of the requirements for a postgraduate degree from the University of Saskatchewan, I agree that the Libraries of the University of Saskatchewan may make this thesis freely available for inspection. I also agree that permission for extensive copying of this thesis, in whole or in part, for scholarly purposes may be granted by the professor or professors who supervised this thesis work or, in their absence, by the Head of the Department or the Dean of the College in which my thesis work was done. It is understood that due recognition shall be given to the author of this thesis and to the University of Saskatchewan in any use of the material in this thesis. Copying or publication or any other use of this thesis for financial gain without approval by the University of Saskatchewan and the author’s written permission is prohibited. Request for permission to copy or to make any other use of the material in this thesis in whole or part should be addressed to:
Head of the Department of Mechanical Engineering 57 Campus Drive University of Saskatchewan Saskatoon, Saskatchewan S7N 5A9, Canada
I
ACKNOWLEDGEMENTS
The author is indebted to Dr. Glen Watson and hereby would like to express her sincere appreciation and gratitude to him for his valuable guidance, help and encouragement during the process of this research work and in the preparation of this thesis. Without his guidance and support this work would have been impossible. The author also would like to offer her sincere gratitude to Dr. Szyszkowski for his invaluable technical guidance and advice throughout the course of this research. The author is grateful to the faculty and the staff of the Department of Mechanical Engineering, University of Saskatchewan, who have provided the most cooperative assistance to her for this research work. The author also acknowledges the financial assistance provided by Dr. Glen Watson and the Department of Mechanical Engineering, University of Saskatchewan for a scholarship during my master studies. The author wishes to extend her thanks to her husband Yong Zhang and her daughter Yun Zhang, who were a constant and active source of support throughout the endeavor.
II
and the transmission errors of gears in mesh. shearing displacement and contact deformation. Both results agree very well. The contact stresses were examined using 2-D FEM models. bending stresses. Transmission error measurement has become popular as an area of research on gears and is possible method for quality control. To estimate transmission error in a gear system. which were originally derived for contact between two cylinders. Many different positions within the meshing cycle were investigated. This thesis also considers the variations of the whole gear body stiffness arising from the gear body rotation due to bending deflection. the stiffness relationship between the two contact areas is usually established through a spring placed between the two contacting areas. The bending stresses in the tooth root were examined using a 3-D FEM model. Current methods of calculating gear contact stresses use Hertz’s equations. This indicates that the FEM model is accurate. To enable the investigation of contact problems with FEM. This can be achieved by inserting a contact element placed in between the two areas where contact occurs.ABSTRACT This thesis investigates the characteristics of an involute gear system including contact stresses. Gearing is one of the most critical components in mechanical power transmission systems. The results of the two dimensional FEM analyses from ANSYS are presented. III . the characteristics of involute spur gears were analyzed by using the finite element method. These stresses were compared with the theoretical values. Transmission error is considered to be one of the main contributors to noise and vibration in a gear set.
....................2.................................................................................................................................2 2...............................................................1 2.........................................................................................................................................................................................IV LIST OF FIGURES ........ III TABLE OF CONTENTS............................................... 7 Literature Review and Background ............................. 16 Contact Stress Simulation of Two Cylinders...............II ABSTRACT ...................................................................................................................................... 1 Research Overview ........... 4 Layout of Thesis......................................... 20 Types of Contact Models ....................................1 3.............................................2 Contact Problem Classification....................... 21 IV ........ 1 Objectives of the Research............. VII LIST OF TABLES .......................................TABLE OF CONTENTS PERMISSION TO USE ........................................................ X Chapter 1 1....................4 Chapter 3 3.... I ACKNOWLEDGEMENTS...................................................................................................... 12 Models of a Whole Gearbox ...........................................................................IX Nomenclature................3 Chapter 2 2........................................................................................................................................ 16 Models for Optimal Design of Gear Sets ........1 1........................... 19 How to Solve the Contact Problem .............................................................................................................................................................................................................. 19 Why is the Contact Problem Significantly Difficult .......................... 8 Model with Tooth Compliance ..................................................................1 3......2 1.............3 2...........................................2.......2 INTRODUCTION... 20 3........ 9 Models of Gear System Dynamics..........
....... 52 4..............................................................................................................3 Comparison with Results using AGMA Analyses..................................................................4 Chapter 4 4.................6..................................2 5...........................2.............................................. 31 Involute Gear Tooth Contact and Bending Stress Analysis............................... 67 2D FEA Transmission Error Model ...........5 3....................................................3.......................8 Chapter 5 5. 59 Torsional Mesh stiffness and Static Transmission Error ...... 40 Analytical Procedure ............................. 25 The FEM Numerical Procedure ................................ 60 Introduction and Definition of Transmission Error.....1 4.........................................................3 Analysis of the Load Sharing Ratio ....................6 3................... 40 Introduction ........................ 40 Rotation Compatibility of the Gear Body ........6..................................... 49 FEM Models. 46 The Lewis Formula ................3.................................1 5..................... 57 Conclusion... 67 5....... 24 Numerical Example ---.............................2.............2 5.....5 4............................................................3..................... 29 The Result of the Contact Stress Analysis ....................3 4................................................................................................................ 60 The Combined Torsional Mesh Stiffness................... 21 Contact Element Advantages..... 70 V ................................. 62 Transmission Error Model ........... 43 Gear Contact Stress ..............2 4.. 55 4...4 4............................................................6 How to Solve the Contact Problem ......3 3........... 69 Overcoming the convergence difficulties ..............2.........3 3......7 4............................................................3...1 5.................Contact Problem of Two Circular Discs................. 27 Hertz Contact Stress Equations ................2 The Two Dimensional Model ...........2............ 52 The Three Dimensional Model ..................................... Disadvantages and their Convergence............1 4.........4 3.....................
......................................................................1 6.............................................................................. 79 Future Work ................................ 79 REFERENCES ..........................................................................5 Chapter 6 6.............................3............................ 75 The Transmission Error.............5................. 80 Appendix A Input File of A Model of Two Cylinders......................... 79 Conclusions ....................................................................................................................................................2 The Results from ANSYS ................. 78 Conclusions and Future Work ............................................................. 76 Conclusion.....4 5....................................4 5................................... 86 VI ..........
................................................................................................. 24 Figure 3-2 Two steel cylinders are pressed against each other ......................................... 33 Figure 3-7 Contact stress from ANSYS agrees with the Hertz stress........................................................ 42 Figure 4-2 Gear contact stress model.......... 37 Figure 3-12 Maximum shear stress from ANSYS ..................................................................................................................................................................................... 34 Figure 3-8 Stress along depth distance below the contact surface from ANSYS ................................... 30 Figure 3-5 Rectangular shaped elements were generated near contact areas ............ 39 Figure 4-1 Involutometry of a spur gear . 43 Figure 4-3 Illustration of one complete tooth meshing cycle ................................................................. 6 Figure 2-1 Meshing of a helical pair ........................................... 27 Figure 3-3 Equilibrium iteration ..................................................................... 34 Figure 3-9 FEM stresses agree with the theoretical values........................................................................................... 11 Figure 3-1 Point-to-surface contact element ...................... 36 Figure 3-11 Orthogonal shear stress magnitudes ... 29 Figure 3-4 Ellipsoidal-prism pressure distribution......................................................... 44 Figure 4-4 Different positions for one complete tooth meshing cycle ...................... 45 VII .....................LIST OF FIGURES Figure 1-1 Fatigue failure of the tooth surface............................................... 36 Figure 3-10 Comparison between calculated values and ANSYS values............................... 32 Figure 3-6 Normal contact stress along the contact surface...
................................... 66 Figure 5-2 Vectors of displacement ................................................................................................................. 48 Figure 4-7 Contact stress along contact areas ...................... 71 Figure 5-6 The fine mesh near the two contact surfaces..Figure 4-5 FEM Model of the gear tooth pair in contact ............................................................. 67 Figure 5-3 Vectors of displacement near the contact surfaces.................. 71 Figure 5-5 Meshing model for spur gears ..................... 54 Figure 4-13 FEM bending model with meshing ................................................................ 75 Figure 5-8 The distribution of contact stresses between two teeth ........ 47 Figure 4-6 Fine meshing of contact areas .................................................. 56 Figure 5-1 The beam elements were used in the FEA model ............ 76 Figure 5-9 Static transmission error from ANSYS .................................................... 49 Figure 4-9 Length dimensions used in determining bending tooth stress.... 50 Figure 4-10 FEM gear tooth bending model with 3 teeth ......................................................................................................................................................................... 53 Figure 4-11 A two dimension tooth from a FEM model with 28 teeth.............................. 53 Figure 4-12 Von Mises stresses with 28 teeth on the root of tooth......................... 48 Figure 4-8 A fine mesh near contact areas................. 72 Figure 5-7 Von Mises stresses in spur gears ................ 68 Figure 5-4 Contact elements between the two contact surfaces....................... 77 VIII ............................................................................. 55 Figure 4-14 Von Mises stresses with 28 teeth on the root of tooth.............................................................................................................................................
..........1 Bending Stresses for 3-D and 2D FEM bending model........1 Specifications of spur gears used……………………………………………26 Table 4.LIST OF TABLES Table 3........59 Table 5.1 Gear Parameters Used in the Model…………………………………………69 IX ..........
Nomenclature K u Structural stiffness Displacement vector Applied load vector Maximum contact stress Pinion pitch diameter Gear pitch diameter Load per unit width Radius of cylinder i Pressure angle Poisson’s ratio for cylinder i Young’s modulus for cylinder i Maximum Hertz stress. Contact width Any radius to involute curve Radius of base circle Vectorial angle at the pitch circle Vectorial angle at the top of tooth Pressure angle at the pitch circle F Pmax d1 d2 Fi Ri ϕ υi Ei σH a r rb θ ξ φ X .
φ1 B BP Pressure angle at radius r Tooth displacement vectors caused by bending and shearing of the pinion Tooth displacement vectors caused by bending and shearing of the gear Contact deformation vectors of tooth pair B for the pinion Contact deformation vectors of tooth pair B for the gear Transverse plane angular rotation of the pinion body Transverse plane angular rotation of the gear body Diametral pitch Lewis form factor Application factor Size factor Load distribution factor Dynamic factor Normal tangential load Geometry factor Angular rotation of the output gear Angular rotation of the input gear B Bg B HP B Hg B θP θ gB pd Y Ka Ks Km Kv Ft Yj θg θp XI .
The increasing demand for quiet power transmission in machines. analysis of the characteristics of involute spur gears in a gearbox was studied using nonlinear FEM. and in most industrial rotating machinery. Speed reducers are available in a broad range of sizes. higher reliability and lighter weight gears are necessary as lighter automobiles continue to be in demand. the largest manufacturer of gears.Chapter 1 INTRODUCTION 1. the success in engine noise reduction promotes the production of quieter gear pairs for further noise reduction. has created a growing demand for a more precise analysis of the characteristics of gear systems. Noise reduction in gear pairs is especially critical in the rapidly growing field of office-automation equipment as the office environment is adversely affected by noise.. In addition. the rapid shift in the industry from heavy industries such as shipbuilding to industries such as automobile manufacture and office automation tools will necessitate a refined application of gear technology.1 Research Overview Gearing is one of the most critical components in a mechanical power transmission system. In the automobile industry. gear head. It is possible that gears will predominate as the most effective means of transmitting power in future machines due to their high degree of reliability and compactness. Their job is to convert the input provided by a prime mover (usually an electric motor) into an output with lower speed and correspondingly higher torque. capacities and speed ratios. gear reducer etc. vehicles. shafts and bearings that are factory mounted in an enclosed lubricated housing. In addition. and machines are playing an ever1 . In this thesis. A gearbox as usually used in the transmission system is also called a speed reducer. which consists of a set of gears. elevators and generators.
Transmission error is a term used to describe or is defined as the differences between the theoretical and actual positions between a pinion (driving gear) and a driven gear. such as that provided by Pro/Engineer. With prior knowledge of the operating conditions of the gear set it is possible to design the gears such that the vibration and noise is minimized. the geometry is saved as a file and then it can be transferred from Pro/E to ANSYS. The prime source of vibration and noise in a gear system is the transmission error between meshing gears. 2 . Pro/Engineer can generate models of three-dimensional gears easily. Designing highly loaded spur gears for power transmission systems that are both strong and quiet requires analysis methods that can easily be implemented and also provide information on contact and bending stresses. a shortage of these specialists exists in the newer. In ANSYS. In order to reduce the modeling time. In Pro/E. a preprocessor method that creates the geometry needed for a finite element analysis may be used.widening role in that environment. The reduction of noise through vibration control can only be achieved through research efforts by specialists in the field. the only effective way to achieve gear noise reduction is to reduce the vibration associated with them. along with transmission errors. one can click File > Import > IGES > and check No defeaturing and Merge coincident key points. However. The finite element method is capable of providing this information. but the time needed to create such a model is large. lightweight industries in Japan [42] mainly because fewer young people are specializing in gear technology today and traditionally the specialists employed in heavy industries tend to stay where they are. Ultimately. It has been recognized as a main source for mesh frequency excited noise and vibration.
Transmission error is usually due to two main factors. Gear designers often attempt to compensate for transmission error by modifying the gear teeth. Among the types of gearbox noise. people have tended to use numerical approaches to develop theoretical models to predict the effect of whatever are studied. static contact and bending stress analyses were performed. while trying to design spur gears to resist bending failure and pitting of the teeth. This suggests that the gear noise is closely related to transmission error. causing variations in angular rotation of the gear body. In this thesis. one of the most difficult to control is gear noise generated at the tooth mesh frequency. If a pinion and gear have ideal involute profiles running with no loading torque they should theoretically run with zero transmission error. these slight variations can cause noise at a frequency which matches a resonance of the shafts or the gear housing. which required a number of assumptions and simplifications. Numerical methods 3 . when these same gears transmit torque. as both affect transmission error. gear analyses are multidisciplinary. This has improved gear analyses and computer simulations. The first is caused by manufacturing inaccuracy and mounting errors. The second type of error is caused by elastic deflections under load. However. causing the noise to be enhanced. As computers have become more and more powerful. including calculations related to the tooth stresses and to tribological failures such as like wear or scoring. This phenomenon has been actively studied in order to minimize the amount of transmission error in gears. In general. the combined torsional mesh stiffness of each gear changes throughout the mesh cycle as the teeth deflect. Even though the transmission error is relatively small. Gears analyses in the past were performed using analytical methods. Transmission error is considered to be one of the main contributors to noise and vibration in a gear set.
The main focus of the current research as developed here is: 4 . and the torsional mesh stiffness of gears in mesh using the ANSYS 7. first. must be chosen carefully to ensure that the results are accurate and that the computational time is reasonable. There have been numerous research studies in the area [2]. such as a gear. 1.[3] as described in chapter 2. The model and the solution methods. The finite element method is very often used to analyze the stress state of an elastic body with complicated geometry. The objectives of this thesis are to use a numerical approach to develop theoretical models of the behavior of spur gears in mesh. to help to predict the effect of gear tooth stresses and transmission error.1 software package based on numerical method. Then. and thereby reduce the amount of noise generated. contact and bending stresses.2 Objectives of the Research In spite of the number of investigations devoted to gear research and analysis there still remains to be developed. the finite element models and solution methods needed for the accurate calculation of two dimensional spur gear contact stresses and gear bending stresses were determined. torsional mesh stiffness and transmission errors. In this thesis. The purpose of this thesis is to develop a model to study and predict the transmission error model including the contact stresses. The aim is to reduce the amount of transmission error in the gears.1 were compared to the results obtained from existing methods.can potentially provide more accurate solutions since they normally require much less restrictive assumptions. the contact and bending stresses calculated using ANSYS 7. a general numerical approach capable of predicting the effects of variations in gear geometry. however.
The 5 . • To determine the static transmission errors of whole gear bodies in mesh.1 [35] are the examples of failures which resulted in the fatigue failure of tooth surface. prognosis. There are two theoretical formulas. • To generate the profile of spur gear teeth and to predict the effect of gear bending using a three dimensional model and two dimensional model and compare the results with theose of the Lewis equation. fault detection. which deal with these two fatigue failure mechanisms. there are many types of gear failures but they can be classified into two general groups. Prediction of transmission efficiency. diagnosis. One is failure of the root of the teeth because the bending strength is inadequate. to calculate contact stresses using ANSYS and compare the results with Hertzian theory. Different analysis models will be described in chapter 2. to transmission error during the last five decades. The goals in gear modeling may be summarized as follows: • • • • • Stress analysis such as prediction of contact stress and bending stress. Evaluating condition monitoring. Finding the natural frequencies of the system before making the gears. which can be used to calculate the contact stresses. The other is the Lewis formula. reliability and fatigue life. The other is created on the surfaces of the gears. The objectives in the modeling of gears in the past by other researchers have varied from vibration analysis and noise control.• To develop and to determine appropriate models of contact elements. The surface pitting and scoring shown in Figure 1. One is the Hertzian equation. Performing vibration analyses of gear systems. which can be used to calculate the bending stresses. For gears.
In other words. But that available on the gear tooth contact stress problem is small. especially for transmission error including the contact problem. Klenz [1] examined the spur gear contact and bending stresses using two dimensional FEM. which occurs on gear tooth surfaces when a pair of teeth is transmitting power. Gatcombe and Prowell [10] studied the 6 . Figure 1-1 Fatigue failure of the tooth surface Pitting and scoring is a phenomena in which small particles are removed from the surface of the tooth due to the high contact stresses that are present between mating teeth. Hardness is the primary property of the gear tooth that provides resistance to pitting. The literature available on the contact stress problems is extensive. Pitting is actually the fatigue failure of the tooth surface. pitting is a surface fatigue failure due to many repetitions of high contact stress. Coy and Chao [9] studied the effect of the finite element grid size on Hertzian deflection in order to obtain the optimum aspect ratio at the loading point for the finite element grid.Hertzian equation will be used to investigate surface pitting and scoring by obtaining the magnitude of the contact stresses.
Chapter 3 describes why the contact problem is difficult. and the objectives to be achieved. In Chapter 5. namely a particular rocket motor gear tooth. However.3 Layout of Thesis This thesis is comprised of a total of six chapters.Hertzian contact stresses and duration of contact for a very specific case. Finally the layout of the thesis is described. and suggests future work. Many graphical results from ANSYS are shown. Chapter 2 is a literature review and gives background of characteristics of involute spur gears for different types of modeling. Chapter 4 begins with presentation of an involute gear tooth contact stress analysis model from ANSYS. Chapter 1 presents a general introduction. The results are compared with the results from the Lewis Formula. Finally a discussion on how to overcome some of the disadvantages is presented. 1. 7 . Chapter 6 gives the conclusions of this thesis. Tsay [11] has studied the bending and contact stresses in helical gears using the finite element method with the tooth contact analysis technique. The contact stress model between two cylinders was then developed. and then presents the bending stresses from 3-D models and 2-D models for the different numbers of teeth. the details of the techniques used to evaluate the transmission error including contact stresses were not presented. FEM will be used to determine the transmission error model including the contact problem for ideal involute spur gears and how to obtain the transmission error in mesh from ANSYS. A contact problem classification was done which as well as provides a discussion of the advantages and disadvantages of contact elements.
and the optimal design for gear sets are always major concerns in gear design. In later years. Kubo et al [18] estimated the transmission error of cylindrical involute gears using a tooth contact pattern. gear noise. the transmission errors. • • • • Models with Tooth Compliance Models of Gear system Dynamics Models of A Whole Gearbox Models for Optimal Design of Gear Sets 8 . Mark [15] and [16] analyzed the vibratory excitation of gear systems theoretically. The following classification seems appropriate [64]. The current literature reviews also attempt to classify gear model into groupings with particular relevance to the research. The first study of transmission error was done by Harris [14]. the prediction of gear dynamic loads. and a large body of literature on gear modeling has been published. The gear stress analysis. He derived an expression for static transmission error and used it to predict the various components of the static transmission error spectrum from a set of measurements made on a mating pair of spur gears. Errichello [12] and Ozguven and Houser[13] survey a great deal of literature on the development of a variety of simulation models for both static and dynamic analysis of different types of gears. He showed that the behavior of spur gears at low speeds can be summarized in a set of static transmission error curves.Chapter 2 Literature Review and Background There has been a great deal of research on gear analysis. Kohler and Regan [17] discussed the derivation of gear transmission error from pitch error transformed to the frequency domain.
For the models with paired teeth. The transmission error was suggested as a new concept for determining the gear quality.2. There are studies of both single tooth and tooth pair models. The basic characteristic in this group is that the only compliance considered is due to the gear tooth deflection and that all other elements have assumed to be perfectly rigid. Cornell [21] obtained a relationship between compliance and stress sensitivity of spur gear teeth. His work can be summarized in a set of static transmission error curves. For single tooth models. The tooth root stresses 9 . variation in the tooth stiffness and non-linearity in tooth stiffness as three internal sources of vibration. rather than individual errors. In 1969. Due to the loss of contact he considered manufacturing errors. In 1981. Tordion [68] first constructed a torsional multi-degree of freedom model with a gear mesh for a general rotational system. He modeled the vibration characteristics of gears by considering tooth profile errors and pitch errors. The importance of transmission error in gear trains was discussed and photo-elastic gear models were used in his work. The system is often modeled as a single degree of freedom spring-mass system. In 1967. Harris [14] made an important contribution to this area. Aida [67] presented other examples of studies in this area. the contact stresses and meshing stiffness analysis usually were emphasized.1 Model with Tooth Compliance These models only include the tooth deformation as the potential energy storing element in the system. The magnitude and variation of the tooth pair compliance with load position affects the dynamics and loading significantly. Harris was the first investigator who pointed out the importance of transmission error by showing the behavior of spur gears at low speeds. a method of stress analysis was developed. and by including the variation of teeth mesh stiffness.
versus load varies significantly with load positions. These improved compliance and stress sensitivity analyses were presented along with their evaluation using tests. in which the tooth is replaced by a spring and the gear blank is replaced by a mass. When the rotational vibration of a powertransmitting helical gear pair is considered along the line-of-action model similar to the case of a spur-gear pair. With improved fillet/foundation compliance analysis the compliance analysis was made based on work by Weber [22] and O’Donell [23]. and analytic transformation results. the position of line-of-contact CC c by C ' and the ending point E by E ' on the line-of-action. It finishes at point E. The length of path of contact is on the plane of action of helical gear pairs in Figure 2. finite element analysis. the position of the line-ofcontact is represented by the coordinate Y along the line-of-action of the helical gear (hereafter simply stated as the line-of-action) which is considered to be the middle of the face width.1 [27]. A vibration model was built [28] there. The stress sensitivity analysis is a modified version of the Heywood method [24]. That is. A simple outline of the theoretical analysis on the vibration of a helical gear is given below. The developed simulator was created through theoretical analysis on the vibration of a narrow face width helical gear pair. In 1988. Umezawa [27] developed a new method to predict the vibration of a helical gear pair. 10 . The meshing of the pair proceeds on the plane with the movement of the contact line. which indicated good agreement. A pair of mated teeth starts meshing at point S on the plane of action. the starting point of meshing S is substituted by S ' . The studies on a helical gear are very different from the ones on a spur gear.
Vijayarangan and Ganesan [58] studied static contact stresses including the effect of friction between the mating gear teeth. If the external forces at the various nodes are known. Then the stress can be calculated. Each gear is divided into a number of elements such that in the assumed region of contact there is equal number of nodes on each gear. then the system of equations is written as: [ K ]{U } = {F } (2.Figure 2-1 Meshing of a helical pair In 1992. The system of equations is solved and {U } is obtained. Using the conventional finite element method the element stiffness matrices and the global stiffness matrix [K ] of the two gears in mesh were obtained. These contact nodes are all grouped together. 11 .1) where {U } is the nodal displacement vector and {F } is the nodal force vector.
analytical methods have been developed [53]. gear life predictions have been investigated [55]. bearings stiffness. The flexibility of 12 . The objective of this work was to study the effect of the moving gear tooth load on crack propagation predictions. As an example. Analysis tools that predict crack propagation paths can be a valuable aid to the designer to prevent such catastrophic failures. the analytical methods have been used in numerical form (finite or boundary element methods) while solving a static stress problem. gear tooth bending stiffness. A finite element model of a single tooth was used to analyze the stress. Rim failures would lead to catastrophic events and should be avoided. From publications on gear crack trajectory predictions.2 Models of Gear System Dynamics The current models can predict shaft torsional vibration. etc. shaft bending stiffness. Numerical techniques such as the boundary element method and the finite element method have also been studied [54]. Even effective designs have the possibility of gear cracks due to fatigue. Using weighting function techniques to estimate gear tooth stress intensity factors. crack trajectories that propagate through the gear tooth are the preferred mode of failure compared to propagation through the gear rim. In addition. David and Handschuh [20] investigated the effect of this moving load on crack trajectories. Moving loads normal to the tooth profile were studied.In 2001. Based on stress intensity factors. 2. At different points on the tooth surface impulsive loads were applied. The models of gear system dynamics include the flexibility of the other parts as well as the tooth compliance. The gear crack trajectory predictions have been addressed in a few studies [56]. but crack propagation trajectories. deformation and fracture in gear teeth when subjected to dynamic loading. and fatigue crack growth. truly robust designs consider not only crack initiation.
In his research. Using a torsional vibratory model. the gear mesh stiffness is the key element in the analysis of gear train dynamics. gear tooth deflections. An interactive method was developed to calculate directly a variable gear mesh stiffness as a function of transmitted load. These components are the static transmission errors of the individual pairs in the system. load sharing.shafts and the bearings along the line of action are discussed. some simple models were developed for the purpose 13 . gear tooth deflections and gear hub torsional deformation. In 1981. Certain types of simulated sinusoidal profile errors and pitting can cause interruptions of the normal gear mesh stiffness function. In the 1980s although more and more advanced models were developed in order to obtain more accurate predictions. Kasuba [66] determined dynamic load factors for gears that were heavily loaded based on one and two degree of freedom models. In 1979 Mark [15] [16] analyzed the vibration excitation of gear systems. and the position of contacting points. gear tooth errors. formulation of the equations of motion of a generic gear system in the frequency domain is shown to require the Fourier-series coefficients of the components of vibration excitation. In 1971. A general expression for the static transmission error is derived and decomposed into components attributable to elastic tooth deformations and to deviations of tooth faces from perfect involute surfaces with uniform lead and spacing. he published another paper [48]. These methods are applicable to both normal and high contact ratio gearing. increase the dynamic loads. the torsional vibration of the system is usually considered. profile modifications. The gear mesh stiffness and the contact ratio are affected by many factors such as the transmitted loads. he considered the torsional stiffness of the shaft. In these models. In his papers. gear profile errors. and position of contacting profile points. and thus.
The tooth contact was maintained during the rotation and the mesh was rigid in those models. the coupled torsionalflexural vibration of a shaft in a spur geared system was investigated by some researchers. rather than two shafts. The gear mesh was modeled by a pair of rigid disks connected by a spring and a damper with a constant value which represented the average mesh value. and applied the transmission error as the excitation at the mesh point to simulate the variable mesh stiffness. That the output shaft was flexible in bearing and the input shaft was rigid in bearing was assumed. Sweeney’s model is applicable to cases where the dominant source of transmission error is geometric imperfections. Coupling between the torsional and transverse vibrations of the gear was considered in the model. In 1992. one of them being a counter shaft. based on the effects of geometric parameter variation on the transmission error. other researchers presented another model that consists of three shafts.of simplifying dynamic load prediction for standard gears. He assumed that the tooth (pair) stiffness is constant along the line of action (thin-slice model) and that the contact radius for calculation of Hertzian deformation is the average radius of the two profiles in contact. and is particularly suited to automotive quality gear analysis. The results of his model gave very good agreement with measurements on automotive quality gears. Sweeney [25] developed a systematic method of calculating the static transmission error of a gear set. Randall and Kelley [26] modifications have been made to Sweeney’s basic model to extend it to higher quality gears where the tooth deflection component is more 14 . In 1980. Kahraman [41] developed a finite element model of a geared rotor system on flexible bearings. In 1996. Four years later. Researchers derived equations of motion for a 6-degree-offreedom (DOF) system. the case where the tooth deflection component is the dominant source of the transmission error nylon gears were used. All the simulation results have been compared with the measured transmission errors from a single-stage gearbox. In 1999, Kelenz [1] investigated a spur gear set using FEM. The contact stresses were examined using a two dimensional FEM model. The bending stress analysis was performed on different thin rimmed gears. The contact stress and bending stress comparisons were given in his studies. In 2001, Howard [34] .
15 [38] [57].
2.4 Models for Optimal Design of Gear Sets
Several approaches to the models for optimum design of gears have been presented in the recent literature. Cockerham [29] presents a computer design program for 20-degree pressure angle gearing, which ignores gear-tooth-tip scoring. This program 16
varies the diametral pitch, face width, and gear ratio to obtain an acceptable design. Tucker [30] and Estrin [31] look at the gear mesh parameters, such as addendum ratios and pressure angles and outline the procedures for varying a standard gear mesh to obtain a more favorable gear set. Gay [32] [33], [36] to determine the optimal size of a standard gear mesh. With the object of minimizing size and weight, optimization methods are presented for the gearbox design [37], [39]. The gear strengths must be considered including fatigue as treated by the AGMA (American Gear Manufacturing Association) [40]. Surface pitting of the gear teeth in the full load region must also be handled with [43]-[45] as scoring at the tip of the gear tooth [46], [47]. In 1980, Savage and Coy [19]objective as they often involve more than one design goal to be optimized. These design goals impose potentially conflicting requirements on the technical and cost reduction performances of system design. To
17
in addition a design method for cylindrical gear pairs to balance the conflicting objectives by using a goal programming formulation was proposed. 18 .study the trade-offs that exist between these conflicting design goals and to explore design options. To help the exploration of different multiobjective formulations Stadler and Dauer [49] incorporated Pareto optimality concepts into the optimization algorithms. A comprehensive survey of multiobjective optimization methods is also given. Tappeta [51] and Hwang and Masud [50] summarized the progress in the field of multi-criteria optimization. The design method reduces both the geometrical volume and the meshing vibration of cylindrical gear pairs while satisfying strength and geometric constraints. which attains the multiple objectives as closely as possible while strictly satisfying constraints. This scalarization was usually achieved using either weights or targets that the designers have to specify for each objective a priori. The results of the relation between the geometrical volume and the vibration of a gear pair were analyzed. one needs to formulate the optimization problem with multiple objectives. The optimization algorithms seek an optimum design. A variety of techniques and many applications of multiobjective optimization have been developed over the past few years. which require the designer’s involvement as a decision maker. In 2001. Some of the disadvantages of traditional methods are listed there [52]. The most traditional methods involve converting a multiobjective problem into a single objective problem for a compromise solution are also presented. Chong and Bar [8] demonstrated a multiobjective optimal design of cylindrical gear pairs for the reduction of gear size and meshing vibration.
such as the conductance of heat and electrical 19 . and boundary conditions. Mechanical problems involving contacts are inherently nonlinear. There are several friction laws and models to choose from. In addition to those difficulties. and the temperature of the contacting surfaces. and all are nonlinear. Why is it “nonlinear” behavior? Usually the loading causes significant changes in stiffness. along with other factors. materials. First. Nonlinear structural behavior arises for a number of reasons. Large Deflections) (2) Material Nonlinearities (Plasticity) (3) Change in Status Nonlinearities (Contact). Frictional response can be chaotic. surfaces can come into and go out of contact with each other in a largely unpredictable manner. the actual region of contact between deformable bodies in contact is not known until the solution has been obtained. making solution convergence difficult (ANSYS). which can be reduced to three main categories: (1) Geometric Nonlinearities (Large Strains. which results in a structure that is nonlinear. Secondly. So the contact between two bodies belongs to the case (3). contact effects are rarely seriously taken into account in conventional engineering analysis. the physical and chemical properties of the material. The modeling of friction is very difficult as the friction depends on the surface smoothness.Chapter 3 Contact Stress Simulation of Two Cylinders 3. most contact problems need to account for friction.1 Why is the Contact Problem Significantly Difficult Despite the importance of contact in the mechanics of solids and its engineering applications. Why is the contact problem significantly difficult? Contact problems present many difficulties. Depending on the loads. because of the extreme complexity involved. the properties of any lubricant that might be present in the motion. many contact problems must also address multi-field effects.
to . Rigid . including contact stress.currents in the areas of contact.2. Many metal forming problems fall into this category. fluid flow.1 How to Solve the Contact Problem Contact Problem Classification There are many types of contact problems that may be encountered. because of its proven success in treating a wide range of engineering problem in areas of solid mechanics.flexible bodies in contact. In rigid . Flexible-to-flexible is where both contacting bodies are deformable. crash dynamics. one or more of the contacting surfaces are treated as being rigid material. however. which has a much higher stiffness relative to the deformable body it contacts. and for electromagnetic field and coupled field problems. ranging from relatively simple ones to quite complicated ones. With the rapid development of computational mechanics. The Finite Element Method can be considered the favorite method to treat contact problems.flexible bodies in contact. many contact problems. All of these contact problems.to .2 3. etc. great progress has been made in numerical analysis of the problem. dynamic impacts.to . heat transfer. can be split into two general classes (ANSYS). assemblies of components with interference fits. and interference fits. metal forming. can be solved with high accuracy.flexible contact problems. bolted joints. bolted joints. Using the finite element method. Examples of a flexible-to-flexible analysis include gears in mesh. 3. Bodies in contact may have complicated geometries and material properties and may deform in a seemingly arbitrary way. 20 . Flexible . as well as other types of contact analysis.
These types of contact problems allow large amounts of deformation and relative sliding. Also.3. 21 . Surface-to-surface contact is typically used to model surface-to-surface contact applications of the rigid-to-flexible classification. The combined penalty plus Lagrange multiplier approach satisfies compatibility to a user-defined precision by the generation of additional contact forces that are referred to as Lagrange forces. Point-to-surface contact: the exact location of the contacting area may not be known beforehand.2. It will use in chapter 5. opposing meshes do not have to have the same discretisation or a compatible mesh. There are two methods of satisfying contact compatibility: (i) a penalty method. 3. The penalty method enforces approximate compatibility by means of contact stiffness.2. Point-to-point contact: the exact location of contact should be known beforehand.3 How to Solve the Contact Problem In order to handle contact problems in meshing gears with the finite element method. These types of contact problems usually only allow small amounts of relative sliding deformation between contact surfaces. and (ii) a combined penalty plus a Lagrange multiplier method. there are three basic types of contact modeling application as far as ANSYS use is concerned. Point to surface contact was used in this chapter. the stiffness relationship between the two contact areas is usually established through a spring that is placed between the two contacting areas.2 Types of Contact Models In general. This can be achieved by inserting a contact element placed in between the two areas where contact occurs.
They are the combined normal contact stiffness k n and the combined tangential contact stiffness k t . On the other hand. The combined normal contact stiffness k n is used to penalize interpenetration between the two bodies. which can be controlled by changing the penalty parameter of the combined normal contact stiffness. which is a real constant of the contact element. If the combined normal contact stiffness is too small. while the combined tangential contact stiffness k t is used to approximate the sudden jump in the tangential force.It is essential to prevent the two areas from passing through each other. if the penalty parameter is too large. as 22 . E = smallest value of Young’s Modulus of the contacting materials h = the contact length The contact stiffness is the penalty parameter. the surface penetration may be too large. k n ≈ fEh (3. the value of the combined normal contact stiffness may be estimated [ANSYS] as. The penalty allows surface penetrations. Thus the stiffness must be big enough to keep the surface penetrations below a certain level. then the combined normal contact stiffness may produce severe numerical problems in the solution process or simply make a solution impossible to achieve. This method of enforcing contact compatibility is called the penalty method. the combined normal contact stiffness and the combined tangential or sticking contact stiffness. The element is based on two stiffness values.01 and 100. For most contact analyses of huge solid models. This factor is usually be between 0.1) where f is a factor that controls contact compatibility. There are two kinds of contact stiffness. which may cause unacceptable errors.
and point-to-surface contact element. However. For the problem in hand. This rotation ensured that the friction forces would develop in the proper direction. The friction forces are developing in various directions because the generation of a tangential friction force facing right on one node would tend to pull the node on its left to the right. the three nodes. This would generate a friction force facing left on this node. pulling back on the other node. This problem was eliminated by applying a small rotation to the above cylinder model forces as it was displaced and loaded vertically. to problems with or without friction. or axisymmetry situations. This is due to Poission’s effect causing small transverse deflections of the nodes in the contact zone. The contact problem is addressed using a special contact element. The area of contact between two or more bodies is generally not known in advance. 23 .represented by the Coulomb friction when sliding is detected between two contacting nodes. It is applicable to 2-D geometry. and to flexible-toflexible or rigid-to-flexible body contact. These deflections are enough to activate the friction forces of the contact elements [1]. A detailed examination of the model’s nodal force during the vertical loading may indicate the problem. This continual tug-of-war causes the poor convergence. Not only are friction forces developing but they develop in random directions. the element to be used is a two-dimensional. A number of contact elements were available (two and three dimensional. serious convergence difficulties may exist during the vertical loading process and application of the tangential load often results in divergence. the CONTAC48 element from the ANSYS element library as the contact elements between the two contact bodies shown as Figure 3. It may be applied to the contact of solid bodies for static or dynamic analyses. plane strain. spring and damper combinations). In the input file. plane stress.1 was chosen.
the advantages of using contact elements are: • • • They are easy to use They are simple to formulate. 24 .Contact nodes Target nodes Target surface Figure 3-1 Point-to-surface contact element 3.2. depends on user defined parameters.4 Contact Element Advantages. However. using contact elements poses some difficulties such as the fact that their performance. and They are easily accommodated into existing FE code. in term of convergence and accuracy. Disadvantages and their Convergence Because of the simplicity of their formulation.
can also affect both accuracy and expense. and if many iterations are required. In order to get convergence in ANSYS. Consider two circular discs. two circular elastic discs under two-dimensional contact are analysed. such as contact stiffness. If solution fails to converge. as shown in Figure 3. The calculation is carried out under a plane strain condition with a Poisson’s ratio of 0. and the numerical solutions are compared with that of the Hertz theory. One must use their own engineering judgment to determine how much accuracy is needed versus how much expense can be afforded. 25 . A and B. If the solution converges. difficult problems might require many load increments. which affect both accuracy and expense. with a radius of R1= 3 in. However.Contact Problem of Two Circular Discs First. the number of load increments. the overall solution time increases. half of the discs are partitioned to the finite element mesh. the start was outside the radius. 3. the start was within the radius. there is no simple way to determine the radius of convergence. Nonlinear analyses add an extra factor. the number of elements and nodes for each disc is 1766 and 1281.2. Balancing expense versus accuracy: All FEA involves a trade-off between expense and accuracy. and R2= 3 in. usually the biggest challenge is that the solution must start within the radius of convergence.5 Numerical Example ---. Other nonlinear parameters. but requires more time and system resources. More detail and a finer mesh generally leads to a more accurate solution.In overcoming convergence difficulties. respectively.3 using eight-node isoparametric elements.2. Trial-and-error must be used to obtain convergence. To reduce the number of nodes and elements and to save more computer memory space. to investigate the accuracy of the present method.
000. In each sub-step the number of equilibrium iterations was set. first.00 M 1.1 Specifications of spur gears used Number of teeth Normal Module (M) Addendum Modification coefficient Normal Pressure Angle Face Width (mm) Addendum (mm) Dedendum (mm) 25 6 mm 0 20 degrees 0.25 M 26 .2. In each step there are a lot of sub-steps.In this problem. the geometry of two half cylinders. must be described. Then the geometry areas were meshed. The loads also were applied four times as four steps. two steel cylinders are pressed against each other. This model was built based on the Hertz contact stress theoretical problem. In the input file.015 M 1. The boundary conditions were applied in this model.1 and Figure 3. The contact stress of this model should represent the contact stress between two gears. The radii were calculated from the pitch diameters of the pinion and gear and other parameters shown in Table 3.000 psi and the Poisson’s ratio was 0. The steel material properties have an elastic Young’s modulus of 30. Table 3.30. In contact areas a fine mesh was built.
It can use the linear problem iterated many times instead of solving the nonlinear problem.6 The FEM Numerical Procedure The resulting contact problem is highly nonlinear and usually requires significant computer resources to solve. in the 1600s. For a linear elastic problem.Figure 3-2 Two steel cylinders are pressed against each other 3.2) 27 .2. This nonlinear contact problem can be simulated using the FEA method. That means that the nonlinear problem is usually solved based on the linear problem. Robert Hooke discovered a simple linear relationship between force { F } and displacement {u}: {K }{u} = {F } where { K } is the stiffness matrix. and represents structural stiffness. (3. Contact nonlinearities occur when two components come into or out of contact with each other or when two components slide relative to each other.
the contact area is not known in advance. However. Because a plot of F versus u for such structures is not a straight line. 28 . the applied load and structure’s reaction force are not in equilibrium. the deflections {u1 } are calculated. Since the stiffness of the structure in the displaced configuration is different than in the previous configuration[1]. using the stiffness of the undeflected shape. It becomes a function of applied load. A full Newton-Raphson iterative analysis for one increment of load and four iterations is shown as Figure 3. The Newton Raphson method uses this force imbalance to drive the structure to equilibrium. such structures are said to be nonlinear.3. with corrections. In Figure 3.{ u } is the displacement vector. Each iteration is known as an equilibrium iteration. a nonlinear structure can be analyzed using an iterative series of linear approximations. significant classes of structures do not have a linear relationship between force and displacement. For example in modeling most contact problems.3) Where {u i −1 } is known. For example. the problem can be solved for {u} using a linear equation solver. {K } is a function of {u} and an iterative procedure is needed. Linear structures are well suited to finite-element analysis.3 the relationship is shown between the loads and the displacement when the linear problem is used instead of the nonlinear problem. the deflection {u i } is calculated by Gaussian elimination. If {K } is constant and known. In a nonlinear analysis. A linear structure obeys this linear relationship. The stiffness is no longer a constant K . However. ANSYS uses an iterative process called the Newton-Raphson method which functions as follows: {K (u i −1 )}{u i } = {F } (3. A common example is a simple spring. and { F } is the applied load vector. the response cannot be predicted directly with a set of linear equations. which is based on linear matrix algebra.
Load F 1 2 4 3 Displacement U Figure 3-3 Equilibrium iteration 3. the Finite Element Method treats contact problems by extending the variational formulation upon which the Finite Element Method is based.4. 29 . Contact stresses between two cylinders were shown in Figure 3. The solution is then obtained by solving the resulting set of nonlinear equations. which were originally derived for contact between two cylinders.In other words. The stiffness matrix associated with contact elements and other element stiffness matrices of the body are formulated and assembled into the original finite element model.3 Hertz Contact Stress Equations Usually. An ellipsoidal-prism pressure distribution is generated between the two contact areas. the current methods of calculating gear contact stresses use Hertz’s equations.
5) The maximum contact stress Pmax = 2F .4 the width of the contact zone is 2a. The maximum surface (Hertz) stress: 30 . which shows the relationship between the force F and the pressure p(x): F = 2 L ∫ 0 a p ( x ) dx .6) d 1 and d 2 represent the pinion and gear pitch diameters. πaL (3.4) Contact width a = 2 F (1 − υ1 ) / E1 + (1 − υ 2 ) / E 2 1 / d1 + 1 / d 2 πL 2 2 . If total contact force is F and contact pressure is p(x). there is a formula [5]. (3. (3.Figure 3-4 Ellipsoidal-prism pressure distribution From Figure 3.
4 The Result of the Contact Stress Analysis The objective of the contact stress analyses was to gain an understanding of the modeling and solution difficulties in contact problems and examine the contact stresses in the gears. only half cylinders were meshed in the model as shown in Figure 3. contact between two cylinders was modeled. which means that the finite element mesh near the contact zone needs to be highly refined. 564 1 1 + ) R1 R2 1 − υ 12 1 − υ 22 + E1 E2 F( (3. The dimensions of the elements are based on the half width of the contact area. It is recommended not to have a fine mesh everywhere in the model to reduce the computational requirements. Ei is Young’s modulus for cylinder i . Ri is the radius of cylinder i . The fine meshed rectangular shaped elements were generated near contact areas shown as 3. Ri = d i sin ϕ 2 for the gear teeth. To reduce computer time. It was hoped that the 31 . In order to verify the FEM contact model procedure. 3. ϕ is pressure angle.5 (b). Num is the number of elements in the contact zone as specified in the input file. υ i is Poisson’s ratio for cylinder i . Finer meshing generally leads to a more accurate solution. The edge length dx of the rectangular shaped fine mesh elements: dx = 2 * a / Num. but requires more time and system resources.5(a).Pmax = σ H = 0 .7) F is the load per unit width. The contact conditions are sensitive to the geometry of the contacting surfaces.
The red color line represents the value from the theoretical Hertz equation and the blue color points represent the results from ANSYS.6 (a) and (b) show the distributions of the contact stress along the contact area. 32 .7 in which the two distributions lie very close. The comparison of results from FEM and the Hertzian theoretical formula are shown in Figure 3. It is easy to see the blue color points are on the red curve. and Figure 3. Num is equal to 10 here.number of elements in the Hertz contact zone could be related to the solution accuracy. (a) (b) Figure 3-5 Rectangular shaped elements were generated near contact areas The normal contact stress along the contact surface from the ANSYS solution is shown in Figure 3.6. independent of the specific force or cylinder sizes considered. Figure 3. They match very well.6 (c) shows the magnitude directly from ANSYS.
(a) (b) (c) Figure 3-6 Normal contact stress along the contact surface 33 .
12 0.00E-03 -4.00E-03 0. σ y as a function of depth y along a radius of the cylinder. The depth is normalized to the half-width a of the contact patch.2000 0 -2000 -4000 -6000 -8000 -10000 -12000 -6.8 shows the stresses σ x .04 0.14 0. This plot provides a dimensionless picture of the stress distribution on the centerline under an ellipsoidal contact. Note all the stresses have diminished to <10% of Pmax within y = 5a .00E+00 2. 2000 sy 0 -2000 sx -4000 -6000 -8000 SX ANSYS -10000 -12000 0 0.16 0.1 0.00E-03 6.02 0.08 0.00E-03 4.00E-03 -2.18 SY ANSYS Figure 3-8 Stress along depth distance below the contact surface from ANSYS 34 .00E-03 SY SY ANSYS SY Theory Figure 3-7 Contact stress from ANSYS agrees with the Hertz stress Figure 3.06 0.
13) 35 . The stresses due to the normal loading Fmax are [1] y a 2 + 2x 2 + 2 y 2 2π σx = − [ β− − 3xα ]Fmax π a a (3.11) k2 k1 + k 2 − 4 a 2 2 ) +( k1 k1 β = π k1 k2 k1 2 1+ k2 k1 2 k2 k + k2 − 4a + ( 1 k1 k1 (3. Both of these stresses distributions are along the depth distance.12) ) k1 = (a + x) 2 + y 2 k 2 = (a − x) 2 + y 2 (3.10) where the factors α and β are given by α = π k1 k2 k1 1− k2 k1 (3.The blue colour curve represents stress in the x direction.9) π (3. and the red color curve represents the stress in the y direction.8) σ y = − [aβ − xα ]Fmax π τ xy = − 1 y 2αFmax y (3. The next step is to compare results from ANSYS with the results from the theoretical equations. which is perpendicular to contact surface.
00E+00 1.00E-02 6.00E-02 Sx ANSYS Sx Theory Depth distance below surface(in) Figure 3-9 FEM stresses agree with the theoretical values 0 -2000 -4000 Stress (psi) σy -6000 -8000 -10000 -12000 -14000 0.00E-02 4.00E-02 5.00E-02 5.00E-02 2.2000 0 -2000 Stress (psi) σx -4000 -6000 -8000 -10000 -12000 0.00E-02 2.00E+00 1.00E-02 3.00E-02 The depth distance below the surface(in) Sy ANSYS Sy Theory Figure 3-10 Comparison between calculated values and ANSYS values 36 .00E-02 6.00E-02 3.00E-02 4.
where σ H is the maximum Hertz stress. The peak values of the equivalent stress using the Von Mises criterion.25σ H .30σ H .Note that these above equations cannot be used to calculate the stresses on the surface because if we set y equal zero it will result in the stresses being calculated as zero. (3.57σ H .7) as follows[1]: σVonMiss = 0. and the maximum orthogonal shear stress can be calculated from the maximum Hertz stress (3. τ OrthoShear = 0. the maximum shear stress. τ MaxShear = 0.14) (a) (b) Figure 3-11 Orthogonal shear stress magnitudes 37 .
it occurs at a depth of about 0.9 and Figure 3. In the author’s experience. The largest orthogonal shear stress lies below the surface at the edge of the contact zone. one can get a great deal of information from “General Postproc” for example : Von Mises. The subsurface location of the maximum shear stress can also be seen lying below the surface at the center of the contact zone shown in Figure 3. The FEA model from ANSYS is reliable if the solution is convergent. The shear stress is about 0. When finishing running the program. whether the solution has converged is checked after many times of equilibrium iteration. As long as the solution has converged.10 show a comparison of ANSYS results with the theoretical equations for stresses in x and y direction respectively. If both materials are steel. The subsurface location of the maximum 38 . Figures 3.12 (b).Figure 3. Usually for nonlinear problems it is not easy to get convergence.12 (a) and (b) show maximum shear stresses under the contact areas between two cylinders. Principal. Shear. It can be seen that the FEM results are essentially identical to the theoretical solution for both stresses σ x and σ y .30 Pmax . troubleshooting is necessary. Usually a converged solution occurred at an expected “time” value such as the end of the load step. Contact Stresses. If there is no convergence indicated in ANSYS.11 Pmax at the surface on the z axis.11 (b). the red curves represent the values from the above theoretical formula and blue points represent the results from ANSYS. which can provide rapid convergence (3) Increasing the number of sub-steps.11 (a) and (b) show orthogonal shear stress. there are several ways to do that: (1) Change the FKN – Normal Penalty Stiffness value (2) Solve the nonlinear analysis using “Line Search”. This was shown in Figure 3.63 a where a is half of the contact length shown in Figure 3. Figures 3.4 and its magnitude is about 0. In both figures.
It was found that initial loading using displacements as inputs was helpful in reducing numerical instabilities. such as the incremental technique of applying the external load in the input file. The theory indicates that cracks that begin below the surface eventually grow to the point that the material above the crack breaks out to form a pit.shear stress is believed to be a significant factor in surface-fatigue failure. (a) (b) Figure 3-12 Maximum shear stress from ANSYS 3. the deformation of the stiffness matrix.5 Conclusion Finite element modelling of the contact between two cylinders was examined in detail. The finite element method with special techniques. 39 . and the introduction of the contact element were used.
the tooth contact stresses and the tooth deflections of a pair of spur gears analyzed by ANSYS 7. The finite element method is very often used to analyze the stress states of elastic bodies with complicated geometries.1 Introduction When one investigates actual gears in service. Since the present 40 . which have calculated the elastic stress distributions in gears. the conditions of the surface and bending failure are two of the most important features to be considered. Special techniques of the finite element method were used to solve contact problems in chapter 3. It is essential to use a three-dimensional analysis if gear pairs are under partial and nonuniform contact. Because it is a nonlinear problem it is better to keep the number of nodes and elements as low as possible. In the bending stress analysis the 3-D model and 2-D models are used for simulation. such as gears. various calculation methods for the analysis of elastic contact problems have been presented. In these works. 4. The finite element method for two-dimensional analysis is used very often. which is proposed to estimate the tooth contact stresses of a gear pair. a problem is created due to the large computer memory space that is necessary.Chapter 4 Involute Gear Tooth Contact and Bending Stress Analysis 4. However. There are published papers.2 Analytical Procedure From the results obtained in chapter 3 the present method is an effective and accurate method.4. in the threedimensional calculation. Using the present method.1 are given in section 4. In this chapter to get the gear contact stress a 2-D model was used.
it is applicable to many types of gears. the dedendum circle. and base circle of the gear. shown in Figure 4. The equations of an involute curve below were taken from Buckingham [6]: r = rb * (1 + β 2 )1 2 ψ =θ + π 2n1 −ξ (4. First. rb = radius of the base circle β = ξ +φ θ = vectorial angle at the pitch circle ξ = vectorial angle at the top of the tooth φ φ1 = pressure angle at the pitch circle = pressure angle at radius r One spur tooth profile was created using equation 4.1. A two-dimensional and an asymmetric contact model were built. In early works. 41 . as are the outside diameter circle.1. the following conditions were assumed in advance: • • There is no sliding in the contact zone between the two bodies The contact surface is continuous and smooth Using the present method ANSYS can solve the contact problem and not be limited by the above two conditions. parameter definitions were given and then many points of the involute profile of the pinion and gear were calculated to plot an involute profile using a cylindrical system.1) θ = tan φ − φ = invφ where r = radius to the involute form.method is a general one.
There are two ways to build the fine mesh near the contact surfaces. One is the same method as presented in chapter 3.Secondly. a fine mesh of rectangular shapes were constructed only in the contact areas. and “MESH” and so on. in ANSYS from the tool bars using “CREATE”. “COPY”. in order to reduce the computational requirements. was chosen and the fine mesh near the contact area was automatically created. “SMART SIZE” in ANSYS. which means that the element near the contact zone needs to be refined. “MOVE”. The contact conditions of gear teeth are sensitive to the geometry of the contacting surfaces. It is not recommended to have a fine mesh everywhere in the model. The other one.2. θ ξ β φ Figure 4-1 Involutometry of a spur gear 42 . A FEM gear contact model was generated as shown in Figure 4. any number of teeth can be created and then kept as the pair of gear teeth in contact along the line of the action.
It is also an important concept for transmission error. The contact pair was inserted between the involute profiles. Figure 4-2 Gear contact stress model 4. proper constraints on the nodes were given. It is a complex process when more than one-tooth pair is simultaneously in contact taking into account the composite tooth deflections due to bending. shearing and contact deformation. and finally. This section presents a 43 .3 Rotation Compatibility of the Gear Body In order to know how much load is applied on the contact stress model and the bending stress model. ANSYS was run to get the solution. the external loads were applied on the model from ANSYS “SOLUTION > DEFINE LOAD > FORCE / MOMENT”.Thirdly. evaluating load sharing between meshing gears is necessary.
the line tangent to both base circles is defined as the line of action for involute gears. In one complete tooth mesh circle. as shown in Figure 4. B A Figure 4-3 Illustration of one complete tooth meshing cycle Consider two identical spur gears in mesh. The mesh cycle ends at point E.general approach as to how the load is shared between the meshing teeth in spur gear pairs.4 where the outside diameter of the pinion intersects the line of action. the contact starts at points A shown in Figure 4. When the gears are put into mesh. the addendum circle of the gear intersects the line of action.3 [64] where the outside diameter circle. When the first tooth pair is in contact at point A it is between the tooth tip of the output gear and the tooth root of the input gear (pinion). At the same time a second tooth pair is already in contact at point D in Figure 44 .
the second tooth pair disengage at point E leaving only the first tooth pair in the single contact zone. As the gear rotates.3. Finally. one complete tooth meshing cycle is completed when this tooth pair rotates to point E. including the effects of tooth bending deflection and shearing displacement and 45 . When this tooth pair rotates to point D.4. After this time there are two pairs of gear in contact until the first tooth pair disengage at point E.4. the another tooth pair begins engagement at point A which starts another mesh cycle. After this time there is one pair of gear in contact until the third tooth pair achives in contact at point A again. the point of contact will move along the line of action APE. the load sharing compatibility condition is based on the assumption that the sum of the torque contributions of each meshing tooth pair must equal the total applied torque. To simplify the complexity of the problem. When the first tooth pair reaches point B shown in Figure 4. Figure 4-4 Different positions for one complete tooth meshing cycle Analytical equations can also be developed for the rotation of the gear and pinion hubs.
Considering the single pair contact zone at point B. Conversely.4 Gear Contact Stress One of the predominant modes of gear tooth failure is pitting.3) B B where B P and B g are the tooth displacement vectors caused by bending and B B shearing for pairs B of the pinion and gear respectively. The details of the subsurface stress 46 . shearing displacement and contact deformation of the tooth pair B while the gear is stationary. for the gear rotation while the pinion is stationary. contact stress exceeding surface endurance strength with no endurance limits or a finite life causes this kind of failure. H P and H g are the contact B deformation vectors of tooth pair B of the pinion and gear respectively. Contact failure in gears is currently predicted by comparing the calculated Hertz stress to experimentallydetermined allowable values for the given material. while the gear rotates due to an applied torque. θ = B g (4. B θP = B B BP + H P B RP B B Bg + H g B Rg (4.contact deformation [64]. θ gB gives the transverse plane angular rotations of the gear body. In the pinion reference frame. the condition of angular rotation of the gear body will then be given by [64] For the pinion. Pitting is a surface fatigue failure due to many repetitions of high contact stress occurring on the gear tooth surface while a pair of teeth is transmitting power. The AGMA has prediction methods in common use. 4. In other words.2) and for the gear. it is assumed that the pinion hub remains stationary. θ P denotes the transverse plane angular rotation of the pinion body caused by bending deflection.
5 shows the first one. a plane strain analysis can be used. However. Figure 4.5. The nodes on the bottom surface of the gear were fixed.6 shows the enlarged-area with a fine mesh which is composed of rectangular shapes. This approach is used because the contact stress field is complex and its interaction with subsurface discontinuities are difficult to predict. without loss of generality. Since a spur gear can be considered as a two-dimensional component.field usually are ignored. Figure 4. all of this information can be obtained from the ANSYS model. A total load is applied on the model. which is the same method as one in chapter 3 to create the contact element COCNTA 48 and the rectangular shape fine mesh beneath the contact surfaces between the contact areas. The nodes in the model were used for the analysis. It was assumed to act on the two points shown in Figure 4. Figure 4-5 FEM Model of the gear tooth pair in contact 47 .2 and three points in Figure 4. There are two ways to get the contact stress from ANSYS.
Figure 4-6 Fine meshing of contact areas Figure 4-7 Contact stress along contact areas 48 .
7 shows the normal contact stress along the contact areas. Different methods should show the close results of maximum contact stress if the same dimension of model and the same external loads are applied on the model.8 presents how to mesh using a second method. Figure 4.5 The Lewis Formula There are several failure mechanisms for spur gears. Bending failure and pitting of the teeth are the two main failure modes in a transmission gearbox. The results are very similar to the results in the two cylinders in chapter 3. Pitting of the teeth 49 . If there is a small difference it is likely because of the different mesh patterns and restricted conditions in the finite element analysis and the assumed distribution form of the contact stresses in the contact zone. 4.Figure 4-8 A fine mesh near contact areas Figure 4.
uniform across the face. This bending stress equation was derived from the Lewis formula. Bending failure in gears is predicted by comparing the calculated bending stress to experimentally-determined allowable fatigue values for the given material.4) Ft l x t/2 A Figure 4-9 Length dimensions used in determining bending tooth stress 50 . When loads are too large. the area moment of inertia is M = Ft l and c = t 2 . bending failure will occur. length = l. For a rectangular section.9 are Cross-section = b * t . stress then is I= bh 3 12 σ= F l (t 2) 6 Ft l M = t 3 = 2 I c b t 12 bt (4. The bending stresses in a spur gear are another interesting problem. This was already discussed in the last section. Wilfred Lewis (1892) [5] was the first person to give the formula for bending stress in gear teeth using the bending of a cantilevered beam to simulate stresses acting on a gear tooth shown in Figure 4.is usually called a surface failure. load = Ft .
The following design equation. where Y j = Y / K c is introduced. The crack will likely start from the point A. and is also independent of tooth size and only a function of shape. the maximum stress is expected at point A.6) where p d = diametral pitch Y= 2 xp d = Lewis form factor 3 (4. From similar triangles tan α = t 2 l = x t 2 where l= t2 4x (4.7) into (4. The stress on the area connecting those two points is thought to be the worst case. Two points can be found at each side of the tooth root fillet. For a gear tooth. and Y is called the Lewis form factor.5) Substituting (4. The Lewis equation considers only static loading and does not take the dynamics of meshing teeth into account. The Lewis form factor is given for various numbers of teeth while assuming a pressure angle of 20 o and a full – depth involute.6): 6 Ft t2 4 x = 3Ft = 3Ft p d = Ft p d 2 2bx 2bp d x bY bt σ= (4. developed by Mott (1992) is used 51 . which is a tangential point where the parabola curve is tangent to the curve of the tooth root fillet called parabola tangential method.8) [5] in the next page is known as the Lewis equation.7) Equation (4. The concentrated stress on the tooth fillet is taken into account by K c and a geometry factor Y j . The Lewis form factor is dimensionless.Where b = the face width of the gear. The above stress formula must be modified to account for the stress concentration K c . Other modifications are recommended by the AGMA for practical design to account for the variety of conditions that can be encountered in service.
K m = load distribution factor.6 FEM Models 4. K v = dynamic factor. which is the worst case. If one tooth pair was considered to carry the whole load and it acts on the top of the tooth this is adequate for gear bending stress fatigue. In order to predict fatigue and yielding. Suppose that the greatest stress occurs when the force is exerted at top of tooth. Ft = normal tangential load. are required. and does not consider effects of the radial force. with present computer 52 . Each of these factors can be obtained from the books on machine design such as [5]. When the load is moving at the top of the tooth. 4. the maximum stresses on the tensile and compressive sides of the tooth.σt = Ft p d K a K s K m bY j K v (4.6. usually there are a least two tooth pairs in contact. which will cause a compressive stress over the cross section on the root of the tooth. two teeth pairs share the whole load if the ratio is larger than one and less than two. K s = size factor . In the past.8) where K a = application factor . the bending stress sensitivity of a gear tooth has been calculated using photo elasticity or relatively coarse FEM meshes. However. This analysis considers only the component of the tangential force acting on the tooth. respectively.1 The Two Dimensional Model Fatigue or yielding of a gear tooth due to excessive bending stresses are two important gear design considerations. When the load is at top of the tooth. the maximum stress at the root of tooth occurs when the contact point moves near the pitch circle because there is only one tooth pair in contact and this teeth pairs carries the entire torque. Y j = Geometry factor. In fact.
Figure 4-10 FEM gear tooth bending model with 3 teeth Figure 4-11 A two dimension tooth from a FEM model with 28 teeth 53 .developments we can make significant improvements for more accurate FEM simulations.
respectively. the equations used to generate the gear tooth profile curve were the same as the ones in section 4.12 shows how much Von Mises stress is on the root of tooth when the number of teeth is 28 for the gear.1 in section 4.7. Figure 4.10 shows that the maximum tensile stresses on the tensile side and maximum compressive stresses on other side of the tooth. It also indicates that only one tooth is enough for the bending stress analysis for the 3-D model or the 2-D model. Figure 4. When meshing the teeth in ANSYS. There are more detailed results for different number of teeth in table 4. if “SMART SIZE” is used the number of elements near the roots of the teeth are automatically much greater than in other places. which are compared with the results from the Lewis Formula. 54 .Figure 4-12 Von Mises stresses with 28 teeth on the root of tooth In the procedure for generating a FEM model for bending stress analyses.11 shows one tooth FEM model and Figure 4.2.
6. Because “SMART SET” was chosen on the tool bar there are many more elements near the root of the tooth than in other places.14 shows how to mesh the 3D model and how to apply the load on the model. For the bending stresses.4. the numerical results are compared with the values given by the draft proposal of the standards of the AGMA in the next section.2 The Three Dimensional Model In this section the tooth root stresses and the tooth deflection of one tooth of a spur gear is calculated using an ANSYS model. So a large number of degrees of freedom in this 3D model take a longer time to finish running. Figure 4-13 FEM bending model with meshing 55 . Figure 4. There are middle side nodes on the each side of each element. The element type “SOLID TETRAHEDRAL 10 NODES 187” was chosen.
14 shows large Von Mises stresses at the root of the tooth. if they are large enough. They are equal to the tensile stresses. The tensile stresses are the main cause of crack failure. the diametral pitch will be changed or the module of gear will be changed. That is why cracks usually start from the tensile side. Different Maximum Von Mises with different numbers of teeth are shown in the table 4. From the Lewis equation if the diameters of the pinion and gear are always kept the same and the number of teeth was changed. Figure 4.From the stress distributions on the model. the large concentrated stresses are at the root of the tooth. That means that there are different bending strengths between the different teeth numbers. Figure 4-14 Von Mises stresses with 28 teeth on the root of tooth 56 .1.
2. b = 1.2 *1.429MPa 1.2 *1.8 bY j K v Detailed investigations.022 * 5.7 Comparison with Results using AGMA Analyses In this section.842 * 1. The meshing spur gear has a pitch radii of 50 mm and a pressure angle of 20 ° .022 * 6.2 * 1.112 d 1.2 *1.15 = = 91.5 * 0.8 bY j K v 57 .8 bY j K v If the number of teeth is changed from 28 to 25 and the other parameters were kept the same. including the effects with the two different numbers of teeth on the tooth root stress were carried out.112 *1. The transmitted load is 2500 N. the number of gear teeth is 28. Eq.37 * 0. The gear face width.15 = = 84.5 * 0.37 * 0.2 *1.8) is recommended by the AGMA and the other coefficients.1mm). a comparison of the tooth root stresses obtained in the three dimensional model and in the two dimensional model using ANSYS with the results given by the standards of the AGMA is carried out. Here analysis of gears with different numbers of teeth are carried out. are set at 1.9685in 2500 N = 562.15 = = 102. First.9685 * 2 σt = Ft p d K a K s K m 562.5 in (38. If the number of teeth is changed from 28 to 23 and the other parameters were kept the same.35 * 1.5 * 0. 50mm = 1. σt = Ft p d K a K s K m 562. σt = Ft p d K a K s K m 562. (4.4.02 Pounds pd = 28 N = = 7.37 * 0.770MPa 1.022 * 7. such as the dynamic factor.783MPa 1.2 *1.
The results are shown in Table 4. These differences are believed to be caused by factors such as the mesh pattern and the restricted conditions on the finite element analysis. and the assumed position of the critical section in the standards.149MPa 1.5 * 0.022 * 8.8 bY j K v The above calculations of the Von Mises stresses on the root of tooth were carried out in order to know if they match the results from ANSYS. 2D models are suggested to be use because much more time will be saved when running the 2D models in ANSYS. From these results.1.15 = = 132.636 * 1 *1 * 1.15 = = 124. For the cases from 23 teeth to 37 teeth.398 * 1 *1 * 1. the maximum values of the tooth root stress obtained by the ANSYS method were given.37 * 0. There are not great differences between the 3D and 2D model in Table 4. the values range from 91% to 99% of the value obtained by the AGMA. it was found that for all cases give a close approximation of the value obtained by the methods of the AGMA in both 3D and 2D models. σt = Ft p d K a K s K m 562. the ANSYS results are about 97% (2D) of the values obtained by the AGMA.If the number of teeth is changed from 28 to 34 with the other parameters kept the same.5 * 0. Here the gears are taken as a plane strain problem. For the number of teeth of 28.1.805MPa 1.022 * 9. In this table. 58 .37 * 0. σt = Ft p d K a K s K m 562. with the other parameters kept the same.8 bY j K v If the number of teeth is changed to 37.
89% (7.15 Difference 3D (2D) 2.418 95. 59 .74%) 4.of teeth Stress 3D (2D) (ANSYS) 23 25 28 31 34 37 86. effective methods to estimate the tooth contact stress by the two-dimensional and the root bending stresses by the three-dimensional and twodimensional finite element method are proposed.802 109.06 143. To determine the accuracy of the present method for the bending stresses.43%) 4.80 132.8 Conclusion In the present study.39% (0.34 132.39% (2.90 (85.35% (0.129) (106.26% (3.46) (141.86) (116.21 123.1 presented are much smaller than previous work done by other researchers for the each case.1 Von Mises Stress of 3-D and 2-D FEM bending model Num. The results with the different numbers of teeth were used in the comparison.050) (91.770 102. So those FEA models are good enough for stress analysis.97) Stresses (AGMA) 84.79 124.97%) 8.82% (2. both three dimensional and two dimensional models were built in this chapter. The errors in the Table 4.69%) 5.69%) 6.93%) 8.Table 4.86) (128.429 91.78 113.
Two different models of a generic gear pair have been built to analyze the effects of gear body deformation and the interactions between adjacent loaded teeth. 60 . an FEA numerical modeling system has been developed. This chapter deals with estimation of static transmission error including the contact problem and the mesh stiffness variations of spur gears. Results are from each of the two models’ average values.Chapter 5 Torsional Mesh stiffness and Static Transmission Error 5. This is based on a two dimensional finite element analysis of tooth deflections. Two models were adopted to obtain a more accurate static transmission error.1 Introduction and Definition of Transmission Error Getting and predicting the static transmission error (TE) is a necessary condition for reduction of the noise radiated from the gearbox. For this purpose. for a set of successive positions of the driving gear and driven gear. The static transmission error is defined by Smith [59]. Researchers usually assume that transmission error and the variation in gear mesh stiffnesses are responsible for the noise radiated by the gearbox. The main source of apparent excitation in gearboxes is created by the meshing process. For spur gears a two dimensional model can be used instead of a three dimensional model to reduce the total number of the elements and the total number of the nodes in order to save computer memory. In the previous literature to obtain TE the contact problem was seldom included because the nonlinear problem made the model too complicated. It is generally accepted that the noise generated by a pair of gears is mainly related to the gear transmission error.
Its characteristics depend on the instantaneous positions of the meshing tooth pairs. spacing errors. The first two types of transmission errors are commonly referred to in the literature [7][17]. One of the most important criteria for each model was that the potential contact nodes of both surfaces would be created on the 61 . The static transmission error of gears in mesh at particular positions throughout the mesh cycle was generated in this study by rotating both solid gears one degree each time then creating a finite element model in that particular position. the transmission error is mainly caused by: • Tooth geometry errors: including profile. • Elastic deformation: local contact deformation from each meshing tooth pair and the deflections of teeth because of bending and shearing due to the transmitted load. In service. and gear tooth runout. a large number of finite element models at the different meshing positions were undertaken for this investigation. When the gears are unloaded. • Imperfect mounting: geometric errors in alignment.The term transmission error is used to describe the difference between the theoretical and actual relative angular rotations between a pinion and a gear. In chapter 5 the second case is considered. spacing and runout errors from the manufacturing process. which may be introduced by static and dynamic elastic deflections in the supporting bearings and shafts. The first case has manufacturing errors such as profile inaccuracies. The second case is loaded transmission error. In order to develop representative results. which is similar in principle to the manufactured transmission error but takes into account tooth bending deflection. a pinion and gear have zero transmission error if there is no manufacturing error. Under load at low speeds (static transmission error) these situations result from tooth deflections and manufacturing errors. and shearing displacement and contact deformation due to load.
At each particular meshing position. the gear was restrained with degrees of freedom in radius and rotating θ p with the pinion having the torque input load and the resulting angular rotation of the pinion was computed. After compensating for torque and angular rotation for the particular gear ratio.nodes near the intersection point between the pressure line and the involute curve for that particular tooth. In relation to the gear reference frame: the local cylindrical system number 11. 5. By constraining the all nodes on the pinion in radius and rotating θ g with the gear having a torque input load the model was built.1) Where Z is the gear ratio and θ p . and so the mean of these two angular rotations would give the best estimate of the true static transmission error of the involute profile gears under load. In this case. after running ANSYS the results for angular rotation of the gear due to tooth bending. In the pinion reference frame: the local cylindrical system number 12 was created by definition in ANSYS. θ p = 0 and θ g is in the opposite direction to that resulting from forward motion of θ p changing the TE result to positive as seen by equation (5. In this second case θ g = 0 and the TE will be positive for forward motion of θ g . g is the angular rotation of the input and output gears in radians respectively. The additional problem of determining the penalty parameter at each contact position could be user-defined or a default value in the finite element model.1) TE = θ g − ( Z )θ p (5.2 The Combined Torsional Mesh Stiffness Because the number of the teeth in mesh varies with time. the results from these two models should be the same. shearing and contact displacement were calculated. the combined torsional mesh stiffness varies periodically. When a gear with perfect involute profiles is loaded 62 .
It decreases and increases dramatically as the meshing of the teeth change from the double pair to single pair of teeth in contact. The gear transmission error is related directly to the deviation of the angular rotation of the two gear bodies and the relative angular rotation of the two gears is inversely proportional to the combined torsional mesh stiffness. the single tooth torsional mesh stiffness of a single tooth pair in contact is defined as the ratio between the torsional mesh load (T) and the elastic angular rotation (θ ) of the gear body. the single tooth torsional mesh stiffness of the 63 . Considering the combined torsional mesh stiffness for a single tooth pair contact zone. which can be seen from the results of ANSYS later in this document. The combined torsional mesh stiffness is defined as the ratio between the torsional load and the angular rotation of the gear body. as the pinion rotates. which are transmitted to the housing through shafts and bearings. The development of a torsional mesh stiffness model of gears in mesh can be used to determine the transmission error throughout the mesh cycle. In the single tooth pair contact zone. In other words under operating conditions. Sirichai [60] has developed a finite element analysis and given a definition for torsional mesh stiffness of gear teeth in mesh. The excitation located at the mesh point generates dynamic mesh forces. the mesh stiffness variations are due to variations in the length of contact line and tooth deflections. The combined torsional mesh stiffness is different throughout the period of meshing position. Noise radiated by the gearbox is closely related to the vibratory level of the housing.the combined torsional mesh stiffness of the gear causes variations in angular rotation of the gear body. The combined torsional mesh stiffness of gears is time dependent during involute action due to the change in the number of contact tooth pairs.
K g . B KP = TPB B θP (5. the single tooth torsional stiffness of both gears is equal because both of them were assumed to be identical spur gears with ratio 1:1 in order to make the analysis simple. The torsional mesh stiffness can then be given by Frb Frb2 Km = = = θ c / rb c T (5.pinion. The single tooth torsional mesh stiffness of the pinion and the gear are given by [64]. By considering the total normal contact force F. K P is decreasing while the single tooth torsional stiffness of the gear. the torque T will be given by the force multiplied by the perpendicular distance (base circle radius rb ) T = Frb if there is one pair gear on contact. acting along the line of action. The torsional mesh stiffness can be seen to be the ratio between the torque and the angular deflection. The elastic angle of rotation θ of the gear body can then be calculated from related to the arc length c. When the pinion rotates to the pitch point P .2) B Kg = TgB θ gB (5.4) 64 .3) B B where K P and K g are the single tooth torsional mesh stiffness of the single tooth pairs at B of the pinion and gear respectively. by the base circle radius as θ = c / rb . The torsional mesh stiffness can be related to the contact stiffness by considering the normal contact force operating along the line of action tangential to the base circles of the gears in mesh. is increasing.
the Von Mises stresses. can be seen to be the ratio of the normal contact force F to the displacement along the line of action. then creating a finite element model in that particular position. The moment was applied on the center of the pinion. For example. The gears were modeled using quadratic two dimensional elements and the contact effect was modeled using 2D surface-to-surface (line-to-line) general contact elements that can include elastic Coulomb frictional effects.5) The contact between the gears is a nonlinear problem. while restraining all nodes on the internal circle of the output gear hub. K mb = Km rb2 (5. After running ANSYS for the each particular position of the FEA model there were volumous results from the postprocessor. The torsional mesh stiffness of gears in mesh at particular positions throughout the mesh cycle was generated by rotating both solid gears one degree each time. The center node of pinion was constrained in the X and Y directions and it was kept the degree of freedom for rotation around the center of the pinion.The tooth contact stiffness K mb .1 was used to help to solve this nonlinear problem.1 shows how to apply load and how to define the input torque by a set of beam elements (beam3) connected from the nodes on the internal cycle of rim to the center point of the pinion. where the length a is equal to the arc c length for a small angles θ . when the transmission error was obtained from the results of the FEA model. Figure 5. which gives K mb = F / a . 65 . The relationship between the linear contact stiffness and torsional mesh stiffness then becomes. This cannot be put in the form of a linear differential equation if the problem is solved by the equations so here ANSYS was used to study this problem. The torsional mesh stiffness K m in mesh was automatically considered. In this chapter the program ANSYS 7.
In Figure 5. Figure 5-1 The beam elements were used in the FEA model 66 .contact stresses and deformations in the X and Y directions can easily be gotten.2 θ represents TE at one position.2. The results here are based on FEA modeling and also on the tooth stiffness change. These results indicated that variation in the mesh stiffness is clearly evident as the gears rotate throughout the meshing cycle. The static transmission error and the torsional mesh stiffness were then automatically obtained from ANSYS in the postprocessor. Twenty-six positions were chosen and for each position ANSYS would produced numerous results. The vectors of displacement in the global system at one particular meshing position were shown in Figure 5.
the main source of vibration excitation is from the periodic changes in tooth stiffness due to non-uniform load distributions from the double to single contact zone and then from the single to double contact zone in each meshing cycle of the mating teeth. For the spur involute teeth gears.3 Transmission Error Model 5.θ Figure 5-2 Vectors of displacement 5.3. The torsional stiffness of two spur gears in mesh varied within the 67 . in mesh.1 Analysis of the Load Sharing Ratio Under normal operating conditions. This indicates that the variation in mesh stiffness can produce considerable vibration and dynamic loading of gears with teeth. the load was transmitted between just one to two pairs of teeth gears alternately.
In addition. If the gears were absolutely rigid the tooth load in the zone of the double tooth contacts should be half load of the single tooth contact. the tips of the teeth are often modified so as the tooth passes 68 .meshing cycle as the number of teeth in mesh changed from two to one pair of teeth in contact. even small errors may have a large influence. The elastic deformation of a tooth can result in shock loading. Usually the torsional stiffness increased as the meshing of the teeth changed Figure 5-3 Vectors of displacement near the contact surfaces from one pair to two pairs in contact. and contact stresses. which may cause gear failure. They alter the distribution of load. in reality the teeth become deformed because of the influence of the teeth bending. shear. In order to prevent shock loading as the gear teeth move into and out of mesh. However. every gear contains surface finishing and pitching errors. These factors change the load distribution along the path of contact. Because the teeth are comparatively stiff.
1.3.1 Gear Parameters Used in the Model Gear Type Modulus of Elasticity.2 2D FEA Transmission Error Model Usually calculation of the static transmission error requires estimation of the loaded teeth deflections. the hypotheses related to these models can not be justified because characteristic dimensions of gear teeth are neither representative of a beam nor a plate for the calculation of the static transmission error and tooth deflection behavior changes because of non-linear contact. Tavakoli [61] proposed to model gear teeth using a non uniform cantilever beam. while numerous authors have developed finite element tooth modeling excluding the contact problem. Most of the previously 69 . Dedendum Standard Involute.25*M 5.00*M. E Module (M) Number of Teeth Pressure Angle Addendum. Full-Depth Teeth 200GPa 3.75 mm 27 20 1.through the mesh zone the load increases more smoothly.1 shows the gear parameters. Table 5. Unfortunately. Table 5. Tobe [62] used a cantilever plate. In order to evaluate these required quantities. Two identical spur gears in mesh are considered here. The static transmission error model of gears in mesh can be used to determine the load sharing ratio throughout the mesh cycle.
The one or two sets of contact elements were enlarged for the single or the double pairs of gears in contact. If the constraints established on the model are not proper.000.3 Overcoming the convergence difficulties In this study the contact stress was always emphasized.5.5 displays a meshing model of a spur gear. Here 2D plane42 elements were used with 2 degrees of freedom per node. 5. sudden changes in stiffness often cause severe convergence difficulties. This procedure was successively applied to the pinion and the gear. In addition. In a static analysis unconstrained free bodies are mathematically unstable and the solution “blows up”. Those kinds of large. 70 .3. Figure 5. This operation allows extracting the compliance due to bending and shear deformation. Both the normal and tangential stiffness at the contact surfaces change significantly with changing contact status. The contact problem is usually a challenging problem because contact is a strong nonlinearity. Fine meshing was used shown in Figure 5. For the contact surface the contact element was Conta172 and for the target surface the target element was Targe169 shown in Figure 5. The whole model has 5163 nodes.4 that matches the position in Figure 5.published FEA models for gears have involved only a partial tooth model. 4751 elements. it will result zero overall stiffness. In this section to investigate the gear transmission error including contact elements. not just the local stiffness. the whole bodies of gears have to be modeled because the penalty of parameter of the contact elements must account for the flexibility of the whole bodies of gears.000. the solution will not be in convergence if the total number of degrees of freedom exceeds 1.6. including the contact deformation.
Figure 5-4 Contact elements between the two contact surfaces Figure 5-5 Meshing model for spur gears 71 .
” Several methods were used in order to overcome such difficulties. The output window always displayed: “The system process was out of virtual memory”. the author learned that it is necessary to make sure there is the enough computer memory for the 3D model so here the 2D model was chosen. First. If the constraints are inadequate. From this simple model. For example.Figure 5-6 The fine mesh near the two contact surfaces The 3D model first exhibited difficult convergence behavior. Or “the value at the certain node is greater than current limit of 10 6 . It is also very important to allow the certain constraint conditions for the model to be modeled. the contact stress between the two square boxes or two circles was obtained using ANSYS. at the beginning a simple model was built. the displacement values at the nodes may 72 .
0. different ICONT values were chosen. • Initial contact closure (ICONT) – Moves the nodes on the contact surface within the adjustment band to the target surface. For example. This allowed a large amount of computer memory to be saved. 0. • Initial allowable penetration range (PMIN & PMAX) – Physically moves the rigid surface into the contact surface. for the second one. If the elements with middle side nodes were chosen. The total number of the nodes and total number of the elements were thus reduced. from ANSYS there are three advanced contact features that allow you to adjust the initial contact conditions to prevent the rigid body from moving away: • Automatic contact adjustment (CNOF) – The program calculates how large the gap is to close the gap. numerous times. For instance. 73 . This generally indicates rigid body motion as a result of an unconstrained model so one must verify that the model is properly constrained. Especially. In the author’s opinion there are the four important keys to get correct solutions for this FEA model: Firstly. which make it hard to get convergence. try to choose the different type of contact element options or choose different element types underlying the contact surfaces. ICONT = 0.exceed 10 6 . All three of these methods have been used by trial and error. Secondly. plane42 was chosen instead of the element with middle side nodes on element edges. there are several choices to deal with the gaps between contact surfaces.02. It worked very well.012 … However the first one seemed better than other ones.015. one must remove the middle side nodes along every element edge before the contact element was built.
• Delete the all the nodes which are not attached the elements. In order to control nonlinear SOLUTION “Large Displacement Static” was chosen from listing. Too tight a value for penetration tolerance. However it took a long time to get convergence. 74 .The first one was chosen for this model. The penetration tolerance is equal to 0. it seemed that the accuracy was improved a little but it would take a very long time to solve or to run it. if convergence difficulties are encountered. The larger the number of substeps the more time was consumed. So at the beginning in this model the maximum number of substeps is equal to 100. Compress the nodes and the elements to reduce the total number of nodes & elements. The normal penalty stiffness is chosen for default. If the maximum number of substeps was equal to 100. Finally.1 (DEFAULT Value). In ANSYS. Too large a value for the minimum time step size or too small maximum number of substeps. One should try to decrease the number of substeps as long as it can obtain convergence and a certain accuracy. before going to the solution do not forget the three important things that should be done: • • Merge the node if necessary otherwise it is difficult to get convergence. they may generally arise from: • • • Too great a value for contact stiffness. from Contact Pair in Create from Modeling: Settings > Initial Adjustment > Automatic Contact adjustment: Choose “Close Gap” from listing. and to save more memory in the computer. This is the reason why the author eventually used 10 as the number of substeps. Thirdly.
So the distribution of contact stresses is resonable. For the gears the contact stress was compared with the results from the Hertz equations. there are 4751 elements and 5163 nodes. For the contact surfaces there are more than eight nodes on each contact side.3. and the two results agree with each other well. It is much simpler to use “WIZARD BAR” and to create contact pair between the contact surfaces from “Preprocessor>Modeling>Create>Contact Pair”. 75 . Figure 5-7 Von Mises stresses in spur gears In this model.7 and Figure 5.4 The Results from ANSYS Here Von Mises stresses and the contact stresses just for one position are shown below in Figure 5.8.5. In this chapter the transmission error is emphasized and contact is a nonlinear problem so the solution will likely be done after a greater time compared with the time in linear analysis.
These contact lines were discretized.4 The Transmission Error The static transmission error is expressed as a linear displacement at the pitch point [63]. which was used to predict static transmission error of a pair of spur gears in mesh including the contact deformation. This section considers a FEA model. the iterative procedures were used to solve the static equilibrium of the gear pair and to calculate the load distribution on the contact lines and the static transmission error. For each position of the driving gear. The total length of lines of contact grows with the applied load.S3 Figure 5-8 The distribution of contact stresses between two teeth 5. The 76 . However the contact deformation was excluded in those models. A kinematic analysis of the gear mesh allows determining the location of contact line for each loaded tooth pair.
01 0 0 5 10 15 20 25 30 Rotation angle of gears (degree) TE Figure 5-9 Static transmission error from ANSYS 77 . 0. When one pair of teeth is meshing one set of contact elements was established between the two contact surfaces. the individual torsional mesh stiffness of each gear changes throughout the mesh cycle.03 0. causing variations in angular rotation of the gear body and subsequent transmission error.06 Angle of Transmision error(degree) 0. when gears with involute profiles are loaded. coupled with contact elements near the points of contact between the meshing teeth. The theoretical changes in the torsional mesh stiffness throughout the mesh cycle match the developed static transmission error using finite element analysis shown in Figure 5.model involves the use of 2-D elements. a pinion and gear with perfect involute profiles should theoretically run with zero transmission error. However. When gears are unloaded.9. while when two pairs of teeth are meshing two sets of contact elements were established between the two contact bodies.05 0.04 0.02 0.
Numerous simulations allowed validating this method and showed that a correct prediction of transmission error needed an accurate modeling of the whole toothed bodies. The developed numerical method allows one to optimize the static transmission error characteristics by introducing the suitable tooth modifications. 78 . These offer interesting possibilities as first steps of the development of a transmission system and can be also successfully used to improve to control the noise and vibration generated in the transmission system. Numerical methods using 2-D FEM modeling of toothed bodies including contact elements have been developed to analyze the main static transmission error for spur gear pairs. This excitation exists even when the gears are perfectly machined and assembled.5 Conclusion Mesh stiffness variation as the number of teeth in contact changes is a primary cause of excitation of gear vibration and noise. The elasticity of those bodies modifies the contact between loaded tooth pairs and the transmission error variations.5.
spiral bevel and other gear tooth form. • • Three-dimensionally meshed simulations for both spur and helical gears. 6. Effective methods to estimate the tooth contact stress using a 2D contact stress model and to estimate the root bending stresses using 2D and 3D FEA model are proposed. Further numerical method investigations should be conducted on: • The transmission error for all types of gears for example: helical. In Chapter 5 the development of a new numerical method for FEA modelling of the whole gear body which can rotate in mesh including the contact problem is presented. The static transmission error was also obtained after running the models in ANSYS. 79 .Chapter 6 Conclusions and Future Work 6. The analysis of gear contact stress and the investigation of 2D and 3D solid bending stresses are detailed in Chapter 4.2 Future Work The following areas are worthy of further research as computer capabilities increase. • A whole gearbox with all elements in the system such as the bearing and the gear casing. Simulation of an oil film in contact zone.
New Jersey: Prentice-Hall Inc. 1988. I. 2001. S.. “ Fundamentals of Machine Elements”. JSME International Journal Series III Vol. J.31. Prowell. University of Saskatchewan.. Journal of Applied Mechanics [4] Norton. of Mechanical Engineering..Sc. T. R. 1988.. R.B. 1982. “Stresses Due to Tangential and Normal Loads on an Elastic Solid with Applications to Some Contact Stress Problems”. J. 2003. S. J. K. 1949. [5] Hamrock. “Rocket motor gear tooth analysis”. R. L. Trans. E. E. [7] Wang.. K.. 1960. Jacobson. “Finite Element Analyses of A Spur Gear Set”. H. and Automation in Design 80 . [6] Buckingham. 2. B.. 1999. JSME International Journal. O. Vol.REFERENCES [1] Klenz. pp 357-362 [3] Smith. Design 104 759-766 [10] Gatcombe. tooth contact analysis. Dept.. McGraw-Hill. C. 44. “Analytical Mechanics of Gears”. S.. Mech.K. Engng Industry [11] Tsay. Mechanisms. H. 1. ASMA. J. C.. “A method of selecting grid size to account for Hertz deformation in finite element analysis of spur gears”. R.. “Multiobjective optimal Design of Cylindrical Gear Pairs for the Reduction of Gear Size and Meshing Vibration”.. New York. M. and stress analysis”. No. Liu. “Machine Design: An Integrated Approach”. “Survey of Nonlinear Vibration of Gear Transmission Systems” Appl Mech Rev vol 56. J. Bar.. Chao. [8] Chong. J. [2] Umezawa. No 3. computer simulation. (Hertzian contact stresses and times) Trans. No. Trans. Transmissions. J. “Helical gears with involute shaped teeth: Geometry. C.. “Recent Trends in Gearing Technology”.W. ASME.. J. Thesis. pp 291-292 [9] Coy.
.. 1978. of Scientific and Industrial Research. Proc. D. W. Westervelt. W.[12] Errichello... L. S. Mech. 1988. Instn Meth. 368-372. Handschuh F. “State-of-art review: gear dynamics”. 17581787. D. R. “Analysis of the vibratory excitation of gear system. Proc.. Instn Mech. Vol.J. approximations. 1980. 121. 1985. R. J.104 749-777 [20] David. Journal of Mechanical Engineering Science.. 3 [23] O’Donnell. W. 101(3). “The derivation of gear transmission error from pitch error records”. W. Engrs. Trans. [13] Ozguven.. III. II: tooth error representations. Jan. [16] Mark. W. 1958. “Optimal Tooth Number for Compact Standard Spur Gear Sets”. Sound Vibr. M. “The Deformations of Loaded Gears and the Effect on Their LoadCarrying Capacity”. ASME... 1979. 252-259. 1991. Am. 87-112. 63. “Consideration of Moving Tooth Load in Gear Crack Propagation Predictions”. L. D. 172. ASME. H. “Analysis of the vibratory excitation of gear system: Basic theory”. 1409-1430. 62-WA-16 81 . 1979. Ser. 1974. J. et al.. Report No.... “Stress and Deflection of Built-in Beams”. Houser. 2001. Am. 1949.. J. 199(C3). C.123 118-124 [21] Cornell. [17] Kohler.. Transations of the ASME vol. R. Scouts. British Dept. Soc.. J.. by Journal of Mechanical Design. W. 66. [14] Harris. Acoust. Regan. Journal of Mechanical Design. 195-201. Sponsored Research (Germany).. “Estimation of transmission error of cylindrical involute gears by tooth contact pattern”. “Dynamic load on the teeth of spur gears”.. R. N. J. vol.. “Mathematical models used in gear dynamics”. J. [18] Kubo. “Dynamic Tooth Loads and Stressing for High Contact Ratio Spur Gears”. 34(2). Engrs. A.383-411.. Part C. Soc. and application”. 1978. G... JSME int. Des. 100 [22] Weber. R. [15] Mark. ASME Paper No. Coy. H. [19] Savage.
Vol. On Automotive Eng. Machines and Tooling. 1974. Ltd.. G. pp. S. D.9 pp.[24] Heywood. No.E. S.. Sankar.. 831-853.Google. Ishikawa. “On the Design of a Low-Vibration of Helical Gear for Automobiles”. [33] Anon. Vol. “Computer-Aided Design of Spur or Helical Gear Train”.W. R. Nov. Jia. P. [35] From “www. JSME.100. “Modeling of spur gear mesh stiffness and static transmission error” . 1987. K. p. 1994. “Gear transmission error measurement and analysis”. Ishikawa. R. “How to Design to Minimize Wear in Gears” . ASME paper 80-C2/DET-101. Australia [26] Randall. Vol. pp. 1978. Dukkipati. 1966. 02 [34] Howard. Machine Design.. Chapman and Hall.26. Mechanical System and Signal Processing 15(5). 27. No..8 No.42. C. Suzuki.. “Designing by Photoelasticity”. “Design Procedure for Aircraft Engine and Power Take-Off Spur and Helical Gears”.. 2. 1980 “The Gear Design Process”. 4th Int. Pacific Conf. S. M. 2. 1970. “Optimization of Tooth Proportion for a Gear Mesh”. K.A.. V.102 [28] Umezawa. 303-310 [37] Kamenatskaya. 1975.11-15 82 . J.287-297 [27] Umezawa.com”. “Computer-Aided Design of Optimal Speed Gearbox Transmission Layouts”. 871222 [29] Cockerham. 1967. Proc Instn Mech Engrs Vol 212 Part C pp. J.. University of New South Wales.. AGMA Standard No. I.. Computer-Aided Design. M. PhD dissertation. T... [25] Sweeney. Bull. I. Vol.uk [36] Osman. Sato.. 411. “Design Synthesis of a Multi-Speed Machine Tool Gear Transmission Using Multiparameter Optimization”. Paper No.. “The Dynamic Modeling of Spur Gear in Mesh Including Friction and A Crack”. B. Kelly. M. 2001... J. ASME Paper 80-c2/DET-13 [31] Estrin. Vol. ASME Journal of Mechanical Design. P. 46. pp. D. Proc.. T. 84-88.. [30] Tucker..92-97. ncel@tribology.. “Neale Consulting Engineers”. No. 1980.223.. “Simulation on Rotational Vibration of spur Gear”.co. [32] Gay. 1952.
W. Zaresky. “The Practical Significance of Designing to Gear Pitting Fatigue Life Criteria”.. Townsend. “Model for Gear Scoring” . A.267-276. Lund. Evans. AGMA Standard 210. AGMA Standard 220. pp 507-514.L. J.02.02. [45] Bowen. AGMA Information Sheet 217.P. W. M. Edited by M.. 1977. A. Transactions of Machine Elements Division. JSME International Journal Series III Vol. W. “Surface Durability (Pitting) of Spur Teeth”. P.. 1966. 2.pp. “Vibration Transmission through Rolling Element Bearings.32. 1979. J. Godet. ASMA Journal of Lubrication Technology. pp 31-54. T. 1973.100. V. No. “Rating the Strength of Spur Teeth”.01. 1989. Journal of Mechanical Design.98. [46] Anon. C. Springer-Verlag.153(1). No.ASME Paper 77-DET-60.E. J. Masud. Lund Technical University. 1978. H. [40] Anon... 1992. Journal of Sound and Vibration. 114 (September).. S... [41] Kahraman.150. “An Extended Model for Determining Dynamic Loads in Spur Gearing” [49] Stadler. E. “An Effective Method for Three-Dimensional Finite Element Analysis of a Gear Pair under Partial Contact”. 2. pp 246-252 [43] Anon.. Vol. “Dynamic Capacity and Surface Fatigue Life for Spur and Helical Gears”.. [44] Coy.. Kamat. S.. 1981. Pre. A. 1991. “Multiple Objective Decision MakingMethods and Applications. “On the design of internal Involute Spur Gears”.46-53. “ Multicriteria Optimization in Engineering: A Tutorial and Survey”. M. pp. [42] Ishikawa.J... “Dynamic Analysis of Geared Rotors by Finite Elements”. 1 pp.209-244 [50] Hwang. Sweden. 1992. Progress in Aeronautics.. [47] Rozeanu. 1965. C. C. ASMA Journal of Mechanical Design. 1976. [48] Kasuba R.. No. Vol. Dauer. [39] Andersson.Berlin” 83 . D. 1965. Structural Optimization: Status and Promise. Part III : Geared Rotor System Studies”. “Gear Scoring Design Guide for Aerospace Spur and Helical Power Gear”..[38] Lim. L.
1993. Anal Boundary Elem. 1997.. M. D. 3. [61] Tavakoli M. Ballarini. Vol. Arizona. “Bending of Stub Cantilever Plate and some Application to Strength of Gear Teeth”. N... [53] Nicoletto. “Static Contact Stress Analysis of A Spur Gear Tooth Using the Finite Element Method Including Friction Effects”. Inoue K.. J. G... 2. pp.. 1997. pp. Journal of Mechanical Design. 1994.pp.. No. Sabot. [62] Tobe T. “Experimental Analysis of Propagation of Fatigue Crack on Gears”. Australia. July.. 1986. pp 86-95. pp 869-876. E. pp 249-258. Scottdale. 51 No. 6th International Power Transmission and Gearing Conference. “Dynamics of Truck Gearbox”. Fifth International Congress on Sound and Vibration. “Gears and Their Vibration”. 84 . USA. V. Mech. Guagliano. Struct.. No.. “Approximate Stress Intensity Factors for Cracked Gear Teeth”. 8..G. R. L. V. 1983. 231-242 [54] Sfakiotakis.2.. R.. V.. 6 pp767-770 [59] Smith. No. AIAA J.E. K. Vergani.. “Fatigue Crack Growth Predictions in Specimens Similar to Spur Gear Teeth”. Renaud.. 1978. [56] Lewicki. “Finite Element Analysis of gears in Mesh”. 44. Eng. 108. D. Exp. Journal of Mechanisms. Houser D.pp881-889 [52] Tappeta. [58] Vijayarangan S. Transmission and Automation in Design. M. Eng. S... 169-175 [55] Blarasin. Anifantis. Vol. Kato. “Optimum Profile Modifications for the minimization of Static Transmission Errors of Spur Gears”. Vol. [57] Perret-Liaudet.. D. Eng. New York [60] Sirichai. 123 pp. Mater. “Interative MultiObjective Optimization Procedure”. 1997. G. 2001..37.7. Mech. 20.. R. Fatigue Fract.. 38. 100. 1171-1182. pp 374381. pp. J. A. No. Fract. Katsareas. 20.205-215.. 226-230. J. Marcel Dekker. Journal of Mechanical Design. et al 1997. “Boundary Element Analysis of Gear Teeth Fracture”. 1994. “Interactive Multiobjective Optimization Design Strategy for Decision Based Design”.. No.[51] Tappeta. J. Ganesan N. 1999. Computer & Struture Vol.
Transaction of the Japanese Society of Mechanical Engineering. “Torsional Properties of Spur Gear in Mesh using nonlinear Finite Element Analysis”. Hamrock. Ph. [65] B. E. Curtin University of Technology. Proc.D.D. “Fundamentals of Machine Elements” [66] Kasuba. 2113-2119 [68] Tordian.. V. “dynamic Measurement of the Transmission Error in Gear”. “Fundamental Research on Gear Noise and Vibration I”. 1967. Ph. “Modelling and Analysis of Static Transmission Error – Effect of Wheel Body Deformation and Interactions Between Adjacent Loaded Teeth” [64] Sirichai S. pp. “An Analytical and experimental Study of dynamic Loads on Spur Gear Teeth”. 1969. University of Illinolis [67] Aida. B.. R.[63] Rigaud. T.. Jacobson... 279-287 85 . 35. R.J. pp. Thesis. 1999. G. Schmid 1999. S. JSME Semi-International Symposium September .
5 *SET.acos(-1) *SET.Appendix A Input File of A Model of Two Cylinders !*********************************************** ! Parameter Definitions !*********************************************** !Cyclinder Geometry and Materials *SET.30e6 *SET.0.1 *SET.1 *SET.20 *SET.st2.v2.v1.1 *SET.0.5 *SET.1 *SET.st1.ns4i.91.1 *SET.st4.F.0.1 *SET.kn.L.mu.1e-6 !Load Step Options *SET.10e8 *SET.3 *SET.st3.ptype.ns3i.R1.1 *SET.R2.tol.3 *SET.coloumb.30e6 *SET.ns2i.-1e-6 *SET.4 86 .pnot.disp.E1.545 *SET.E2.0.3 *SET.PI.3 *SET.2 !Loading Controls *SET.
13*(F*delta/(1*(1/R1+1/R2)))**0.4 !Meshing Controls *SET.1.25 !Non-Contact Element Properties *SET.nec.5 !*SET.0 *SET.hi.1.(1-v1**2)/E1+(1-v2**2)/E2 *SET.gamma2.555 !Calculated Values *SET.1 /pnum.2*b/nec *SET.11.elemtype.08*sqrt(F*R1/E1) *SET.itop.delta.b.1.0*2 !Model Size *SET.0 *SET.1 *SET.delta.0.ratio1.rot.b.dx.10 *SET.gamma1.po.R1+R2+1e-9.delta csys.5 *SET.30e9 *SET.wi.atan(b/R2) /title.ratio2.atop.564*(F*(1/R1+1/R2)/(L*delta))**0.0.rotate2.atan(b/R1) *SET.line.50 *SET.0.rotate1.355 *SET.gamma1/nec*180/pi*rot local. Two cylinders' contact 2002 with friction !**************************************************** ! /prep7 *SET.5 *SET.1..*SET.1 87 Geometry Generation !**************************************************** .etop.
R2 l.R2.4.1.R2.21.180 k.1.24 l.21.6.R2-hi*2*b.8.90 k.90-gamma2*wi*180/pi k.15.3 l.6.R1+R2+1e-9.180 k.7 larc.90 k.1.25.5.0 k.90-100*gamma2*wi*160/pi k.15 l.19 l.3.kp.R2.6 l.4.90-gamma2*wi*180/pi k.16 l.R2-hi*100*b.0 k.90-100*gamma2*wi*180/pi larc.R2 larc.1.1 k.22.19.R2.24.3.15.23.24.21.R2-hi*180*b.R2 larc.19.90+gamma2*wi*180/pi k.5.1.5 l.7.90+100*gamma2*wi*180/pi k.90+100*gamma2*wi*160/pi k.R2.2.R2 l.1.7.25.R2 larc.4.90+gamma2*wi*180/pi k.8.R2.R2/2.1 k.16 88 .R2-hi*100*b.7./pnum.1 l.16.6.25.R2-hi*2*b.90 k.8.R2-hi*2*b.R2/2.4.16.
2.27.18.-90 k.13.22 l.2.R1 k.-90 k.23 l.10.17.R1 larc.21.11 l.14.R1.R1/2.9.-90+gamma1*wi*180/pi k.30.20.R1 larc.14.24 l.15 l.12 l.R1-hi*2*b.-90+gamma1*wi*180/pi k.R1-hi*180*b.26.12.R1.-90+100*gamma1*wi*160/pi k.2.13.13 larc.13.R1 89 .28.R1-hi*2*b.22 l.20.23 l.-90-100*gamma1*wi*160/pi k.l.22.11.19.-90-gamma1*wi*180/pi k.-90+100*gamma1*wi*180/pi larc.-90-100*gamma1*wi*180/pi k.9.5.R1 larc.12.2.R1.R1 l.R1/2 k.10.R1-hi*100*b.23.11.30.10.22.25 csys.-180 k.30.10.2.26.23.R1.R1-hi*100*b.1 l.-90-gamma1*wi*180/pi k.26.24.-180 k.R1.20 l.R1-hi*2*b.29.11 k.
2 l.26.19.28.3.40.20.27.11.20 al.27 l.17.33 90 .17.27.6.11.22 al.14.45.37.46.9.28.4 al.43.7 al.41.12.34 al.18 l.14.18.45 al.22.6.26.37.28.19.35 al.16.17.1.30.25.42.21 al.4.23 al.5 al.24.3 al.39.28.43 al.14 l.10.18.21.27.27.28 l.32.29.40.12.29.17 l.8 al.5.18.44 al.38.29 l.29 l.13.30 al.23.30 al.9.44.20.42.46 al.2 l.15.39.27 l.18 l.36 al.15.29.28 l.2.41.29.2.17 l.16.l.31.38.
!******************************************************* ! Meshing !******************************************************* !Define element type *if,elemtype,eq,1,then et,1,plane42,,,ptype *else et,1,plane82,,,ptype *endif mp,ex,1,30e6 mp,nuxy,1,0.3 eshape,3 real,1 mat,1 type,1 lesize,3,dx lesize,4,dx lesize,5,dx lesize,6,dx lesize,7,dx lesize,26,dx lesize,27,dx lesize,28,dx lesize,29,dx lesize,30,dx asel,all amesh,all *if,elemtype,eq,2,then modmesh,detach type,1 csys,1 nsel,s,loc,x,r2-1e-4,r2+1e-10 91
esln,s,0 emid,remove,both csys,11 nsel,s,loc,x,r1-1e-4,r1+1e-10 esln,s,0 emid,remove,both allsel nsel,all nsel,inve ndele,all allsel *endif !Define and Generate contact elements et,2,contac48,,0,coloumb,,,,1 r,2,kn,kn,,1,tol mp,mu,2,mu type,2 real,2 mat,2 !Generate contact elements on one surface csys,11 nsel,s,loc,x,r1-1e-10,r1+1e-10 nsel,r,loc,y,-90-3*gamma1*180/pi,-90+3*gamma1*180/pi cm,uppern,node !Generate contact elements on the other surface csys,1 nsel,s,loc,x,r2-1e-10,r2+1e-10 nsel,r,loc,y,90-3*gamma2*180/pi,90+3*gamma2*180/pi cm,lowern,node csys,0 gcgen,uppern,lowern gcgen,lowern,uppern 92
allsel !Generate ....... n,,0,r1+r2+1e-9 nsel,s,loc,x,0-1e-8,0+1e-8 nsel,r,loc,y,r1+r2,r1+r2+2e-9 *get,ntop,node,,num,max nsel,all csys,11 nsel,s,loc,x,R1-1e-12,R1+1e-12 nsel,r,loc,y,-180-1e-12,-180+1e-12 *get,natkp14,node,,num,max nsel,all nsel,s,loc,x,R1-1e-12,R1+1e-12 nsel,r,loc,y,0-1e-12,0+1e-12 *get,natkp9,node,,num,max nsel,all et,4,beam3 r,4,atop,itop,1 mp,ex,4,etop mp,nuxy,4,0.3 mat,4 type,4 real,4 lmesh,33 lmesh,34 lmesh,35 lmesh,36 nsel,all e,ntop,natkp14 e,ntop,natkp9 !******************************************************* ! Boundary Conditions 93
!******************************************************* !Rotate all nodes in upper cylinder to be in a cylindrical system csys.y.-R2.all !Fix bottom of lower cylinder csys.0 allsel wsort /dist.s.0.loc.ux.0 nsel.all d.x.f.1 nrotate.R2+1e-12.center /pbc.loc.s.11 nrotate.y.ntop csys.R2 nsel.node allsel csys.upper.all.s.all csys.0.all !Eliminate lateral motion of upper cylinder's totation center nsel.1 /dscale.node.0 allsel nsel.400 cm..u.node csys..0 nrotate.s.R2+1e-10 cm.0 d.all.y.loc.lower.r.ntop.1 94 .0 nsel.dist /focus.1 /pbc.loc..
rotz.then ddele.1.r.uy.eq.1.ntop.200 allsel solve save *endif Solution !************************************************************ 95 .then d.25 allsel solve *endif !***********Load Step 2************ *If.0 neqit.R1+R1 f.s.loc.disp d.1 neqit.eplot !************************************************************ ! /solu load=F !***********Load Step 1 *********** *if.uy ddele.ntop.0 nsel.ntop.loc.eq.st2.x.rotz d..rotate1 !Apply a pressure csys.ns2i.ntop.fy.0 nsel.0 nsubst.all.y.st1.-load*pnot csys.rotz.ntop.
10 allsel solve *endif finish 96 .-load /psf.st3.fy.0 nsubst.r.ntop.1 neqit.y.2 csys..st4.eq.R1+R2 f.1.then ddele.all.ns4i.pres.0 nsel.1..0 nsel.loc.loc.ntop.then d.-5e-3 csys.ns3i.rotz nsubst.0 allsel solve *endif !**************Load Step 4************ *if.x.s.!***********Load Step 3************* *if.eq.rotz.1 csys. | https://www.scribd.com/doc/60269472/Gear-Thesis | CC-MAIN-2017-51 | refinedweb | 21,269 | 58.89 |
graphql-to-io-tsgraphql-to-io-ts
Thin wrapper around graphql-code-generator that utilizes custom templates to generate both native typescript and io-ts types with the included templates.
usageusage
npm install graphql-to-io-ts@0.1.3, then put something like the following in your
package.json, then run
yarn generate-types:
the
bin file just prefixes the regular cli arguments to
gql-gen so that it'll use the configuration, helpers, and templates included here.
Custom ScalarsCustom Scalars
All custom scalar types should be defined with
io-ts and exported from a file above the
--out target called
CustomScalars.ts:
// represents a Date from an ISO string
This is why I think
./src/io-types/generated/ makes a good target - it also gives you space to organize your generated types, like defining a universal decoder:
Note that in typescript you can't
import from outside the project directory. | https://www.npmjs.com/package/graphql-to-io-ts/v/0.1.5 | CC-MAIN-2020-34 | refinedweb | 152 | 53.1 |
Introduction
Oracle unveiled its roadmap for BEA acquisition's products back in July 2008. During the webcast, Oracle Senior VP Thomas Kurian explained that Oracle has divided BEA’s products into three groups (strategic1, continue and converge2, and maintenance3). He then assigned each of the BEA products to one of these groups. WebLogic Integration (WLI), was assigned to the "continue and converge" group; it was no longer listed as a strategic product. This means that incremental extensions will be made to WLI 10gR3 and it will be converged with the Oracle BPEL Process Manager. In fact, extended support has already ended for many of the earlier WLI releases. For more information, refer to Oracle Information Driven Support: Lifetime Support Policy.
Because WLI is no longer a strategic product at Oracle, all WLI customers will eventually be forced to migrate their business processes and applications from WLI to an alternative platform, such as Oracle BPEL Process Manager or IBM BPM Advanced.
If you are one of those Oracle customers that are lucky enough to be running on WLI 10gR3, you can defer that decision for a few years because the extended support for 10gR3 doesn't end until Jan 2017. But if you are like most Oracle customers and are running your business processes on earlier versions of WLI, you will need to make a decision soon. In making such a decision, there are two options to consider. Specifically, you can:
- Migrate to WLI 10gR3 now and migrate to an alternative platform in a few years.
- Migrate to an alternative platform now and avoid the cost of migrating to 10gR3.
If you decide to migrate to an alternative platform, one option is Oracle BPEL Process Manager, which provides common infrastructure services to create, deploy, and manage BPEL business processes. Oracle has tooling to assist in the migration of WLI business processes and applications.
However, another strategic replacement product for WLI is IBM BPM Advanced, which is also a fully functional BPEL solution with tools to assist in the migration from WLI, as illustrated in the comparison below.
Notes:
1.
2.
3 Maintenance — These products were already declared by BEA prior to the acquisition to be at the ends of their lives. Oracle will honor BEA’s maintenance contracts on these products by supporting them for at least five years.
Table 1. Feature comparison of IBM BPM Advanced V8 and Oracle Weblogic Integration 10gR3
Series overview
This series of articles describes the overall process and supporting tools for exporting BPEL and supporting artifacts from WLI to IBM BPM Advanced. This tool-assisted approach enables you to produce a complete replica of your WLI application running on the IBM BPM Advanced platform. You can perform manual editing for optimum use of the new features provided by the platform. To obtain the migration tools described in this series, please contact the authors directly.
The series does not present a feature by feature comparison of Oracle BPEL Process Manager and IBM BPM Advanced. Contact your IBM sales representative for such a comparison. For this series, it is sufficient to say that IBM BPM Advanced is a superset of the features and functions in WLI, as illustrated in Table 2, and is therefore a viable alternative to WLI.
The articles in this series are as follows:
- Part 1: "Introduction" describes the tools and techniques that have been successfully used to migrate WLI business processes and associated artifacts to BPM. This article covers the following:
- Artifacts describes WLI artifacts that make up the business processes.
- Tooling describes the tools that can be used to migrate these artifacts.
- The migration process describes the high-level process of exporting and migrating these artifacts.
- Part 2: "Data Transformations" describes the different transformations that may be required to reuse business logic that is encapsulated inside the WLI artifacts.
- Part 3: "Migrating WLI Controls to IBM BPM" shows you how to convert WLI Controls to Service Component Architecture (SCA) components that can be run on IBM BPM.
- Part 4: "Migrating WLI processes (JPDs) to IBM BPM" pulls all of the pieces together by demonstrating the migration of a business process that runs on Oracle WLI to one that runs on IBM BPM.
The issues discussed in this series apply directly to the migration of applications from Oracle WebLogic Integration V8.x, V9.x, and V10.x to IBM BPM Advanced V7.0, V8.0, and V8.5. Most of the information here also applies to earlier versions of WLI.
Artifacts
This section describes the artifacts that make up a WLI application.
- JPD
- WLI represents workflows in files with a .jpd extension. A JPD is a Java file, with some extra Javadoc annotations that define the orchestration logic.
- WSDL
- WLI uses WSDL to define the interface to the JPD and its partners.
- XQuery
- WLI represents XQueries in files with an .xq extension.
- DTF
- Data Transformation File (DTF) is a WLI control that can be invoked by a JPD. DTF files have an extension of .dtf. DTF files contain definitions of a data transformation that can be invoked from a JPD. DTF controls generally retrieve some data from an XML document by invoking XQuery (which uses XPath to address specific parts of the XML document).
- JCS
- Java Control Source (JCS) files are Java components that developers write to provide business logic and access other controls. These Java controls have an extension of .jcs. They are invoked by JPDs, may have per-process state, and may also access collaborators on behalf of their JPD.
- JCX
- Java Control Extension (JCX) files act as wrappers for Java EE resource adapter modules and have an extension of .jcx. They are invoked by JPD callouts.
- XMLBeans
- WLI uses XMLBeans to generate Java types from WSDL and XSDs. These Java types are used as parameters to many of the aforementioned WLI artifacts.
Tooling
This section describes the installation and configuration of the migration tools.
BPEL 2.0 Importer
Background
The BPEL 2.0 Importer is an Eclipse plug-in for importing WS-BPEL 2.0 process definitions into IBM Integration Designer V8.0 or V7.5 (or WebSphere® Integration Developer V7.0) so they can be run on IBM BPM. Although IBM BPM supports the majority of WS-BPEL 2.0, some of the language elements in BPM still use the syntax defined in the preliminary BPEL4WS 1.1 specification. The BPEL 2.0 Importer handles these language differences by running a series of XSLT transformations. It even allows you to add new XSLT transformations if required.
Installation
Follow the installation instructions for the BPEL 2.0 Importer described in the developerWorks article Importing WS-BPEL 2.0 process definitions.
BPEL 2.0 Importer – WLI customization
Background
As mentioned, the BPEL 2.0 Importer was designed to import WS-BPEL 2.0 language elements and extended to handle differences. This extensibility feature is quite useful because there are parts of the WLI BPEL that are nonstandard. Thus, IBM has created a number of additional XSLT transformations to account for the required changes between the WLI BPEL and BPM BPEL. These conversions are syntactic in nature and preserve the runtime semantics.
Some of the additional transformations are:
- Convert BPEL v2.0's "if-else/if-else" constructs to v1.1 "switch-case" constructs.
- Convert <empty>, <scope>, and <sequence> nodes under the main "if" element.
- Convert "condition" attributes, nodes, or both.
- Convert XPath or Java snippet conditions.
- Convert <empty> nodes with a <jpd:javacode> child to an <invoke> node.
- Refactor <jpd:javacode> nodes to <wpc:javaCode> nodes.
- WLI's <jpd:javacode> elements wraps Java snippet codes in a method block with method name and curly braces. Those are stripped for BPM Java Snippet constructs.
- Add TODO comments in the Java code to remind developers to review and refactor the Java codes to be BPM or WebSphere Process Server compatible.
- Remove incompatible XQuery related nodes.
- Attempt to give a unique name to <scope>, <sequence>, <assign> nodes.
- Convert variables with initialized values. (Integer and String only so far).
- Refactor PartnerLinkType.
Installation
Once the BPEL 2.0 Importer has been installed, you can import BPEL as described in the BPEL plug-in documentation. When BPEL process definitions are imported using the BPEL 2.0 Importer, these process definitions may contain XPath expressions that call XPath functions provided by WLI. If so, the BPEL 2.0 Importer leaves these XPath expressions unchanged. When the processes are in IBM Integration Designer, the calls to these WLI proprietary XPath functions are marked as errors as these functions are unknown in the IBM BPM environment
To handle these WLI proprietary XPath expressions, we have implemented
about 15 XPath functions that we have found in WLI BPEL processes. These
XPath expressions have become a base for a growing repository of XPath
function implementations that can be reused for WLI migrations. These
XPath function implementations are made known to the IBM BPEL 2.0 Importer
by replacing the XSLT file that came with the BPEL 2.0 Importer. The
location of that file is:
{IID_Install_Dir}\p2\cic.p2.cache.location\plugins\com.ibm.wbit.bpel20.importer_{Version#+Release_Date}\xslt\ImportBPEL20.xsl
The migration of WLI proprietary XPath expressions will be described in more detail in Part 3 of this series.
OpenESB BPEL 1.1 to 2.0 transform tool
Background
The BPEL 1.1 to 2.0 transform tool is a third-party tool that can be downloaded to migrate your BPEL process from 1.1 to 2.0. You may need this tool if you are running earlier versions of WLI that only support BPEL 1.1 exports. This tool can be at the Open ESB web site.
Installation
The BPEL transformation tool is an executable JAR. Example usage
is:
java –jar transform.jar <input folder> <output
folder>
Note:
<input folder> should contain any referenced BPEL,
XSD, or WSDL files.
WLI migration utilities
This section describes the migration utilities available to help you migrate your WLI applications to IBM BPM.
JCS migration utility
The JCS Migration Utility helps migrate JCS (Java Control Source) to Java Objects that can be run on IBM BPM. In WLI, JSCs are essentially Java implementations with a .jcs extension. This utility automatically modifies JSC files and their corresponding interfaces, and modifies them into standard Java Objects that can be used by BPM. This utility automatically migrates JSCs by:
- Changing the extension from .jsc to .java
- Modifying the interface and implementation to remove any proprietary APIs
- Creating an SCA implementation that can be used by BPM
Note: The SCA implementation references some conversion libraries that we developed to handle the data transformations between XMLBeans and Service Data Objects. These libraries are also included in the project classpath.
The utility is an executable JAR that can be run at the command line.
Example usage
is:
java –jar transformationUtil.jar JCStoJAVA <location of
jcs>.jcs
For example, suppose that
<location of jcs> had the
files:
- Example.java – Interface file
- ExampleImpl.jcs – Implementation of Example, and business logic
After running the utility you would have:
- Example.java – New interface with proprietary APIs removed
- Example.java.old – Original Java interface for reference (this can be discarded)
- ExampleImpl.java – Implementation of Example.java with proprietary APIs removed and some other changes
- ExampleSCAImpl.java – An SCA implementation that does some data transformation and calls the corresponding methods in ExampleImpl.java. This can be used in BPM
- ExampleImpl.jcs – The unchanged jcs file (this can be discarded)
DTF Migration Utility
The DTF Migration Utility assists in the migration of WLI DTF (Data Transformation Files) to Java Objects that can be run on IBM BPM Advanced. In WLI DTF files are used to help execute XQuery files for performing data transformations. References to the XQuery files are defined as Java doc comments above each method in the DTF.
The DTF migration utility automatically modifies DTF files by converting them to standard Java Objects that can be used by BPM. This utility automatically migrates the DTFs by:
- Changing the extension from .dtf to .java
- Removing the abstract definition from the class name
- Changing the abstract methods to standard methods, and modifying the methods to execute the corresponding XQuery file that was defined within the comments
- Modifying the class by removing any WLI proprietary APIs
- Modifying the return type of the methods to return a standard DataObject
The tool is an executable JAR that can be run at the command line. Example
usage
is:
java –jar transformationUtil.jar DTFtoJAVA <location of
dtf>.dtf
XQuery Migration Utility
The XQuery Migration Utility automatically migrates the XQuery files that run on WLI so that they can be executed in BPM. These XQuery files were written specifically for execution in DTF files, and a few modifications need to be made to make them standard. They were migrated by:
- Adding namespace declarations
- Adding ";" at the end of some lines
The tool is an executable JAR that can be run at the command line. Example
usage
is:
java –jar transformationUtil.jar XQueryTranformation <location of
xquery>.xq
The migration process
This section gives a high-level overview of the major steps performed during the migration from WLI to IBM BPM, as illustrated in Figure 1. These steps will be described in more detail in future parts of this series.
Figure 1. The migration process
Preparation
During the preparation stage, the required software is installed (it is assumed that WLI is already installed), which includes:
- IBM Integration Designer V8.0
- IBM BPM Advanced V8.0
- BPEL 2.0 Importer
- OpenESB BPEL 1.1 to 2.0 Transform Tool (Optional)
- JCS Migration Utility
- DTF Migration Utility
- XQuery Migration Utility
Extract artifacts
In this stage of the migration process, the following artifacts are extracted or exported from the WLI workspace:
- WSDLs and web services (such as JWS)
- Control implementations (such as JCS and JSX)
- Data transformations (such as DTF and XQ)
- XML Schemas (XSD)
- EARs and Java Source Files
Export BPEL v2.0
If you are using WLI v10.x and have access to JDeveloper, you can export the JPD processes as BPEL v2.0 and avoid having to perform the transformation in the next section. If you are using WLI v7.x, v8.x or v9.x you must export the JPD processes as BPEL v1.1, as described in the next section.
Export BPEL v1.1 and transform to BPEL v2.0
If you are using WLI v7.x through v9.x, you don't have the capability to export the JPD processes as BPEL 2.0 and therefore must first export the JPD processes as BPEL v1.1 by doing the following:
- Use the Export BPEL option in WLI Workshop to export the JPD process as BPEL.
- Copy the BPEL, WSDL and XSD files in to a temporary directory.
- Use the OpenESB BPEL 1.1 to 2.0 Transform Tool to convert the BPEL to BPEL v2.0.
Import artifacts into Integration Designer
The next stage of the migration process is to import the WLI artifacts into IBM Integration Designer using the BPEL 2.0 Import wizard in the Import dialog.
Migrate XMLBean objects
XMLBeans (based on the Apache XMLBeans) is the default XML data construct and access technology leveraged by WLI processes. Many existing WLI artifacts, WLI controls, Java snippets and Java utilities contain XMLBean objects. Given that some of the aforementioned artifacts have XMLBeans deeply embedded and would be too costly to re-code, you can follow these steps to bridge between XMLBeans and SDO.
- Generate XMLBeans Java objects from existing XSD schemas using Apache XMLBeans libraries.
- Import generated XMLBeans into the Integration Designer workspace.
- Locate existing code where XMLBeans are used.
- Use WLI migration utilities to convert between XMLBeans and SDO. (This is a two step conversion process: XMLBeans ↔ XML String ↔ SDO.)
This process will be described in more detail in Part 2 of this series.
Migrate the WSDL
Two WSDL files are generated for each exported WLI JPD BPEL flow.
- One provider WSDL defines the interface for the JPD process.
- One control WSDL defines the interface for all the external services the JPD process invokes. This WSDL has the "_ctrl" suffix in the file name.
After the WSDL files are imported in to Integration Designer, a number of changes may be required:
schemaLocationsometimes need correction.
- Some types will have to be modified (for example, Exceptions, Objects, xsd:base64binary).
- The provider WSDL may have a missing types definition. This can be imported from XSD or copied from the control WSDL.
- Some interfaces in the control WSDL files may be replaced by the original WSDL files or other exported WSDL files (e.g. web service controls, process controls, and so on.)
- PartnerLink information may need to be updated.
This process will be described in more detail in parts 3 and 4 of this series.
Migrate XQuery transforms
WLI uses XQuery language to transform XML messages. Such XQuery transformations are commonly used in WLI JPD processes. Each XQuery is saved in a .XQ file and is invoked using a WLI control (saved in a .DTF file). IBM BPM does not natively support XQuery transformations (it supports transformations using XSLT or Java) and although manually converting the XQuery to XSLT or Java is an option, in some cases it might be easier to use the existing XQuery transformations by invoking the WebSphere Thin Client for XML, which supports XQuery 1.0. To use the XQueries with the WebSphere Thin Client for XML, do the following:
- Run WLI Migration Utilities to transform .DTF to .java code that leverages the Thin Client for XML.
- Run WLI Migration Utilities to transform .XQ files to be compatible with the thin client.
- Create Java SCA component using the converted .DTF Java implementation.
This process will be described in more detail in Part 2 of this series.
Migrate Custom Controls
WLI Custom Controls are externalized Java classes exposed as a WLI control, which are invoked by WLI JPD processes. These Custom Controls often implement complex functionality that is not provided natively by WLI or IBM BPM and may have a large code base that is impractical to re-implement during migration. Complete the following steps to migrate the Custom Control to IBM BPM while preserving as much of the custom code as possible:
- Run WLI Migration Utilities to transform Custom Control .JCS files to POJOs.
- Create a Java SCA component using the converted .JCS Java implementation.
- Perform any manual modifications necessary to correctly convert data types in the converted .DTF Java codes.
This process will be described in more detail in Part 3 of this series.
Migrate Built-in Controls
WLI built-in controls are pre-built integration components that allow the WLI JPD process to interact with external enterprise systems. These built-in controls are exposed through a Java Control Extension (.JCX) file that contains the interface and configuration data for the built-in control.
Some built-in controls can be replaced by embedded IBM BPM business process features (such as Process Control with Invoke, Timer Control with Expiry or Wait, and so on), some can be replaced by WebSphere Adapter and some simply require re-implementation.
This process will be described in more detail in Part 3 of this series.
Migrate the business processes
This step of the migration process is focused on making the required changes to the BPEL process that was exported from WLI to ensure that it is ready to run on IBM BPM. Some of the required changes are:
- Conversion of fault handlers
- Conversion of parallel "or" constructs
- Setting transaction properties
- Conversion of Java snippets
- Modification of partner references
This process will be described in more detail in Part 4 of this series.
Assemble and wire the components
Once the BPEL process and other implementation artifacts have been migrated to IBM BPM, you need to complete the assembly diagram by creating SCA components and wiring them to the BPEL process. Before the application can be deployed, you must create any required J2EE resources on the IBM BPM server and disable the inter-transaction cache.
This process will be described in more detail in Part 4 of this series.
Deploy and test
The final stage of the migration process is to deploy and test the new IBM BPM process using the integration test client in Integration Designer. If there are any unimplemented components or unwired references in the process, they are automatically emulated. This means your process does not need to be complete before you can start testing.
This process will be described in more detail in Part 4 of this series.
Conclusion
The tools and migration process described in this series of articles were developed over the past year to ease the process of migrating Oracle WLI applications to IBM BPM Advanced. These tools have successfully been used at customer sites. To obtain these tools, contact the authors or your IBM sales representative.
Resources
- Importing WS-BPEL 2.0 process definitions Using the WS-BPEL 2.0 standard with IBM Integration Designer
- Oracle WebLogic Integration BPEL Import and Export User Guide 10g Release 3 (10.3.1)
- Oracle Lifetime Support Policy
- Oracle Fusion Middleware
- IBM Business Process Manager Advanced product information
- IBM Business Process Manager Information Center
- IBM Software Services for WebSp. | http://www.ibm.com/developerworks/bpm/library/techarticles/1306_vines/1306_vines.html | CC-MAIN-2015-06 | refinedweb | 3,529 | 56.86 |
Transcript
Turner: Hopefully I've got the three hours done enough because I know I stand between you and beer. You've had literal Google tell you about how they literally invented microservices and then you were meant to have the actual CTO of CERN tell you about how they actually - what's the Sheldon Cooper quote? - rip the mask off nature and stare into the face of God. But you've got me. I think Wes [Reisz] is giving refunds by the door actually.
So who am I? I'm Matt Turner. I have done a bunch of things. I've done some dev and some ops. I helped Sky Scanner move to Kubernetes. If anybody like cheap flights, I was a Kubernetes consultant and I worked at a startup doing service mesh stuff, focused on Istio. I'm now starting my own thing. It's meant to be in stealth mode but the T-shirts turned up on Sunday and they're a really nice color. I guess it's out of stealth right now. I'm now doing a cloud-native consultancy. I guess helping people use this kind of tech.
If anybody's here to learn actually about Istio because you saw it on the name - I know it's a new, cool thing that a lot of people are interested in. I'll spend five minutes on the pitch, on what it does and why but what I'll then do is dive in fairly deep on how it works. We'll try to look at the architecture of why it's built the way it is, because I think that's really interesting, which is, I think, why I was asked to give this talk. We'll do a bit on what containers and Kubernetes pods actually are and how they work, and then we'll look at that architecture from the kernel point of view and then we'll look at the wider architecture of how you build a big distributed system out of all of that kind of stuff. If anybody's completely unfamiliar with containers and kernels and networks and Kubernetes, this might not be the right thing for you. But hopefully it'll make sense as we go along.
The original objectives of this talk - and as I say, I'll try to look at it in a slightly different way today is to see how a packet goes from left to right, traverses an Istio system which is probably running on Kubernetes made of the Envoy proxy that you probably heard of. And then we look at the control plane calls that are made during that process to this Istio control plane, which is this sort of management system. And the original purpose of this is to build this useful mental model for debugging Istio, should you ever hit any of its very few, very, very few edge case bugs, and reasoning about it, which is maybe what I'll focus on today. Yes, so you should probably know a bit about networking and containers, but I'll just go straight into that. Oh, this is three hours. We're not going to do all of that.
Context and Introduction
The Istio pitch. Why are we here? Your business wants value, right? Your business wants business value which is basically new features because that's what customers pay for. They want to get them out fast. They want quick experimentation time, quick cycle time and low risk. So we want this fast feedback loop, we want this scrum or the lean startup approach. So what did we do? We broke the monolith. There's our monolith, our single rock and we cracked it in half.
Did we get microservices in that? No, we get a distributed monolith, which has got all the previous problems and now a whole lot more, because what was a function call that could never fail is now going over a network that's probably on fire. You are left with a distributed monolith. This leads you to do a bunch of things to mitigate that. So you might have two services running in these two anonymous gray boxes representing a compute environment. Previously they would be namespaces in the same Java process, the same JVM. Now they're different processes in different containers that could be on different sides of the planet.
We started off by using, by deferring this to like a library, putting something like Hystrix or Finagle in there to get the back off and retry and deadlines and rate limiting, and all these services that we needed that we heard about in a lot of the earlier talks on this track. The problem with these is that they're libraries, they're in process. So if the library changes you need to spin a new release of your service as well. So you better hope it builds like at that point in time and it's passing tests. These two are specifically JVM only, so Java, Kotlin, Scala, only it's no good if you want to start writing Golang or Rust. You need another implementation of the library that does all the same things. And for anything that requires coordination, like global coordination or an on the wire consensus between two things, they have to speak the same wire protocol so you can't develop these things in isolation. It recently became very hard.
This is where Istio comes in. You take those same two services and you basically admit that all communication these days is HTTP, be that GRPC which is HTTP2 streaming, or be it good old fashioned JSON REST over HTTP1. So you put an HTTP reverse proxy by every service. This is the logo for the Envoy proxy. Then this thing can do all of those network resiliency functions for you. And what Istio can do is put that in front of these services completely transparently.
Istio then has a control plane which is what we're going to look at. It has these three components that sort of program these proxies up and tell them what to do, so you're not there writing manual config and injecting it into your containers. And importantly, this thing has an API on the front so you can write configuration and the control plane will take care of it and get it to the right place and roll it out. And this API is declarative. It's a lot like the Kubernetes API. It takes YAML documents that describe the state of the world as you would like to see it.
Istio bills itself as an open platform. It's an open source project to connect some of these services together to secure them, to control them as in manipulate that traffic, and to observe them. This is pretty much what it does. This is the emergent behavior of all the low-level features we're going to look at. I think Sarah said in her keynote that we should be using service meshes to get these distributed systems, the network functions that they need for free. Retries and back off and deadlines. Then I think Ben was saying that Google does actually have this stuff in a library because they have much more control over their source code, but it's the same principle. You need that stuff. And the dream is that your service is left being only business logic.
Networking and Containers
So that was the super-fast pitch. Super-fast operating systems 201. Oh, no, we're starting already. This is our left to right packet. Little Nyan cat packet here coming across an Istio system. The first thing it does is it hits an ingress point. So this is a request from a user out on the internet with an app or a website, and they hit an ingress point. This isn't actually too interesting, just to say there's no magic here. This ingress is a bank of the Envoy proxy. This does the same as your ingress controller on Kubernetes. There's no magic. It does the dance that everybody has to learn when they first get hands-on with Kubernetes as you point your wild card DNS record and your wild card TLS cert at a sort of a load balance from your cloud. It terminates things, it reissues to a node port. In through a cluster IP, it gets to a proxy. The whole dance. We know how this works. For the sake of 15 minutes and your beer, let's take ingress as a sort of fait accompli.
Our service has come through ingress, it's being routed to the right service. So this is all layer seven. You get this in any Kubernetes system. Your ingress controller does layer seven. These requests would come in with an HTTP host and a path and various headers and those could all be used to route the requests to the right service that you want in your microservices system. In this case, service A. So the packet moves across and it gets there. What does it find? Well, it's no big secret that we've got this Envoy proxy stuck in front of the actual service, the actual business logic. But what is going on here, what is the architecture of this?
Let's remember what a container is and let's remember that actually there's no such thing. In the Linux kernel you probably won't find this word in the source code. There's no first class consent of a container in Linux. Previously you had jails, and Solaris had zones. Plan 9 is the best operating system. It had full namespaces but we're not on the best timeline. We've got some student's reimplementation of 4.4 BSD. So what we've got in our Linux kernel is containers and namespace made of namespaces. So we've got these six namespaces that are software isolation mechanism.
Very briefly, imagine we have a container. Morally Nginx, called Nginx. It's running Nginx and then maybe it's running something else, some of the Unix processes like supervisord to keep it up. It's in these six isolation points. Briefly, this mount namespace isolates the mount table. It's like chroot on steroids. These processes see a different version of the mount table, a different virtual file system built up from the forward slash, the root path to things outside of this namespace. This, if you think about it, is necessary, right. Containers run from an image. So actually the very first thing you need to do is make sure that forward slash, the root of the file system is that image, that tarball, rather than the host's disc. And then you can mount volumes into these containers. That's obviously just inserting mounts into the mount table like you would mount a USB drive on your host operating system. That's isolated.
The UTS namespace means that this container can have a separate hostname and DNS domain to the stuff outside of it. The PID namespace means that process IDs can't be seen on the outside from inside. You shell into a container. Run a shell. You do PS and you see like two things. You see bash and PS. You don't see any of the stuff from the host system. The user namespace isolates the user IDs as well. So the user 1000 in here isn't the same as user 1000 on the outside. Can't start mapping pages. User namespaces - we won't go there. The IPC namespace stops you sending some signals. SystemV IPC requests, systemV shared memory across this boundary. Then, as will become interesting for us, the network namespace isolates “networking” and we'll see what that means, but it basically means that there's a different set of interfaces, a different set of IPs inside this namespace to outside.
What is a Kubernetes pod? Because what this packet hit was a Kubernetes pod, containing two containers. Because that's what Kubernetes pods are there. They're several containers kind of stuck together. So a Kubernetes pod is quite interesting. What we build to give us this dev experience from the primitives that we find in the Linux kernel is kind of shown by this diagram here. It's two containers coupled together. This is why you have to deploy a pod as an atomic unit, as the atomic unit of scheduling. It has to go onto one machine because they have to share a kernel because these two containers actually share some of these namespaces. They both have a separate mount namespace, as they have to because they run from separate images. They actually both have to have separate UTS namespaces so they can have different hostnames.
But they share a PID namespace. So the processes in one can see the processes in the other. It can signal them, it can talk to them. They share a user namespace so that file. Unix file permissions work because they agree on the set of users and groups. They share an IPC namespace if you want to use any of the systemV mechanisms. And importantly for us, they share this network namespace, which means they have one view of the network. What does that mean? It means they've got one interface. It's actually one end of a Veth pair. I think Wes likes the long explanation of sort of veth pairs and virtual networking I gave in the three-hour version. It doesn't fit here, but this is an interface that we've renamed to eht0. So it looks like a sort of standard actual PCI card I/O. This thing kind of looks like a small virtual machine. It's one end of a veth pair.
But anyway, we have our one interface with one IP address shared by all of these processes in these two containers. We have loopback. We also have one set of routes, one route table. We have one set of sockets, one domain for Unix domain sockets. And importantly, we have one set of IP tables rules. I could write an IP tables rule, a process in here, get set up an IP tables rule that, say, dropped all traffic, and that would drop all traffic coming in and out of this one as well because they're in the shared network namespace, although they're allegedly two separate containers. So Nginx can for example bin to 8080 TCP and then FluentD couldn't because one socket space; address is in use.
For our purposes for building this service mesh, we can do more interesting things. Imagine we replace that Fluent D that was a sidecar log exporter with a proxy like Envoy, and then we set up some IP tables rules to say, "I want to intercept all traffic coming in and out of this port 8080 and I first want it to come into Envoy and then Envoy is going to punt it back out to say “loopback." And then there's another rule that says, "Okay. From loopback you can finally go from Nginx." This is how we leverage this shared IP table system to do this transparent interception of network traffic.
This is called the sidecar model. We originally have Fluent D. I didn't point it out, but this idea of morally a process should do one thing and it should do it well. That's the Unix philosophy. Morally a container should do one thing right. It should have one primary process like an Nginx. If you're a putting a database in here you're doing it wrong, but it's okay to have sort of ancillary services. The same with the pod. They should have one primary purpose. This thing presumably serves HTML, but it also has this sidecar giving extra functionality that we might want.
The sidecar injection is a big topic. Liz Rice who works for Aqua does this amazing talk where she basically builds containers from scratch. She live codes a couple of hundred of lines of Golang and makes all the system calls to build these namespaces and to make these containers. Watching this go through is really interesting. But basically as the kubelet tries, it starts to build these pods up, it creates these namespaces. Then it goes through this list of init containers, which are more container images that just contain a one-shot process that does something and quits.
But what's interesting is that they affect this namespace. They affect if something writes to IP tables rules or changes the route table, just like running route on your command line, when that route userspace command quits, the route table is still changed. The kernel remembers that. It's a persistent thing and it then affects every other process subsequently in that network namespace. So the first init container just turns on core dumps. You can draw your own conclusions about perceptions of stability of the system from that. I will not comment.
The next one is more interesting and it runs a very long shell script that I won't go through, that basically sets up all those interception rules that I talked about. This is what makes it transparent, is the fact that this comes along, sets up these rules, and then your primary container has to have no idea that it's in this intercepting environment, but it doesn't need to contain any of the sort of networking logic we've talked about, for the retries and the back-offs that we want.
This is an init container basically because it's a privileged operation to manipulate IP tables rules. This thing runs with CAP_NET_ADMIN capability and then obviously when it's gone that's dropped. Then we can start the, the actual two containers. There's a bunch of details. Envoy listens on 15,001. The IP tables rules have persisted from the manipulation by that init container and they reroute the packets through Envoy.
That's how the very early interception works and that's how we build this up from those namespace perimeters in the kernel and C groups as well. I didn't mention them, but you've probably heard of C groups which is the kind of hardware side of that isolation mechanism. A container or a pod also existed in a bunch of C groups which limits its visibility of hardware devices and limits its rate of access. So you can limit network bandwidth and CPU and memory usage with the use of C groups. Together they provide hardware and software isolation.
Pilot and Routing
So, how am I doing? What happens next? The next thing is that maybe the packet bounces in through Envoy into service A back out again. If service A has just crashed and never responds to Envoy, Envoy will maybe wait a second and then just return a 503 on your behalf, or whatever you've got it configured to do. But service A is going to issue another call in the back end to service B. and it wants to talk to service B. The first thing it's going to do is service discovery. How does it know where that service B is? So you're probably in Kubernetes. As I say, I'm assuming you’ve got a bit of Kubernetes knowledge here. You've probably got a Kubernetes Service fronting all of the pods that comprise service B. You will have a cluster IP as it's called, a virtual IP, a VIP for that service. So you could just fling packets at that.
The problem with that is that it's then the Kubernetes proxy that does the back end selection of the load balancing, and it really has no idea what's going on. It can't do a great job other than just as round robin. But we can do better than that, right? That's part of what Istio is for because, like I said, the ingress is layer seven and does host and path based routing and could look at headers and make much more intelligent decisions. With an Istio system, that's not the only thing that's HTTP aware. All of these sidecars are. What this Envoy wants to do is it wants the full list of potential back ends, and it wants to be able to choose one itself rather than just throwing it at a round robin thing. It wants to be able to talk to the other Envoys, and do a least weighted or a geographically closest or something like that. So it needs to be able to find out where all of these things are in order to be able to do that.
So what do I do? I'm probably on a Kubernetes system. I can ask Kubernetes. So we can get this service for service B and we see that sure enough, it's got one cluster IP. This is a virtual IP and this just gets round robin between the real back ends. That's not really good enough. The way these things work though, the way kube knows where to find the back ends is this label selector. So in this case we've got app equals to service B, because that's how the pods are selected. So can I do anything with that? Well, let's have a look in DNS first. Service B, that's the kind of name I've given this thing. Again, 1 A record, service IP range. Not a pod IP.
Indeed though, I can go get all the pods and I know we're looking for service B. So maybe I grep for that and I find all these things. The labels aren't shown but I now find that I do have three pods and they all start with service B. But this just isn't sufficient. Why? Because services are based on these app selectors that can be arbitrarily complicated. You can't just go fumbling around like this. This isn't sufficient either. We need a way to get always the right set of pods. We need to take that label selector and we need to run it ourselves basically.
Kubernetes luckily gives you an API endpoint to do that. Unsurprisingly it's called endpoints. So I can ask to get the endpoints for service B, and now I get three IP addresses in this example, and they are pod IP ranges, not service IP ranges. This is an example. The execution environment I found myself in has a service discovery mechanism. It's actually got two in this case. It's got a naïve one which is, "Oh, you want to get packets to something that quacks like a service B? Great. I can do that for you. I offer you a layer of abstractions.’ And it's also got an, “Okay. If you want to kind of lift the lid off, if you know what you're doing, if you want to be taking the intelligent networking decisions, I can give you the actual IPs of the workloads if that would help.” In Kubernetes we can hit that endpoint and in other systems there are similar things. You might imagine raw DNS on VMs, you just look for SRV records or something.
I can get a longer form of this. And for each entry I get the IP address. I also get interesting things like what node it's on, so I could go and look up what region and what zone that's in, look at how close it is to me. I find out what kind of ports is expected for this. And of that useful information is in this service discovery mechanism.
I need to take that service discovery information and I need my Envoys to have it. This is one of the first talking points maybe about the Istio architecture, is I want this Envoy to have this preprogrammed. I don't want it to have to reach out every time. It can't look in DNS. That's not good enough. I don't really want it calling Kubernetes to hit the endpoints API every time because that's going to really load the system, it's going to slow Envoy down. So what I really want is to have that service discovery information ready and available in Envoy so it can start doing things. We introduce our first Kubernetes control plane component, which is this thing called Pilot that does exactly that. Pilot's the thing that configures these Envoys and pushes configuration to them. So as I say, you don't have to. Because out of the box it configures them to do default retries and timeouts and all these kind of things. So that's the pilot component.
How does it get its configuration? Well, it's actually got a bunch of adapters. Pilot is the interface to your environment. It knows how to go talk to Kubernetes service discovery to go and find out where your pods are. If you're not running in Kube, it will also talk to consul, it'll also talk to zookeeper. It can actually talk to all of them at once so it can build a shared database of, "Here are all the endpoints in Kubernetes and then you also told me about a consul system managing your legacy VMs. I've ingested those services as well and I've synthesized that information together." It then kind of churns that data and it pushes it to each of the Envoy proxies.
Another interesting point is that that API is what Envoy, Matt Klein at Lyft is calling the data plane API. They've gone to lengths to standardize and open this API. The idea being that in a system like this, this is open source, this is free software. You are free to swap Envoy out for anything else that implements the data plane API. And I think maybe HA proxy does now. So that's also another sort of interesting part. So this is, as I say, a push model. Actually, a Pilot will do its best to establish watches on these back ends so it gets kind of long-polls when they get changed so it doesn't have to spam them. It'll spam them if it has to. Then Pilot churns that config information. If and when it changed, it pushes it to Envoy asynchronously so Envoy has new configuration ready to go. Envoy doesn't have to poll. So that's how we do this remote asynchronous ingestion of service discovery and push it into Envoys.
What can Pilot do? Well, it's the thing that configures your proxy in a static way. It can affect the routing of the ingress because that ingress controller is provided by Istio subjected of the same configuration. It's the thing that'll do your traffic mirroring for testing, prod, and staging. It'll do your AB testing, traffic shifting, canary deployments. It'll set up circuit breakers, it'll set up fault injections. Anything that that proxy can be told to do. “One percent of the time I want you to return a 503 just because. And if the back end takes more than seconds then throw a circuit breaker and return this default.”
Mixer and Policy
We found service B. Here it is. There are three instances of it, three pods, in an amorphous gray compute blob. Remember, they may not be on top of each other. Can the packet now traverse? Well, not necessarily. There are a few more checks we need to make, a few more things that Pilot can't configure the proxy to do ahead of time. We need to check that there's no security policy in place that says that A isn't allowed to talk to B. We need to check there are no rate limits that have been exceeded. So this isn't a kind of stuff you could preprogram the proxy with. It needs to kind of know.
So unicast rate limiting is easy. We could tell this Envoy that it's got a 1,000 QPS over here. Well, what that means is this one instance of service A gets a 1,000 QPS to what? Each instance of service B or all of them? But then what if other instances of Service A are calling this? What if there's a service C that's calling this? So to do global rate limiting to basically say, "I've load tested my new service. SRE are happy to take it over. We know it hockey sticks at 5,000 QPS per pod. I've got three. So I want a global rate limit of 15,000 QPS." from wherever. And by the way, service A is a higher priority than service B. That is a more difficult thing to do, and that requires a few extra components.
Introducing Mixer, the next control plane component. This thing does those policy checks about security and rate limits and it's also the thing that gathers telemetry. Not only have we moved retries and rate limits and whatever out of our service by pushing them to Envoy, also because this thing's on the wire because every packet goes through it and because it understands layer seven, HTTP, it can generate logs, it can add trace headers and generate trace spans. It can generate metrics for us. Again, something that can be taken out of the service, Envoy implements that for us, and then Mixer is just an aggregation point for that. Again to plug it into the environment.
We now take a digression. This is where we get into some architectures you probably haven't wondered about. I'm talking about layer seven, routing these things, treating these things like a layer seven network, routing this stuff based on HTTP information. When you're doing IP layer three, layer four networks, you have this thing called the IP 5-tuple and this is the set of five data points that are sufficient to identify an IP flow, an IP connection. They are the source address and the address to the source port and the destination address and a destination port and the protocol. That being UDP, TCP, that kind of IP protocol. So with these five you can identify any TCP stream, any UDP connection between endpoints.
The way you build these big IP routers, the big systems that do internet backbone kind of stuff, is they have this segregated architecture. They have a control plane and they have a data plane. The control plane ingests all the information it needs to make routing decisions from BTP and open shortest path first, and then also local protocols like spanning tree and ARP. So all of these different pieces of information that would come together to tell a big iron router where to send a packet all come into this control plane which is a general purpose computer and it builds this thing called the router information base, which is like a SQL database. There's a different data schema for each one of these protocols. They all get put into tables with that schema and there's these big JOIN statements that merge them all together, know priorities and work out what decisions to make.
You do that on this general purpose asynchronous computer with no real hard deadlines. You do that and every time one of these protocols gives you a new piece of information about your topology or your peers, you put this into your RIB and you churn it and compile it. And what you emit is entries for your forwarding information base. This FIB is much more like a NoSQL database. It's a bunch of denormalized tables that are heavily indexed. They're all meant to be constant time lookup. So as soon as I get a packet, I can look at that IP 5-tuple and say, "Okay. Which TCP connection is this? Oh, that's your current YouTube stream because it's your IP, your browser's IP and port hitting YouTube 80 protocol TCP."
I could look that up in constant time because there's probably a table keyed on that and I can then make a really fast decision about where to send it. I don't have to do all that crunching involving this business logic, know that it understands all of these protocols, and I don't have to call up into this database every time. So this is kind of pushed into the FIB which is part of what's called the data plane. Actually that data plane itself has- and this is getting into implementation details- but it has what's called slow paths and fast paths and slow paths.
So if this packet has very recently been seen the actual interrupt handler for the network card can probably deal with it because it's got a small fixed piece of memory, it's got a small cache. It can cache parts of the FIB. It knows it's done an access control list check in the last 100 milliseconds, so it still considers that information good and the top half of the interrupt handler can probably just punt that packet without doing anything. If that information isn't in that small cache, or if you need a little bit more decisions taking for maybe look checking, ACL information in a different table than this FIB or something, you might actually have to call a kernel. You might have to come out of the interrupt into the kernel proper, so somewhere you can allocate memory. For example, you might actually have to call into a kernel module. And if that can't handle it, the architecture of these systems is you punt over a socket. You actually get into the user space where you really can do anything you want.
These things have slower paths and faster paths based on the locality and the recent validity of cache information. But they all access smaller or bigger parts of this forwarding information base, which is this denormalized indexed store. Why the aside into an IP router? Why do we care about sort of big iron boxes? I think this actually looks very similar to the Istio architecture. I would say the Pilot is your control plane. It's your RIB that ingests all of these service discovery protocols and all of the user configuration that tells it who's allowed to talk to what. And then it compiles that configuration and it punts it off to Envoy, which is the thing that actually has that if I see this kind of set of headers, I need to send it over there. If it's literally this path that goes to service B kind of thing. So Envoy to me is the data plane, but it's the fast path of the data plane. So there are some decisions that Envoy can't make on its own. For example, applying a global rate limit. Can't be done. In locality it can't be an Envoy's little interrupt handler, because we don't have all the information we need. We need to go coordinate with some other people.
To me, Mixer is not actually control plane even though it's drawn there in the diagram. To me, it's the slow path of this data, plane because Mixer is on-line and it's part of every packet flow as far as I'm concerned. So where would we draw Mixer? I would take it out of its box and kind of put it down here? As I say, there are two things it can do. It can do the checking, this packet allowed to traverse based on security rules modeled as RBAF, based on sort of global rate limits, and Mixer's the thing that holds that counter. And then as I say, it also sees all of this telemetry information. It's an aggregation point and it's also an adapter. If you want your metrics to go into Prometheus and then also into cloud watch metrics and if you want your logs to go into elastic search, you just tell Mixer where those things are and it gets everything from all the pilots and Mixer will talk to them.
What's interesting about this is, I said it's on the data plane, I've said it's on the hot path. That's not entirely true. It's an architecture diagram, right? You're a senior engineer. You're in a design review. That looks like a single point of failure, maybe. It certainly did to me to start with. But there's a whole bunch of implementation details that mitigate that. So Envoy obviously calls to Mixer, but it uses what they call a fat client. There's quite a lot of code in this Envoy plugin that calls to Mixer. Basically what that means is that firstly the reporting stuff, the telemetry information that's sent up is batched, sometimes aggregated. It's asynchronous. It's not on the main thread. It gets off the main Envoy thread straight away, and then if you can't reach a Mixer, if it's being slow, it blocks a different thread and that thing times it out and that thing's asynchronous. So simple batching and asynchronicity takes it off that hot path, off the main worker threads in Envoy.
The checking is even more interesting. So a request will come in. Maybe I want service B and I'm getting this path and I'm this user agent. Say we're blocking some buggy version of IE that's just sending us malformed requests and a query of doom for our system. Your service A is allowed to access service B on this path, as long as it's not IE. So first request hits Envoy and the fat Mixer client talks to Mixer and it says, "Well, I've got all these headers. Am I allowed? Yes or no?" And Mixer says, "No, you're not. Drop that packet. Don't sent it across."
And by the way, you can cache that and you can cache it for 500 milliseconds or 100 requests. Whichever comes first. And by the way, the key for that cache is just the user agent. You send me the user agent and all the other headers and the path and the host, but I'm telling you that IE is just blanket banned. So actually, when I did all of my machinations I decided to ban it just based on that user agent header. So you can put Envoy fat client. You can put that no in your own cache just under the heading of user agent. If any user agent IE ever comes up, it doesn't matter what host it's going to, what path it's going to. Just drop that packet. So Mixer gives an optimal cache key back to Envoy, and it says then, “This is valid for a 100 milliseconds, 50 requests. And if you can't reach me to get another answer after that, if that cache expires and you can't reach me, this thing fails open or fails closed,” depending on how you've got it set up. Maybe whether it's a security mechanism or a sort of soft rate limit.
All of those implementation details go into hopefully making this thing that looks like a single point of failure actually a more resilient system, because Envoy is preprogrammed by Pilot to do what it can. Then in a way, it's almost preprogrammed by Mixer. If you can get even one answer out of Mixer you send it to Envoy and then it's got this preprogramming, which is yes for now, but after that you've got to fail close if you can't reach me. So it's basically a no because this is a security thing, so we're going to err on the side of caution. If you can reach me and if I can validate that, all the rules are in place then I might say yes. I might open the gates for a 100 milliseconds. In that sense it makes it almost preprogrammed and actually makes the system more resilient, even though it might look like a single point of failure. So, yes, Mixer can do this checking of ACLs and authorization. It can do rate limiting and it can do reporting of logs and metrics and tracing.
Can we finally traverse? Maybe not. This lady here is called Eve. She's interested in dropping in on our packets and hearing what they have to say. How do we mitigate this? Well, we stick it in an mTLS tunnel.? Well, we encrypt it. When your browser talks to an origin web server, you use simple TLS, right? The server presents a certificate. You trust that because it's signed by a root authority whose certs you've got installed. That gives you encryption but it gives your browser verification of the identity of the origin server. It doesn't give the origin server verification of the identity of your browser. It doesn't let amazon.com know who you are. You could be anybody, because you're not presenting a certificate. That's why you have to log in to Amazon. You have to use a different form of credentials, a username and a password.
Because we've got control of all of this and because it's between two services that we control, we can actually do mutual TLS. You not only get that encryption on the wire, but you get strong verification of the identity of both ends. In order to do that, they need certificates, mutually trusted certificates. This is the third control plane component, a thing called Citadel, which issues those certificates to the Envoys. It pushes the certs out and they're quite short lived and it renews them quite often.
There's a whole bunch of stuff again that I don't have time to go into about how Envoy calls Citadel and says, "Hey, I'm service B. Can I have a certificate to assert that?" Citadel has to trust that Envoy, right? Your security chain's only as strong as its weakest link. So actually there's a side channel through to an agent that runs on the node where Citadel can verify that. It doesn't do much today, but there's a whole bunch of work going on to have that side channel agent check the binary signature and the binary hash of the service binary, the Docker daemon, the kernel, talk to the TPM, the BIOS, all of these security vectors will be verified. Those attestations go to Citadel. Citadel then says, "Oh, yes. I know you’re service B. Have a certificate to prove it." Service A then accepts the cert.
So that's kind of the third part of the architecture. If you see Pilot as a reactive config compiler and pusher, Mixer is a sort of data plane fast path. Citadel is like a batch job, I guess. Citadel is something that runs in the background. This is almost like let's encrypt agent, whatever that's called. It just keeps rotating your certs. So that's the third part of the control plane, and again, it's got a slightly different model.
I'd say we're there. I'd say the packet can reach. It's gone left to right. We've seen how and we've seen all of the control plane components that it hits along the way, and what they all do. Just a few more things to say on the subject. There's also an egress controller which is ingress in reverse. Another bank of proxies. Controls your access to the internet. This isn't normally done, but actually if you think about it, your average back end microservice probably doesn't want to talk to the internet. It should only be talking to other microservices. It might need to talk to databases and queues and stuff from your cloud provider from your PaaS. Almost certainly shouldn't be accessing Russian IP ranges. So you might want to block that by default. You also might just have used an Ubuntu based image because you were lazy and the damn thing's trying to update itself in the background. Just stop it from doing that.
So egress control is provided, again, under the same Envoy proxy, under the control of the same control plane, same set of documents. Config documents applied to these Envoys is applied to these. We actually need to get configuration into this system and so Pilot takes the config. It takes the information from all of these service discovery mechanisms, but it actually needs to mix that in with what the user wants. So the user's got to say, "Well, I want this particular rate limit and I want this fault injection, but only between staging service A and staging service B." So the user has to get configuration into this as well.
Istio is normally run in Kubernetes. It hijacks the Kubernetes API server currently to do that. You use kubectl. You write these YAMLs that look like kube configs. You use kubectl to pump them to the kube API server. Through various hooks and hacks, Istio just goes and reads those and then Kubernetes uses its own etcd instance which is this key-value store database to persist that data.
What Istio is doing soon- this is in development at the moment, and there was a small change to this slide. It was to rename this Galley. Istio is writing its own component to take user configuration and to store it and to validate it, to persist it, to store it and to send it into pilot, and that'll just be another stream of information like the service discovery is. This, I think, for me completes the picture. This gives us the full three-tier architecture. So I say three-tier architecture as if it's the 90s. I guess everybody's thinking Oracle DB and PHP and all that horribleness. And sure, that was the thing. Actually it didn't serve us that badly. In a lot of cases, we got ourselves ORMs, we got ourselves schema migration tools. We applied science to it computer science, at least.
But now with Galley, I think you've got that same sort of three-tier model and it does fit almost. You've got a management plane now, and then you've got a control plane, and then you've got a data plane. Much like this would be the UI of your web app, and this would be the execution tier and this would be the database. This thing, this management plane, is optimized for user-friendliness. It doesn't need to be fast. It can operate on human time. It doesn't need to be particularly highly available. We just optimize of that user-friendliness and all it does is it takes user input and it presents it in a nice way, and it validates here and it stores it in a very resilient way.
Then you have a control plane, which if you like, it actually does most of the work, as in it implements most of your business logic, most of your actual value. It's the complicated business logic in this control plane as it would be in the execution tier, if you're doing your three-tier web app. And this thing, as a group, all the replicas of them are optimized for concurrency and for availability because that's what a control plane is doing in your system. And then they push configuration to the data plane. This is maybe your most even your database. As we know, Envoy does all the heavy lifting but it does it in a very dumb preprogrammed way. Like as dumb a possible way, because we just want it to work. These things are optimized for latency and they're optimized for throughput. And the way to do that is to make them dumb and to give them these pre-indexed, like pre-chewed configurations.
To me that's kind of the equivalent of putting just views and indexes and stored procedures into your database. I'm sure we've all seen applications that are implemented entirely in store procedures, and that's a nightmare. That's an anti-pattern, but a little bit of a stored procedure to give you a wrapper and some transactions around updates over several tables, just views so you don't have to fetch a bunch of tables, and then do the joins yourself in Java code up here. That is a legitimate use of pushing things to the data plane. And I think you can see analogies for that now with our cloudflare workers, and with eBPF, which is basically Lambda for the Linux kernel. All of these systems, these little hook points where you can just add little bits of code, they need to get run all the time and need to be highly performant and need to scale with the data plane and be optimized for latency and for throughput.
That's me trying to fit into the architecture track maybe. That may be a bit of a squint, but I actually think that model works quite well. I think the analogy to the router with the control plane and the data plane is there. To me Galley or currently what kube does, is a good approximation to a management plane. So that's the architecture of Istio. That's how it works. Its reason to exist, it is a service mesh, right? It's those network functions taken out of your service or it's an HTTP-addressed overlay network, whatever you want to call it.
We heard the pitch for what it does. This is the way it's built. I hope I've explained why with some parts of the control plane being batched jobs, some being online things, some being compilers. So, yes, I don't think I've got any more slides. Hopefully, that was interesting. I took you through the introduction, we did a bit of how do I use the Linux kernel primitives to build something a lot more emergent, like a Kubernetes pod, which is containers, and then what are containers? And then given that, given that ability to transparently intercept traffic and do intelligent HTTP-aware things with it, how do we then build a distributed system across an entire region or maybe the world, and give that a consistent configuration and a consistent set of things that you want it to do for you, and how do we keep it secure? That's really all I wanted to say.
See more presentations with transcripts
Community comments | https://www.infoq.com/presentations/life-packet-istio/ | CC-MAIN-2022-40 | refinedweb | 8,628 | 73.47 |
UPDATE: The code in this post relates to SignalR v1. For an updated version that works for SignalR v2 check out this post.
I’ve been doing some work with SignalR recently. If you’ve not encountered SignalR before then take a look at the project wiki or Scott Hanselman’s post to find out more.
By default, SignalR preserves the case of property names when sending objects from the server to the client. My preference is for PascalCase on the server and camelCase on the client, and in this post I’ll show how you can achieve that.
Basic functionality
To avoid breaking what seems to be a tradition for SignalR posts I’ll start with a (very) basic chat-style application. I’m going to start with pretty much the same code as the hubs version of Scott Hanselman’s post. I’m not going to spend much time breaking down the initial code so if you want more explanation then check out Scott’s post.
In a standard ASP.NET Web Application project I added SignalR and modified Default.aspx to update the body content to:
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
< script</script>
<script src="/signalr/hubs" type="text/javascript"></script>
< script
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
$('#messages').append($('<li>').text(message));
};
$("#broadcast").click(function () {
// Handle button click and call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
<h2>SignalR camelCasing</h2>
<input type="text" id="msg"/>
<input type="button" id="broadcast" value="Send" />
< ul</ul>
Then I created a very simple Hubs\Chat class:
public class Chat : Hub
{
public void Send(string message)
{
Clients.addMessage("SENT: " + message);
}
}
This code creates a simple chat application. When the user clicks on the “send” button, the text from the “msg” input is sent to the SignalR Chat hub which then echoes it to all clients via the addMessage call. Clients register for this call and append the message to the “messages” list.
Aside from the functionality, there are a couple of things to point out here. Firstly, the hub is called “Chat” in the server-side code, but we refer to $.connection.chat to access it client-side. I use PascalCase server-side and camelCase client-side, so this all feels good to me. Simlarly, the hub has a “Send” method, and it is called from the client using “chat.send”.
Then we get to the call from the server to the client, and we use “Clients.addMessage” on the server. To me this doesn’t feel quite right. But it’s not all bad as I can change this to “Clients.AddMessage” on the server and SignalR still allows the client to register with the “chat.addMessage” event. So far, so good!
Adding additional data as parameters
The next step is to send some more data – suppose we want to send the timestamp for when the server received the message (or the originating user…).
One way to do this is to pass additional parameters, e.g. on the server:
public void Send(string message)
{
Clients.AddMessage("SENT: " + message, DateTime.UtcNow);
}
And on the client:
chat.addMessage = function (message, timestamp) {
$('#messages').append($('<li>').text(timestamp + ' ' + message));
};
This all works, but sometimes it makes more sense to group related data into an object.
Adding additional data as objects
Let’s suppose that we have a Message type that we want to use to encapsulate the message properties on the server:
public class Message
{
public string Body { get; set; }
public DateTime Timestamp { get; set; }
}
We could use this type on the server:
public void Send(string message)
{
Clients.AddMessage(new Message { Body = "SENT: " + message, Timestamp = DateTime.UtcNow });
}
And then consume it on the client:
chat.addMessage = function (message) {
$('#messages').append($('<li>').text(message.Timestamp + ' ' + message.Body));
};
This all works, but note how we’ve had to use “message.Body” with PascalCase on the client? If we try to use “message.body” we simply get “undefined” as there is JavaScript is case-sensitive and there is no “body” property.
Fixing the casing
As we’ve seen, for the most part SignalR is quite forgiving about casing, but when serialising objects it has to pick an option. Unfortunately (for me) it serialises the properties with the original server case. All is not lost - SignalR builds on top of JSON.NET, which has a lot of extensibility points for serialisation.
For example, we can use the JsonProperty attribute to override the name of the property when it is serialised to JSON. This can be applied to the Message class as shown:
public class Message
{
[JsonProperty("body")]
public string Body { get; set; }
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
}
With this change, we can use the PascalCase form on the server (i.e. “message.Body”), and have it serialised into camelCase for consumption on the client (i.e. “message.body”)
Fixing the casing – take 2
The JsonProperty approach works (i.e. I can use the ‘correct’ casing in each context), but I’m lazy – I don’t want to have to mechanically go through and add the JsonProperty attribute to each object I return via SignalR. Fortunately, JSON.NET allows us to plug in custom “contract resolvers” and actually ships with a CamelCasePropertyNamesContractResolver which automatically performs the camelCase conversion for you. Sadly, using this contract resolver breaks SignalR as it affects the case for properties on all serialised objects and SignalR expects PascalCased objects on the client. Instead, we can create a custom contract resolver that only performs the case conversion for a filtered subset of types. The code for this contract resolver is in the download (link at the end of the article), but we can configure SignalR to use it by adding the following code in Application_Start in global.asax
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new FilteredCamelCasePropertyNamesContractResolver
{
TypesToInclude =
{
typeof(Hubs.Message),
}
}
};
var jsonNetSerializer = new JsonNetSerializer(serializerSettings);
GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => jsonNetSerializer);
With this configuration in place we can remove the JsonProperty attributes from the Message class as we’ve registered the Message class with the contract resolver so it will automatically add this behaviour for us. We can add additional types to the collection initializer, or use the AssembliesToInclude collection
AssembliesToInclude =
{
typeof(Hubs.Message).Assembly,
}
The code above automatically applies the case-conversion behaviour to all types in the same assembly as the Message class (and we can specify multiple assemblies if desired).
Summary
In this post we saw that SignalR allows us to use PascalCase on the server and camelCase on the client in most cases. When we’re passing objects from the server the objects are serialised into JSON using the exact property names. We saw how we can use the JsonProperty to control this for individual properties on our classes, and we then looked at how we can create a contract resolver to instruct JSON.NET to convert the property names on serialisation.
The accompanying code can be downloaded from:
Hi,
Thanks for the code on fixing the casing. I turned it around to be a blacklist approach rather than whitelist. By adding the main signalr assembly to the blacklist I still get correct capitalisation for anon and dynamics, which is pretty useful.
Hopefully this is going to be fixed in signalr prior to 1.0?
Hi Daniel,
My initial implementation of this used exactly that blacklist approach but I turned it round for the blog-post as it seemed the (slightly) safer approach 🙂
– Stuart
Hi,
This is awesome! I just ran in to this requirement myself and you've saved me a couple of hours (at least). Thanks for putting this up. 🙂
— Ragesh.
Hi Ragesh,
Glad to hear it helped!
– Stuart
Thanks! Saved me a ton of time. | https://blogs.msdn.microsoft.com/stuartleeks/2012/09/10/automatic-camel-casing-of-properties-with-signalr-hubs/ | CC-MAIN-2018-51 | refinedweb | 1,319 | 55.84 |
.
Tutorial Overview
This tutorial is divided into 6 parts; they are:
- The Problem with Text
- What is a Bag-of-Words?
- Example of the Bag-of-Words Model
- Managing Vocabulary
- Scoring Words
- Limitations of Bag-of-Words
Need help with Deep Learning for Text Data?
Take my free 7-day email crash course now (with code).
Click to sign-up and also get a free PDF Ebook version of the course.
Start Your FREE Crash-Course Now bag-of-words model, or BoW for short, is a way of extracting features from text for use in modeling, such as with machine learning algorithms.
The approach is very simple and flexible, and can be used in a myriad of ways for extracting features from documents.
A bag-of-words is a representation of text that describes the occurrence of words within a document. It involves two things:
- A vocabulary of known words.
- A measure of the presence of known words.
It is called a “bag” of words, because any information about the order or structure of words in the document is discarded. The model is only concerned with whether known words occur in the document, not where in the document. in all documents, so that the scores for frequent words like “the” that are also frequent across all documents are penalized.
This approach to scoring is called Term Frequency – Inverse Document Frequency, or TF-IDF for short, where:
- Term Frequency: is a scoring of the frequency of the word in the current document.
- Inverse Document Frequency: is a scoring of how rare the word is across
- Bag-of-words model on Wikipedia
- N-gram on Wikipedia
- Feature hashing on Wikipedia
- tf–idf on Wikipedia
Books
- Chapter 6, Neural Network Methods in Natural Language Processing, 2017.
- Chapter 4, Speech and Language Processing, 2009.
- Chapter 6, An Introduction to Information Retrieval, 2008.
- Chapter 6, Foundations of Statistical Natural Language Processing, 1999.. article, thanks for keeping it concise and still easy to understand and read.
Thanks Samuel.
great read and good references.
Thanks!
It is really a gentle intro.
I hope it helped.
Very helpful and clear step by step explanation.
Thanks.
Fatma
Thanks.
Hi Jason,
Great article! So, since using Bag-of-Words does not take into account the relation between words or word order. Does transferring the Bag-of-Words model into CNN could tackle the problem and increase the prediction accuracy? I’ve been searching for the article of implementing BOW + CNN for text classification but no luck so far.
Thank you
No. But you could use a word embedding and an LSTM that would learn the relationship between words.
If I understood it correctly, the purpose of word hashing is to easily map the value to the word and get to easily update the count. My question is, would it be easier if I just use a dictionary instead of implementing word hashing?
A dictionary of what?
Note that in Python, a dictionary IS an implementation of a hash table. You’ll still need to decide what the words map to, though, and I think the idea with word hashing is that each words maps to its own hashed value. It might be helpful to have a dictionary mapping each word to its own hashed value, if lookups are quicker than your hash function and memory is not a limitation, but you can’t really *replace* a hash function with a dictionary.
This would be a set.
Thank you for article
i dont actually understand what bag of words is after reading
1) The binary vector is the ready BOW model output?
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
2) How would it look like if we have more than one occurrence of a word?
[1, 1, 2, 1, 1, 1, 0, 0, 0, 0] (not a strict example but suppose “the” was twice in the doc)
3) I dont understand why we cant put bag of words into rnn models? Into lstm for example
The representation of a document as a vector of word frequencies is the BoW model.
You can choose how to count, either exists/not-exists, or a count, or something else.
We can plug words into RNNs, often we use a word embedding on the front end to get a more distributed representation of the words:
Does that help Georgy?
Hello! Thank you for your illustration. We are doing a project of music genre classification based on the song lyrics. However, due to the license issue we only obtained the lyrics in a bag-of-words format and couldn’t access the full lyrics. We are trying to use TFIDF, in combination of bag-of-words model. However, in our case we couldn’t get document vectors since we don’t have information of complete sentences. Do we need to get the full lyric texts to do the training? Or is it sufficient to implement the model with the data we have right now? Thank you very much!
See how far you can get with BoW. To use the embedding/LSTM you will need the original docs.
Say I have 10 documents. After removing stop words and stemming etc. I have 50 word vocabulary. My each document would be a vector of 50 tf-idf values which I will model using the dependent variable. That means my modeling data has 10rows*50 features + 1 dependent column..And each cell holds the tf-idf of that vocabulary word. Is this right approach?
Also, tf-if is a value is a function the term and document and all the documents., Since tf comes from what is the term and what is it’s frequency in a given document…And idf comes from what is that term’s frequency in the overall set of all documents.
Is this understanding right?
Or is tf-idf …After being computed….is summarized at a term level or a document level??
Yes, it is terms described statistically within and across documents in the corpus.
Hi, DR. Jason,
I have two questions, I am seeking for help:
1. I saw something called Term Document Matrix (TDM) in R is it the same thing as Bag-of-Words in Python?
2. I read from one of your posts about Bag-of-Words result in a sparse vector I would like to know if after having the sparse vector is necessary to convert them in a dense vector before using whit machine learning algorithms.
Best Regards
I don’t know about TDM sorry.
No need to convert to dense.
Understood. Thanks.
Hi. I just want to ask if I can use the Bag Of Words Model in filtering word. For example, I got the tweets from Twitter, then I need to filter those tweets which I will consider as relevant data. And those filtered data will be used for classification.
I need your help about this. Thank you in advance.
Sorry, I don’t have an example of text filtering, I cannot give you good advice.
Hey Dr. Jason,
thank you so much.
It is really a gentle and great introduction.
Thanks!
You have mentioned this:
This results in a vector with lots of zero scores, called a sparse vector or sparse representation.
But in Google’s ML Crash Course they have mentioned this:
*.
Link:
Sure. It is saying we don’t save the zeros when using a sparse coding method.
You can learn more here:
Hi Jason, excellent article. I’m trying to categorize Tweets based on topics. Ex. tweets with amazon get placed into one cluster, and tweets with netflix get put into another cluster. Say there are 3 topics, A, B, C. My incoming stream of tweets is ABABAACCABA etc. I just need to cluster these into their respective groups. I’m using Spark Streaming, and the StreamingKMeans model to do this.
How can I vectorize tweets such that those vectors when predicted on by the K-Means model, get placed in the same cluster
Sorry, I don’t have examples of working with streaming models.
Hi Jason,
How can you model a system where you have a collection of documents mapped to some labels, and some unlabelled examples.
Document label
D1 —- c1
D2 —- c2
D3 —- c3
.
.
.
.
.
Dk —– c1
Two questions here:-
Q).
Q2..
Sorry, I don’t have examples of semi-supervised learning.
Hi, I followed the tutorial and Now I have a model which I trained using Bag of Word,
What I did was converted my text into Sparse Matrix and trained the model. It is giving 95 percent accuracy but now I am unable to predict a simple statement using the model.
This is my code –
I have a data frame with 2 classes labels and body.
# using bag of word model for the same
cout_vect = CountVectorizer()
# Convert from object to unicode
final_count = cout_vect.fit_transform(df[‘body’].values.astype(‘U’))
#model
# Using a classifier for the bag of word representation
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
X_train, X_test, y_train, y_test = train_test_split(final_count, df[‘label’], test_size = .3, random_state=25)
model = Sequential()
model.add(Dense(264, input_dim=X_train.shape[1], activation=’relu’))
model.add(Dense(128, activation=’relu’))
model.add(Dense(64, activation=’relu’))
model.add(Dense(32, activation=’relu’))
model.add(Dense(16, activation=’relu’))
model.add(Dense(8, activation=’relu’))
model.add(Dense(3, activation=’softmax’))
# Compile model
model.compile(loss=’categorical_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])
y_train = np_utils.to_categorical(y_train, num_classes=3)
y_test = np_utils.to_categorical(y_test, num_classes=3)
model.fit(X_train, y_train, epochs=50, batch_size=32)
model.evaluate(x=X_test, y=y_test, batch_size=None, verbose=1, sample_weight=None)
Now I want to predict this statement using my model. How to do this
x = “Your account balance has been deducted for 4300”
model.predict(x, batch_size=None, verbose=0, steps=None)
Well done.
To make a prediction you must prepare the input in the same way as you did the training data.
Hi,
I followed this article.I want to ask how can we extract some difficult words(terminologies) from l
different document and store it in vector to make it as the vocabulary for the machine.Will BoW be better solution or should i look for something else.
Not sure I follow.
Bag of words and word2vec are two popular representations for text data in machine learning.
Really fantastic article. Excellent clarity. Thanks Jason!
Thanks Mike, glad it helped.
Thanks for this informative article. I wonder
What is the difference between BOW and TF?
Are these same things?
BOW and TF?
Bag of words and term frequency?
Same generally, although the vector can be filled with counts, binary, proportions, etc.
Hey, thanks for the article, Jason. Very informative and concise.
Thanks, I’m glad it helped.
thanks for the article, Jason.
i have a question.
if I want to do a classification task with TFIDF vector representation, should that technique representation be carried out on all datasets (training data + test data) first, or done separately, on the training data first then then do the test data?
Good question.
Prepare the vocab and encoding on the training dataset, then apply to train and test.
Dear Jason,
I’m thinking of writing a thesis about using text from a social media platform(twitter or facebook) to measure the social influence of people(maybe just influencers) on purchase behavior of software licences on mobile apps. Do you think the the Bag-of-Words Model is a good fit, or would you suggest other text analysis models?
If you have any recommendations please!
Thanks in advance,
Youri
I recommend testing a suite of representations and models in order to see what works best for your specific prediction problem.
Thanks, Jason.
I am a reader from China, and you are a minor celebrity due to your concise and helpful explanation on those machine learning topics. Thanks for your works.
One of my personal question is how long did it take for you to compose of this piece of article?
Thanks!
I try to write one tutorial per day. Usually, I can write a tutorial in a few hours.
Really great article! Thanks for sharing!
Thanks, I’m glad it helped! | https://machinelearningmastery.com/gentle-introduction-bag-words-model/ | CC-MAIN-2019-09 | refinedweb | 2,049 | 67.04 |
In the comments on the entry on spring effects under third-party LAFs, Chris has asked if it would be possible to make this functionality available under the platform's system look and feel. My first response mentioned one possible way to do this - download the sources for JDK, create a custom Ant build script to inject this functionality into core LAFs (such as Windows or Ocean), take the resulting jar and use the boot classpath switch to have JVM load this jar before the classes in rt.jar.
Now, this approach has a few disadvantages:
One big advantage of this approach is that the existing application code (call to UIManager.setLookAndFeel) doesn't need to be changed, since the class name of the main LAF class remains the same.
UIManager.setLookAndFeel
Well, it so happens that the above approach is not the only way to tackle the request (and no, it's not an April Fools joke). The new laf-widget-windows subproject provides another way to inject widgets, transition layout and image ghosting effects into the core look and feels.
First, here are two screenshots of a sample application under a widgetized Windows look and feel, one under Windows Vista and another under Windows XP. Note the menu search widget, tab overview widget, password strength checker widget and lock widget on uneditable text components:
Here are two Flash movies showing the widgets and the transition
layout in action (under Windows Vista and Windows XP):
Here are two Flash movies showing the ghost effects (rollover icon ghosting and button press ghosting) under Windows Vista and Windows XP:
Here is the code for the only class in this project:
package org.jvnet.lafwidget.windows;
public class WindowsLookAndFeel extends
com.sun.java.swing.plaf.windows.WindowsLookAndFeel {
}
All the rest is taken care of by the custom Ant tasks. This way, all the disadvantages of the first approach are addressed - the code is not tied to a particular implementation of the core LAF, the binaries size is kept to the minimum, and you don't need to change the boot classpath. On the other hand, you now have to use the org.jvnet.lafwidget.windows.WindowsLookAndFeel class as the parameter to pass to UIManager.setLookAndFeel.
org.jvnet.lafwidget.windows.WindowsLookAndFeel
Feel free to download the binaries and leave comments..
What is it with people on Swing forums? Need help with Swings, help required in Swings, i am new to Swings... Searching for the "new to swings" on Google produces 14 results. Searching for the "new to delphis" produces zero. "New to cocoas" - zero. "New to MFCS" produces this, but apparently that's how it's spelled. Even "new to javas" produces this which is just a part of "new to javas cript". Sighs....
So, i'm reading a book and in one of the first chapters the authors try to put some reasoning behind an awkward API:
This process means that the last transformation command called in your program is actually the first one applied [...]. Thus, one way of looking at it is to say that you have to specify the matrices in the reverse order. Like many other things, however, once you've gotten used to thinking about this correctly, backward will
seem like forward.
Here, instead of acknowledging that the API implementation actually dictates the API usage, the authors try to blame the API users for being too dumb to grasp its beauty. It's not API, stupid, it's you not thinking about this correctly :) (all the screenshots and the Excel 2007 spreadsheet are available right here):.
This is the third part in series about ghosting image (aka spring) effects on Swing buttons.
Since then (last November) the implementation has been improved to provide the following:
JButton
JToggleButton):
main()
Ant.
augment-*.bat
update().
The first Desktop Matters is officially over (although there still may be a few people still talking in the conference room as we speak...) First of all, many thanks and congratulations to Ben and Dion for organizing this (and making it take place 10 minutes away from where i live).
In addition, it was great finally seeing all the real people behind the java.net (and jroller) blogs (sometimes you get a weird feeling that perhaps some of them are not real, but maybe it's just me :) Thanks for everybody who came to chat, inquire about Substance and other projects and for listening to my presentation. The slides are available in the following formats:
Note that i didn't have enough time for all the slides, so even you listened to me live, there are additional 8-9 slides that go deeper into the implementation of the ghosting effects outside the button borders. And now that it's over, finally some time for a little entertainment.... | http://weblogs.java.net/blog/kirillcool/archive/2007/03/index.html | crawl-001 | refinedweb | 801 | 65.66 |
Hello.On Fri, Sep 5, 2008 at 10:59 PM, Willy Tarreau <w@1wt.eu> wrote:> Hello,>> On Fri, Sep 05, 2008 at 11:27:00AM +0300, Nir Tzachar wrote:>> Changes:>> 1) Fixed segfaults in help window.>> 2) Removed the instructions window, made the instructions appear as a button>> which displays a popup window.>> 3) Added hot keys support. As ncurses does not support several colors inside>> a menu, keys are highlighted using "()".>> 4) Optimized for 80x24 terminals.>> 6) Fixed zconf.y to use _menu_init>> 7) added nconfig to "make help">> 8) Misc fixes.>>>> Comments are appreciated.>> OK, I've just tried it. Here are the first comments I can make :>> - colors are too dark. Cyan on black is barely readable, red on black is> almost unreadable and blue on black is not readable at all, I have to> switch off the light to read it. Most often you'll see light shades of> grey (even white) in interfaces because it's hard to see dark shades,> and bright flashy letters would dazzle and be seen as fuzzy. Many colors> are perfectly readable on while or even light grey (except yellow and> sometimes cyan). Blue backgrounds were often used under DOS and were> OK with almost all colors except red (well-known eye focus problem).> But there was a trick, pixels were very large in 640x200, nowaydays> we have small pixels and letters are not much readable anymore on blue> backgrounds. For your tests, you can try to load> xterm -bg <color> -fg <color> and ensure that you're using a medium> font (tickness of 1-pixel).The thing with colors is that they are very personal... The colors Ihave work great on my terminals. I don't think I can come up with onescheme which looks nice to everybody, hence the support for colorschemes. If you can come up with a color scheme which works gr8 foryou, I'll be happy to add it. If you are interested, check theINIT_PAIR macros of the patch.> - pressing arrows too fast regularly escapes (probably because of the> ESC prefix, I don't know). This is rather strange, because no other> application does this to me.I cannot reproduce this. What terminal emulator are you using, andwhich ncurses version? Also, can you please send me the terminalemulator config file?> Is there a specific initialization> sequence with ncurses to state that arrows should return special codes> instead of the ESC prefix ? (I have no idea)Yes. You need to specify you want to get keypad events, otherwise theyjust appear as ESC.> - entering text in boxes (eg: local version) does not move the cursor,> it remains at the beginning of the line. If I press any arrow, the> box immediately closes (most likely the Esc prefix again).Fixed.> - in the input boxes, spaces are missing aroung the title, which touches> the frame (eg: Local version again).Fixed.> - in "instructions", it's not explained how to leave that box. I found> both Enter and Esc to work, but a last line with a small message would> be better.Done.> - I noticed I was tempted a lot to press "?" to get help, but the key is> not bound. It would be nice to have it bound to Help since make oldconfig> and menuconfig to both report help that way.It was supposed to work, I mistyped '?' with ':' . Fixed.> - I'm not convinced that the parenthesis around hotkeys make the menu> that much readable, especially when there are lots of short words or> even acronyms. Eg :> [ ] (U)TS namespace> [ ] (I)PC namespace> [ ] (U)ser namespace (EXPERIMENTAL)> [ ] (P)ID Namespaces (EXPERIMENTAL)I agree, but could not come up with any other visible mark to note the hotkey.> I don't know if there is something such as a bold attribute in ncurses,> it would make sense to use it IMHO because you don't force a color on> people's terms, you rely on the style which works well for them.There is a bold attribute, but you cannot set it for a single letterof a menu item, as far as I know.> I'm sorry I don't go further for now, the arrows causing frequent exits is> too bothersome, I've started it about 30 times just for this report, it's> too hard to navigate. I hope that the points above are already helpful.Thanks for the input. I would really like to solve the issue you havewith arrow keys. Can you also send a trace of key presses which causeyou to exit, and which window is active?Cheers. | https://lkml.org/lkml/2008/9/6/14 | CC-MAIN-2019-22 | refinedweb | 763 | 73.07 |
$ 39.99 US
25.99 UK
P U B L I S H I N G
E x p e r i e n c e
D i s t i l l e d
Angular 2 Essentials
Your quick, no-nonsense guide to building real-world apps
with Angular 2
Sa
m
pl
C o m m u n i t y
Pablo Deeleman
Angular 2 Essentials
Angular 2
Essentials
ee
Pablo Deeleman
After getting his BA (Hons) degree in marketing and moving through different
roles in the advertising arena, he took his chance and evolved into a self-taught,
passionate UX designer and frontend developer with a crunch for beautifully crafted
CSS layouts and JavaScript thick clients, having produced countless interactive
designs and web desktop and mobile applications ever since.
During these years, he has fulfilled his career as both an UX designer and frontend
developer by successfully leading Internet projects for a wide range of clients and
teams, encompassing European online travel operators, Silicon Valley-based start-ups,
international heavy-traffic tube websites, global banking portals, or gambling and
mobile gaming companies, just to name a few. At some point along this journey, the
rise of Node.js and single-page-application frameworks became a turning point in his
career, being currently focused on building JavaScript-driven web experiences.
After having lived and worked in several countries, Pablo Deeleman currently lives
in Barcelona, Spain, where he leads the frontend endeavor in the Barcelona studio
of Gameloft, the world leader in mobile gaming, and the home of internationally
acclaimed games, such as Despicable Me: Minions Rush and Asphalt 8.
When not writing books or taking part in industry events and talks, he spends most
of his time fulfilling his other passion: playing piano and guitar.
Preface
Over the past years, Angular 1.x has became one of the most ubiquitous JavaScript
frameworks for building cutting edge web applications, either big or small. At
some point, its shortcomings with regard to performance and scalability became too
prominent as soon as applications grew in size and complexity. Angular 2 was then
conceived as a full rewrite from scratch to fulfill the expectations of modern developers,
who demand blazing fast performance and responsiveness in their web applications.
Angular 2 has been designed with modern web standards in mind and allows full
flexibility when picking up your language of choice, providing full support for ES6
and TypeScript, but working equally well with today's ES5, Dart, or CoffeeScript.
Its built-in dependency injection functionalities let the user build highly scalable
and modular applications with an expressive and self-explanatory code, turning
maintainability tasks into a breeze, while simplifying test-driven development to
the max. However, where Angular 2 stands out is when it shows off its unparalleled
level of speed and performance, thanks to its new change detection system that is up
to five times faster than its previous incarnation. Cleaner views and an unsurpassed
standards-compliant templating syntax compound an endless list of powerful
features for building the next generation of web mobile and desktop apps.
Angular 2 is here to stay and will become a game changer in the way modern web
applications are envisioned and developed in the years to come. However, and due
to its disruptive design and architecture, learning Angular 2 might seem a daunting
effort to newcomers.
This is where this book comes inits goal is to avoid bloating the reader with
API references and framework descriptions, but to embrace a hands-on approach,
helping the reader learn how to leverage the framework to build stuff that matters
right from day one. This is learning by doing right from the start.
Preface
This book aims to give developers a complete walkthrough of this new platform and
its TypeScript-flavored syntax by building a web project from back to forth, starting
from the basic concepts and sample components and iterating on them to build up
more complex functionalities in every chapter until we launch a complete, tested,
production-ready sample web application by the end of the book.
Preface
Chapter 10, Unit Testing in Angular 2, will guide the reader through the steps required
for implementing a sound testing foundation in our application, and the general
patterns for deploying unit tests on components, directives, pipes, routes, and services.
[1]
The defining traits of Angular 2 go beyond the concept of just being a mere web
components framework, since its features encompass pretty much everything you
need in a modern web application: component interoperability, universal support
for multiple platforms and devices, a top-notch dependency injection machinery,
a flexible but advanced router mechanism with support for decoupling and
componentization of route definitions, advanced HTTP messaging, and animation or
internationalization, just to name a few.
In this chapter, we will:
Learn how to set up our code environment to work with Angular 2 and
TypeScript
Build our very first Angular 2 web component and learn how to embed it on
a web page
A fresh start
As mentioned before, Angular 2 represents a full rewrite of the Angular 1.x
framework, introducing a brand new application architecture completely built from
scratch in TypeScript, a strict superset of JavaScript that adds optional static typing
and support for interfaces and decorators.
In a nutshell, Angular 2 applications are based on an architecture design that
comprises trees of web components interconnected between them by their own
particular I/O interface. Each component takes advantage under the covers of a
completely revamped dependency injection mechanism. To be fair, this is a simplistic
description of what Angular 2 really is. However, the simplest project ever made in
Angular is cut out by these definition traits. We will focus on learning how to build
interoperable components and manage dependency injection in the next chapters,
before moving on to routing, web forms, or HTTP communication. This also explains
why we will not make explicit references to Angular 1.x throughout the book.
Obviously, it makes no sense to waste time and pages referring to something that
will not provide any useful insights on the topic, besides the fact we assume that you
might not know about Angular 1.x, so such knowledge does not have any value here.
[2]
Chapter 1
Shadow DOM: This provides a sandbox to encapsulate the CSS layout rules
and JavaScript behaviors of each custom element, good news is that Angular 2 gives you the toolset required for delivering this
very same functionality, so we can build our own custom elements (input controls,
personalized tags, and self-contained widgets) featuring the inner HTML markup
of our choice and a very own stylesheet that does not affect (nor is impacted) by the
CSS of the page hosting our component.
[3]
[4]
Chapter 1
Installing dependencies
Our first requirement will obviously be to install Angular 2 onto our workspace,
including its own peer dependencies. The Angular 2 team has made a great effort to
ensure the installation is modular enough to allow us to bring only what we need,
becoming our projects more or less lean depending on the requirements.
At the time of writing, these are all the different third-party libraries that are required
as peer dependencies in an Angular 2 project, apart from the Angular 2 module itself:
zone.js, a polyfill for the Zone specification that is used to handle change
[5]
These dependencies may evolve without prior notice so please refer to the GitHub
repository for the most up-to-date list of requirements.
You will be probably surprised by the amount of libraries that
Angular 2 does need and the fact that these dependencies are
not part of the Angular bundle itself. This is because these
requisites are not specific to Angular 2, but of a vast majority of
modern JavaScript applications nowadays.
With all these dependencies and third-party libraries in mind, you can run the
following set of bash commands in your terminal console, once you have created a
folder for the project we will cover in this book:
$ mkdir angular2-essentials
$ cd angular2-essentials
$ npm init
$ npm install angular2 es6-shim reflect-metadata rxjs zone.js --save
Apart from the dependencies enlisted previously, we will also need to install
the SystemJS universal module loader package in order support module loading
between code units once transpiled into ES5. SystemJS is not the only option
available for managing module loading in Angular 2. In fact we can swap it for other
module loaders such as WebPack (), although all
examples provided in this book make use of SystemJS for handling code injection.
We will install SystemJS, flagging it as a development dependency by executing the
following command:
$ npm install systemjs --save-dev
Last but not least, we will also install Bootstrap in our application so that we can
easily craft a nice UI for the example application we will build incrementally in each
chapter. This is not an Angular 2 requirement, but a particular dependency of the
project we will carry out throughout this book.
$ npm install bootstrap --save
The installation can throw different alerts and warnings depending on the versions
of each peer dependency required by Angular 2 at this moment in time, so in case
of issues I strongly recommend to fetch the latest version of the package.json file
available at this book's code repository:.
[6]
Chapter 1
Download the file to your directory workspace and run npm install. NPM will find
and install all the dependencies for you automatically.
Mac OS users who have not claimed ownership rights on the npm
directory located at /usr/local/bin/npm (or /usr/local/npm
for those users on OS versions prior to Mac OS El Capitan) might
need to execute the npm install with sudo privileges.
Installing TypeScript
We have now a complete set of Angular 2 sources and their dependencies, plus the
Bootstrap module to beautify our project and SystemJS to handle module loading
and bundle generation.
However, TypeScript is probably not available on your system yet. Let's install
TypeScript and make it globally available on your environment so that we can
leverage its convenient CLI to compile our files later on:
$ npm install -g typescript
Great! We're almost done. One last step entails informing TypeScript about how we
want to use the compiler within our project. To do so, just execute the following onetime command:
$ tsc --init --experimentalDecorators --emitDecoratorMetadata --target
ES5 --module system --moduleResolution node
[7]
Simple, right? The set of properties included in our config manifest is self-descriptive
enough, but we can highlight three interesting properties. They are as follows:
rootDir: This points to the folder the compiler will use to scan for
outDir: This defines where the compiled files will be moved unless we
define our own output path by means of the --outDir parameter in the
command line, the compiler will default to the built folder created at
runtime in the same location where the tsconfig.json file lives.
sourceMap: This sets the source code mapping preferences to help debugging.
Toggle its value to true if you want source map files to be generated at runtime
to back trace the code to its source through the browser's dev tools in case
exceptions arise.
Besides these properties, we also can see that we have marked the node_modules
folder as excluded, which means that the tsc command will skip that folder and all
its contents when transpiling TypeScript files to ES5 throughout the application tree.
I would encourage you to refer to the TypeScript compiler wiki
at
Compiler-Options for a full rundown of options available in
the compiler API.
[8]
Chapter 1
First, we install the typings tool globally and then we leverage the typings CLI to
install the es6-shim types definition file into our project, creating the typings.json
file that will store the references to the source origin for all type definition files we
will install now and later on. A new folder named typings is created and it contains
the definition files we require. Without them, basic ES6 features like the new
functional methods of the Array class would not be available.
Before moving forward, we need to tackle one more step regarding the TypeScript
typings. When installing type definition files, two faade files are generated by the
CLI: typings/main.d.ts and typings/browser.d.ts. However, only one should
be exposed to the TypeScript compiler. Otherwise, it will raise an exception after
finding duplicated type definitions. Since we are building frontend applications, we
will stick to browser.d.ts and exclude main.d.ts and its linked definition files by
marking it as excluded at tsconfig.json:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es5",
[9]
On the other hand, it is actually recommended to exclude the typings folder from
your project distribution by including it in your .gitignore file, same as we usually
do with the node_modules folder. You only want to include the typings.json
manifest when distributing your app and then have all the installation processes
handled by npm, so it is very convenient to include the type definition files installation
as an action handled by the postinstall script in the package.json file. This way,
we can install the npm dependencies and the definition files in one shot. The code is as
follows:
"scripts": {
"typings": "typings",
"postinstall": "typings install"
},
When taking this approach, the typings package should be included in the
package.json as part of the development dependencies. Thus, reinstall it with the
--save-dev flag. Again, please refer to the book code repository at GitHub to fetch
the latest version of the package.json file for this chapter.
Hello, Angular 2!
With the Angular 2 library bundle in place and full support for TypeScript now
available, the time has come to put everything to the test. First, create and empty file
named hello-angular.ts (.ts is the natural extension for TypeScript files) at the
root of our working folder.
[ 10 ]
Chapter 1
Now, open that file and write the following at the top:
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
We have just imported the most basic type and function we will need to scaffold a
very basic component in the next section. The importing syntax will be familiar to
those who are already familiar with ECMAScript 6. For those who are not familiar
with its code paradigm, don't worry. We will discuss more on this in Chapter 2,
Introducing TypeScript.
TypeScript classes
Let's now define a class:
class HelloAngularComponent {
greeting: string;
constructor() {
this.greeting = 'Hello Angular 2!';
}
}
ECMAScript 6 (and TypeScript as well) introduced classes as one of the core parts of its
building blocks. Our example features a class field property named greeting typed as
string, which is populated within the constructor with a text string, as you can see in
the preceding code. The constructor function is called automatically when an instance
of the class is created, and each and every property (and functions as well) should be
annotated with the type it represents (or returns in the case of functions).
Do not worry about all this now. Chapter 2, Introducing TypeScript, will give you the
insights you need to better understand the mechanics of TypeScript. Now, let's focus
on the actual layout of our component. You have probably noticed the name structure,
which conforms to another common coding convention in Angular 2. We define each
and every class in Pascal casing by appending a suffix pointing out its type (will it be a
component, directive, pipe, and so on), which is Component for this case.
[ 11 ]
Chapter 1
A new hello-angular.js file will show up within the built directory (or the path
you have defined in the outDir property at tsconfig.json), and it will contain
an ECMAScript 5 version of the TypeScript code we just built. This file already
contains some functional code to implement support for the Metadata decorator
we configured.
Please note the --watch flag in our command. This parameter
informs the compiler that we want the compilation to be
automatically triggered again upon changing any file.
Disregard the flag when you just need to compile your stuff
once and do not need to watch the code for changes.
Our component is looking better by the minute and now we are in a good state to
start using it, but we still need to embed it somewhere in order to see it live. It's time
to define the HTML shell or web container where it will live.
[ 13 ]
This is the most basic, barebones version of an HTML container for an Angular 2
application we can come up with. This is great because most of the presentation logic
and dependency management will be handled by our component itself.
However, two things catch our attention in this template. I am obviously referring
to the script includes in the previous HTML code. The first script tag introduces
support for the SystemJS module loader in this project. As we pointed out in
the previous section, SystemJS is an open source universal module loader, and
since both the Angular 2 library (included in the following script tags block) and
our own Angular 2 component make use of ES6 module loading functionalities,
we need something in place to ensure that both scripts can actually expose and
require modules. Then, we include a reference to the RxJS bundle, which is a core
dependency of the Angular main bundle that has not been integrated in the main
package in order to keep it as lean as possible. Last but not least, we find the Angular
2 polyfills and the Angular 2 main bundle itself.
In the next JavaScript block of the previous code, we can find the SystemJS
configuration block. We basically configure a package named built whose modules
conform to the System.register polyfill module format. An additional property
allows us to refer to those modules without pointing out the .js file extension, as we
will see shortly.
Do not try to reshuffle the sorting layout of these code blocks
unless you want to face unexpected exceptions.
[ 14 ]
Chapter 1
Then, you can run a web server with live-reloading functionality by running the
following command in a terminal shell after moving into your project folder:
$ lite-server
After executing the preceding command, a browser window will be fired, pointing
to your working directory. Please refer to the NPM module official repository
in order to check out all the options available (
lite-server).
It is actually recommended to install the lite-server package
paired up with the typescript and concurrently packages,
all of them as development dependencies installed with the
--save-dev flag. This way, you can run the TypeScript compiler
in watch mode and the local server at the same time with a single
command that can be wrapped in the start script of package.
json. Then, you can start building stuff right away by accessing
your working folder and executing npm start. This book's code
repository in GitHub implements this approach, so feel free to
borrow the package.json example for your convenience.
How cool is that? Now, we can create our own custom elements that render
whatever we define in them. Let's bring up the page in our web server and see it in
action by going to (or whatever host and port your local
web server operates in).
Unfortunately, if we reload the browser, nothing will happen and we will only see
a blank page with nothing in there. This is because we still need to bootstrap our
component to instantiate it on the HTML page.
Let's return to our component file hello-angular.ts and add a final line of code:
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
@Component({
selector: 'hello-angular',
template: '<h1> {{greeting}} </h1>'
})
class HelloAngularComponent {
greeting: string;
constructor() {
this.greeting = 'Hello Angular 2!';
}
}
bootstrap(HelloAngularComponent); // Component is bootstrapped!
[ 16 ]
Chapter 1
The bootstrap command instances the controller class we pass as an argument and
uses it to lay out a complete application scaffold. Basically, the bootstrap method
kickstarts the following actions:
Analyzes the component configured as its first argument and checks its type.
Searches the DOM after an element with a tag matching the component
selector.
Creates a child injector that will handle the injection of dependencies in that
component and all the child directives (including components, which are
directives too) that such a component might host, in a very similar way a tree
has ramifications.
It creates a new Zone. We will not cover Zones in this book, but let's just say
that Zones are in charge of managing the change detection mechanism of
each instance of a bootstrapped component in an isolated fashion.
The component controller class is instantiated straight away and the change
detection machinery is fired. Now that we have the Shadow DOM placeholders
in place, data providers are initiated and data is injected where required.
Later in this book, we will cover how we can leverage the bootstrap command
to display debugging information or how application providers can be globally
overridden throughout the whole application so the dependency injector baked in
Angular 2 picks the right dependency where required.
[ 17 ]
Hopefully, you are running the TypeScript compiler in watch mode. Otherwise,
please execute the tsc command to transpile our code to ES5 and reload the browser.
We can delight ourselves with the rendered content of our very first Angular 2
component. Yay!
[ 18 ]
Chapter 1
Sublime Text 3. Please refer to this page to learn how to install the plugin and all
the shortcuts and key mappings..
[ 19 ]
Atom
Developed by GitHub, the highly customizable environment and ease of installation
of new packages has turned Atom into the IDE of choice for a lot of people. It is
worth mentioning that the code examples provided in this book were actually coded
using Atom only.
In order to optimize your experience with TypeScript when coding Angular 2.
[ 20 ]
Chapter 1.
[ 21 ]
Chapter 1
Now, you can launch the build process and watch the file changes by executing the
following command:
$ gulp watch
Improving productivity
Sometimes, we need some helpers to boost our focus, especially when we deal
with too abstract stuff that requires additional attention. A widely accepted
approach is the Pomodoro technique, in which we put together a task list and then
split the deliverables into to-do items that won't require us more than 25 minutes to
accomplish. When we pick any of those to-do items, we focus under distraction-free
mode on its delivery for 25 minutes with the help of a countdown timer. You can
grab more information about this technique at.
In this book, we are going to build a major component that represents this
functionality and fill the component with additional functionalities and UI items
wrapped inside their own components. To do so, we will use the Pomodoro
technique, so let's start by creating a Pomodoro timer.
Our new component is, in fairness, not that much different from the one we previously
had. We updated the names to make them more self-descriptive and then defined
two property fields, statically typed as numbers in our PomodoroTimerComponent
class. These are rendered in the contained view, wrapped inside an <h1> element.
Now, open the index.html file and replace the <hello-angular></hello-angular>
custom element with our new <pomodoro-timer></pomodoro-timer> tag. You can
duplicate index.html and save it under a different name if you do not want to loose
the HTML side of our fancy "Hello World" component.
A note about naming custom elements
Selectors in Angular 2 are case sensitive. As we will see later in this
book, components are a sub set of directives that can support a wide
range of selectors. When creating components, we are supposed to
set a custom tag name in the selector property by enforcing a dashcasing naming convention. When rendering that tag in our view, we
should always close the tag as a non-void element. So <customelement></custom-element> is correct, while <customelement /> will trigger an exception. Last but not least, certain
"common" camel case names might conflict with the Angular 2
implementation, so avoid names like AppView or AppElement.
You will want to update the reference in your System.import(...) block to point to
our new component as well:
System.import('built/pomodoro-timer')
.then(null, console.error.bind(console));
[ 24 ]
Chapter 1
If you bring up a browser window and load this file, you will see a representation
of the numbers defined in the component class. But(): void {
if (--this.seconds < 0) {
this.seconds = 59;
if (--this.minutes < 0) {
this.minutes = 24;
this.seconds = 59;
}
}
} that we will cover in more detail in Chapter 2,Pomodoro();
setInterval(() => this.tick(), 1000);
}
resetPomodoro(): void {
this.minutes = 24;
[ 25 ] gets on the
way. We need to provide some sort of interactivity so the user can start, pause, and
resume the current pomodoro timer.
[ 26 ]
Chapter 1
In the meantime, just focus on the fact that we introduced a new chunk of HTML that
contains a button with an event handler that listens to click events and executes the
togglePause method upon clicking. This (click) attribute is something you might
not have seen before, even though it is fully compliant with the W3C standards.
Again, we will cover this in more detail in Chapter 3, Implementing Properties and Events
in Our Components. Let's focus on the togglePause method and the new buttonLabel
binding. First, let's modify our class properties so that they look like this:
class PomodoroTimerComponent {
minutes: number;
seconds: number;
isPaused: boolean;
buttonLabel: string;
// Rest of code will remain as it is below this point
}
We introduced two new fields. First is buttonLabel that contains the text that
will be later on displayed on our newly-created button. isPaused is a newlycreated variable that will assume a true/false value, depending on the state of our
timer. So, we might need a place to toggle the value of such a field. Let's create the
togglePause method we mentioned earlier:
togglePause(): void {
this.isPaused = !this.isPaused;
// if countdown has started
if (this.minutes < 24 || this.seconds < 59) {
this.buttonLabel = this.isPaused ? 'Resume' : 'Pause';
}
}
By executing togglePause every time, we reset the Pomodoro to make sure that
whenever the Pomodoro reaches a state where it requires to be reset, the countdown
behavior will switch to the opposite state it had previously. There is only one tweak
left in the controller method that handles the countdown:
private tick(): void {
if (!this.isPaused) {
this.buttonLabel = 'Pause';
if (--this.seconds < 0) {
this.seconds = 59;
if (--this.minutes < 0) {
this.resetPomodoro();
}
}
}
}.
Chapter 1
5, Building an Application with Angular
2 stylesheet we downloaded through NPM when installing the
project dependencies. Open pomodoro-timer.html and add this snippet at the end
of the <HEAD> element:
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/
bootstrap.min.css">
Now, let's beautify our UI by inserting a nice page header right before our
component:
<body>
<nav class="navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<strong class="navbar-brand">My Pomodoro Timer</strong>
</div>
</div>
</nav>
<pomodoro-timer></pomodoro-timer>
</body>
[ 29 ]
Tweaking the component button with a Bootstrap button class will give it more
personality and wrapping the whole template in a centering container and
appending a nice icon at the top will definitely compound up the UI. So let's update
the template in our template to look like this:
<div class="text-center">
<img src="assets/img/pomodoro.png" alt="Pomodoro">
<h1> {{ minutes }}:{{ seconds | number: '2.0' }} </h1>
<p>
<button (click)="togglePause()"
class="btn btn-danger">
{{ buttonLabel }}
</button>
</p>
</div>
For the icon, we picked a bitmap icon depicting a pomodoro. You can use any
bitmap image of your choice or you can just skip the icon for now, even though we
will need an actual pomodoro icon in the forthcoming chapters. This is how our
Pomodoro timer app looks after implementing all these visual tweaks:
[ 30 ]
Chapter 1
Summary
We looked at web components according to modern web standards and how
Angular 2 components provide an easy and straightforward API to build our
own components. We covered TypeScript and some basic traits of its syntax as a
preparation for Chapter 2, Introducing TypeScript. We saw how to set up our working
space and where to go to find the dependencies we need to bring TypeScript into the
game and use the Angular 2 library in our projects, going through the role of each
dependency in our application.
[ 31 ]
Our first component gave us the opportunity to discuss the form of a controller class
containing property fields, constructor, and utility functions, and why metadata
annotations are so important in the context of Angular 2 applications to define
how our component will integrate itself in the HTML environment where it will
live. Now, we also know how to deploy web server tools and enhance our code
editors to make our lives easier when developing Angular 2 apps, leveraging type
introspection and checking on the go. 2 in no time.
[ 32 ]
Stay Connected: | https://www.scribd.com/document/311444338/Angular-2-Essentials-Sample-Chapter | CC-MAIN-2019-39 | refinedweb | 4,890 | 50.16 |
Python Decorator Tutorial – Chaining Decorators, Python Pie Syntax
Keeping you updated with latest technology trends, Join DataFlair on Telegram
1. Python Decorator – Objective
In this Python Decorator tutorial, we will study what is a decorator in Python and why we use a Python Nested Functions. Along with this, we will learn Python Decorators with Parameters and Python Pie Syntax. At last, we will study Chaining Decorators in Python programming language.
In Python, a function is a first-class object. This means that you can pass it around with absolute ease. You can return it, and even pass it as an argument to another. You can also nest a python function inside another.
So, let’s start the Python Decorator Tutorial.
2. What is Python Decorator?
Python Decorator function is a function that adds functionality to another, but does not modify it. In other words, Python Decorator wraps another function. This is like a gift wrapper in real life. Also, this is called metaprogramming, because a part of the program tries to modify another at compile time. In the rest of the lesson, we will see the python syntax of a Python decorator in detail.
This is useful in cases when you want to add functionality to a function, but don’t want to modify it for the same. Let’s take a look.
3. A Simple Python Decorator
Talking about Python decorator for the first time can be confusing. So we begin with a very simple example with no arguments. Take this code.
>>> def decor(func): def wrap(): print("$$$$$$$$$$$$$$$$$$$$$$") func() print("$$$$$$$$$$$$$$$$$$$$$$") return wrap >>> def sayhello(): print("Hello") >>> newfunc=decor(sayhello) >>> newfunc()
$$$$$$$$$$$$$$$$$$$$$$
Hello
$$$$$$$$$$$$$$$$$$$$$$
Now let’s see each part of the syntax one by one. Also, Read Recursion in Python.
a. Python Decorator Function
First, we define a simple function sayhello() that prints out “Hello”. Now, we’ll define the decorator function in Python. You can call this anything; it doesn’t have to be ‘decor’. This is a higher order function. Note that the relative order of these functions does not matter. You could define sayhello() before defining decor(), and it wouldn’t make a difference. Let’s discuss the decor function in detail.
def decor(func):
The first thing to notice here is that it takes a function as an argument. This is the function that we want to decorate. We want to call it func; you may want to call it something else. Inside this function, we nest a function, and we call it wrap(). Again, you can call it anything you want.
b. The nested wrap function
It is inside this function that we put our extra functionality, and also call the function to be decorated.
def wrap(): print("$$$$$$$$$$$$$$$$$$$$$$") func() print("$$$$$$$$$$$$$$$$$$$$$$")
Here, we used some print statements. It could have been anything else too, like an if-block.
Finally, we make the decor() function return the wrap function.
return wrap
Why do we do this? We’ll discuss this further in this lesson.
c. Assigning and Calling
Finally, we assign this Python decorator to a variable and pass the function to be decorated as an argument to the decorating function.
newfunc=decor(sayhello)
Then, we call the function using parentheses after the variable to which we assign the decorators in
python.
newfunc()
However, you can also assign this to the function to be decorated itself. This will reassign it. Let’s see that as well.
>>> def sayhello(): print("Hello") >>> def decor(func): def wrap(): print("$") func() print("$") return wrap >>> sayhello=decor(sayhello) >>> sayhello()
$
Hello
$
Before Proceeding Read Python Functions with Syntax and Examples.
4. Why use a Python Nested Function?
When I was attempting to understand Python decorator, this question totally confused me. Why do we use the wrap function, and then return it? Couldn’t we simply write the code inside the decor function? So I ended up on the interpreter, trying it out.
>>> def decor(func): print("$") func() print("$") >>> def sayhello(): print("Hello")
Here, we wrote the extra functionality right inside our decor() function. Now, let’s try to assign it to a variable.
>>> newfunc=decor(sayhello)
$
Hello
$
Woah. Why did it print it out? This is because decor() calls a function (here, func) instead of returning a value. When we use wrap (or whatever you’d call it), and then return it, we can store it in a variable. Then, we can use that name to call the decorated function whenever we want. Now let’s call the newfunc() function.
>>> newfunc()
Traceback (most recent call last):
File “<pyshell#70>”, line 1, in <module>
newfunc()
TypeError: ‘NoneType’ object is not callable
As you can see, since decor did not return a value, the line of assignment did not assign the decorated function to newfunc. This is why it isn’t callable. So, it is impossible to access this Python decorator again except for the following method:
>>> decor(sayhello)
$
Hello
$
Finally, let’s try calling our original function sayhello().
>>> sayhello()
Hello
Works perfectly. See, decor() did not modify sayhello().
We use the same example everywhere so you can focus on what’s being explained, and not be invested in trying to understand the code.
5. Python Decorator with Parameters
So far, we’ve only seen decorators in python with regular print statements. Now, let’s get into the real thing. To see how decorators fare with parameters, we’ll take the example of a function that divides two values. All that our function does is to return the division of two numbers. But when we decorate it, we add functionality to deal with the situation where the denomination is 0. Watch how.
>>> def divide(a,b): return a/b >>> def decorator(func): def wrapper(a,b): if b==0: print("Can't divide by 0!") return return func(a,b) return wrapper
Like you can see, the Python decorator function takes one argument for the function to decorate. The wrapper here takes the same arguments as does the function to decorate. Finally, we return the function to be decorated instead of calling it. This is because we want to return a value here from the divide() to the wrapper() to the decorator().
a. Python Closure
When we call func, it remembers the value of func from the argument to the function decorator(). This is called closure in Python. Here’s another example to clear this up.
>>>>> def func1(msg): def func2(): print(msg) func2() >>> func1(msg)
Hello
Also, note that if we called func(a,b) instead of returning it, we’d get this:
>>> divide(2,3) >>> print(divide(2,3))
None
Now, let’s assign and call.
>>> divide=decorator(divide) >>> divide(2,3)
0.6666666666666666
>>> divide(2,0)
Can’t divide by 0!
Problem Solved.
b. *args and **kwargs
If you don’t want to type in the whole list of arguments for the two statements, *args and **kwargs will do the trick for you.
>>> def divide(a,b): return a/b >>> def decorate(func): def wrapper(*args,**kwargs): if args[1]==0: print("Can't divide by 0!") return return func(*args,**kwargs) return wrapper >>> divide=decorate(divide) >>> divide(2,0)
Can’t divide by 0!
See, it works. Actually, *args is a tuple of arguments, and **kwargs is a dictionary of keyword arguments.
Any Doubt yet in Python 3 Decorators? Please ask in comments.
6. Pie Syntax in Python
First Go through Python Syntax | The Best Tutorial to Python Syntax
If you feel the assignment and calling statements are unnecessary, we’ve got the pie syntax for you. It’s simple; name the decorating function after the @ symbol, and put this before the function to decorate. Here’s an example.
>>> @decor def sayhello(): print("Hello") >>> sayhello()
$$
Hello
$$
7. Chaining Decorators in Python
You don’t have to settle with just one Python decorator. That’s the beauty of the pie syntax. Let’s see how.
>>> def decor1(func): def wrap(): print("$$$$$$$$$$$$$$") func() print("$$$$$$$$$$$$$$") return wrap >>> def decor2(func): def wrap(): print("##############") func() print("##############") return wrap
Now, let’s define the sayhello() function. We’ll use decor1 and decor2 on this.
>>> @decor1 @decor2 def sayhello(): print("Hello") >>> sayhello()
$$$$$$$$$$$$$$
########
Hello
########
$$$$$$$$$$$$$$
Note how the octothorpes (#) are sandwiched by dollars ($)? This lends us an important piece of information- the order of the decorators in python in the pie syntax matters. Since we used decor1 first, we get the dollars first.
This was all about the Python Decorator Tutorial.
8. Conclusion
Concluding what we discussed so far in this Python Decorator with arguments simple examples Tutorial, decorators in python help us add extra functionality to a function without modifying it. We also saw the pie syntax for the same. And now you know- anything that confuses you, you can conquer it by facing it, for you can’t run forever. Escape isn’t real. See you again.
Also See:
Hi,
The tutorial is good but Can you give us some more insight on how the pie syntax works in decorators.
we just call the decorator name using ‘@’ symbol, the decorator will have outer function & return and inner function & return, so the return of outer function is directly going to call inner function and the return values of inner function where it is stored, all those.
Because @decor, is just a single word but many things happen inside the flow | https://data-flair.training/blogs/python-decorator/ | CC-MAIN-2020-34 | refinedweb | 1,551 | 66.44 |
Hi,
I am studying this peice of code used in bluej, it is part of the world of zuul game example but there is this part of it that I want to know what it does. what does the public static etc do,...
Hi,
I am studying this peice of code used in bluej, it is part of the world of zuul game example but there is this part of it that I want to know what it does. what does the public static etc do,...
I want to comment them like this //comment
but I do not know what to put, could you suggest for each one
Hi,
now it prints out this line which is what I want
******************************
** **
** Ticket **
** **...
hi,
again there is something wrong with my code it comes it with and error and highlights lottoticket.add(new Numbers());
no suitable method found for add(numbers)
import java.util.ArrayList;...
are you talking about does this peice of code executes
public Ticket(int numOfLines)
{
lottoticket = new ArrayList<Numbers>();
//needs a loop
for(int i=0; i<qty;...
when I create an instance of the ticket class and call the method print ticket, it comes up with this,
1699
this is my code
import java.util.ArrayList;
/**
* lucky dip lottery ticket...
I commented the code but lost it a long time ago and now forgot what comments to put in the code now
my tutor was like you should start to be able to comment on your code and I did when I started this but I have lost some of it
basically it is a Numbers class should provide the following...
hi a while back I started to put comments on the code and now I have lost some of them, could anyone help me comment this unfinshed peice of code
//access to the java.utill.random libary.
...
I was just asking what name suits most for my mock app development business, I have an idea, target market but i need to pitch the idea to people at the business fair
Hi
I have been asked for a project to think of a business idea and pitch at an event
the idea is an outsourcing app development which isn't new but I just need a name
the ones I have came up...
for our coursework we had to make a lottery random number ticket generator
The Numbers class should provide the following functionality:
Generates 6 random numbers in a range 1 to 49.
Write...
public class Month
{
private int [] months = {31,28,31,30,31,30,30,31,30,31,30,31,99};
private int[] fib = new int[10];
public Month()
{
}
hi,
I did but I do not know if some information is correct for what I need
Hi, I am new and only just found out this forum
im doing computing and business in uni and the way the lecture is teach us java allows me to work hard in the lesson but for all techniques and... | http://www.javaprogrammingforums.com/search.php?s=6f61e26d9d869ac3e049fab4ddea5b1b&searchid=1273251 | CC-MAIN-2014-52 | refinedweb | 502 | 64.78 |
Article¶
- The project originally started during GSoC project 2012
- “DCE cradle: simulate network protocols with real stacks for better realism”, WNS3 2013, [PDF]
This is the manual of Direct Code Execution (DCE).
This document is written in reStructuredText for Sphinx and is maintained in the doc/ directory of ns-3-dce’s source code. document consists of the following parts:
- IPv4/IPv6
- TCP/UDP/DCCP
- running with POSIX socket applications and ns-3 socket applications
- configuration via sysctl-like interface
- multiple nodes debugging with single gdb interface
- memory analysis by single valgrind execution with multiple nodes
- ns-3 native stack (IPv4/IPv6, partially)
- Network simulation cradle network stack (IPv4 TCP only)
- Linux network stack (IPv4/IPv6/others)
Currently, DCE only supports Linux-based operating system. DCE has been tested on the following distributions:
but you can try on the others (e.g., CentOS, RHEL). If you got run on another distribution, please let us know.
The DCE ns-3 module provides facilities to execute within ns-3 existing implementations of userspace and kernelspace network protocols.
As of today, the Quagga routing protocol implementation, the CCNx CCN implementation, and recent versions of the Linux kernel network stack are known to run within DCE, hence allowing network protocol experimenters and researchers to use the unmodified implementation of their protocols for real-world deployments and simulations.
First you need to download Bake using Mercurial and set some variables:
hg clone bake export BAKE_HOME=`pwd`/bake export PATH=$PATH:$BAKE_HOME export PYTHONPATH=$PYTHONPATH:$BAKE_HOME
then you must to create a directory for DCE and install it using bake:
mkdir dce cd dce bake.py configure -e dce-ns3-|version| bake.py download bake.py build
note that dce-ns3-1.4 is the DCE version 1.4 module. If you would like to use the development version of DCE module, you can specify dce-ns3-dev as a module name for bake.
the output should look likes this:
Installing selected module and dependencies. Please, be patient, this may take a while! >> Downloading ccnx >> Download ccnx - OK >> Downloading iperf >> Download iperf - OK >> Downloading ns-3-dev-dce >> Download ns-3-dev-dce - OK >> Downloading dce-ns3 >> Download dce-ns3 - OK >> Building ccnx >> Built ccnx - OK >> Building iperf >> Built iperf - OK >> Building ns-3-dev-dce >> Built ns-3-dev-dce - OK >> Building dce-ns3 >> Built dce-ns3 - OK
If you would like to try Linux network stack instead of ns-3 network stack, you can try the advanced mode. The difference to build the advanced mode is the different module name dce-linux instead of dce-ns3 (basic mode).
mkdir dce cd dce bake.py configure -e dce-linux-|version| bake.py download bake.py build
note that dce-linux-1.4 is the DCE version 1.4 module. If you would like to use the development version of DCE module, you can specify dce-linux-dev as a module name for bake.
While Bake is the best option, another one is the configuration and build using WAF. WAF is a Python-based framework for configuring, compiling and installing applications. The configuration scripts are coded in Python files named wscript, calling the WAF framework, and called by the waf executable.
In this case you need to install the single packages one by one. You may want to start with ns-3:
# Download pybindgen (optional) bzr clone cd pybindgen ./waf configure --prefix=$HOME/dce/build ./waf ./waf install # Download ns-3 hg clone # Configure ./waf configure --enable-examples -d optimized --prefix=$HOME/dce/build \ --includedir=$HOME/dce/include/ns-3.19 # Build and install in the directory specified by # --prefix parameter ./waf build ./waf install
Then you can download and install net-next-sim and DCE (net-next-sim includes the linux stack module):
# Clone net-next-sim git clone cd net-next-sim # Select a kernel version git checkout sim-ns3-3.10.0-branch # Configure and build make defconfig OPT=yes ARCH=sim make library OPT=yes ARCH=sim cd .. # Download, configure, build and install DCE hg clone -r dce-1.2 ./waf configure --with-ns3=$HOME/dce/build --enable-opt \ --enable-kernel-stack=$HOME/dce/net-next-sim/arch \ --prefix=$HOME/dce/build ./waf build ./waf install
If you got succeed to build DCE, you can try an example script which is already included in DCE package.
This example execute the binaries named udp-client and udp-server under ns-3 using DCE. These 2 binaries are written using POSIX socket API in order to send and receive UDP packets.
If you would like to see what is going on this script, please refer to the user’s guide.
$ cd source/ns-3-dce $ ./waf --run dce-udp-simple $ ls elf-cache files-0 exitprocs $ ls -lR files-0 files-0: total 4 drwxr-x--- 3 furbani planete 4096 Sep 2 17:02 var files-0/var: total 4 drwxr-x--- 4 furbani planete 4096 Sep 2 17:02 log files-0/var/log: total 8 drwxr-x--- 2 furbani planete 4096 Sep 2 17:02 53512 drwxr-x--- 2 furbani planete 4096 Sep 2 17:02 53513 files-0/var/log/53512: total 12 -rw------- 1 furbani planete 12 Sep 2 17:02 cmdline -rw------- 1 furbani planete 185 Sep 2 17:02 status -rw------- 1 furbani planete 0 Sep 2 17:02 stderr -rw------- 1 furbani planete 21 Sep 2 17:02 stdout files-0/var/log/53513: total 12 -rw------- 1 furbani planete 22 Sep 2 17:02 cmdline -rw------- 1 furbani planete 185 Sep 2 17:02 status -rw------- 1 furbani planete 0 Sep 2 17:02 stderr -rw------- 1 furbani planete 22 Sep 2 17:02 stdout
This simulation produces two directories, the content of elf-cache is not important now for us, but files-0 is. files-0 contains first node’s file system, it also contains the output files of the dce applications launched on this node. In the /var/log directory there are some directories named with the virtual pid of corresponding DCE applications. Under these directories there is always 4 files:
Before launching a simulation, you may also create files-xx directories and provide files required by the applications to be executed correctly.
This example shows the usage of iperf with DCE. You are able to generate traffic by well-known traffic generator iperf in your simulation. For more detail of the scenario description, please refer to the user’s guide.
Once you successfully installed DCE with bake, you can execute the example using iperf.
cd source/ns-3-dce ./waf --run dce-iperf
As we saw in the previous example the experience creates directories containing the outputs of different executables, take a look at the server (node 1) output:
$ cat files-1/var/log/*/stdout ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: 124 KByte (default) ------------------------------------------------------------ [ 4] local 10.1.1.2 port 5001 connected with 10.1.1.1 port 49153 [ ID] Interval Transfer Bandwidth [ 4] 0.0-11.2 sec 5.75 MBytes 4.30 Mbits/sec
the client (node-0) output bellow:
$ cat files-0/var/log/*/stdout ------------------------------------------------------------ Client connecting to 10.1.1.2, TCP port 5001 TCP window size: 124 KByte (default) ------------------------------------------------------------ [ 3] local 10.1.1.1 port 49153 connected with 10.1.1.2 port 5001 [ ID] Interval Transfer Bandwidth [ 3] 0.0- 1.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 1.0- 2.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 2.0- 3.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 3.0- 4.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 4.0- 5.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 5.0- 6.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 6.0- 7.0 sec 512 KBytes 4.19.75 MBytes 4.72 Mbits/sec
if you have already built the advanced mode, you can use Linux network stack over iperf.
cd source/ns-3-dce ./waf --run "dce-iperf --kernel=1"
the command line option –kernel=1 makes the simulation use the Linux kernel stack instead of ns-3 network stack.
$ cat files-1/var/log/*/stdout ------------------------------------------------------------ Server listening on TCP port 5001 TCP window size: 85.3 KByte (default) ------------------------------------------------------------ [ 4] local 10.1.1.2 port 5001 connected with 10.1.1.1 port 60120 [ ID] Interval Transfer Bandwidth [ 4] 0.0-11.2 sec 5.88 MBytes 4.41 Mbits/sec
$ cat files-0/var/log/*/stdout ------------------------------------------------------------ Client connecting to 10.1.1.2, TCP port 5001 TCP window size: 16.0 KByte (default) ------------------------------------------------------------ [ 3] local 10.1.1.1 port 60120 connected with 10.1.1.2 port 5001 [ ID] Interval Transfer Bandwidth [ 3] 0.0- 1.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 1.0- 2.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 2.0- 3.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 3.0- 4.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 4.0- 5.0 sec 640 KBytes 5.24 Mbits/sec [ 3] 5.0- 6.0 sec 512 KBytes 4.19 Mbits/sec [ 3] 6.0- 7.0 sec 640 KBytes 5.24.88 MBytes 4.84 Mbits/sec
Interestingly, the two results between two network stacks are slightly different, though the difference is out of scope of this document.
This document is for the people who want to use your application in ns-3 using DCE.
Direct Code Execution (DCE) allows us to use POSIX socket-based applications as well as Linux kernel network stack.
As explained in How It Works, DCE needs to relocate the executable binary in memory, and these binary files need to be built with specific compile/link options.
In order to this you should follow the two following rules:
- (option) Some application needs to be compile with -U_FORTIFY_SOURCE so that the application doesn’t use alternative symbols including __chk (like memcpy_chk).
Copy the executable file produced in a specified directory in the variable environment DCE_PATH so that DCE can find it. (FIXME: to be updated)
Now that you have compiled your executable you can use it within ns-3 script with the help of a set of DCE Helper Class:
Note that the table above indicates the name of includes, so you can look at the comments in them, but in reality for DCE use you need to include only the file ns3/dce-module.h.
The directory named myscripts is a good place to place your scripts. To create a new script you should create a new directory under myscripts, and put your sources and a configuration file for waf build system, this file should be named wscript. For starters, you may refer to the contents of the directory myscripts/ping.
For more detail, please refer DCE API (doxygen) document.
To compile simply execute the command waf. The result must be under the directory named build/bin/myscripts/foo/bar where foo is your directory and bar your executable according to the content of your wscript file.
The execution of the apps using DCE generates special files which reflect the execution thereof. On each node DCE creates a directory /var/log, this directory will contain subdirectory whose name is a number. This number is the pid of a process. Each of these directories contains the following files cmdline, status, stdout, stderr. The file cmdline recalls the name of the executable run followed arguments. The file status contains an account of the execution and dating of the start; optionally if the execution is completed there is the date of the stop and the return code. The files stdout and stderr correspond to the standard output of the process in question.
The example uses two POSIX socket-based application in a simulation. Please take time to look at the source dce-udp-simple.cc:
int main (int argc, char *argv[]) { CommandLine cmd; cmd.Parse (argc, argv); NodeContainer nodes; nodes.Create (1); InternetStackHelper stack; stack.Install (nodes); DceManagerHelper dceManager; dceManager.Install (nodes); DceApplicationHelper dce; ApplicationContainer apps; dce.SetStackSize (1<<20); dce.SetBinary ("udp-server"); dce.ResetArguments(); apps = dce.Install (nodes.Get (0)); apps.Start (Seconds (4.0)); dce.SetBinary ("udp-client"); dce.ResetArguments(); dce.AddArgument ("127.0.0.1"); apps = dce.Install (nodes.Get (0)); apps.Start (Seconds (4.5)); Simulator::Stop (Seconds(1000100.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
You can notice that we create a ns-3 Node with an Internet Stack (please refer to ns-3 doc. for more info), and we can also see 2 new Helpers:
- DceManagerHelper which is used to Manage DCE loading system in each node where DCE will be used.
- DceApplicationHelper which is used to describe real application to be launched by DCE within ns-3 simulation environment.
The example uses iperf traffic generator in a simulation. The scenario is here:
#include "ns3/network-module.h" #include "ns3/core-module.h" #include "ns3/internet-module.h" #include "ns3/dce-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/netanim-module.h" #include "ns3/constant-position-mobility-model.h" #include "ccnx/misc-tools.h" using namespace ns3; // =========================================================================== // // node 0 node 1 // +----------------+ +----------------+ // | | | | // +----------------+ +----------------+ // | 10.1.1.1 | | 10.1.1.2 | // +----------------+ +----------------+ // | point-to-point | | point-to-point | // +----------------+ +----------------+ // | | // +---------------------+ // 5 Mbps, 2 ms // // 2 nodes : iperf client en iperf server .... // // Note : Tested with iperf 2.0.5, you need to modify iperf source in order to // allow DCE to have a chance to end an endless loop in iperf as follow: // in source named Thread.c at line 412 in method named thread_rest // you must add a sleep (1); to break the infinite loop.... // =========================================================================== int main (int argc, char *argv[]) { bool useKernel = 0; bool useUdp = 0; std::string bandWidth = "1m"; CommandLine cmd; cmd.AddValue ("kernel", "Use kernel linux IP stack.", useKernel); cmd.AddValue ("udp", "Use UDP. Default false (0)", useUdp); cmd.AddValue ("bw", "BandWidth. Default 1m.", bandWidth); cmd.Parse (argc, argv); NodeContainer nodes; nodes.Create (2); PointToPointHelper pointToPoint; pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); pointToPoint.SetChannelAttribute ("Delay", StringValue ("1ms")); NetDeviceContainer devices; devices = pointToPoint.Install (nodes); DceManagerHelper dceManager; dceManager.SetTaskManagerAttribute( "FiberManagerType", StringValue ( "UcontextFiberManager" ) ); if (!useKernel) { InternetStackHelper stack; stack.Install (nodes); } else { dceManager.SetNetworkStack ("ns3::LinuxSocketFdFactory", "Library", StringValue ("liblinux.so")); LinuxStackHelper stack; stack.Install (nodes); } Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.252"); Ipv4InterfaceContainer interfaces = address.Assign (devices); // setup ip routes Ipv4GlobalRoutingHelper::PopulateRoutingTables (); dceManager.Install (nodes); DceApplicationHelper dce; ApplicationContainer apps; dce.SetStackSize (1<<20); // Launch iperf client on node 0 dce.SetBinary ("iperf"); dce.ResetArguments(); dce.ResetEnvironment(); dce.AddArgument ("-c"); dce.AddArgument ("10.1.1.2"); dce.AddArgument ("-i"); dce.AddArgument ("1"); dce.AddArgument ("--time"); dce.AddArgument ("10"); if (useUdp) { dce.AddArgument ("-u"); dce.AddArgument ("-b"); dce.AddArgument (bandWidth); } apps = dce.Install (nodes.Get (0)); apps.Start (Seconds (0.7)); apps.Stop (Seconds (20)); // Launch iperf server on node 1 dce.SetBinary ("iperf"); dce.ResetArguments(); dce.ResetEnvironment(); dce.AddArgument ("-s"); dce.AddArgument ("-P"); dce.AddArgument ("1"); if (useUdp) { dce.AddArgument ("-u"); } apps = dce.Install (nodes.Get (1)); pointToPoint.EnablePcapAll (useKernel?"iperf-kernel":"iperf-ns3", false); apps.Start (Seconds (0.6)); setPos (nodes.Get (0), 1, 10, 0); setPos (nodes.Get (1), 50,10, 0); Simulator::Stop (Seconds(40.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
This scenario is simple there is 2 nodes linked by a point 2 point link, the node 0 launch iperf as a client via the command iperf -c 10.1.1.2 -i 1 –time 10 and the node 1 launch iperf as a server via the command iperf -s -P 1. You can follow this to launch the experiment:
There are a number of protocols implemented in kernel space, like many transport protocols (e.g., TCP, UDP, SCTP), Layer-3 forwarding plane (IPv4, v6 with related protocols ARP, Neighbor Discovery, etc). DCE can simulate these protocols with ns-3.
This document describes an example when we supported new protocol, Stream Control Transmission Protcool (SCTP), with DCE. Although other protocols may not adapt this patterns as-is, you will see what’s needed to implement for your purpose.
To build the liblinux.so, DCE version of Linux kernel,
make defconfig make library ARCH=sim
You can use make menuconfig command (below) instead of editing the defconfig file. If everything is fine, you will see liblinux.so linked to libsim-linuxv.y.z.so file at the root directory of Linux kernel.
make menuconfig ARCH=sim
Then, we need to write userspace applications using new feature of kernel protocol. In case of SCTP, we wrote sctp-client.cc and sctp-server.cc.
Optional You may optinally need external libraries to build/run the applications. In this case, the applications need lksctp-tools, so that applications fully benefit the features of SCTP, rather than only using standard POSIX socket API.
Moreover, adding system dependency to bake configuration file (i.e., bakeconf.xml) would be nice to assist build procedure. The following is an example of lksctp-tools, which above applications use.
<module name="lksctp-dev"> <source type="system_dependency"> <attribute name="dependency_test" value="sctp.h"/> <attribute name="try_to_install" value="True"/> <attribute name="name_apt-get" value="lksctp-dev"/> <attribute name="name_yum" value="lksctp-tools-devel"/> <attribute name="more_information" value="Didn't find: lksctp-dev package; please install it."/> </source> <build type="none" objdir="no"> </build> </module>
The next step would be writing ns-3 simulation scenario to use the applications you prepared. dce-sctp-simple.cc is the script that we prepared. In the script, you may need to load the applications by using DceApplicationHelper as follows.
DceApplicationHelper process; ApplicationContainer apps; process.SetBinary ("sctp-server"); process.ResetArguments (); process.SetStackSize (1<<16); apps = process.Install (nodes.Get (0)); apps.Start (Seconds (1.0)); process.SetBinary ("sctp-client"); process.ResetArguments (); process.ParseArguments ("10.0.0.1"); apps = process.Install (nodes.Get (1)); apps.Start (Seconds (1.5));
./waf --run dce-simple-sctp
If you’re lucky, it’s done.
If you aren’t lucky, you may face errors of DCE, such as unresolved symbols in system calls (called by userspace applications) or missing kernel functions (used by newly added CONFIG_IP_SCTP option), or invalid memory access causing segmentation fault. In that case, adding missing functions, so called glue-code would be the next step.
If your applications running with DCE are not able to run due to missing function symbols, you need to add the function call or system call to DCE by hand. The POSIX API coverage of DCE is growing day by day, but your contribution is definitely helpful not only for your case, but also for someone will use in future.
More specifically, if you faced the following error when you executed, you need to add a function call to DCE. In the following case, a symbol strfry not defined in DCE is detected during the execution of the simulation.
% ./waf --run dce-udp-perf 'build' finished successfully (0.704s) /home/tazaki/hgworks/dce-dev/source/ns-3-dce/build/bin/dce-udp-perf: **relocation error: elf-cache/0/udp-perf: symbol strfry**, version GLIBC_2.2.5 not defined in file 0002.so.6 with link time reference Command ['/home/tazaki/hgworks/dce-dev/source/ns-3-dce/build/bin/dce-udp-perf'] exited with code 127
There are two types of symbols that is defined in DCE.
NATIVE symbol is a symbol that DCE doesn’t care about the behavior. So this type of symbol is redirected to the one provided by underlying host operating system (i.e., glibc).
DCE symbol is a symbol that DCE reimplements its behavior instead of using the underlying system’s one. For instance, socket() call used in an application redirected to DCE to cooperate with ns-3 or Linux network stack managed by DCE. malloc() is also this kind.
In general (but not strictly), if a call is related to a kernel resource (like NIC, clock, etc), it should use DCE macro. Otherwise (like strcmp, atoi etc), the call should use NATIVE.
In order to add function calls or system calls that DCE can handle, you need to modify the following files.
This is the first file that you need to edit. You may lookup the symbol that you’re going to add and once you can’t find it, add the following line.
NATIVE (strfry)
This is the case of the symbol strfry(), which we don’t have to reimplement. But you may need to add include file that defines the symbol (strfry()) at model/libc-dce.cc.
If the symbol needs to reimplemented for DCE, you may add as follows.
DCE (socket)
In case of DCE symbol, you’re going to introduce DCE redirected function. We use naming convention with prefix of dce_ to the symbol (i.e., dce_socket) to define new symbol and add the implementation in a .cc file. The following is the example of dce_socket() implementation.
We implemented dce_socket() function in the file model/dce-fd.cc.int dce_socket (int domain, int type, int protocol)
In the function, we carefully fill the function contents to cooperate with ns-3. The below line is creating DCE specific socket instance (i.e., ns-3 or DCE Linux) instead of calling system call allocating kernel space socket resources.UnixFd *socket = factory->CreateSocket (domain, type, protocol);
Other function calls such as file system related functions (e.g., read, fopen), time reheated features (e.g., gettimeofday, clock_gettime), signal/process utilities (e.g., getpid, sigaction), and thread library (e.g., pthread_create). All these functions should be DCE since DCE core reimplements these feature instead of using underlying host system.
Once you got implemented the new redirected function, you may add the function prototype declaration to refer from other source files. dce_socket() is added to model/sys/dce-socket.h.
If your application has a configuration file to modify the behavior of applications, introducing a particular Helper class will be helpful to handle your application. In this section, we will give you an advanced way of using your application with DCE.
Some of existing submodule are following this way. You can find ns-3-dce-quagga and ns-3-dce-umip as examples to add sub-module.
First of all, you could start with referring sub module template available as follows.
hg clone (your module name)
The template consists of, wscript, helper, test and documentation. You could rename all/some of them for your module. Then, put ns-3-dce-submodule directory under ns-3-dce/myscripts/. This will be required to build under ns-3-dce module as an extension (sub-module) of dce.
The DCE specifics variables are essentially two PATH like variables: so within them you may put paths separated by ‘:’ character.
DCE_PATH is used by DCE to find the executable you want to launch within ns-3 simulated network. This variable is used when you reference the executable using a relative form like ‘ping’.
DCE_ROOT is similar to DCE_PATH but it is used when you use an absolute form for exemple ‘/bin/bash’.
Please pay attention that executables that you will place in the directories indicated in the previous variables should be recompiled accordingly to the rules defined in the next chapter.
(FIXME: to be updated)
This document describes what DCE Cradle is, how we can use it, how we extend it.
Tutorials and how to reproduce the experiment of WNS3 2013 paper is available DCE Cradle Tutorial.
DCE Cradle enables us to use Linux kernel via Direct Code Execution from the ns-3 native socket application. Applications can access it via ns-3 socket API. Currently (6th Jan. 2014) the following sockets are available:
- IPv4/IPv6 UDP
- IPv4/IPv6 TCP
- IPv4/IPv6 RAW socket
- IPv4/IPv6 DCCP
- IPv4/IPv6 SCTP
DCE Cradle is already integrated in ns-3-dce module. You can just build and install DCE as instructed in the parent document.
OnOffHelper onoff = OnOffHelper ("ns3::LinuxTcpSocketFactory", InetSocketAddress (interfaces.GetAddress (1), 9));
Aspect-based tracing, provided by libaspect, allows us to use tracing facility with unmodified code.
One of contradictions when we use DCE is, tracing, how to put trace sources into unmodified code. While DCE gives an opportunity to use unmodified codes as simulation protocols, one might want to investigate which function is called or how many messages of a particular protocol are exchanged.
ns-3 originally has a nice feature of tracing with such a purpose, with on-demand trace connector to obtain additional information. Instead of inserting TraceSource into the original code, DCE gives dynamic trace points with this library, based on the idea of aspect-based tracing.
For more detail, see the Chapter 6.3.2 of the thesis.
To put trace sources without modifying the original code, aspcpp::HookManager gives trace hooks into arbitrary source codes and functions.
#include <hook-manager.h> HookManager hooks; hooks.AddHookBySourceAndFunction ("ip_input.c", "::ip_rcv", &IpRcv); hooks.AddHookByFunction ("::process_backlog", &ProcBacklog); hooks.AddHookByFunction ("::arp_xmit", &ArpXmit);
The above examples specifies file name and functions with callback functions in the simulation script.
This module provides an additional network stack support for DCE with FreeBSD kernel.
bake.py configure -e dce-freebsd-dev bake.py download bake.py build
Once you finished to build dce-freebsd module, you can write a simulation script that uses FreeBSD kernel as a network stack. All you need is to specify the library name with an attribute Library to ns3::FreeBSDSocketFdFactory, then install FreeBSDStackHelper to the nodes.
DceManagerHelper processManager; processManager.SetNetworkStack ("ns3::FreeBSDSocketFdFactory", "Library", StringValue ("libfreebsd.so")); processManager.Install (nodes); FreeBSDStackHelper stack; stack.Install (nodes);
No configuration support (like make menuconfig in Linux) right now. You need to add files into sys/sim/Makefile.
The following represents an example to add Multipath-TCP feature of FreeBSD by adding mptcp_subr.o to the freebsd-sim/sys/sim/Makefile. If you want to add your code into the kernel build, you may add object file names that is from your own codes.
diff --git a/sys/sim/Makefile b/sys/sim/Makefile index 8115e3d..1b2feab 100644 --- a/sys/sim/Makefile +++ b/sys/sim/Makefile @@ -100,7 +100,7 @@ ip_divert.o tcp_hostcache.o ip_ecn.o tcp_input.o ip_encap.o \ tcp_lro.o ip_fastfwd.o tcp_offload.o ip_gre.o tcp_output.o \ ip_icmp.o tcp_reass.o ip_id.o tcp_sack.o ip_input.o tcp_subr.o \ tcp_syncache.o ip_mroute.o tcp_timer.o ip_options.o tcp_timewait.o \ -ip_output.o tcp_usrreq.o raw_ip.o udp_usrreq.o if_llatbl.o +ip_output.o tcp_usrreq.o raw_ip.o udp_usrreq.o if_llatbl.o mptcp_subr.o
While this release gives a proof of concept to use FreeBSD kernel with DCE, there are tons of limitations (listed below) that have to be improved in near future.
- No delete IP addresses support
DCE optionally supports an alternative ELF loader/linker, so-called elf-loader, in order to replace system-provided linker/loader module. The intention of the loader is to support unlimited number of instances used by dlmopen call, which provides DCE to load a single ELF binary to multiple different memory space. dlmopen-based loader (ns3::DlmLoaderFactory) is much faster than another default one (ns3::CoojaLOaderFactory), but few issues are remain so, this is optional.
When dealing with large or complex models, you can easily reach the limits of your system. For example, you cannot open more than a fixed number of files. You can try the command “limit –a” to check them.
You may see the following error:
msg="Could not open "/var"", file=../model/dce-manager.cc, line=149 terminate called without an active exception
This error masks error “24 Too many open files”. The cause of this is that the simulation process exceeded the limit of open files per process. Check the limit of open files per process with “ulimit -n” To solve it, you can edit file /etc/security/limits.conf and add the following lines at the end:
* hard nofile 65536 * soft nofile 65536
or
myuser hard nofile 65536 myuser soft nofile 65536
DCE directly manages the stack of the processes running on it, assigning it a default value 8192. For complex executables this value is too small, and may raise ‘stack overflow’ exceptions, or in other cases it may originate inconsistent values. For example, a value passed to a function changes without apparent reason when the program enters in that function. The value of the stack size can be changed with the SetStackSize instruction:
DceApplicationHelper dce; dce.SetStackSize (1<<20);
It is possible to use gdb to debug a script DCE/ns-3. As explained somewhere in the execution of a script is monoprocess, then you can put breakpoints in both sources of DCE and those of binaries hosted by DCE.
Although it is not strictly necessary, it is recommended that you recompile a CVS Gdb for use with ns-3-dce. First, download:
cvs -d :pserver:anoncvs@sourceware.org:/cvs/src login {enter “anoncvs” as the password} cvs -d :pserver:anoncvs@sourceware.org:/cvs/src co gdb
Note that you might consider looking at to obtain more efficient (cpu/bandwidth-wise) download instructions.
Anyway, now, you can build:
cd gdb ./configure make
And, then, invoke the version of gdb located in gdb/gdb instead of your system-installed gdb whenever you need to debug a DCE-based program.
If you use gdb (a CVS or stable version), do not forget to execute the following command prior to running any DCE-based program:
(gdb) handle SIGUSR1 nostop Signal StopPrintPass to programDescription SIGUSR1 NoYesYesUser defined signal 1 (gdb)
An alternate way to do this and avoid having to repeat this command ad-nauseam involves creating a .gdbinit file in your ns-3-dce directory and putting this inside:
handle SIGUSR1 nostop
or it can be put on the command line using the “-ex” flag:
./waf --run SCRIPT_NAME_HERE --command-template="gdb -ex 'handle SIGUSR1 nostop noprint' --args %s <args>"
To remotely debug a DCE script you can use gdbserver as in the following example, changing the host name and port (localhost:1234):
./waf --run dce-httpd --command-template="gdbserver localhost:1234 %s <args>"
Then you can point a gdb client to your server. For example, in the following figure is reported an Eclipse debug configuration:
Once you start the debug session, you can use the usual Eclipse/gdb commands.
There are a couple of functions which are useful to put breakpoints into:
- ns3::DceManager::StartProcessDebugHook
If you got a trouble in your protocol during interactions between distributed nodes, you want to investigate a specific state of the protocol in a specific node. In a usual system, this is a typical case of using distributed debugger (e.g., ddt, or mpirun xterm -e gdb –args xxx), but it is annoying task in general due to the difficulty of controlling distributed nodes and processes.
DCE gives an easy interface to debug distributed applications/protocols by the single-process model of its architecture.
The following is an example of debugging Mobile IPv6 stack (of Linux) in a specific node (i.e., home agent). A special function dce_debug_nodeid() is useful if you put a break condition in a gdb session.
(gdb) b mip6_mh_filter if dce_debug_nodeid()==0 Breakpoint 1 at 0x7ffff287c569: file net/ipv6/mip6.c, line 88. <continue> (gdb) bt 4 #0 mip6_mh_filter (sk=0x7ffff7f69e10, skb=0x7ffff7cde8b0) at net/ipv6/mip6.c:109 #1 0x00007ffff2831418 in ipv6_raw_deliver (skb=0x7ffff7cde8b0, nexthdr=135) at net/ipv6/raw.c:199 #2 0x00007ffff2831697 in raw6_local_deliver (skb=0x7ffff7cde8b0, nexthdr=135) at net/ipv6/raw.c:232 #3 0x00007ffff27e6068 in ip6_input_finish (skb=0x7ffff7cde8b0) at net/ipv6/ip6_input.c:197 (More stack frames follow...)
Since DCE allows protocol implementations to expose network conditions (packet losses, reordering, and errors) with the interactions among distributed nodes, which is not easily available by traditional user-mode virtualization tools, exercising your code is easily done with a single simulation script.
Improving code coverage with writing test programs is one of headache; - writing test program is annoying, - preparing test network tends to be short-term, and - the result is not reproducible.
This text describes how to measure code coverage of protocol implementations with DCE.
First, you need to compile your application with additional flags. -fprofile-arcs -ftest-coverage is used for a compilation flag (CFLAGS/CXXFLAGS), and -fprofile-arcs is used for a linker flag (LDFLAGS).
gcc -fprofile-arcs -ftest-coverage -fPIC -c foo.c gcc -fprofile-arcs -pie -rdynamic foo.o -o newapp
Next, write a test program like ns-3 simulation script for your application (i.e., newapp).
$ cat myscripts/dce-newapp.cc int main (int argc, char *argv[]) { CommandLine cmd; cmd.Parse (argc, argv); NodeContainer nodes; nodes.Create (2); InternetStackHelper stack; stack.Install (nodes); DceManagerHelper dceManager; dceManager.Install (nodes); DceApplicationHelper dce; ApplicationContainer apps; // application on node 0 dce.SetBinary ("newapp"); dce.ResetArguments(); apps = dce.Install (nodes.Get (0)); apps.Start (Seconds (4.0)); // application on node 1 dce.SetBinary ("newapp"); dce.ResetArguments(); apps = dce.Install (nodes.Get (1)); apps.Start (Seconds (4.5)); Simulator::Stop (Seconds(100.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
Then, test your application as normal ns-3 (and DCE) simulation execution.
./waf --run dce-newapp
If you successfully finish your test, you will see the coverage data files (i.e., gcov data files) with a file extension .gcda.
$ find ./ -name "*.gcda" ./files-0/home/you/are/here/ns-3-dce/newapp.gcda ./files-1/home/you/are/here/ns-3-dce/newapp.gcda
We use lcov utilities as a parse of coverage test result.
Put the compiler (gcc) generated files (*.gcno) in the result directory,
cp *.gcno ./files-0/home/you/are/here/ns-3-dce/ cp *.gcno ./files-1/home/you/are/here/ns-3-dce/
then run the lcov and genhtml command to generate coverage information of your test program.
lcov -c -d .-b . -o test.info genhtml test.info -o html
You will see the following output and generated html pages.
Reading data file test.info Found 8 entries. Writing .css and .png files. Generating output. Processing file ns-3-dce/example/udp-server.cc genhtml: Use of uninitialized value in subtraction (-) at /usr/bin/genhtml line 4313. Processing file ns-3-dce/example/udp-client.cc genhtml: Use of uninitialized value in subtraction (-) at /usr/bin/genhtml line 4313. Processing file /usr/include/c++/4.4/iostream Processing file /usr/include/c++/4.4/ostream Processing file /usr/include/c++/4.4/bits/ios_base.h Processing file /usr/include/c++/4.4/bits/locale_facets.h Processing file /usr/include/c++/4.4/bits/char_traits.h Processing file /usr/include/c++/4.4/bits/basic_ios.h Writing directory view page. Overall coverage rate: lines......: 49.3% (35 of 71 lines) functions..: 31.6% (6 of 19 functions)
To start a program in the world of ns-3 you must indicate on which node it will be launched. Once launched this program will have access only to the file system corresponding to the node that corresponds to a directory on your machine called file-X where X is the decimal number of the corresponding node. The file-X directories are created by DCE, only when they do not already exist. Also note that the contents of this directory is not cleared when starting the script. So you can copy the files required for the operation of your executables in the tree nodes. If possible it is best that you create these files from the script itself in order to simplify maintenance. DCE provides some helpers for creating configuration files necessary to the execution of certain apps like CCNx and Quagga.
Currently DCE includes an experimental support to the Python language. To enable it, you may need to recompile it with the flags:
--with-pybindgen=HERE_THE_PYBINDGEN_PATH
indicating the path to an existing Pybindgen source tree to use. Or in case waf didn’t find the interpreter, you can try to use the flags:
--with-python=HERE_THE_PYTHON_PATH
The first thing you may want to do is to import the DCE module. For example a minimal DCE script in Python could be:
from ns.DCE import * print "It works!"
In this example, DCE executes a program running ten seconds on a single node.
# DCE import from ns.DCE import * # ns-3 imports import ns.applications import ns.core import ns.network # Increase the verbosity level ns.core.LogComponentEnable("Dce", ns.core.LOG_LEVEL_INFO) ns.core.LogComponentEnable("DceManager", ns.core.LOG_LEVEL_ALL) ns.core.LogComponentEnable("DceApplication", ns.core.LOG_LEVEL_INFO) ns.core.LogComponentEnable("DceApplicationHelper", ns.core.LOG_LEVEL_INFO) # Node creation nodes = ns.network.NodeContainer() nodes.Create(1) # Configure DCE dceManager = ns.DCE.DceManagerHelper() dceManager.Install (nodes); dce = ns.DCE.DceApplicationHelper() # Set the binary dce.SetBinary ("tenseconds") dce.SetStackSize (1<<20) # dce.Install returns an instance of ns.DCE.ApplicationContainer apps = dce.Install (nodes ) apps.Start ( ns.core.Seconds (4.0)) # Simulation ns.core.Simulator.Stop (ns.core.Seconds(20.0)) ns.core.Simulator.Run () ns.core.Simulator.Destroy () print "Done."
You can then run the example with “waf –pyrun ...”
./waf --pyrun PATH_TO_YOUR_SCRIPT_HERE
or attach gdb to the python script:
./waf shell gdb python -ex "set args PATH_TO_YOUR_SCRIPT_HERE" -ex "handle SIGUSR1 nostop noprint"
This document is for the people who want to develop DCE itself.
This technical documentation is intended for developers who want to build a Linux kernel in order to use with DCE. A first part will describe the architecture and the second will show how we went from a net-next kernel 2.6 has a Linux kernel-stable 3.4.5.
The source code can be found in the following repository:. You must use mercurial to download the source code.
The goal of this work is to use the real implementation of the Linux Network Stack within the Simulation environment furnished by ns-3.
The solution chosen was to use the Linux kernel source, compile the Net part and make a dynamic library and interface the result with DCE.
The following schema shows the different parts between a software user space application and the hardware network.
The following schema show the same application running under DCE and ns-3 and using a real kernel network stack:
The green parts are implemented in ns-3-linux source files, the grays parts comes from the Linux kernel sources and are not modified at all or with only few changes. Application should not be modified at all.
If you need a more theoretical documentation you can read the chapter 4.5 of this Ph.D. thesis Experimentation Tools for Networking Research.
After doing the cloning of the source,
$ hg clone destination directory: ns-3-linux requesting all changes adding changesets adding manifests adding file changes added 62 changesets with 274 changes to 130 files updating to branch default 125 files updated, 0 files merged, 0 files removed, 0 files unresolved
Below are the files delivered under the directory ns-3-linux:
$ ls ns-3-linux/ generate-autoconf.py generate-linker-script.py kernel-dsmip6.patch kernel.patch Makefile Makefile.print processor.mk README sim
The main file is the Makefile its role is to recover the kernel source, compile the NET part of the kernel and all that is necessary for the operation, the end result is a shared library that can be loaded by DCE.
$ ls ns-3-linux/sim cred.c glue.c Kconfig pid.c random.c seq.c sim-socket.c softirq.c tasklet.c timer.c defconfig hrtimer.c Makefile print.c sched.c sim.c slab.c sysctl.c tasklet-hrtimer.c workqueue.c fs.c include modules.c proc.c security.c sim-device.c socket.c sysfs.c time.c $ ls ns-3-linux/sim/include asm generated sim-assert.h sim.h sim-init.h sim-printf.h sim-types.h
These directories contains the architecture specific code and the code doing the interface between the kernel and DCE and ns-3. Ideally we should not change a line of code outside the kernel arch portion, but in practice we make small changes : see the patchs files.
Recall: the code of Linux source is mainly C so it is very easy to port to new architecture, the architecture specific code is contained in a specific directory under arch/XXX directory where XXX name recall the processor used. In our case we have chosen to create a special architecture for our environment NS3 + DCE, we called sim.
In order to install a kernel on a Node DCE do the following steps:
Methods (there is also one variable) of DCE called by the kernels are the following:
there are located in the source file linux-socket-fd-factory.cc of DCE.
Methods of Kernel (sim part) called by DCE are the following:
the corresponding sources are located in the sim directory.
All build operations are done using the make command with the Makefile file under the directory ns-3-linux.
First you should call make setup in order to download the source of the kernel:
$ make setup git clone git://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git net-next-2.6; \ cd net-next-2.6 && git reset --hard fed66381d65a35198639f564365e61a7f256bf79 Cloning into net-next-2.6... remote: Counting objects: 2441000, done. remote: Compressing objects: 100% (377669/377669), done. Receiving objects: 100% (2441000/2441000), 493.28 MiB | 28.45 MiB/s, done. remote: Total 2441000 (delta 2043525), reused 2436782 (delta 2039307) Resolving deltas: 100% (2043525/2043525), done. Checking out files: 100% (33319/33319), done.
This sources correspond to a specific version well tested with DCE the net-next 2.6 and git tag = fed66381d65a35198639f564365e61a7f256bf79.
Now the directory net-next-2.6 contains the kernel sources.
Finally make will compile all the needed sources and produce a file named libnet-next-2.6.so: this is the library contains our net-next kernel suitable for DCE usage.
To use this kernel you should:
1. configure DCE in order to compile using the includes under sim directories to have the good interfaces between DCE and the kernel. For this you should give to the waf configure the path to the ns-3-linux directory i.e.:
$ ./waf configure ----enable-kernel-stack=/ABSOLUTE-PATH-TO/ns-3-linux
dceManager.SetNetworkStack("ns3::LinuxSocketFdFactory", "Library", StringValue ("libnet-next-2.6.so"));
Use DCE unit test:
$ ./waf --run "test-runner --verbose" PASS process-manager 9.470ms PASS Check that process "test-empty" completes correctly. 0.920ms PASS Check that process "test-sleep" completes correctly. 0.080ms PASS Check that process "test-pthread" completes correctly. 0.110ms PASS Check that process "test-mutex" completes correctly. 0.200ms PASS Check that process "test-once" completes correctly. 0.070ms PASS Check that process "test-pthread-key" completes correctly. 0.070ms PASS Check that process "test-sem" completes correctly. 0.080ms PASS Check that process "test-malloc" completes correctly. 0.060ms PASS Check that process "test-malloc-2" completes correctly. 0.060ms PASS Check that process "test-fd-simple" completes correctly. 0.070ms PASS Check that process "test-strerror" completes correctly. 0.070ms PASS Check that process "test-stdio" completes correctly. 0.240ms PASS Check that process "test-string" completes correctly. 0.060ms PASS Check that process "test-netdb" completes correctly. 3.940ms PASS Check that process "test-env" completes correctly. 0.050ms PASS Check that process "test-cond" completes correctly. 0.160ms PASS Check that process "test-timer-fd" completes correctly. 0.060ms PASS Check that process "test-stdlib" completes correctly. 0.060ms PASS Check that process "test-fork" completes correctly. 0.120ms PASS Check that process "test-select" completes correctly. 0.320ms PASS Check that process "test-nanosleep" completes correctly. 0.070ms PASS Check that process "test-random" completes correctly. 0.090ms PASS Check that process "test-local-socket" completes correctly. 0.820ms PASS Check that process "test-poll" completes correctly. 0.320ms PASS Check that process "test-exec" completes correctly. 0.380ms PASS Check that process "test-iperf" completes correctly. 0.070ms PASS Check that process "test-name" completes correctly. 0.080ms PASS Check that process "test-pipe" completes correctly. 0.160ms PASS Check that process "test-dirent" completes correctly. 0.070ms PASS Check that process "test-socket" completes correctly. 0.270ms PASS Check that process "test-bug-multi-select" completes correctly. 0.260ms PASS Check that process "test-tsearch" completes correctly. 0.080ms
All is OK.
Now we will try to use a more recent linux kernel. We start with a fresh clone of the ns-3-linux sources.
First we need to modify the makefile in order to change the kernel downloaded. For that we need to modify the value of 2 variables:
Also we need to remove the patch target named .target.ts because the patch will not pass for this newer version of kernel.
Now we can try to build:
$ make defconfig $ make menuconfig $ make mkdir -p sim cc -O0 -g3 -D__KERNEL__ -Wall -Wstrict-prototypes -Wno-trigraphs -fno-inline \ -iwithprefix ./linux-stable/include -DKBUILD_BASENAME=\"clnt\" \ -fno-strict-aliasing -fno-common -fno-delete-null-pointer-checks \ -fno-stack-protector -DKBUILD_MODNAME=\"nsc\" -DMODVERSIONS \ -DEXPORT_SYMTAB -include autoconf.h -U__FreeBSD__ -D__linux__=1 \ -Dlinux=1 -D__linux=1 -I./sim/include -I./linux-stable/include \ -fpic -DPIC -D_DEBUG \ -I/home/furbani/dev/dce/dev/etude_kernel/V3/ns-3-linux \ -DCONFIG_64BIT -c sim/fs.c -o sim/fs.o In file included from ./linux-stable/include/asm-generic/bitops.h:12:0, from ./sim/include/asm/bitops.h:4, from ./linux-stable/include/linux/bitops.h:22, from ./linux-stable/include/linux/thread_info.h:52, from ./linux-stable/include/linux/preempt.h:9, from ./linux-stable/include/linux/spinlock.h:50, from ./linux-stable/include/linux/wait.h:24, from ./linux-stable/include/linux/fs.h:385, from sim/fs.c:1: ./linux-stable/include/linux/irqflags.h:66:0: warning: "raw_local_irq_restore" redefined ./sim/include/asm/irqflags.h:8:0: note: this is the location of the previous definition In file included from ./linux-stable/include/linux/wait.h:24:0, from ./linux-stable/include/linux/fs.h:385, from sim/fs.c:1: ./linux-stable/include/linux/spinlock.h:58:25: fatal error: asm/barrier.h: No such file or directory compilation terminated. make: *** [sim/fs.o] Error 1
Ok now we will try to fix the compilation errors trying not to change too the kernel source. In the following we will list the main difficulties encountered.
Recall: the linux source directory include/asm-generic contains a C reference implementation of some code that should be written in assembly langage for the target architecture. So this code is intented to help the developper to port to new architectures. So our sim implementation use many of these asm-generic include files. The first warning show that our code redefine a method defined elsewhere in kernel sources, so the fix is to remove our definition of this function in opur file named sim/include/asm/irqflags.h.
The file asm/barrier.h is missing, we just create under sim/include/asm directory and the implementation is to include the generic one ie: include/asm-generic/barrier.h.
Another problem arise the function named kern_mount_data defined in sim/fs.c do not compile any more. So we need to investigate about this function:
- Where this function is located in the real code: in linux/fs/namespace.c
- Why it is reimplemented in sim/fs.c: if you look at our Makefile why try to not compile all the kernel we focus on the net part only, you can see this line in the Makefile :
dirs=kernel/ mm/ crypto/ lib/ drivers/base/ drivers/net/ net/
in fact we include only this directories. So at this time we can comment the failing line and insert a sim_assert (false); in order to continue to fix the compilation errors, and then when we will do the first run test we will see if this method is called and if yes we will need to do a better fix. Remark: sim_assert (false); is a macro used to crash the execution, we often place it in functions that we need to emulate because required by the linker but that should never be called.
After we have the following problem while compiling sim/glue.c the macro IS_ENABLED is not defined. After some search we found that we need to include linux/kconfig.h in many files. So we modify our makefile to fix like this:
-fno-stack-protector \ -DKBUILD_MODNAME=\"nsc\" -DMODVERSIONS -DEXPORT_SYMTAB \ - -include autoconf.h \ + -include $(SRCDIR)$(KERNEL_DIR)/include/linux/kconfig.h \ -U__FreeBSD__ -D__linux__=1 -Dlinux=1 -D__linux=1 \ -I$(SRCDIR)sim/include -I$(SRCDIR)$(KERNEL_DIR)/include \ $(AUTOCONF): generate-autoconf.py $(KERNEL_DIR)/.config timeconst.h ./generate-autoconf.py $(KERNEL_DIR)/.config > $@ + cp autoconf.h sim/include/generated/autoconf.h + timeconst.h: $(KERNEL_DIR)/.config perl $(SRCDIR)$(KERNEL_DIR)/kernel/timeconst.pl $(CONFIG_HZ) > $@
Our sim/slab.c do not compile, in this case we want to use our implementation of memory allocation and to do this it is easier to modify slightly an include file in the kernel sources include/linux/slab.h :
--- a/include/linux/slab.h +++ b/include/linux/slab.h @@ -185,6 +185,8 @@ size_t ksize(const void *); #include <linux/slub_def.h> #elif defined(CONFIG_SLOB) #include <linux/slob_def.h> +#elif defined(CONFIG_SIM) +#include <asm/slab.h> #else #include <linux/slab_def.h> #endif
As we have already written we do not recommend to change the kernel sources to facilitate future upgrades.
After a few corrections we finally get a library containing the kernel named liblinux-stable.so. At this moment we need to try it using DCE. For the beginning we will try with test-runner executable.
./test.py assert failed. cond="handle != 0", msg="Could not open elf-cache/0/libnet-next-2.6.so elf-cache/0/liblinux-stable.so: undefined symbol: noop_llseek", file=../model/cooja-loader-factory.cc, line=225 terminate called without an active exception Aborted (core dumped)
We can see that a symbol is not defined : noop_llseek. We find this symbol defined in the kernel source named fs/read_write.cc. We need to choose a way to add this symbol in our kernel library, we can:
- rewrite it in a source under our sim directory,
- or add it in our makefile.
In this case we choose the second solution so we need to modify our makefile, first we see that the directory fs is not present in the dirs entry, so we need to add it in the write order (order is the same as found in the kernel Makefile defined by the variable named vmlinux-main); we also need to indicate that we want only the object read_write.o:
@@ -51,7 +52,7 @@ AUTOCONF=autoconf.h # note: the directory order below matters to ensure that we match the kernel order -dirs=kernel/ mm/ crypto/ lib/ drivers/base/ drivers/net/ net/ +dirs=kernel/ mm/ fs/ crypto/ lib/ drivers/base/ drivers/net/ net/ empty:= space:= $(empty) $(empty) colon:= : @@ -67,11 +68,12 @@ ctype.o string.o kasprintf.o rbtree.o sha1.o textsearch.o vsprintf.o \ rwsem-spinlock.o scatterlist.o ratelimit.o hexdump.o dec_and_lock.o \ div64.o +fs/_to_keep=read_write.o
We continue to try our kernel library, now another symbol is missing generic_file_aio_read, this symbol is defined in the source mm/filemap.cc, it is referenced at least by read_write.c. In this case we decided to create a fake function because the source mm/filemap.cc is voluminous and we do not want to take all the kernel sources. So we create a new source under sim directory named sim/filemap.c the body of the function is sim_assert (false); so if this function called sometimes we will be warned and we will write a more accurate version.
Later we meet again the function kern_mount_data, thanks to the presence of the sim_assert:
0x00007ffff5c8c572 in kern_mount_data (fs=<optimized out>, data=<optimized out>) at sim/fs.c:52 52 sim_assert (false); (gdb) bt #0 0x00007ffff5c8c572 in kern_mount_data (fs=<optimized out>, data=<optimized out>) at sim/fs.c:52 #1 0x00007ffff5d85923 in sock_init () at linux-stable/net/socket.c:2548 #2 0x00007ffff5c8d3aa in sim_init (exported=<optimized out>, imported=<optimized out>, kernel=<optimized out>) at sim/sim.c:169 #3 0x00007ffff7d9151b in ns3::LinuxSocketFdFactory::InitializeStack (this=0x65bde0) at ../model/linux-socket-fd-factory.cc:535 #4 0x00007ffff7d95ce4 in ns3::EventMemberImpl0::Notify (this=0x6597a0) at /home/furbani/dev/dce/dev/build/include/ns3-dev/ns3/make-event.h:94 #5 0x00007ffff76b10a8 in ns3::EventImpl::Invoke (this=0x6597a0) at ../src/core/model/event-impl.cc:39 #6 0x00007ffff7d8ff7c in ns3::LinuxSocketFdFactory::ScheduleTaskTrampoline (context=0x6597a0) at ../model/linux-socket-fd-factory.cc:373 #7 0x00007ffff7d3b7d4 in ns3::TaskManager::Trampoline (context=0x65d170) at ../model/task-manager.cc:250 #8 0x00007ffff7d37acd in ns3::PthreadFiberManager::Run (arg=0x65d5d0) at ../model/pthread-fiber-manager.cc:398 #9 0x00000034be206ccb in start_thread () from /lib64/libpthread.so.0 #10 0x00000034bd6e0c2d in clone () from /lib64/libc.so.6 (gdb)
So this function is called by the initialisation, we must provide an implementation for it:
// Implementation taken from vfs_kern_mount from linux/namespace.c struct vfsmount *kern_mount_data(struct file_system_type *type, void *data) { static struct mount local_mnt; struct mount *mnt = &local_mnt; struct dentry *root = 0; memset (mnt,0,sizeof (struct mount)); if (!type) return ERR_PTR(-ENODEV); int flags = MS_KERNMOUNT; char *name = type->name; if (flags & MS_KERNMOUNT) mnt->mnt.mnt_flags = MNT_INTERNAL; root = type->mount(type, flags, name, data); if (IS_ERR(root)) { return ERR_CAST(root); } mnt->mnt.mnt_root = root; mnt->mnt.mnt_sb = root->d_sb; mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; // br_write_lock(vfsmount_lock); DCE is monothreaded , so we do not care of lock here list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts); // br_write_unlock(vfsmount_lock); DCE is monothreaded , so we do not care of lock here return &mnt->mnt; }
Here we do not want to integrate all the code namespace.c, so we copy and paste the function named kern_mount_data. This solution has the advantage of minimizing code size, the disadvantage is that it can introduce problems if the next version of the kernel need changes in this function.
We will not describe the rest of the port here. But after some iteration we end up with a version that works correctly. Sometimes we should not hesitate to use gdb to trace the actual execution and correct accordingly code. The rules that we can gain from this experience’s are as follows:
The
This section describes how generate the DCE Python bindings. The intended audience are the DCE developers, not the users willing to make simulations. People not interested in adding new public API can ignore this section, and read the chapter DCE Python Scripts.
Waf configuration scripts generate the Python bindings in a semi-automatic way. They use PyBindGen to generate a Python script template. This script needs to be manually updated. This intermediate script will generate a C++ source file that can be then compiled as a shared object, installed and imported by the Python scripts.
In this step, Waf calls PyBindGen to analyze the DCE public reference headers, in order to generate a temporary template Python file, that will generate a C++ file.
./waf --apiscan
The Pyhon script generated in the first step needs to be adjusted and renamed as ns3_module_dce.py. In particular to reduce the coupling with the ns-3 installation the waf configuration has been simplified. For this reason you need to paste the correct references for the ns-3 exported symbols, as for example:
module.add_class('Object', import_from_module='ns.core') module.add_class('Node', import_from_module='ns.network') module.add_class('NodeContainer', import_from_module='ns.network')
ns3_module_dce.py can directly generate a C++ file for the Python module: ns3_module_dce.cpp. It should be added to the code revision system and included in the distribution. It just requires an installed recent version of Pybindgen.
If you are interested to know why DCE exists and how it can work, you should read this document Experimentation Tools for Networking Research (and in particular the chapter 4) written by the principal author of DCE, Mathieu Lacage. Also you can read the sources too.
You know that the goal of DCE is to execute actual binaries within ns-3. More precisely a binary executed by DCE perceives time and space of ns-3, rather than the real environment.
To do this, DCE does a job equivalent to an operating system like:
The DceManager is somewhat the entry point of DCE. It will create virtual processes and manages their execution. There is an instance of DceManager which is associated to each node which need to virtualize the execution of a process. In reality, the developer uses the classes DceManagerHelper and DceApplicationHelper.
I invite you to look at the source code dce-manager.cc and dce-manager.h and particularly the public methods Start, Stop, Exit, Wakeup, Wait and Yield; the following private methods are also important: CreateProcess, PrepareDoStartProcess, DoStartProcess, AllocatePid, TaskSwitch, CleanupThread and LoadMain. The Start method is called when starting the executable, if you look at, it begins by initializing an object of type struct Process. struct Process is very important, it contains information about the virtual processes that DCE creates, this type is described below. Start then also initializes a structure of type struct thread, it represents the principal thread in which the main entry of the executable will run. Finally Start asks the TaskManager to create a new Task and to start this one using the method DceManager::DoStartProcess as the entry point.
Class TaskManager is a major class of DCE, it is described below.
struct process contains everything you need to describe a process, I invite you to study the source code in the file process.h.
This structure contains references to standard objects for example a list of open files via a vector of FILE *, but it contains also the references to objects useful to manage DCE threads, the memory allocated by the process...
Field openFiles represents the open file descriptors of the process, the key is the fd and the value a pointer to an object of type DCE FileUsage. The field threads contains all the threads in the process see description below. Field loader is a pointer to the Loader used to load the corresponding code.
The alloc field is important it is a pointer to the memory allocator used to allocate the memory used by this process, at the end of the process it will liberate all the memory allocated so as simple and efficient.
struct thread represents a thread, It contains various fields including a pointer to the process to which it belongs, and also a pointer to Task object described later.
The TaskManager manages the Tasks, ie the threads of virtualized processes by DCE. It allows you to create new task. It controls the activity of the task by the following methods: Stop, Wakeup, Sleep and Yield. A Task possesses a stack which contains the call stack functions. There is one instance of TaskManager per node. The implementation of TaskManager is based on a class of type FiberManager described below.
FiberManager actually implements the creation of the execution contexts. These contexts are called fiber. FiberManager offers the following:
DCE provides two implementations:
I invite you to watch the corresponding man.
The Loader is a very important object of DCE. A DCE Loader loads the executable code in memory of a special way, load several times the same executable, while isolating each of the other executable. The Loader must link the executable loaded with the 3 emulated libraries, i.e., lib C, lib pthread and lib rt. The same way the libraries used by the executable must also be linked with the emulated libraries.
DCE offers several actually Loader:
After theory, do a bit of practice. Follow the execution of very simple example.
You can find the used sample under the directory named myscripts/sleep. This executable used by the scenario do only a sleep of ten seconds:
#include <unistd.h> int main(int c, char **v) { sleep (10); return 1; }
The ns-3/DCE scenario execute tenseconds one time starting at time zero:
#include "ns3/core-module.h" #include "ns3/dce-module.h" using namespace ns3; int main (int argc, char *argv[]) { NodeContainer nodes; nodes.Create (1); DceManagerHelper dceManager; dceManager.Install (nodes); DceApplicationHelper dce; ApplicationContainer apps; dce.SetStackSize (1<<20); dce.SetBinary ("tenseconds"); dce.ResetArguments (); apps = dce.Install (nodes.Get (0)); apps.Start (Seconds (0.0)); Simulator::Stop (Seconds(30.0)); Simulator::Run (); Simulator::Destroy (); }
First we can launch tenseconds binary:
$ ./build/bin_dce/tenseconds
after 10 seconds you retrieve the prompt.
Then we can try the DCE scenario:
$ ./build/myscripts/sleep/bin/dce-sleep
This time the test is almost instantaneous, because the scenario is very simple and it uses the simulated time.
Same test by activating logs:
$ NS_LOG=DefaultSimulatorImpl ./build/myscripts/sleep/bin/dce-sleep DefaultSimulatorImpl:DefaultSimulatorImpl(0x6928c0) DefaultSimulatorImpl:SetScheduler(0x6928c0, ns3::MapScheduler[]) 0s -1 DefaultSimulatorImpl:ScheduleWithContext(0x6928c0, 0, 0, 0x692ab0) 0s -1 DefaultSimulatorImpl:ScheduleWithContext(0x6928c0, 0, 0, 0x695220) 0s -1 DefaultSimulatorImpl:Stop(0x6928c0, 30000000000) 0s -1 DefaultSimulatorImpl:Schedule(0x6928c0, 30000000000, 0x692c10) 0s -1 DefaultSimulatorImpl:Run(0x6928c0) 0s -1 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 0 0s 0 DefaultSimulatorImpl:Schedule(0x6928c0, 0, 0x695630) 0s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 0 0s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 0 0s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 0 0s 0 DefaultSimulatorImpl:Schedule(0x6928c0, 10000000000, 0x6954c0) 0s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 10000000000 10s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 10000000000 10s 0 DefaultSimulatorImpl:ProcessOneEvent(): [LOGIC] handle 30000000000 30s -1 DefaultSimulatorImpl:Stop(0x6928c0) DefaultSimulatorImpl:Destroy(0x6928c0) DefaultSimulatorImpl:Destroy(): [LOGIC] handle destroy 0x6928a0 DefaultSimulatorImpl:DoDispose(0x6928c0) DefaultSimulatorImpl:~DefaultSimulatorImpl(0x6928c0)
We can see that an event occurs at 30s it is the end of the simulation corresponding to the line:
Simulator::Stop (Seconds(30.0));
We can also see that at 10s an event occurs, this is the end of our sleep(10).
Now we do the same experiment using the debugger:
$ gdb ./build/myscripts/sleep/bin/dce-sleep (gdb) b ns3::DceManager::DoStartProcess (gdb) b ns3::DceManager::Start (gdb) run Breakpoint 4, ns3::DceManager::Start (this=0x630c50, name=..., .... at ../model/dce-manager.cc:403 403 NS_LOG_FUNCTION (this << name << stackSize << args.size () << envs.size ()); (gdb) bt #0 ns3::DceManager::Start (this=0x630c50, name=.....) at ../model/dce-manager.cc:403 #1 0x00007ffff7cb5e19 in ns3::DceApplication::StartApplication (this=0x633520) at ../model/dce-application.cc:79 #2 0x00007ffff71dea6e in ns3::EventMemberImpl0::Notify (this=0x633650) at ./ns3/make-event.h:94 #3 0x00007ffff76148af in ns3::EventImpl::Invoke (this=0x633650) at ../src/core/model/event-impl.cc:45 #4 0x00007ffff76194c3 in ns3::DefaultSimulatorImpl::ProcessOneEvent (this=0x6308e0) at ../src/core/model/default-simulator-impl.cc:140 #5 0x00007ffff761986a in ns3::DefaultSimulatorImpl::Run (this=0x6308e0) at ../src/core/model/default-simulator-impl.cc:193 #6 0x00007ffff76155dd in ns3::Simulator::Run () at ../src/core/model/simulator.cc:160 #7 0x00000000004075af in main (argc=1, argv=0x7fffffffdaa8) at ../myscripts/sleep/dce-sleep.cc:25 (gdb) info thread Id Target Id Frame * 1 Thread 0x7ffff6600740 (LWP 7977) "dce-sleep" ns3::DceManager::Start (this=0x630c50, .... ) at ../model/dce-manager.cc:403
You can notice that:
Now we continue our execution:
(gdb) continue Continuing. [New Thread 0x7ffff65fc700 (LWP 8159)] [Switching to Thread 0x7ffff65fc700 (LWP 8159)] Breakpoint 3, ns3::DceManager::DoStartProcess (context=0x633d50) at ../model/dce-manager.cc:274 274 Thread *current = (Thread *)context; (gdb) info thread Id Target Id Frame * 2 Thread 0x7ffff65fc700 (LWP 8159) "dce-sleep" ns3::DceManager::DoStartProcess (context=0x633d50) at ../model/dce-manager.cc:274 1 Thread 0x7ffff6600740 (LWP 7977) "dce-sleep" pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_cond_wait.S:162 (gdb) bt #0 ns3::DceManager::DoStartProcess (context=0x633d50) at ../model/dce-manager.cc:274 #1 0x00007ffff7d21b90 in ns3::TaskManager::Trampoline (context=0x633bd0) at ../model/task-manager.cc:267 #2 0x00007ffff7d1da87 in ns3::PthreadFiberManager::Run (arg=0x634040) at ../model/pthread-fiber-manager.cc:402 #3 0x00000034be206ccb in start_thread (arg=0x7ffff65fc700) at pthread_create.c:301 #4 0x00000034bd6e0c2d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115
You can notice that:
This second thread is the thread corresponding to the main thread of our hosted executable tenseconds, if you look at ns3::DceManager::DoStartProcess you can notice that we are on the point of calling the main of tenseconds:
void DceManager::DoStartProcess (void *context) { Thread *current = (Thread *)context; int (*main)(int, char **) = PrepareDoStartProcess (current); int retval = 127; if (main) { StartProcessDebugHook (); retval = main (current->process->originalArgc, current->process->originalArgv); } dce_exit (retval); }
You can also see that the pointer to the main is the result of the method ns3::DceManager::PrepareDoStartProcess. Now we can put a breakpoint before the sleep of tenseconds and follow the code of sleep:
(gdb) break tenseconds.c:5 (gdb) continue Breakpoint 1, main (c=1, v=0x630b30) at ../myscripts/sleep/tenseconds.c:5 5 sleep (10); (gdb) list (gdb) step sleep () at ../model/libc-ns3.h:193 193 DCE (sleep) (gdb) step dce_sleep (seconds=10) at ../model/dce.cc:226 226 Thread *current = Current (); (gdb) list 224 unsigned int dce_sleep (unsigned int seconds) 225 { 226 Thread *current = Current (); 227 NS_LOG_FUNCTION (current << UtilsGetNodeId ()); 228 NS_ASSERT (current != 0); 229 current->process->manager->Wait (Seconds (seconds)); 230 return 0; 231 } (gdb) bt #0 dce_sleep (seconds=10) at ../model/dce.cc:226 #1 0x00007ffff62cdcb9 in sleep () at ../model/libc-ns3.h:193 #2 0x00007ffff5c36725 in main (c=1, v=0x630b30) at ../myscripts/sleep/tenseconds.c:5 #3 0x00007ffff7c9b0bb in ns3::DceManager::DoStartProcess (context=0x633d50) at ../model/dce-manager.cc:281 #4 0x00007ffff7d21b90 in ns3::TaskManager::Trampoline (context=0x633bd0) at ../model/task-manager.cc:267 #5 0x00007ffff7d1da87 in ns3::PthreadFiberManager::Run (arg=0x634040) at ../model/pthread-fiber-manager.cc:402 #6 0x00000034be206ccb in start_thread (arg=0x7ffff65fc700) at pthread_create.c:301 #7 0x00000034bd6e0c2d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115 (gdb) info thread Id Target Id Frame * 2 Thread 0x7ffff65fc700 (LWP 15233) "dce-sleep" dce_sleep (seconds=10) at ../model/dce.cc:226 1 Thread 0x7ffff6600740 (LWP 15230) "dce-sleep" pthread_cond_wait@@GLIBC_2.3.2 () at ../nptl/sysdeps/unix/sysv/linux/x86_64/pthread_cond_wait.S:162 (gdb)
We can notice that sleep call dce_sleep which call Wait, this Wait method is from the class TaskManager. TaskManager is a major class of DCE and we will detail it below. Basically Wait schedules and event in ns-3 event queue (in order to be woken up after sleep time) and give the control to another Task. Now we can put a breakpoint in ns3::DefaultSimulatorImpl::ProcessOneEvent and see the time advance up to 10s:
gdb) b ns3::DefaultSimulatorImpl::ProcessOneEvent Breakpoint 2 at 0x7ffff7619207: file ../src/core/model/default-simulator-impl.cc, line 131. (gdb) c Continuing. [Switching to Thread 0x7ffff6600740 (LWP 3942)] Breakpoint 2, ns3::DefaultSimulatorImpl::ProcessOneEvent (this=0x6308e0) at ../src/core/model/default-simulator-impl.cc:131 warning: Source file is more recent than executable. 131 Scheduler::Event next = m_events->RemoveNext (); (gdb) n 133 NS_ASSERT (next.key.m_ts >= m_currentTs); (gdb) n 134 m_unscheduledEvents--; (gdb) n 136 NS_LOG_LOGIC ("handle " << next.key.m_ts); (gdb) n 137 m_currentTs = next.key.m_ts; (gdb) n 138 m_currentContext = next.key.m_context; (gdb) p m_currentTs $1 = 10000000000 (gdb)
This next event will wake the thread 2 will therefore complete the sleep of our scenario.
In summary we saw briefly that DCE uses the events of ns-3 to schedule the execution between different tasks.
Below are the list of the tested applications with DCE.
CCNx is an open source implementation of Content Centric Networking. All the C written executables are supported and none of the Java ones. The versions tested are those between 0.4.0 and 0.6.1 included.
For more detail document, see CCNx examples.
Quagga is a routing software suite, providing implementations of OSPFv2, OSPFv3, RIP v1 and v2, RIPng and BGP-4 for Unix platforms, particularly FreeBSD, Linux, Solaris and NetBSD. For more information, see the latest support document.
iperf from the following archive as been tested. It is the exception that proves the rule. That is to say that this particular example requires a change in its code. In the source file named Thread.c at line 412 in the function named thread_rest you must add a sleep(1) in order to help DCE to break the infinite loop.
Ping from the following archive is supported.
The umip (Usagi-Patched Mobile IPv6 stack) support on DCE enables the users to reuse routing protocol implementations of Mobile IPv6. UMIP now supports Mobile IPv6 (RFC3775), Network Mobility (RFC3963), Proxy Mobile Ipv6 (RFC5213), etc, and can be used these protocols implementation as models of network simulation.
For more information, see the latest support document.
Linux kernel support is built with ‘dce-linux’ module, downloading separate module available at github. Many protocols implemented in kernel space such as TCP, IPv4/IPv6, Mobile IPv6, Multipath-TCP, SCTP, DCCP, etc, are available with ns-3.
FreeBSD kernel support is based on Linux kernel module of DCE. The code is also maintained at github. A few protocols implemented in kernel space such as TCP, IPv4, etc, are available with ns-3. | https://www.nsnam.org/docs/dce/release/1.4/manual/singlehtml/index.html | CC-MAIN-2017-39 | refinedweb | 11,437 | 50.43 |
Asynchronous Ajax for Revolutionary Web Applications
To understand Ajax Push (variously called "Comet" or "Reverse Ajax") it is necessary to cover a variety of topics. After setting the stage with a practical definition of Web 2.0, we will proceed with an explanation of Ajax Push on the wire, move along to see the impact on the server and what server APIs to use, and then conclude with techniques for application development.
By Ted Goddard & Jean-Francois Arcand
Web 2.0 and the Asynchronous Revolution
Does "Web 2.0" have a useful interpretation that will allow us to build better applications, or is it just an O'Reilly trademark? To extract a useful definition, we need to look at some applications that are typically considered to fall into the category of "Web 2.0", applications such as eBay, Blogger, YouTube, and Flickr. There are a number of common characteristics to these applications, but what we want to focus on here is the fact that they are "created" by their users.
Now let's look more closely at eBay. Is eBay interesting because eBay has a bunch of things to sell us, or is eBay interesting because its users are posting items for auction and bidding on them? Clearly, the eBay application is built collaboratively by its users. eBay is a multi-user collaboration system, where the eBay application is created through the participation of its users. As Jonathan Schwartz said at JavaOne in 2005, we're moving out of the "Information Age" and into the "Participation Age". His intent was that software is now being developed collaboratively through open source, but the comment applies equally well to the web overall.
No longer is the web just about some institution putting their documents on a public file server and letting other people retrieve them. Now, the web is all about users building applications together with their contributions. We're posting auctions. We're posting Wikipedia articles. We're making entries on blogs, contributing photos and movies. All of these things contributed by users are building the web. In other words, the web as a whole is turning into a collaborative environment.
But if we drill down into an individual eBay page, where we're looking at an interesting auction item, we really have little more than a print-out on the screen. Other users could be bidding on the item, but we have no knowledge of that until we press "refresh". The web page itself is not collaborative or multi-user.
Ajax helps to improve the user experience, but it still doesn't allow us to see what the other users are doing at that time; the network operations are still synchronized to the user event stream. To build a collaborative application, we need the full realization of Ajax, or "Ajax Push" where we have an asynchronous channel from the server to the browser that allows us to update the page at any time.
How can we use such an asynchronous communication channel to build a more interesting application that allows users to collaborate?
Imagine that we have two users of a slideshow application: the moderator, Yoda, and a viewer, Luke. Yoda presses a button to advance the slide, thereby sending a user event to the server. The server processes this user event and, using its push capability, pushes the slide change out to Luke on the other computer. In other words, the push capability allowed us to turn the web application into a new type of communication tool. In this case, the new form of communication is a multi-user slide-show.
Now the revolutionary nature of this should be clear; if we look back through history for world-changing technologies, we can see that many of them were inventions that allowed people to communicate with each other in different ways: moveable type, radio, television, just to name a few. If we have a way to turn every web application into a new, unique, communication tool, we are standing on the brink of another revolution. If you take a step back and think about the application that you're working on today, you will realize that there are some very interesting ways to add push capabilities and multi-user interaction.
For instance, in the future, we'll see chat, forums, and blogging all merge into a single, hybrid application. Consider providing a blog with responses updated in real time. This would turn the blogging system into a chat system, and it would improve people's ability to communicate with each other through it.
Let's see what we need to make the revolution a reality.
Ajax Push on the Wire
There are three common techniques for implementing a Push protocol on top of HTTP: polling, long polling, and streaming. Let's examine each in turn.
Polling is not a particularly good option because it always seems unresponsive: either you choose your polling interval to be short in an attempt to receive messages with a minimum delay, and you swamp the server with polling requests (which makes the application unresponsive), or you choose your polling interval to be long to reduce load on the server, and the application seems unresponsive because the messages are not delivered in a timely fashion. Fundamentally, polling is not the right choice for building an event-driven system. (To be fair, there are application cases with very long polling intervals that make it the right choice; for instance, updating a page containing a report on today's final weather statistics. These are not collaborative applications, however).
Long polling (or "blocking HTTP") makes use of a delayed response on the server to push a message at the desired time. The browser performs an HTTP request for a message, and the server simply delays until a message is available, whereupon the process repeats with the browser again making a request for a message. This effectively inverts the message flow of HTTP. Since a slow server cannot be prohibited by the HTTP specification, this technique works well through proxies and firewalls. The only drawback is the network overhead required by the message requests, but this can be mitigated by accumulating messages on the server and sending them in batches.
HTTP streaming is the most efficient at the TCP level, but unfortunately encounters some complications with proxies and the JavaScript API. The potential problem with an HTTP proxy is that (depending on configuration) it may choose to buffer the HTTP response until it is complete. In the case of streaming, the response isn't complete until the application has exited, resulting in no messages being delivered to the browser. The other problem is that JavaScript does not provide a read() API, so to read from a stream, it is necessary to collect the entire stream as a buffer in memory, essentially becoming a memory leak in the browser.
As a point of reference, ICEfaces uses the blocking HTTP technique. The operation can be described very concretely because messages in ICEfaces contain only page updates: When the browser loads an ICEfaces page from the server, it executes some JavaScript whose first operation is to request any page updates. If there are no page updates at that time, the server simply waits. When a page update is ready, for instance when a user has typed in a chat message, the server responds with the associated page changes. The browser then asks again, and the cycle continues.
Ajax Push on the Server
With our wire protocol in hand, we are ready to move to the server, but the two favored push techniques do not scale well on the current Servlet 2.5 API. Let's look at the problem more closely and explore some of the different server APIs that offer solutions.
With Servlet 2.5, holding onto an HTTP response means never emerging from the service() method, thereby consuming a thread. Since we need a push connection for each user, this causes us to consume a thread on the server for every single user. That's not generally good for scalability.
Instead what we need to do is handle multiple requests and responses with a small thread pool. Let's look at some of the various options for this available on Jetty, Tomcat, Resin, WebLogic, and GlassFish, and look slightly into the future with Servlet 3.0.
Jetty
Jetty allows us to suspend request processing with a Continuation. This is not a full Java language Continuation (analogous to making Thread Serializable) but is specific to request processing. By calling continuation.suspend() an exception will be thrown that will be caught by Jetty, causing the request/response pair to be associated with that continuation. Then later, say when it's time to update the page with a chat message, continuation.resume() will call the service() method once again with the same request and response. It's a bit unusual to re-enter the service method with the same objects, but the advantage is that the Servlet API requires no modification.
import org.mortbay.util.ajax.Continuation;
service(request, response) {
Continuation continuation = ContinuationSupport
.getContinuation(request, this);
...
continuation.suspend();
response.getWriter().write(message);
}
To cause the request processing to be resumed when a chat message is ready:
message.setValue("Howdy");
continuation.resume();
Tomcat
The Tomcat 6 API is perhaps closest to the NIO underpinnings of asynchronous request processing. The Tomcat CometProcessor interface must be implemented by the servlet handling the push interaction, but once in place, a variety of events are available, and the request and the response can be manipulated by an arbitrary Thread.
import org.apache.catalina.CometProcessor;Later, when it's time to update the page with a chat message, event.close() causes the response to be complete and flushed to the browser.
public class Processor implements CometProcessor {
public void event(CometEvent event) {
request = event.getHttpServletRequest();
response = event.getHttpServletResponse();
if (event.getEventType() == EventType.BEGIN) { ...
if (event.getEventType() == EventType.READ) { ...
if (event.getEventType() == EventType.END) { ...
if (event.getEventType() == EventType.ERROR) { ...
}
message.setValue("Howdy");
response.getWriter().write(message);
event.close();
Resin
Resin splits the request handling into two methods that return a boolean indicating whether the request should be suspended.
public class CometServlet extends GenericCometServlet {Later, when it's time to update the page with a chat message, cometController.wake() causes the resume() method to be called, and the response is flushed to the browser.
public boolean service(ServletRequest request,
ServletResponse response,
CometController cometController)
...
return true;
}
public boolean resume(ServletRequest request,
ServletResponse response,
CometController cometController)
PrintWriter out = res.getWriter();
out.write(message);
return false;
}
message.setValue("Howdy");
cometController.wake();
WebLogic
WebLogic is just like Resin, but the opposite. Returning false from doRequest() indicates that request processing should not continue.
import weblogic.servlet.http.AbstractAsyncServlet;Later, when it's time to update the page with a chat message, AbstractAsyncServlet.notify() causes doResponse() to be called, and the response is flushed to the browser.
import weblogic.servlet.http.RequestResponseKey;
class Async extends AbstractAsyncServlet {
public boolean doRequest(RequestResponseKey rrk) {
... = rrk;
return false;
}
public void doResponse(RequestResponseKey rrk, Object message) {
rrk.getResponse().getWriter.write(message);
}
message.setValue("Howdy");
AbstractAsyncServlet.notify(rrk, message);
GlassFish
GlassFish provides the most flexible API and one of its strengths is that the asynchronous capability can be detected and used at runtime. When addCometHandler() is called on the cometContext, the request is suspended.
CometContext context =Later, when it's time to update the page with a chat message, cometContext.notify() can be used as an event mechanism to simplify application development, but the key method is cometContext.resumeCometHandler(), which causes the response to be flushed to the browser.
CometEngine.getEngine().register(contextPath);
context.setExpirationDelay(20 * 1000);
SuspendableHandler handler = new SuspendableHandler();
handler.attach(response);
cometContext.addCometHandler(handler);
class SuspendableHandler implements CometHandler {
public void onEvent(CometEvent event) {
response.getWriter().println(event.attachment());
cometContext.resumeCometHandler(this);
}
message.setValue("Howdy");
cometContext.notify(message);
Additionally, GlassFish provides delivery guarantee and Quality-of-Service APIs.
Atmosphere
Atmosphere (atmosphere.dev.java.net) is a framework that hides the container specific Comet/Ajax Push implementation, aiming to simplify the devlopment and improve the portablility of asynchronous web applications. Using the Atmosphere API, you can now write portable applications without worrying about the container you will deploy onto. More important, if a container doesn't support Comet/Ajax Push, Atmosphere will still work by emulating it directly within the framework.
Atmosphere aims to simplify the devlopment and improve the portablility of asynchronous web applications. Any Java object can be enhanced with asynchronous server features through a few annotations, as illustrated below:
@Grizzlet(Grizzlet.Scope.APPLICATION)
@Path("myGrizzlet")
public class MyGrizzlet{
@Suspend(6000)
@GET
@Push
public String onGet(){
return "Suspending the connection";
}
@Push
public String onPost(@Context HttpServletRequest req,
@Context HttpServletResponse res) throws IOException{
res.setStatus(200);
res.getWriter().println("OK, info pushed");
return req.getParameter("chatMessage");
}
Servlet 3.0
Servlet 3.0 will cover the ability to suspend and resume a connection, but will not support asynchronous read/write and delivery guarantee capabilities. As an integration of the best ideas found in existing APIs, the Servlet EG is always looking to the public for feedback. Should it have a re-entrant service() method? Should Filters be supported on both the inbound request and the outbound resumed response? Now is the time to voice your opinion.
The Two-Connection Limit
Having a great server API is only part of the story. A practical problem encountered when trying to implement push is the fact that most browsers generally have a limit of two connections to a given server. If the user opens two browser windows with each window attempting to maintain a push connection with the server, both of the permitted TCP connections are consumed. This means that any user events (such as clicking on a button or a link) will not be sent to the server -- there isn't an available TCP connection to deliver it over. Therefore, we need to share a single TCP connection across the multiple browser windows.
The ICEfaces Ajax Push Server was created to solve this by using JMS to coordinate all of the push updates over a single channel. In the browser, a JavaScript cookie-polling technique is used to share the notification of updates across the browser windows (HTML5 postMessage() would simplify the implementation here). This allows the reliable delivery of push updates from multiple web applications on the server into multiple browser tabs or windows.
For GlassFish, ICEfaces provides an update-center module that allows you to easily add the Ajax Push Server and install it, automatically configuring the JMS topics.
Developing Asynchronous Applications
We've looked at variations on the Servlet API that will allow us to develop scalable push applications, but the fact is that not many developers work directly with the Servlet API today. Developers work with framework APIs, such as Cometd, DWR, and ICEfaces, largely hiding the underlying Servlet capabilities. So, let's briefly examine how to use these frameworks.
For the developer concentrating on JavaScript, a great choice is Cometd. Cometd is based on the idea of publish/subscribe messaging mediated by a server-side reflector. Notice that the server is potentially just a reflector and could be implemented in any language, serving only as a message relay between JavaScript endpoints. Of course, server APIs are possible as well, and these are available for a variety of servers. Note that systems based purely on client message exchange suffer from the "late joiner problem". If you join the application late, you may not have the correct intermediate state to apply the current messages.
Moving more into the realm of the Java developer, we have DWR, or "Direct Web Remoting". DWR essentially provides the familiar Java RMI (or Remote Method Invocation, in case you don't find it familiar) bridged into JavaScript. Primarily, DWR is used to expose server-side JavaBeans through object-oriented JavaScript interfaces, but the "reverse" is also possible: DWR can be used to invoke JavaScript methods in the client from server-side Java code. There are two methods noteworthy for illustration: addScript() allows the application to invoke a common snippet of JavaScript on a group of specified pages, and setValue() allows the application to update a group of browser DOMs uniformly with a specified value. These are powerful client-side capabilities to have available on the server; however, they do require that the application retain detailed knowledge of the contents of the page being viewed.
Now that we've seen several APIs and frameworks, we should take a step back and ask what application developers and designers would ideally work with to produce an Ajax Push application.
First of all, developers should work mainly with JavaBeans, with a minimum of non-standard types (POJOs are preferred).
public class PageBean {
String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Designers should work largely with HTML, but they will also need a natural expression language for dynamically binding to the JavaBean model.
<f:view
xmlns:f=""
xmlns:
<html>
<body>
<h:form>
<h:inputText
</h:form>
</body>
</html>
</f:view>
But creating applications in such a natural way isn't only in our imagination. This clean separation between model and view is one of the great strengths of JavaServer Faces (JSF), and both developers and designers find it very productive (even if "develop" and "design" are roles taken by the same individual at different times). When we look at the syntax provided, we see that it says nothing about Ajax (no JavaScript is visible); yet, shouldn't it be sufficient to define an Ajax application? We have described the objects in the model (in Java), the components that are visible in the view (in XHTML), and how the view relates to the model (in expression language). A framework should be able to translate this into an Ajax application for us; indeed this is precisely the contract that ICEfaces provides to application developers. Nothing more is needed to define an Ajax application.
But what about push? When we consider that ICEfaces incrementally updates the page with current model values in response to user events, it's a small step to ask that the page be incrementally updated with current model values in response to server-side events. In other words, it's enough for the server-side application to be able invoke a render pass of a JSF page, provided the framework can push the incremental changes to the browser. This makes adding push features as simple as two lines of code.
For each user that belongs in a group named "chat":
SessionRenderer.addCurrentSession("chat")
We have added the current user's session into the group of sessions called "chat". Then, when a chat message is received and its time to push the update to the users' pages:
SessionRenderer.render("chat")
This renders all the windows of all the users in the "chat" group (automatically determining the incremental page changes), and pushes those page changes to the users' browsers. Adding push features to an existing JSF application can often be done in no more than two lines of code.
Additionally, more fine-grained APIs are available (such as for directing push updates to specific windows); please see the ICEfaces developer's guide for details.
Conclusion
It should now be clear that the asynchronous web is a revolutionary step forward for multi-user web applications, but such applications can be developed largely with current techniques. The key piece is Ajax Push, and it can scale to meet demand as long as the right application servers and APIs are applied carefully. Of course, the authors believe that you will find the combination of ICEfaces and GlassFish to be the most effective, allowing you to easily add multi-user features to your web application and allowing you to deploy it and scale to meet demand.
- Login or register to post comments
- 6202 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
awewriter replied on Wed, 2008/11/12 - 9:15am
Jose Maria Arranz replied on Wed, 2008/11/12 - 9:45am
The scalability benefits of a NIO solution instead of a thread based is being debunked.
Anyway I agree, Comet is going to change how we develop/understand web applications, may be Comet is going to define the new Web 3.0 = Real Time Web.
By the way, add ItsNat to the list of Comet-capable Java web frameworks (the "add" word is rhetoric yes I know Ted is the technical leader of IceFaces).
Ted Goddard replied on Wed, 2008/11/12 - 12:12pm
Paul's presentation was very interesting, thanks for the reference. Of course, threading, IO, and NIO performance are all very dependent on the particular JVM and operating system used. Historically, threads have been very expensive, but with new manufacturing methods they have come down dramatically in price. Similarly, we can expect to see optimizations for NIO (or AIO) that will allow it to lead in throughput as well as scalability.
muralive replied on Wed, 2008/11/12 - 7:49pm
Jose Maria Arranz replied on Thu, 2008/11/13 - 2:49am
in response to: muralive
This is the kind of opinion I've heard before when the "term" AJAX started to sound (and use). Past five years since today I invite you to review your opinion again.
By the way: HTTP was invented to serve static content, remind this to Google, Amazon or eBay :)
muralive replied on Thu, 2008/11/13 - 3:17am
Jose Maria Arranz replied on Thu, 2008/11/13 - 4:05am
in response to: muralive
@muralive: That is not my point, the author seems to forget the fundamentals, can you imagine the kind of computing resources needed to scale and the complexity of a state machine to handle such a push technology?
Do you know the computing resources needed by Google, Amazon or eBay to serve millions of concurrent requests?
Do you know they are "real" applications handling this complexity? For instance this and this.
@muralive: What I meant as purpose behind HTTP was the "stateless" nature of it (unlike FTP or Telnet)
Yes, Tim Berners-Lee at CERN dixit many years ago, but HTTP + session cookie = stateful service, and HTTP + AJAX = no longer requesting complete pages again and again. We are in 2008.
@muralive: Can you imagine the the heartbeat messages and bandwidth of the server needed to keep the pipes open from a few clients to potentially millions, all concurrent?
In Comet, if nothing occurs nothing is sent, compulsive page reload by users is the real bandwidth consumer.
Do you know any average computer can handle thousand of threads and connections with no very much problem if they're most of the time in idle state?
Does your web site handle millions of concurrent users? Yeah! you're Google!
eirirlar replied on Thu, 2008/11/13 - 5:22am
Ted:.
Ted Goddard replied on Thu, 2008/11/13 - 11:22am
in response to: muralive
[quote=muralive]That is not my point, the author seems to forget the fundamentals, can you imagine the kind of computing resources needed to scale and the complexity of a state machine to handle such a push technology?[/quote]
Jose is right; although the HTTP protocol itself is stateless, our usage today is not. Increasing statefullness (whether the state is on the server or the client) is an indication of increasing sophistication. Push technologies allow us to do more interesting things on the web than we could do before.
Also, as Jose has pointed out, Ajax Push is not necessarily less efficient than Web 1.0 -- pushing a small delta to the page just when, say, an item price changes, is vastly more efficient than having all users frantically pressing refresh in the final moments of an auction.
Ted Goddard replied on Thu, 2008/11/13 - 11:37am
in response to: eirirlar.
[/quote]
JavaServer Faces 2.0 will likely not include push capability; we're hoping to return to that in 2.1, (the first priority is Ajax standardization).
One of the main pieces of ICEfaces (and the other JSF Ajax frameworks) is the mechanism for
This complete stack is being standardized in JSF 2.0 (including a a JavaScript API and a standard format for encoding the HTML page updates) and would be factored out of ICEfaces. As you can imagine, when the various JSF frameworks make use of this standard stack, interoperability should be excellent. | http://java.dzone.com/articles/asynchronous-ajax-revolutionar | crawl-002 | refinedweb | 4,085 | 51.99 |
H2O Word2Vec Tutorial With Example in Scala
H2O Word2Vec Tutorial With Example in Scala
Word2Vec is a method of feeding words into machine learning models. In this code-heavy tutorial, learn how to use its algorithm to build such models.
Join the DZone community and get the full member experience.Join For Free
In this Scala example, we will use the H2O Word2Vec algorithm to build a model using the given text (as a text file or as an array) and then build a Word2Vec model from it.
If you would like to know what Word2Vec is and why you should use it, there is lots of material available. You can learn more about H2O implementation of Word2Vec here, along with its configuration and interpretation.
Here is the full Scala code of the following example at my GitHub.
Let's start the H2O cluster first:
import org.apache.spark.h2o._ val h2oContext = H2OContext.getOrCreate(spark)
Now, we will be importing required libraries to get our job done:
import scala.io.Source import _root_.hex.word2vec.{Word2Vec, Word2VecModel} import _root_.hex.word2vec.Word2VecModel.Word2VecParameters import water.fvec.Vec
Next, we will be creating a "stop words" list of words that are not useful for text mining and have them removed from the word source:
val STOP_WORDS = Set("ourselves", "hers", "between", "yourself", "but", "again", "there", "about", "once", "during", "out", "very", "having", "with", "they", "own", "an", "be", "some", "for", "do", "its", "yours", "such", "into", "of", "most", "itself", "other", "off", "is", "s", "am", "or", "who", "as", "from", "him", "each", "the", "themselves", "until", "below", "are", "we", "these", "your", "his", "through", "don", "nor", "me", "were", "her", "more", "himself", "this", "down", "should", "our", "their", "while", "above", "both", "up", "to", "ours", "had", "she", "all", "no", "when", "at", "any", "before", "them", "same", "and", "been", "have", "in", "will", "on", "does", "yourselves", "then", "that", "because", "what", "over", "why", "so", "can", "did", "not", "now", "under", "he", "you", "herself", "has", "just", "where", "too", "only", "myself", "which", "those", "i", "after", "few", "whom", "t", "being", "if", "theirs", "my", "against", "a", "by", "doing", "it", "how", "further", "was", "here", "than")
Let's ingest the text data. We want to run Word2Vec algorithms to vectorize the data first and then run a machine learning experiment on it.
I have downloaded a free story, The Adventure of Sherlock Holmes, from the internet, and am using that as my source.
val filename = "/Users/avkashchauhan/Downloads/TheAdventuresOfSherlockHolmes.txt" val lines = Source.fromFile(filename).getLines.toArray val sparkframe = sc.parallelize(lines)
Let's define the
tokenize function, which will convert out input text to tokens:
def tokenize(line: String) = { //get rid of nonWords such as punctuation as opposed to splitting by just " " line.split("""\W+""") .map(_.toLowerCase) //Lets remove stopwords defined above .filterNot(word => STOP_WORDS.contains(word)) :+ null }
Now, we will be calling the
tokenize function to create a list of labeled words:
val allLabelledWords = sparkframe.flatMap(d => tokenize(d))
Note: You can also use your own or a custom
tokenize function from a library; you just need to map the function to the DataFrame.
Convert the collection of labeled words into an H2O DataFrame:
val h2oFrame = h2oContext.asH2OFrame(allLabelledWords)
It's finally time to use the H2O Word2Vec algorithm. Configure the parameters first:
val w2vParams = new Word2VecParameters w2vParams._train = h2oFrame._key w2vParams._epochs = 500 w2vParams._min_word_freq = 0 w2vParams._init_learning_rate = 0.05f w2vParams._window_size = 20 w2vParams._vec_size = 20 w2vParams._sent_sample_rate = 0.0001f
Now, we will perform the real action of building the model:
val w2v = new Word2Vec(w2vParams).trainModel().get()
Now we can apply the model to perform some actions on it.
Let's start the first test by finding synonyms using the given Word2Vec model. We will be calling the
findSynonyms method by passing a given word to find N synonyms. The results will be the top count synonyms with their distance values:
w2v.findSynonyms("love", 3) w2v.findSynonyms("help", 2) w2v.findSynonyms("hate", 1)
Let's transform words using the W2V model and aggregate the method average.
The
transform() function takes an H2O vector as the first parameter, where the vector needs to be extracted from the H2O frame.
val newSparkFrame = w2v.transform(h2oFrame.vec(0), Word2VecModel.AggregateMethod.NONE).toTwoDimTable()
And }} | https://dzone.com/articles/h2o-word2vec-tutorial-with-example-in-scala | CC-MAIN-2019-18 | refinedweb | 693 | 64.2 |
!- Search Loader --> <!- /Search Loader -->
I have Intel C++ 14.0.2 installed on Windows 7 with Visual Studio 2008. I need to use some C++11 features, such as:
[cpp]
#include <memory>
int main(int argc, char** argv){
std::unique_ptr<int> ptr;
return 1;
}
[/cpp]
Trying to compile this manually on the Intel Parallel Studio cmd window using: "icl /Qstd=c++11 main.cpp"
results in the error message: 'error: namespace "std" has no member "unique_ptr"'
Is this intended to work? Does Intel Parallel Studio contain its own complete C++ headers, or does it rely on Visual Studio to provide them?
If the latter, what is the purpose of std=c++11? I recall seeing documentation about this topic somewhere in the past, but did not find anything obvious, e.g., in the /Qstd manual entry.
I realize that VS2008 is rather old and hope to upgrade in the near future. However I really have no use for anything but icl/ifort at the moment.
Thank you,
Matt
Hi,
ICC on Windows rely on MSVC headers and CRT library, on Linux on gcc and glibc library. This is for providing maximum compatibility with native environment. MSVC 2008 is very old, you should be fine with 2012 or even better, MSVC 2013.
So this means that Intel C++ on Windows only has the C++11 support that Microsoft provides? Then what is the meaning of the manual description for /Qstd:
DEFAULTS /Qstd=OFF. Note that a subset of C++11 features is enabled by default for compatibility with a particular version of Microsoft Visual Studio* C++, so you only need to specify /Qstd=c++0x if you want additional C++11 functionality beyond what Microsoft provides.
How does Intel "add additional C++11 functionality beyond what Microsoft provides" if it relies on the MS headers and library?! I can understand using these headers and libraries by default (for compatibility), but wouldn't Intel need to provide updated headers for their C++11 improvements?
Thank you,
- Matt
Hi Matt
Remember C++0x and 11 is not only about STL headers, but also the syntax has been improved, like r-value references, variadic template arguments, strongly-typed enums, lambda functions and many more.
Btw, MSVC 2008 reached end-of-life and many projects dropped support for this archaic compiler. When you are speaking about C++11, you are definitely speaking of MSVC 2013. On Linux, the same situation is there.
Yes /Qstd=c++11 provides lots of additional c++11 compiler support (i.e. language features), but does not provide any additional c++11 library support. | https://community.intel.com/t5/Intel-C-Compiler/Requirements-for-C-11-Support-on-Windows/m-p/920621/highlight/true | CC-MAIN-2020-45 | refinedweb | 433 | 54.52 |
A loader is a node module exporting a
function.
This function is called when a resource should be transformed by this loader.
In the simple case, when only a single loader is applied to the resource, the loader is called with one parameter: the content of the resource file as string.
The loader can access the loader API on the
this context in the function.
A sync loader that only wants to give a one value can simply
return it. In every other case the loader can give back any number of values with the
this.callback(err, values...) function. Errors are passed to the
this.callback function or thrown in a sync loader.
The loader is expected to give back one or two values. The first value is a resulting JavaScript code as string or buffer. The second optional value is a SourceMap as JavaScript object.
In the complex case, when multiple loaders are chained, only the last loader gets the resource file and only the first loader is expected to give back one or two values (JavaScript and SourceMap). Values that any other loader give back are passed to the previous loader.
// Identity loader module.exports = function(source) { return source; };
// Identity loader with SourceMap support module.exports = function(source, map) { this.callback(null, source, map); };
(Ordered by priority, first one should get the highest priority)
Loaders should
Loaders can be chained. Create loaders for every step, instead of a loader that does everything at once.
This also means they should not convert to JavaScript if not necessary.
Example: Render HTML from a template file by applying the query parameters
I could write a loader that compiles the template from source, execute it and return a module that exports a string containing the HTML code. This is bad.
Instead I should write loaders for every task in this use case and apply them all (pipeline):
Loader generated modules should respect the same design principles like normal modules.
Example: That’s a bad design: (not modular, global state, …)
require("any-template-language-loader!./xyz.atl"); var html = anyTemplateLanguage.render("xyz");
Most loaders are cacheable, so they should flag itself as cacheable.
Just call
cacheable in the loader.
// Cacheable identity loader module.exports = function(source) { this.cacheable(); return source; };
A loader should be independent of other modules compiled (expect of these issued by the loader).
A loader should be independent of previous compilations of the same module.
If a loader uses external resources (i. e. by reading from filesystem), they must tell about that. This information is used to invalidate cacheable loaders and recompile in watch mode.
// Loader adding a header var path = require("path"); module.exports = function(source) { this.cacheable(); var callback = this.async(); var headerPath = path.resolve("header.js"); this.addDependency(headerPath); fs.readFile(headerPath, "utf-8", function(err, header) { if(err) return callback(err); callback(null, header + "\n" + source); }); };
In many languages there is some schema to specify dependencies. i. e. in css there is
@import and
url(...). These dependencies should be resolved by the module system.
There are two options to do this:
requires.
this.resolvefunction to resolve the path
Example 1 css-loader: The css-loader transform dependencies to
requires, by replacing
@imports with a require to the other stylesheet (processed with the css-loader too) and
url(...) with a
require to the referenced file.
Example 2 less-loader: The less-loader cannot transform
@imports to
requires, because all less files need to be compiled in one pass to track variables and mixins. Therefore the less-loader extends the less compiler with a custom path resolving logic. This custom logic uses
this.resolve to resolve the file with the configuration of the module system (aliasing, custom module directories, etc.).
If the language only accept relative urls (like css:
url(file) always means
./file), there is the
~-convention to specify references to modules:
url(file) -> require("./file") url(~module) -> require("module")
don’t generate much code that is common in every module processed by that loader. Create a (runtime) file in the loader and generate a
require to that common code.
don’t put absolute paths in to the module code. They break hashing when the root for the project is moved. There is a method
stringifyRequest in loader-utils which converts an absolute path to an relative one.
Example:
var loaderUtils = require("loader-utils"); return "var runtime = require(" + loaderUtils.stringifyRequest(this, "!" + require.resolve("module/runtime")) + ");";
peerDependencieswhen they wrap it
using a peerDependency allows the application developer to specify the exact version in
package.json if desired. The dependency should be relatively open to allow updating the library without needing to publish a new loader version.
"peerDependencies": { "library": "^1.3.5" }
query-option
there are situations where your loader requires programmable objects with functions which cannot stringified as
query-string. The less-loader, for example, provides the possibility to specify LESS-plugins. In these cases, a loader is allowed to extend webpack’s
options-object to retrieve that specific option. In order to avoid name collisions, however, it is important that the option is namespaced under the loader’s camelCased npm-name.
Example:
// webpack.config.js module.exports = { ... lessLoader: { lessPlugins: [ new LessPluginCleanCSS({advanced: true}) ] } };
The loader should also allow to specify the config-key (e.g.
lessLoader) via
query. See discussion and example implementation.
© 2012–2015 Tobias Koppers
Licensed under the MIT License. | http://docs.w3cub.com/webpack~1/how-to-write-a-loader/ | CC-MAIN-2017-39 | refinedweb | 896 | 50.63 |
View Rails debug messages in the browser console with Rconsole
Using log messages in Rails can be a huge timesaver when you are debugging. With Rconsole you can save even more time by having those messages appear in the browser console. Rconsole is a fairly new gem with a lot of potential.
Installation is super simple. First add it to your
Gemfile:
group :development do gem 'rconsole', '~> 0.1.0' end
Then run
bundle install. Add to your layout view:
javascript_include_tag(:rconsole) if Rails.env.development?
To use Rconsole simply add
rconsole.log messages where you would normally insert
logger.debug, etc.
def show rconsole.log 'Hello, Changeloggers!' ... end
Now your browser will display your messages:
In addition to debugging, Rconsole is particularly useful when working with students or new rubyists to show the connection between what's happening in the controller and the view.
The entire code base is open source and available on GitHub. | https://changelog.com/posts/view-rails-debug-messages-browser-console-rconsole | CC-MAIN-2017-51 | refinedweb | 156 | 60.01 |
On Mon, 30 May 2016 08:10:17 -0400, Ken Brown wrote: > Does this help? > --- a/src/conf_post.h > +++ b/src/conf_post.h [...] > #ifdef CYGWIN > -#define SYSTEM_PURESIZE_EXTRA 10000 > +#define SYSTEM_PURESIZE_EXTRA 50000 > #endif Yes, it helps. I didn't know it would be in such a place. Thank you! Pure-hashed: 27667 strings, 3832 vectors, 40233 conses, 3752 bytecodes, 103 others Dumping under the name emacs 5369856 of 16777216 static heap bytes used 1931693 pure bytes used Adding name emacs-25.1.50.1 In GNU Emacs 25.1.50.1 (i686-pc-cygwin, GTK+ Version 3.14.13) of 2016-05-31 built on localhost Windowing system distributor 'The Cygwin/X Project', version 11.0.11702000 | https://lists.gnu.org/archive/html/emacs-devel/2016-05/msg00677.html | CC-MAIN-2019-35 | refinedweb | 116 | 75.3 |
Quarterly Report
30 June 2018
Manager AmFunds Management Berhad 9th & 10th Floor, Bangunan AmBank Group 55 Jalan Raja Chulan 50200 Kuala Lumpur
Board of Directors Raja Maimunah Binti Raja Abdul Aziz Dato’ Mustafa Bin Mohd Nor Tai Terk Lin Goh Wee Peng Sum Leng Kuang
Investment Committee Sum Leng Kuang Tai Terk Lin Dato’ Mustafa Bin Mohd Nor Zainal Abidin Bin Mohd Kassim Goh Wee Peng
Trustee HSBC (Malaysia) Trustee Berhad
Taxation Adviser Deloitte Tax Services Sdn Bhd
Head Office 9th & 10th Floor, Bangunan AmBank Group 55, Jalan Raja Chulan, 50200 Kuala Lumpur Tel: 03-2036 2888 Fax: 03-2031 5210
Secretaries Chen Bee Ling (MAICSA 7046517) Tan Lai Hong (MAICSA 7057707) Secretaries’ Office at Level 8, Symphony House, Pusat Dagangan Dana 1, Jalan PJU 1A/46, 47301 Petaling Jaya, Selangor Darul Ehsan
1 Manager’s Report 16 Additional Information 26 Statement of Financial Position 27 Statement of Comprehensive Income 28 Statement of Changes in Equity 29 Statement of Cash Flows 30 Notes to the Financial Statements 51 Directory
Dear Unitholders,
We are pleased to present you the Manager’s report and the unaudited quarterly accounts of ABFMalaysia Bond Index Fund (“Fund”) for the financial period from 1 April 2018 to 30 June 2018.
Note: Any material change to the Fund’s investment objective will require the unitholders’ approval by way of special resolution.
VK120194 Johor Corporation 3.680 14/06/2019 800,000,000 MS04003H Malaysia Government Bond 5.734 30/07/2019 7,315,546,000 GO090001 Malaysia Government Investment Issue 3.910 13/08/2019 6,000,000,000 GL120021 Malaysia Government Investment Issue 3.704 30/09/2019 8,000,000,000 MJ140004 Malaysia Government Bond 3.654 31/10/2019 11,800,000,000 MO090002 Malaysia Government Bond 4.378 29/11/2019 17,119,000,000 ML120006 Malaysia Government Bond 3.492 31/03/2020 11,000,000,000 VI150052 Danga Capital Bhd 4.100 09/04/2020 2,000,000,000
(Forward)
1 Code Issuer Coupon Final Notional % Maturity Amount (RM)
GH160004 Malaysia Government Investment Issue 3.226 15/04/2020 7,000,000,000GO090061 Malaysia Government Investment Issue 4.492 30/04/2020 3,500,000,000GL120098 Malaysia Government Investment Issue 3.576 15/05/2020 11,000,000,000VG170171 Pengurusan Air SPV Berhad 3.960 05/06/2020 700,000,000GN100021 Malaysia Government Investment Issue 4.284 15/06/2020 5,500,000,000MK130006 Malaysia Government Bond 3.889 31/07/2020 7,973,062,000GJ150002 Malaysia Government Investment Issue 3.799 27/08/2020 10,000,000,000VI150192 Pengurusan Air SPV Berhad 4.280 28/09/2020 700,000,000MJ150003 Malaysia Government Bond 3.659 15/10/2020 11,742,134,000GN100060 Malaysia Government Investment Issue 3.998 30/11/2020 3,000,000,000MH170005 Malaysia Government Bond 3.441 15/02/2021 3,500,000,000VN110023 GovCo Holdings Bhd 4.450 23/02/2021 1,500,000,000GL130069 Malaysia Government Investment Issue 3.716 23/03/2021 9,500,000,000VG180101 Cagamas Berhad 4.170 29/03/2021 1,000,000,000GN110025 Malaysia Government Investment Issue 4.170 30/04/2021 12,500,000,000MO110001 Malaysia Government Bond 4.160 15/07/2021 13,500,000,000GJ160002 Malaysia Government Investment Issue 3.743 26/08/2021 7,000,000,000VK140222 Bank Pembangunan Malaysia Berhad 4.190 10/09/2021 700,000,000
(Forward) 2 Coupon Final Notional Code Issuer % Maturity Amount (RM)
ML140003 Malaysia Government Bond 4.048 30/09/2021 11,700,000,000MJ160004 Malaysia Government Bond 3.620 30/11/2021 10,000,000,000UI170031 Cagamas Berhad 4.150 09/03/2022 2,000,000,000MI170001 Malaysia Government Bond 3.882 10/03/2022 8,000,000,000GI170003 Malaysia Government Investment Issue 3.948 14/04/2022 11,000,000,000VI170172 Pengurusan Air SPV Berhad 4.060 06/06/2022 900,000,000VN120195 Johor Corporation 3.840 14/06/2022 1,800,000,000VN120202 Perbadanan Tabung Pendidikan Tinggi Nasional 3.850 15/06/2022 2,500,000,000GL150001 Malaysia Government Investment Issue 4.194 15/07/2022 10,000,000,000MO120001 Malaysia Government Bond 3.418 15/08/2022 10,500,000,000ML150002 Malaysia Government Bond 3.795 30/09/2022 11,000,000,000VI170370 Cagamas Berhad 4.230 03/11/2022 840,000,000GO120037 Malaysia Government Investment Issue 3.699 15/11/2022 8,500,000,000VN120393 Turus Pesawat Sdn Bhd 3.740 18/11/2022 500,000,000VN130068 Turus Pesawat Sdn Bhd 3.770 03/02/2023 500,000,000MN130003 Malaysia Government Bond 3.480 15/03/2023 11,420,000,000MI180002 Malaysia Government Bond 3.757 20/04/2023 4,000,000,000VI180192 Cagamas Berhad 4.500 25/05/2023 1,500,000,000GL160001 Malaysia Government Investment Issue 4.390 07/07/2023 10,500,000,000
(Forward)
3 Code Issuer Coupon Final Notional % Maturity Amount (RM)
4 Code Coupon Notional Issuer % Final Maturity Amount (RM)
MO150001 Malaysia Government Bond 3.955 15/09/2025 13,672,200,000VN150193 Pengurusan Air SPV Berhad 4.630 26/09/2025 860,000,000GO150004 Malaysia Government Investment Issue 3.990 15/10/2025 10,500,000,000MS110003 Malaysia Government Bond 4.392 15/04/2026 11,274,330,000VN160235 Jambatan Kedua Sdn Bhd 4.200 28/07/2026 1,000,000,000VS110260 Prasarana Malaysia Bhd 4.350 04/08/2026 1,200,000,000MX060002 Malaysia Government Bond 4.709 15/09/2026 3,110,000,000GO160003 Malaysia Government Investment Issue 4.070 30/09/2026 10,500,000,000VN160330 Bank Pembangunan Malaysia Berhad 4.500 04/11/2026 850,000,000MO160003 Malaysia Government Bond 3.900 30/11/2026 9,500,000,000VN170037 GovCo Holdings Bhd 4.550 22/02/2027 500,000,000MS120002 Malaysia Government Bond 3.892 15/03/2027 5,500,000,000MX070003 Malaysia Government Bond 3.502 31/05/2027 6,000,000,000GS120059 Malaysia Government Investment Issue 3.899 15/06/2027 5,000,000,000GO170001 Malaysia Government Investment Issue 4.258 26/07/2027 11,000,000,000VN170245 Danga Capital Bhd 4.520 06/09/2027 1,500,000,000MO170004 Malaysia Government Bond 3.899 16/11/2027 14,500,000,000VS120395 Turus Pesawat Sdn Bhd 4.120 19/11/2027 750,000,000
5 Coupon Final Notional Code Issuer % Maturity Amount (RM)
MS130005 Malaysia Government Bond 3.733 15/06/2028 8,500,000,000GT130001 Malaysia Government Investment Issue 3.871 08/08/2028 3,000,000,000MX080003 Malaysia Government Bond 5.248 15/09/2028 5,040,000,000GO180002 Malaysia Government Investment Issue 4.369 31/10/2028 4,000,000,000GS130072 Malaysia Government Investment Issue 4.943 06/12/2028 5,000,000,000VS140224 Bank Pembangunan Malaysia Berhad 4.750 12/09/2029 900,000,000VX090825 Prasarana Malaysia Bhd 5.070 28/09/2029 1,500,000,000VS150043 Prasarana Malaysia Bhd 4.640 22/03/2030 1,100,000,000MX100003 Malaysia Government Bond 4.498 15/04/2030 12,770,000,000VS150104 Jambatan Kedua Sdn Bhd 4.520 28/05/2030 700,000,000GT150003 Malaysia Government Investment Issue 4.245 30/09/2030 7,000,000,000VS160151 GovCo Holdings Bhd 4.730 06/06/2031 550,000,000MX110004 Malaysia Government Bond 4.232 30/06/2031 12,750,000,000VS170036 GovCo Holdings Bhd 4.950 20/02/2032 1,250,000,000VS170042 Bank Pembangunan Malaysia Berhad 4.980 02/03/2032 700,000,000VS170113 Perbadanan Tabung Pendidikan Tinggi Nasional 4.860 12/03/2032 855,000,000MX120004 Malaysia Government Bond 4.127 15/04/2032 5,500,000,000VS170237 Perbadanan Tabung Pendidikan Tinggi 1,300,000,000 Nasional 4.930 17/08/2032VX120396 Turus Pesawat Sdn Bhd 4.360 19/11/2032 1,650,000,000
6 Coupon Final Notional Code Issuer % Maturity Amount (RM)
7 Coupon Final Notional Code Issuer % Maturity Amount (RM)
Duration The Fund was established on 12 July 2005 and shall exist for as long as it appears to the Manager and the Trustee that it is in the interests of the unitholders for it to continue. In some circumstances, the unitholders* can resolve at a meeting to terminate the Fund.
Breakdown For the financial period under review, the size of the Fund stood at 1,265,421,800of Unit units.Holdings bySize (Forward)
8 Size of holding As at 30 June 2018 As at 31 March 2018 No of Number of No of Number of units held unitholders units held unitholders Less than 100 300 6 300 6 100 – 1,000 16,000 31 12,800 26 1,001 -10,000 30,300 7 39,300 9 10,001 – 100,000 103,800 5 86,100 4 100,001 to less than 5% of issue units 53,363,530 5 53,375,430 5 5% and above of issue units 1,211,907,870 1 1,211,907,870 1
Portfolio Details of portfolio composition of the Fund for the financial periods as at 30 June 2018,Composition 31 March 2018 and three financial years as at 31 December are as follows:
As at As at FY FY FY 30-6-2018 31-3-2018 2017 2016 2015 % % % % % Corporate bonds - - - - 0.76 Malaysian Government Securities 95.19 93.61 95.33 95.16 90.57 Quasi-Government bonds 4.63 4.65 4.36 4.41 6.46 Cash and others 0.18 1.74 0.31 0.43 2.21 Total 100.00 100.00 100.00 100.00 100.00
Note: The abovementioned percentages are calculated based on total net asset value.
Performance Performance details of the Fund for the financial periods ended 30 June 2018, 31 MarchDetails 2018 and three financial years ended 31 December are as follows:
3 months 3 months ended ended FY FY FY 30-6-2018 31-3-2018 2017 2016 2015 Net asset value (RM) 1,465,008,607 1,467,049,714 1,450,591,084 1,442,324,912 1,341,876,193* Units in circulation 1,265,421,800 1,265,421,800 1,265,421,800 1,320,421,800 1,265,421,800* Net asset value per unit (RM) 1.1577 1.1593 1.1463 1.0923 1.0604* Highest net asset value per unit (RM) 1.1606 1.1593 1.1463 1.1224 1.0655*
(Forward) 9 3 months 3 months ended ended FY FY FY 30-6-2018 31-3-2018 2017 2016 2015Lowest net asset value per unit (RM) 1.1509 1.1476 1.0921 1.0599 1.0323*Closing quoted price (RM/unit) 1.1540 1.1530 1.1400 1.1100 1.0520* Highest quoted price (RM/unit) 1.1590 1.1530 1.1400 1.1240 1.0680* Lowest quoted price (RM/unit) 1.1500 1.1460 1.1000 1.0520 1.0300 Benchmark performance (%) -0.13 1.16 5.21 3.46 4.12 Total return (%)(1) -0.14 1.13 4.94 3.01 3.74 - Capital growth (%) -0.14 1.13 4.94 3.01 2.12 - Income distribution (%) - - - - 1.62 Gross distribution (sen per unit) - - - - 1.68 Net distribution (sen per unit) - - - - 1.68 Distribution yield (%)(2) - - - - 1.60 Management expense ratio (%)(3) 0.17 0.17 0.17 0.18 0.16 Portfolio turnover ratio (times)(4) 0.03 0.04 0.23 0.47 0.74
* Above price and net asset value per unit are shown as ex-distribution.
Note:(1) Total return is the actual/annualised return of the Fund for the respective financial periods/years computed based on the net asset value per unit and net of all fees.(2) Distribution yield is calculated based on the total distribution for the respective financial years divided by the closing quoted price.(3) Management expense ratio (“MER”) is calculated based on the total fees and expenses incurred by the Fund divided by the average fund size calculated on a daily basis.(4) Portfolio turnover ratio (“PTR”) is calculated based on the average of the total acquisitions and total disposals of investment securities of the Fund divided by the average fund size calculated on a daily basis. The PTR decreased by 0.01 times (25.0%) as compared to 0.04 times for the financial period ended 31 March 2018 mainly due to decrease in investing activities.
10 Average Total Return (as at 30 June 2018)
The Fund performance is calculated based on the net asset value per unit of the Fund. Average total return of the Fund and its benchmark for a period is computed based on the absolute return for that period annualised over one year.
Note: Past performance is not necessarily indicative of future performance and that unit prices and investment returns may go down, as well as up.
Fund For the financial period under review, the Fund registered a negative return of 0.14%Performance which was entirely capital in nature.
Thus, the Fund’s negative return of 0.14% has underperformed the benchmark’s negative return of 0.13% by 0.01%.
As compared with the financial period ended 31 March 2018, the net asset value (“NAV”) per unit of the Fund decreased by 0.14% from RM1.1593 to RM1.1577, while units in circulation remain unchanged at 1,265,421,800 units.
The closing price quoted at Bursa Malaysia of the Fund increased by 0.09% from RM1.1530 to RM1.1540.
The line chart below shows the comparison between the annual performance of ABFMY1 and its benchmark, iBoxx® Index, for the financial years ended 31 December.
(Forward)
11 Note: Past performance is not necessarily indicative of future performance and that unit prices and investment returns may go down, as well as up.
Strategies For the financial period under review, the Fund used a passive strategy whereby theand Policies Manager aims, by way of representative sampling, to achieve a return on the FundEmployed Assets that closely tracks the returns of the benchmark index.
Portfolio This table below is the asset allocation of the Fund for the financial periods underStructure review.
As at As at 30-6-2018 31-3-2018 Changes % % % Malaysian Government Securities 95.19 93.61 1.58 Quasi-Government bonds 4.63 4.65 -0.02 Cash and others 0.18 1.74 -1.56 Total 100.00 100.00
There has been no significant change to the asset allocation since the last reporting period.
Cross There are no cross trades for the Fund during this financial period under review.Trades
Distribution/ There was no income distribution and unit split declared for the financial period underunit splits review.
State of There has been neither significant change to the state of affairs of the Fund nor anyAffairs of circumstances that materially affect any interests of the unitholders during the financialthe Fund period under review.
12 Note: The Manager has appointed Deutsche Trustees Malaysia Berhad (“DTMB”) to carry out the fund accounting and valuation services for all funds effective 20th June 2018.
Rebates It is our policy to pay all rebates to the Fund. Soft commission received fromand Soft brokers/dealers are retained by the Manager only if the goods and services provided areCommission of demonstrable benefit to unitholders of the Fund.
During the financial period under review, the Manager had received on behalf of the Fund, soft commissions in the form of fundamental database, financial wire services, technical analysis software and stock quotation system incidental to investment management of the Fund. These soft commissions received by the Manager are deem to be beneficial to the unitholders of the Fund.
Market Malaysia registered forex reserves of USD107.8b as at 30 Mar 2018, an increase fromReview end-February’s level and the highest level in three years. Again, Malaysia’s external reserves surged USD2.2b in the first two weeks of April to USD110b on the back of export earnings repatriation and corporate inflows, most likely from O&G sector following Saudi Aramco’s investment in RAPID. External reserves now cover 7.7x of imports and 1.1x of short-term external debt.
The downtrend for the headline inflation rate continued in March, as it eased to 1.3% Year-on-Year (YoY) – the lowest in 17 months. This was mainly due to a further decline in transportation and communication as well as F&B costs As UST yields broke 3.00 for the 10y, MGS market suffered significantly as local traders/investors trimmed their positions. Some of them were forced to sell when the prices triggered their cut-loss level. The short tenors (3y and below) suffered the most while ultra-long tenors 20y and 30y were holding up.
On the other hand, foreigners were seen selling the short tenors and buying the long tenors to extend duration. In March, foreigners net bought RM2.9b of domestic bonds, recouping most of the RM3.9b outflows in Feb.
• RM2.5b 20-year reopening of the GII 08/47 which garnered a BTC ratio of 2.12x at average yield of 4.804%. • RM4.0b 5-year new issuance of MGS 04/23 which drew a BTC ratio of 3.33x at average yield of 3.757%. • RM 4.0b 10.5-year new issuance of the GII 10/28 which closed with a BTC ratio of 2.70x at an average yield of 4.369%.
Most investors were mostly on the sidelines pending for the GE14 results on 9 May. The surprise win by Pakatan Harapan in the election saw some knee-jerk reactions in the govvies market with the 10y MGS given 10 bps higher at 4.25%. However, these knee-jerk reactions did not last long as the strong support from the local institutional/pension funds brought the govvies levels almost unchanged as the prior election results.
Towards the later part of the month of May as the UST continued to sell off with 10y UST touching all-time high of 3.12% on higher inflationary pressures, local govvies market saw yields rising again. The bearish sentiment in the govvies market intensified as MYR continued to weaken on heavy foreign selling both in the domestic bond and equity market. 13 In the primary market, there were 3 government bond auctions as follows:
• RM3.0b 15-year new issuance of MGS 11/33 which drew a BTC ratio of 2.722x at average yield of 4.642%. • RM3.0b 7-year new issuance of GII 08/25 which garnered a BTC ratio of 3.397x at average yield of 4.202%. • RM 3.5b 10.5-year new issuance of MGS 6/28 which closed with a BTC ratio of 1.851x at an average yield of 4.202%. • RM 4.0b 5-year new issuance of GII 11/23 which closed with a BTC ratio of 1.989x at an average yield of 4.094%.
The above auctions show that there were substantial onshore demands immediately post the general election results, as shown in the strongest BTC result for the year for 7y GII 8/25. However, toward the end of the month, as the UST yields rose, the demand became lackluster.
The month of May 2016 saw foreigners reduce their holdings of Malaysian government debt securities from MYR205.4b to MYR192.5b. The fall in foreign holdings was driven by the global sell down in emerging markets and may have been further exacerbated by domestic developments following GE14.
• MYR2.5b 20-year new issuance of MGS 6/38 which drew a BTC ratio of 1.94x at average yield of 4.893%.
• MYR3.5b 15-year reopening of GII 6/33 which garnered a BTC ratio of 2.783x at average yield of 4.778%.
Despite the significant reversal in foreign holdings, local MGS yields were anchored by strong local investor support and the fall in UST yields from their highs in May 2018. Trading volume for government securities fell sharply from MYR62.0b in May 2018 to MYR38.0b.
Increasing concern over the likelihood of global trade war has started weigh on growth expectations, which should provide support for global bond yields. The decline in the UST 10Y yield from its recent high of 3.11% to 2.86% has resulted in the UST 10Y vs MGS 10Y spread widening to 135 bps, which is line with historical average spread. There will be sizeable local govvie maturities between August and October 2018 which could cause volatility if foreign investors choose to not roll over their holdings although mitigated by the holding structure as current foreign holdings are mostly real money investors and passive benchmark funds.
Market We expect Bank Negara Malaysia (“BNM”) to maintain the Overnight Policy RateOutlook (“OPR”) at 3.25% for the rest of the year. The domestic economy continued to expand at a healthy rate of 5.4% Year-On-Year (YoY) in 1Q2018 but there are downside risks to growth from here on with the potential escalation of a global trade war. Inflation continues to be benign and the removal of the GST will help suppress inflationary pressure.
Global bond yields will be driven by two increasingly divergent factors, the hawkish monetary policy in the U.S. and increasing concerns over the long term growth outlook of the global economy. These developments have resulted in a significant flattening of the UST yield curve. As at end June 2018, the 2Y vs 10Y spread has stood at 32bps 14 which is the lowest in over a decade.
The weakening of MYR against the USD may also weigh on the market due to fears of more foreign outflows. Nevertheless, unless there are more surprises from both domestic and external events, we expect the bond market to be well supported by local institutions and pension funds as current yields remain attractive to long term investors.
7 August 2018
15ADDITIONAL INFORMATION
The Board of Directors, of which more than one-third are independent members,exercise ultimate control over the operations of the Manager. For the financial periodfrom 1 April 2018 to 30 June 2018, there were three (3) Board of Directors’ meetings held by theManager.
Details of the Directors of the Manager as at 30 June 2018 are set out as below:
16 viii) (June 2009 – June 2011) Bursa Malaysia Berhad [Global Head, Islamic Markets]
ii) (1988-1990) Development & Commercial Bank Berhad 17 [Manager, Treasury Department]
Number)
19Number of Board meeting : Three (3) out of three (3) Board Meetingsattended for the financialperiod from 1 April 2018 to 30June 2018Member of any other Board : i) Investment Committee; andCommittee ii) Audit and Examination Committee (formerly known as Audit Committee of Directors)Date of appointment to the : 15 December 2014Investment CommitteeNumber)
v) (May 2015-Present) Credit Guarantee Corporation Malaysia Berhad [Advisor, Investment (Contract)] 20Occupation : Advisor, Investment of Credit Guarantee Corporation Malaysia BerhadDate of appointment : 18 January 2016Directorship of other public : Pacific & Orient Insurance Co. BerhadcompaniesNumber of Board meeting : Two (2) out of three (3) Board Meetingsattended for the financialperiod from 1 April 2018 to 30June 2018Member of any other Board : i) Investment Committee; andCommittee ii) Audit and Examination Committee (formerly known as Audit Committee of Directors)Date of appointment to the : 18 January 2016Investment CommitteeNumber of Investment : One (1) out of one (1) Investment Committee MeetingCommittee meetings attendedfor the financial period from 1April 2018 to 30 June 2018Family relationship with any : NonedirectorConflict of interest with the : NoneFundList of convictions for offences : Nonewithin the past 10 years (if any)
22Number of Investment : One (1) out of one (1) Investment Committee MeetingCommittee meeting attended forthe financial period from 1 April2018 to 30 June 2018Family relationship with any : NonedirectorConflict of interest with the : NoneFundList of convictions for offences : Nonewithin the past 10 years (if any)
Investment Committee
The Investment Committee, of which more than one-third are independent members, exercise ultimateselect appropriate strategies and efficiently implemented to achieve the proper performance, activelymonitor, measure and evaluate the fund management performance of the Manager. For the financialperiod from 1 April 2018 to 30 June 2018, there was one (1) Investment Committee Meeting held bythe Manager.
23Number)
Material Litigation
For the financial year under review, neither the Directors of the management company nor theManager of the Fund were engaged in any material litigation and arbitration, including those pendingor threatened, and any facts likely to give any proceedings, which might materially affect thebusiness/financial position of the Manager and of its delegates. The Fund has also not engaged in anymaterial litigation and arbitration, including those pending or threatened, and any facts likely to giveany proceedings, which might materially affect the Fund.
Manager
Previously, we have appointed AmInvestment Management Sdn Bhd (“AIM”) to implement theFund’s investment strategy on behalf of us to achieve the objectives of the Fund. However, followingthe consolidation of business activities of AmFunds Management Berhad (formerly known asAmInvestment Services Berhad) (“AFM”) and AIM on 1 December 2014, AFM has acquired/assumethe obligations, undertaking, commitments and contingencies of AIM. Effective 1 December 2014,AFM is a licensed fund manager approved by the Securities Commission Malaysia and manages theFund.
The Investment Committee reviews the Fund’s investment objective and guidelines; and to ensure thatthe Fund is invested appropriately. For the financial period from 1 April 2018 to 30 June 2018, therewas one (1) Investment Committee Meeting held by the Manager.
24Unitholders
25ABF Malaysia Bond Index Fund
30-6-2018 31-12-2017 (unaudited) (audited) Note RM RM
ASSETSInvestments 4 1,462,348,565 1,446,080,288Deposits with financial institutions 5 3,100,293 4,871,480Cash at banks 2,210 1,437
LIABILITIESAmount due to Manager 6 128,846 122,994Amount due to Trustee 7 58,077 57,458Amount due to index provider 8 165,893 72,679Sundry payables and accrued expenses 89,645 108,990
EQUITYUnitholders‟ capital 11(a) 1,334,273,353 1,334,273,353Retained earnings 11(b)(c) 130,735,254 116,317,731
26ABF Malaysia Bond Index Fund
1-4-2018 to 1-4-2017 to 30-6-2018 30-6-2017 Note RM RM
INVESTMENT (LOSS)/INCOMEInterest income 14,589,198 14,266,680Net (loss)/gain from investments:− Financial assets at fair value through profit or loss (“FVTPL”) 9 (16,007,243) 10,809,513
EXPENDITUREManager‟s fee 6 (364,491) (368,589)Trustee‟s fee 7 (182,245) (184,295)Licence fee 8 (42,293) (38,840)Auditors‟ remuneration (2,668) (2,668)Tax agent‟s fee (1,022) (1,022)Other expenses 10 (30,343) (37,098)
(2,041,107) 24,443,681
27ABF Malaysia Bond Index Fund
28ABF Malaysia Bond Index Fund
1-4-2018 to 1-4-2017 to 30-6-2018 30-6-2017 RM RM
3,102,503 3,195,992
29ABF Malaysia Bond Index Fund
1. GENERAL INFORMATION
ABF Malaysia Bond Index Fund (“the Fund”) was established pursuant to a Deed dated 12 July 2005 as amended by Deeds Supplemental thereto (“the Deed”), between AmFunds Management Berhad as the Manager, HSBC (Malaysia) Trustee Berhad as the Trustee and all unitholders.
The Fund was set up with the objective for investors who seek an “index-based” approach to investing in a portfolio of Ringgit Malaysia denominated Government and quasi-Government debt securities. As provided in the Deeds, the “accrual period” or financial year shall end on 31 December and the units in the Fund were first offered for sale on 13 July 2005.
The financial statements of the Fund have been prepared in accordance with Malaysian Financial Reporting Standards (“MFRS”) as issued by the Malaysian Accounting Standards Board (“MASB”) and are in compliance with International Financial Reporting Standards.
The financial statements of the Fund have been prepared under the historical cost convention, unless otherwise stated in the accounting policies.
The adoption of MFRS which have been effective during the financial period did not have any material financial impact to the financial statements.
MFRS 9 reflects International Accounting Standards Board‟s (“IASB”) work on the replacement of MFRS 139 Financial Instruments: Recognition and Measurement (“MFRS 139”). MFRS 9 effective for financial year beginning on or after 1 January 2018. Based on the Fund's preliminary assesment, there is a minimal impact on the classification and measurement of the Fund's investment as the investment will continue to be measured at FVTPL. Further, there is no impact on the classification and measurement of the fund's financial liabilities.
Income recognition
Income is recognised to the extent that it is probable that the economic benefits will flow to the Fund and the income can be reliably measured. Income is measured at the fair value of consideration received or receivable.
30Interest income on fixed income securities and short-term deposits are recognised on an accrualbasis using the effective interest method, which includes the accretion of discounts and amortisationof premiums.
Income tax
Current tax assets and liabilities are measured at the amount expected to be recovered from or paidto the tax authorities. The tax rates and tax laws used to compute the amount are those that areenacted or substantively enacted at the reporting date.
Current taxes are recognised in profit or loss except to the extent that the tax relates to itemsrecognised outside profit or loss, either in other comprehensive income or directly in equity.
Functional currency is the currency of the primary economic environment in which the Fundoperates that most faithfully represents the economic effects of the underlying transactions. Thefunctional currency of the Fund is Ringgit Malaysia which reflects the currency in which the Fundcompetes for funds, issues and redeems units. The Fund has also adopted Ringgit Malaysia as itspresentation currency.
The Fund adopts the direct method in the preparation of the statement of cash flows.
Cash equivalents are short-term, highly liquid investments that are readily convertible to cash withinsignificant risk of changes in value.
Distribution
Distributions are at the discretion of the Fund. A distribution to the Fund‟s unitholders is accountedfor as a deduction from realised reserves. A proposed distribution is recognised as a liability in theperiod in which it is approved.
Unitholders’ capital
The unitholders‟ capital of the Fund meets the definition of puttable instruments and is classified asequity instruments under MFRS 132 Financial Instruments: Presentation (“MFRS 132”).
Financial assets
Financial assets are recognised in the statement of financial position when, and only when, the Fundbecomes a party to the contractual provisions of the financial instrument.
When financial assets are recognised initially, they are measured at fair value, plus, in the case offinancial assets not at fair value through profit or loss, directly attributable transaction costs.
The Fund determines the classification of its financial assets at initial recognition, and the categoriesapplicable to the Fund include financial assets at fair value through profit or loss (“FVTPL”) andloans and receivables.
31(i) Financial assets at FVTPL
Financial assets are classified as financial assets at FVTPL if they are held for trading or are designated as such upon initial recognition. Financial assets held for trading by the Fund include fixed income securities acquired principally for the purpose of selling in the near term.
Subsequent to initial recognition, financial assets at FVTPL are measured at fair value. Changes in the fair value of those financial instruments are recorded in „Net gain or loss on financial assets at fair value through profit or loss‟. Interest earned element of such instrument is recorded separately in „Interest income‟.
Investments are stated at fair value on a portfolio basis in accordance with the provisions of the Deed, fair value is determined based on prices provided by the index provider, Markit Indices Limited, plus accrued interest. Adjusted cost of investments relates to the purchase cost plus accrued interest, adjusted for amortisation of premium and accretion of discount, if any, calculated over the period from the date of acquisition to the date of maturity of the respective securities as approved by the Manager and the Trustee. Unrealised gain or loss recognised in profit or loss is not distributable in nature.
On disposal of investments, the net realised gain or loss on disposal is measured as the difference between the net disposal proceeds and the carrying amount of the investments. The net realised gain or loss is recognised in profit or.
The Fund assesses at each reporting date whether there is any objective evidence that a financialasset is impaired.
To determine whether there is objective evidence that an impairment loss on financial assets has been incurred, the Fund considers factors such as the probability of insolvency or significant financial difficulties of the debtor and default or significant delay in payments.
If any such evidence exists, the amount of impairment loss is measured as the difference between the asset‟s carrying amount and the present value of estimated future cash flows discounted at the financial asset‟s original effective interest rate. The impairment loss is recognised in profit or loss.
32 The carrying amount of the financial asset is reduced through the use of an allowance account. When loans and receivables become uncollectible, they are written off against the allowance account..
Financial liabilities
Financial liabilities are classified according to the substance of the contractual arrangements enteredinto and the definitions of a financial liability.
Financial liabilities, within the scope of MFRS 139, are recognised in the statement of financialposition when, and only when, the Fund becomes a party to the contractual provisions of thefinancial instrument.
The Fund‟s financial liabilities are recognised initially at fair value plus directly attributabletransaction costs and subsequently measured at amortised cost using the effective interest method.
A financial liability is derecognised when the obligation under the liability is extinguished. Gainsand losses are recognised in profit or loss when the liabilities are derecognised, and through theamortisation process.
Unrealised gains and losses comprise changes in the fair value of financial instruments for theperiod and from reversal of prior period‟s unrealised gains and losses for financial instrumentswhich were realised (i.e. sold, redeemed or matured) during the reporting period.
Realised gains and losses on disposals of financial instruments classified at fair value through profitor loss are calculated using the weighted average method. They represent the difference between aninstrument‟s initial carrying amount and disposal amount.
The preparation of the Fund‟s financial statements requires the Manager to make judgments,estimates and assumptions that affect the reported amounts of revenues, expenses, assets andliabilities, and the disclosure of contingent liabilities at the reporting date. However, uncertaintyabout these assumptions and estimates could result in outcomes that could require a materialadjustment to the carrying amount of the asset or liability in the future.
The Fund classifies its investments as financial assets at FVTPL as the Fund may sell itsinvestments in the short-term for profit-taking or to meet unitholders‟ cancellation of units.
33 No major judgments have been made by the Manager in applying the Fund‟s accounting policies. There are no key assumptions concerning the future and other key sources of estimation uncertainty at the reporting date, that have a significant risk of causing a material adjustment to the carrying amounts of assets and liabilities within the next financial period.
4. INVESTMENTS
30-6-2018 31-12-2017 RM RM Financial assets at FVTPL
At nominal value: Quasi-Government Bonds 65,000,000 60,000,000 Malaysian Government Securities 817,500,000 822,500,000 Government Investment Issues 578,500,000 548,500,000
1,461,000,000 1,431,000,000
At fair value: Quasi-Government Bonds 67,759,006 63,177,503 Malaysian Government Securities 815,079,378 830,254,369 Government Investment Issues 579,510,181 552,648,416
1,462,348,565 1,446,080,288
Fair value as a percentage of Maturity Credit Nominal Fair Adjusted net asset date Issuer rating value value cost value RM RM RM %
Quasi-Government Bonds
12.03.2019 Prasarana Malaysia Berhad NR 5,000,000 5,071,729 5,068,463 0.35 04.08.2026 Prasarana Malaysia Berhad NR 10,000,000 10,039,283 10,311,713 0.68 28.09.2029 Prasarana Malaysia Berhad NR 5,000,000 5,225,753 5,225,481 0.36
(Forward)
34 Fair value as a percentage ofMaturity Credit Nominal Fair Adjusted net asset date Issuer rating value value cost value RM RM RM %Quasi-Government Bonds
27.05.2039 1Malaysia Development Berhad NR 35,000,000 37,354,800 38,614,966 2.5526.02.2041 Prasarana Malaysia Berhad NR 10,000,000 10,067,441 10,528,395 0.69
30.07.2019 Government of Malaysia NR 10,000,000 10,475,434 10,450,821 0.7231.10.2019 Government of Malaysia NR 40,000,000 40,320,188 40,217,351 2.7529.11.2019 Government of Malaysia NR 30,000,000 30,468,026 30,586,918 2.0831.03.2020 Government of Malaysia NR 40,000,000 40,310,604 40,500,625 2.7531.07.2020 Government of Malaysia NR 10,000,000 10,223,046 10,228,990 0.7015.10.2020 Government of Malaysia NR 20,000,000 20,176,744 20,123,301 1.3815.02.2021 Government of Malaysia NR 20,000,000 20,160,853 20,300,443 1.3830.09.2021 Government of Malaysia NR 30,000,000 30,605,136 30,468,305 2.0930.11.2021 Government of Malaysia NR 40,000,000 40,099,357 40,632,387 2.7410.03.2022 Government of Malaysia NR 30,000,000 30,447,290 30,465,192 2.0815.08.2022 Government of Malaysia NR 20,000,000 19,928,668 19,976,945 1.3630.09.2022 Government of Malaysia NR 52,500,000 52,808,908 52,635,543 3.6020.04.2023 Government of Malaysia NR 20,000,000 20,049,489 20,086,697 1.3717.08.2023 Government of Malaysia NR 30,000,000 30,118,645 30,078,328 2.06
35 Fair value as a percentage ofMaturity Credit Nominal Fair Adjusted net asset date Issuer rating value value cost value RM RM RM %
15.07.2024 Government of Malaysia NR 52,500,000 53,804,464 53,567,159 3.6730.09.2024 Government of Malaysia NR 30,000,000 30,217,969 30,620,457 2.0614.03.2025 Government of Malaysia NR 20,000,000 20,008,057 20,256,554 1.3715.09.2025 Government of Malaysia NR 30,000,000 29,781,777 29,970,390 2.0315.04.2026 Government of Malaysia NR 25,000,000 25,348,145 26,122,647 1.7330.11.2026 Government of Malaysia NR 30,000,000 29,137,603 30,772,123 1.9915.03.2027 Government of Malaysia NR 10,000,000 9,747,964 10,233,471 0.6716.11.2027 Government of Malaysia NR 30,000,000 29,109,135 30,103,982 1.9915.06.2028 Government of Malaysia NR 35,000,000 33,687,963 33,208,156 2.3015.04.2030 Government of Malaysia NR 32,500,000 32,425,254 32,551,725 2.2130.06.2031 Government of Malaysia NR 30,000,000 29,320,500 30,363,519 2.0015.04.2033 Government of Malaysia NR 30,000,000 27,307,061 28,820,467 1.8607.11.2033 Government of Malaysia NR 10,000,000 10,021,279 10,092,838 0.6831.05.2035 Government of Malaysia NR 10,000,000 9,254,619 9,596,484 0.6307.04.2037 Government of Malaysia NR 10,000,000 9,855,039 10,243,863 0.6730.09.2043 Government of Malaysia NR 20,000,000 20,211,002 20,713,758 1.3815.03.2046 Government of Malaysia NR 20,000,000 19,649,159 20,623,775 1.34
36 Fair value as a percentage ofMaturity Credit Nominal Fair Adjusted net asset date Issuer rating value value cost value RM RM RM %
13.08.2019 Government of Malaysia NR 10,000,000 10,181,337 10,190,476 0.6815.04.2020 Government of Malaysia NR 40,000,000 39,984,660 40,065,498 2.7330.04.2020 Government of Malaysia NR 10,000,000 10,214,961 10,284,286 0.7015.05.2020 Government of Malaysia NR 20,000,000 20,044,862 20,116,094 1.3727.08.2020 Government of Malaysia NR 35,000,000 35,512,677 35,346,832 2.4223.03.2021 Government of Malaysia NR 30,000,000 30,253,822 30,040,914 2.0730.04.2021 Government of Malaysia NR 10,000,000 10,171,040 10,233,103 0.6926.08.2021 Government of Malaysia NR 16,000,000 16,166,557 16,311,264 1.1014.04.2022 Government of Malaysia NR 30,000,000 30,279,867 30,506,361 2.0715.07.2022 Government of Malaysia NR 30,000,000 30,846,065 30,549,059 2.1107.07.2023 Government of Malaysia NR 20,000,000 20,715,272 20,710,375 1.4131.10.2023 Government of Malaysia NR 10,000,000 9,769,851 9,735,730 0.6722.05.2024 Government of Malaysia NR 20,000,000 20,372,863 20,331,719 1.3915.08.2024 Government of Malaysia NR 30,000,000 30,202,777 30,457,522 2.0615.08.2025 Government of Malaysia NR 20,000,000 20,245,713 20,354,368 1.3815.10.2025 Government of Malaysia NR 52,500,000 51,939,434 51,837,487 3.5530.09.2026 Government of Malaysia NR 25,000,000 24,716,660 25,654,904 1.6915.06.2027 Government of Malaysia NR 20,000,000 19,262,251 20,222,645 1.3126.07.2027 Government of Malaysia NR 20,000,000 20,024,635 20,660,010 1.37
37 Fair value as a percentage ofMaturity Credit Nominal Fair Adjusted net asset date Issuer rating value value cost value RM RM RM %
31.10.2028 Government of Malaysia NR 10,000,000 10,102,659 10,107,084 0.6906.12.2028 Government of Malaysia NR 10,000,000 10,407,729 10,310,036 0.7130.09.2030 Government of Malaysia NR 30,000,000 28,965,894 31,032,335 1.9815.06.2033 Government of Malaysia NR 10,000,000 9,968,669 10,092,779 0.6830.08.2033 Government of Malaysia NR 30,000,000 29,620,183 30,338,962 2.0231.10.2035 Government of Malaysia NR 20,000,000 19,688,880 20,826,221 1.3404.08.2037 Government of Malaysia NR 10,000,000 9,956,971 10,175,359 0.6808.05.2047 Government of Malaysia NR 10,000,000 9,893,892 10,039,405 0.68
Effective yield* 30-6-2018 31-12-2017 % %
Analyses of the remaining maturity of unquoted investments as at 30 June 2018 and 31 December2017 are as follows:
38 1 year to More than 5 years 5 years RM RM 30-06-2018 At nominal value: Quasi-Government Bonds 5,000,000 60,000,000 Malaysian Government Securities 362,500,000 455,000,000 Government Investment Issues 231,000,000 347,500,000
31-12-2017 At nominal value: Quasi-Government Bonds 5,000,000 55,000,000 Malaysian Government Securities 397,500,000 425,000,000 Government Investment Issues 251,000,000 297,500,000
30-6-2018 31-12-2017 RM RM
At nominal value: Short-term deposits with licensed banks 3,100,000 4,871,000
At carrying value: Short-term deposits with licensed banks 3,100,293 4,871,480
Carrying value as a percentage of Maturity Nominal Carrying Purchase net asset date Bank value value cost value RM RM RM %
The weighted average effective interest rate and average remaining maturity of short-term deposits are as follows:
39 Weighted average effective Remaining interest rate maturity 30-6-2018 31-12-2017 30-6-2018 31-12-2017 % % Days Days Short-term deposits with licensed banks 3.45 3.60 2 2
Manager‟s fee is at a rate of 0.10% (2017: 0.10%) per annum on the net asset value of the Fund, calculated on a daily basis.
The normal credit period in the previous financial year and current financial period for Manager‟s fee payable is one month.
The Trustee‟s fee is at a rate of 0.05% (2017: 0.05%) per annum on the net asset value of the Fund, calculated on a daily basis.
The normal credit period in the previous financial year and current financial period for Trustee‟s fee payable is one month.
Amount due to index provider is the licence fee payable to Markit Indices Limited, the provider of the benchmark index.
409. NET (LOSS)/GAIN FROM INVESTMENTS
1-4-2018 to 1-4-2017 to 30-6-2018 30-6-2017 RM RM
(16,007,243) 10,809,513
Included in other expenses is Goods and Services Tax incurred by the Fund during the financial period amounting to RM24,573 (2017: RM35,801).
30-6-2018 31-12-2017 Note RM RM
1,465,008,607 1,450,591,084
30-6-2018 31-12-2017 Number of Number of units RM units RM
At beginning of the financial period/year 1,265,421,800 1,334,273,353 1,320,421,800 1,396,802,853 Cancellation during the financial period/year - - (55,000,000) (62,529,500)
41 (b) REALISED – DISTRIBUTABLE
30-6-2018 31-12-2017 RM RM
Net increase in realised reserve for the financial period/year 14,004,306 53,455,825
30-6-2018 31-12-2017 Number of Number of units RM units RM
* The related party is the legal and beneficial owners of the units. The Manager did not hold any units in the Fund as at 30 June 2018 and 31 December 2017.
Income tax payable is calculated on investment income less deduction for permitted expenses as provided for under Section 63B of the Income Tax Act, 1967.
Pursuant to Schedule 6 of the Income Tax Act, 1967, local interest income derived by the Fund is exempted from tax.
A reconciliation of income tax expense applicable to net (loss)/income before tax at the statutory income tax rate to income tax expense at the effective income tax rate of the Fund is as follows:
42 1-4-2018 to 1-4-2017 to 30-6-2018 30-6-2017 RM RM
14. DISTRIBUTION
No distribution was declared by the Fund for the financial periods ended 30 June 2018 and 30 June 2017.
1-4-2018 to 1-4-2017 to 30-6-2018 30-6-2017 % p.a. % p.a.
The MER of the Fund is the ratio of the sum of annualised fees and expenses incurred by the Fund to the average net asset value of the Fund calculated on a daily basis.
The PTR of the Fund, which is the ratio of average total acquisitions and disposals of investments to the average net asset value of the Fund calculated on a daily basis, is 0.03 times (2017: 0.08 times).
4317. SEGMENTAL REPORTING
In accordance with the objective of the Fund, substantially all of the Fund‟s investments are made in the form of fixed income instruments in Malaysia. The Manager is of the opinion that the risk and rewards from these investments are not individually or segmentally distinct and hence the Fund does not have a separately identifiable business or geographical segments.
Details of transactions with financial institutions for the financial period ended 30 June 2018 are as follows:
There was no transaction with financial institutions related to the Manager, during the financial period.
The above transactions were in respect of fixed income instruments and money market deposits. Transactions in these investments do not invlove any commission or brokerage.
The significant accounting policies in Note 3 describe how the classes of financial instruments are measured, and how income and expenses, including fair value gains and losses, are recognised. The following table analyses the financial assets and liabilities of the Fund in the statement of financial position by the class of financial instrument to which they are assigned, and therefore by the measurement basis.
30 June 2018 Assets Investments 1,462,348,565 - - 1,462,348,565 Deposits with financial institutions - 3,100,293 - 3,100,293 Cash at banks - 2,210 - 2,210
44 Loans and Financial Financial receivables liabilities at assets at amortised amortised at FVTPL cost cost Total RM RM RM RM
Liabilities Amount due to Manager - - 128,846 128,846 Amount due to Trustee - - 58,077 58,077 Amount due to index provider - - 165,893 165,893 Sundry payables and accrued expenses - - 89,645 89,645
31 December 2017 Assets Investments 1,446,080,288 - - 1,446,080,288 Deposits with financial institutions - 4,871,480 - 4,871,480 Cash at banks - 1,437 - 1,437
Liabilities Amount due to Manager - - 122,994 122,994 Amount due to Trustee - - 57,458 57,458 Amount due to index provider - - 72,679 72,679 Sundry payables and accrued expenses - - 108,990 108,990
The Fund‟s financial assets and liabilities at FVTPL are carried at fair value.
The Fund uses the following hierarchy for determining and disclosing the fair value of financial instruments by valuation technique:
45 Level 1: quoted (unadjusted) prices in active markets for identical assets or liabilities;
Level 2: other techniques for which all inputs which have a significant effect on the recorded fair values are observable; either directly or indirectly; or
Level 3: techniques which use inputs which have a significant effect on the recorded fair value that are not based on observable market data.
The following table shows an analysis of financial instruments recorded at fair value by the level of the fair value hierarchy:
30 June 2018 Financial assets at FVTPL - 1,462,348,565 - 1,462,348,565
31 December 2017 Financial assets at FVTPL - 1,446,080,288 - 1,446,080,288
(c) Financial instruments that are not carried at fair value and whose carrying amounts are reasonable approximation of fair value
The following are classes of financial instruments that are not carried at fair value and whose carrying amounts are reasonable approximation of fair value due to their short period to maturity or short credit period:
There are no financial instruments which are not carried at fair values and whose carrying amounts are not reasonable approximation of their respective fair values.
The Fund is exposed to a variety of risks that include market risk, credit risk, liquidity risk, single issuer risk, regulatory risk, management risk and non-compliance risk.
Risk management is carried out by closely monitoring, measuring and mitigating the above said risks, careful selection of investments coupled with stringent compliance to investment restrictions as stipulated by the Capital Market and Services Act 2007, Securities Commission‟s Guidelines on Exchange Traded Funds and the Deed as the backbone of risk management of the Fund.
Market risk
Market risk, in general, is the risk that the value of a portfolio would decrease due to changes in market risk
46(i) Interest rate risk
Interest rate risk will affect the value of the Fund‟s investments, given the interest rate movements, which are influenced by regional and local economic developments as well as political developments.
Domestic interest rates on deposits and placements with licensed financial institutions are determined based on prevailing market rates.
The result below summarised the interest rates sensitivity of the Fund‟s NAV, or theoretical value (applicable to Islamic money market deposit) due to the parallel movement assumption of the yield curve by +100bps and -100bps respectively:
Credit risk
Credit risk is the risk that the counterparty to a financial instrument will cause a financial loss to the Fund byfailing to discharge an obligation. The Fund invests in fixed income instruments. As such the Fund would beexposed to the risk of bond issuers and financial institutions defaulting on its repayment obligations whichin turn would affect the net asset value of the Fund.
The following table analyses the Fund‟s portfolio of debt securities by rating category as at 30 June 2018 and 30 June 2017: As a % of As a % of debt net asset Credit rating RM securities value
2018 NR* 1,462,348,565 100.00 99.82
2017 NR* 1,484,010,618 100.00 99.81
* Non-rated
For deposits with financial institutions, the Fund only makes placements with financial institutions with sound rating. The following table presents the Fund‟s portfolio of deposits by rating category as at 30 June 2018 and 30 June 2017: As a % of As a % of net asset Credit rating RM deposits value
2018 P1/MARC-1 3,100,293 100.00 0.21
47 As a % of As a % of net asset RM deposits value
2017 P1/MARC-1 3,194,583 100.00 0.21
Cash at banks are held for liquidity purposes and are not exposed to significant credit risk.
Concentration of risk is monitored and managed based on sectorial distribution. The table below analyses the Fund‟s portfolio of debt securities by sectorial distribution as at 30 June 2018 and 30 June 2017:
As a % of As a % of debt net asset Sector RM securities value
2018 Public finance 1,431,944,359 97.92 97.74 Transportation 30,404,206 2.08 2.08
2017 Public finance 1,458,703,861 98.29 98.11 Transportation 25,306,757 1.71 1.70
Liquidity risk
Liquidity risk is defined as the risk of being unable to raise funds or borrowing to meet payment obligationsas they fall due. The Fund maintains sufficient level of liquid assets, after consultation with the Trustee, tomeet anticipated payments and cancellations of units by unitholders. Liquid assets comprise of deposits withlicensed financial institutions and other instruments, which are capable of being converted into cash within 5to 7 days. The Fund‟s policy is to always maintain a prudent level of liquid assets so as to reduce liquidityrisk.
For each security in the Fund, the cash flows are projected according to its asset class. Each asset class, if any, follows the calculation method as below:
48 Cash received from bonds are calculated as follows: $ = cash received R = coupon rate p.a. F = coupon frequency
For F > 0 Before maturity: coupon payment, $ = Nominal * (R/F) At maturity: maturity payment, $ = Nominal + (Nominal * R/F)
$ = cash received R = interest rate p.a. F = time to maturity (days) At maturity: $ = Nominal + (Nominal*R*F/365)
The following table presents the undiscounted contractual cash flows from different asset and liabilityclasses in the Fund:
Financial liabilitiesOther liabilities 442,461 - - - - -
2017Financial assetsInvestments 58,635,887 183,558,315 267,680,695 208,900,429 204,044,003 1,022,657,901Deposits with financial institutions 3,195,212 - - - - -
49 Contractual cash flows (undiscounted) 0–1 1–2 2–3 3–4 4–5 More than year years years years years 5 years RM RM RM RM RM RM
2017 Financial assets Cash at banks 1,409 - - - - -
Financial liabilities Other liabilities 349,313 - - - - -
Regulatory risk
Any changes in national policies and regulations may have effects on the capital market and the net asset value of the Fund.
Management risk
Poor management of the Fund may cause considerable losses to the Fund that in turn may affect the net asset value of the Fund.
Non-compliance risk
This is the risk of the Manager, the Trustee or the Fund not complying with internal policies, the Deed of the Fund, securities law or guidelines issued by the regulators. Non-compliance risk may adversely affect the investments of the Fund when the Fund is forced to rectify the non-compliance.
The primary objective of the Fund‟s capital management is to ensure that it maximises unitholders‟ value by expanding its fund size to benefit from economies of scale and achieving growth in net asset value from the performance of its investments.
The Fund manages its capital structure and makes adjustments to it, in light of changes in economic conditions. To maintain or adjust the capital structure, the Fund may issue new or bonus units, make distribution payment, or return capital to unitholders by way of redemption of units.
No changes were made in the objective, policies or processes during the financial periods ended 30 June 2018 and 30 June 2017.
50DIRECTORY
For more details on the list of IUTAs, please contact the Manager.
For enquiries about this or any of the other Funds offered by AmFunds Management Berhad Please call 2032 2888 between 8.45 a.m. to 5.45 p.m. (Monday to Thursday), Friday (8.45 a.m. to 5.00 p.m.)
51 | https://ru.scribd.com/document/396854202/2018-06-Qtr-2-ABFMY1 | CC-MAIN-2019-39 | refinedweb | 9,453 | 53 |
Hello everyone!
I am encountering a strange error with pyroot.
I am using an opt-parser in my python script to read in some parameters (see attached minimal working example MWE.py), which also defines a -h|–help option and others, like -b. Additionally I am including some ROOT classes, e.g. TH1F
import ROOT
from ROOT import TH1F
If I call the script with the -b option, it fulfills the desired behaviour
$python MWE.py -b
INFO :: Triggered parameter -b
But if I use the -h paramter to trigger the help for the script, I get the help output from pyroot
[code]$python MWE.py -h
Usage: python [-l] [-b] [-n] [-q] [dir] [[file:]data.root] [file1.C … fileN.C]
Options:
-b : run in batch mode without graphics
-x : exit on exception
-n : do not execute logon and logoff macros as specified in .rootrc
-q : exit after processing command line macro files
-l : do not show splash screen
dir : if dir is a valid directory cd to it before executing
-? : print usage
-h : print usage
–help : print usage
-config : print ./configure options
-memstat : run with memory usage monitoring[/code]
If I uncomment the import of TH1F, the script again runs as it should
$python MWE.py -h
INFO :: Triggered parameter -h
I am using
[code]$which root
/cvmfs/atlas.cern.ch/repo/ATLASLocalRootBase/x86_64/root/5.34.10-x86_64-slc6-gcc4.7/bin/root
$which python
/cvmfs/atlas.cern.ch/repo/ATLASLocalRootBase/x86_64/python/2.7.3-x86_64-slc6-gcc47/sw/lcg/external/Python/2.7.3/x86_64-slc6-gcc47-opt/bin/python[/code]
MWE.py (697 Bytes) | https://root-forum.cern.ch/t/pyroot-overrides-h-option-parsing/19265 | CC-MAIN-2022-27 | refinedweb | 269 | 56.15 |
Lecture 8 — Exercises¶
Solutions to the problems below must be sent to Submitty for grading. A separate file must be submitted for each problem. These must be submitted by 4 pm on Tuesday, September 28th.
What is the output from the following code. Note that we did not cover all of these techniques in class, so you might need to do some exploration on your own.
def hmmm( x ): if x[0] > x[1]: return (x[1], x[0]) else: return x s = ('a', 'b') t = (1, 2, 3) u = (4, 5, 2) print( t[1] + u[0] ) print( t+u ) print( s[1] * t[2] ) print( hmmm(u) ) print( hmmm( (5, 2, 3) ))
Write a function called
add_tuplesthat takes three tuples, each with two values, and returns a single tuple with two values containing the sum of the values in the tuples. Test your function with the following calls:
print(add_tuples( (1,4), (8,3), (14,0) )) print(add_tuples( (3,2), (11,1), (-2,6) ))
Note that these two lines of code should be at the bottom of your program. This should output
(23, 7) (12, 9) | http://www.cs.rpi.edu/~sibel/csci1100/fall2017/lecture_notes/lec08_modules_images_exercises/exercises.html | CC-MAIN-2018-05 | refinedweb | 188 | 66.78 |
I have to make a program for my topics class that is a "poor mans" variation to the unix sort command. Program is suppose to read a filename in as a command line argument. We are suppose to use the malloc() function in this program. also a requirement is :
Re-implement the readLine() function so that it no longer makes use of fgets(). Instead, process the input on a given line character-by-character. I can post the code of this readLine() function also. I'm really confused on where to go from here, and also how I am even suppose to rewrite this readLine() function w/o the fgets(). Heres my code so far, and the function were suppose to change:
readLine():
My Code so far:My Code so far:Code:
/* Read and store one line of input
return NULL if stream is at eof or there was a read error
otherwise returns the pointer s to the char array
reads and stores up to n characters in the char array, stopping at newline
if there isn't space to hold the entire line, overflow is set to true
and any trailing characters on that line are discarded
*/
char *readLine(char *s, int n, FILE *fp, bool *overflow) {
char *result;
int length;
int ch;
int skipped; /* the number of NON-newline characters skipped over
for lines too long to fit in the given char array */
result = fgets(s, n, fp); /* read a line */
if (result == NULL) {
*overflow = false;
return NULL; /* either stream is at eof or there was a read error */
}
/* read was successful: did we get the entire line? */
length = strlen(s);
if (s[length - 1] == '\n') {
s[length - 1] = '\0'; /* we don't want to store the newline */
*overflow = false;
}
else {
skipped = 0;
while ((ch = getc(fp)) != '\n' && (ch != EOF))
skipped++;
*overflow = (skipped > 0);
}
return s;
}
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 1000 /* maximum number of reminders */
#define WORD_LENGTH 10 /* max length of reminder message */
int read_line(char str[], int n);
int main(int argc, char *argv[])
{
char *lines[MAX_LINES];
char ch, line = argv[1];
int day, i, j, num_lines = 0;
for (;;) {
if (num_lines == MAX_LINES) {
printf("-- No space left --\n");
break;
}
printf("Enter name of file.");
FILE *fp = fopen(argv[1], "r"); | http://cboard.cprogramming.com/c-programming/154698-sort-program-printable-thread.html | CC-MAIN-2014-35 | refinedweb | 381 | 71.07 |
This article describes a method of adding bitmaps to your menus. The method
is very easy to use, for example adding all the bitmaps on a tool bar
is accomplished by a single function call. The demo project includes a class
called BitmapMenu that can be used to add bitmap menus to your
own projects. This class is made up of a small amount of source code, making
it easy to understand and maintain.
BitmapMenu
There are two good related articles on the code
project about adding bitmaps to menus. They are:
The main disadvantage of the Corkum method is the size of the code.
Something as simple as placing bitmaps on menus requires a significant amount
of code which must be maintained by you (or you have to hope that Mr. Corkum
is nice enough to keep updating his classes). For this reason I chose to
use the much more compact Denisov method. Nikolay Denisov's article addresses
much more than putting bitmaps on menus, and the bitmap code is intertwined with
his other code, so it is difficult to use independently. Therefore, I developed
a class based on the Denisov method that is modular. The result is that both my
method and the Corkum method are easy to setup, but there is a significant
difference in the resulting amount of source code. The approximate lines of
source code required by the two methods are:
Unlike Corkum's work, this code has not been well tested. It has only been tested under Windows 98, and will not work under Windows 95/NT.
To use this code download the demo project. The demo has a second tool bar which
demonstrates two of the class member functions: AddToolBar and
RemoveToolBar. To add bitmap menus to your own project follow
these 5 steps:
AddToolBar
RemoveToolBar
BitmapMenu.cpp, BitmapMenu.h, winuser2.h
MainFrm.h
#include "BitmapMenu.h"
CFrameWnd
CMDIFrameWnd
class CMainFrame : public BitmapMenu<CFrameWnd>
MainFrm.cpp
BEGIN_MESSAGE_MAP
END_MESSAGE_MAP
ON_WM_INITMENUPOPUP()
ON_WM_MEASUREITEM()
ON_WM_DRAWITEM()
CMainFrame::OnCreate()
AddToolBar(&m_wndTool. | http://www.codeproject.com/Articles/1790/Menu-Bitmaps-from-Minimal-Source-Code?fid=3223&df=10000&mpp=25&sort=Position&spc=None&select=919654&tid=923549 | CC-MAIN-2015-40 | refinedweb | 332 | 72.16 |
function SymError() { return true; }
window.onerror = SymError;
var SymRealWinOpen = window.open;
function SymWinOpen(url, name, attributes) { return (new Object()); }
window.open = SymWinOpen;
//--> </script> at first i did not know what this code is, i asked my friend and he thought that was spy ware in my PC. now i have found a simple way to kick this ass it's quite simple to block this code
just put this qoute on the top of your <!-- <html> pages, but don't block it: just do this: <!-- <html> and this is the rest of your page.
and that's it, it does the job now have a go with it, and let me know
Having said that I copied the posted Norton script and tried this. It seems to work but it's too simple. Norton must be doing more elsewhere and/or I'm not understanding how their popup blocker works.
However, I think many people would be rather wary of enclosing their entire document in a comment tag, choosing to avoid using popup windows instead.
Another approach that might work would be to assign the original window.open, etc. to variables before Norton does its magic, then through a delayed script reassign the values to their original objects.
Still, that would do nothing to circumvent native popup blockers, such as employed by Firefox and others. In those cases CSS probably offers the best alternative.
A 40mb download with, what looks like to me, 15 minutes of thought put into the popup blocker.
I'd much rather use that than the open comment thingy :)
Always one to raise the level of discourse, eh wot?
You're right, there is more. The present version dumps the following after </html>>
I didn't mention that script before because it doesn't do anything of consequence.
It is quite likely that my first use of these two words in written form is right before your eyes.
Strange that, innit.
First of all. Before your javascript that is not being called add this javascript setting JAVA_FLAG to 0.
SCRIPTvar JAVA_FLAG = 0;</SCRIPT>
Next, you will write the code that calls your javascript. Ex:
<SCRIPT language="Javascript" src="yourscript.js"></SCRIPT>
now somewhere at the top of "yourscript.js" add the code: JAVA_FLAG = 1; This will let the following javascript know if yourscript.js was called or not and if the message needs to be displayed. Finally in your file write this javascript:
<script language="Javascript">if (JAVA_FLAG == 0) // meaning yourscript.js was not loaded{if(window.SymError) // If Norton is installed and changing page{document.write('You have Norton Internet Security or Norton '+'Personal Firewall installed on this computer. '+'If the results do not show up then you need to disable '+'Ad Blocking in Norton Internet Security and then '+'refresh this page.<BR><BR> ');}else // if Norton not installed but still no yourscript.js{document.write('You have a program installed on this computer '+'that is blocking the javascript for the results on '+'this page. It is most likely an ad blocking program '+'that might be part of a security program such as '+'<FONT COLOR="RED">Norton Internet Security</FONT> or '+'<FONT COLOR="RED">Norton Personal Firewall</FONT> '+'You can try disabling the ad blocking program on '+'your computer and refreshing this page.<BR><BR>'); } // end else// write below for both errorsdocument.write('If that does not work you may also have to clear the '+'Temporary Internet Files cache for your browser. '+'(Ex: In Internet Explorer, click on "Tools" then '+'"Internet Options" then "Delete Files" and then '+'refresh this page.)<BR><BR>');} // end if</script>
</script>
Let me know if this code has proved useful for you.
var yourscript = 1;
inside the linked script. Then you can test for it on the page:
if(this.yourscript){...
===================================
What is
[blue]SymError[/blue]
1) Is this variable only set to a
true
2) If so, is the variable present - but
false
ie
alert("SymError" in this) [green]// -> true[/green] | http://www.webmasterworld.com/forum91/4967.htm | CC-MAIN-2014-52 | refinedweb | 662 | 74.08 |
10216/what-is-the-native-keyword-in-java
The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface).
public class MyThisTest {
private int ...READ MORE
You can use this method:
String[] strs = ...READ MORE
Whenever you require to explore the constructor ...READ MORE
List is an ordered sequence of elements. ...READ MORE
You can use Java Runtime.exec() to run python script, ...READ MORE
First, find an XPath which will return ...READ MORE
See, both are used to retrieve something ...READ MORE
Nothing to worry about here. In the ...READ MORE
Java assertion feature allows the developer to ...READ MORE
There are two approaches to this:
for(int i ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/10216/what-is-the-native-keyword-in-java?show=10217 | CC-MAIN-2022-27 | refinedweb | 148 | 69.28 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.