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 |
|---|---|---|---|---|---|
IOPL(2) Linux Programmer's Manual IOPL(2)
iopl - change I/O privilege level
#include <sys/io.h> int iopl(int level);.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
EINVAL level is greater than 3. ENOSYS This call is unimplemented. EPERM The calling thread 5.08 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. Linux 2020-08-13 IOPL(2)
Pages that refer to this page: afs_syscall(2), break(2), fattach(2), fdetach(2), getmsg(2), getpmsg(2), gtty(2), inb(2), inb_p(2), inl(2), inl_p(2), insb(2), insl(2), insw(2), inw(2), inw_p(2), ioperm), systemd.exec(5), capabilities(7) | https://man7.org/linux/man-pages/man2/iopl.2.html | CC-MAIN-2020-40 | refinedweb | 130 | 52.97 |
The Java Specialists' Newsletter
Issue 059b
2002-11-13
Category:
Performance
Java version:
Subscribe
RSS Feed
Thanks to those of you who wrote back after my last newsletter. There are some issues I want to follow-up on.
To start off, the date on the newsletter was incorrect.
Then, the original topic of this newsletter was "Verrrrrry looooong Strings and other things". One of my subscribers from Poland suggested that the topic did not really represent the content as there is no real limit on how long ordinary Strings can be, except for the limit on char array length and physical memory. I renamed it to: "When arguments get out of hand..."
Talking about long constant Strings, many thanks to Frank Peters from Process Management Consulting in Cologne for pointing out the problem with long constant Strings to me at the beginning of June 2002. Apologies for forgetting to thank you in the original newsletter, our email conversation had slipped my conscious mind. Something that Frank pointed out to me in the original discussion was that if you have a unicode character, it might be converted to more than two bytes in certain circumstances, so the limit is actually less than 65535 in some cases.
Some readers also wrote to tell me that the problem with looong constant Strings used to appear with JSP pages generated by Dreamweaver.
Last, but definitely not least, thanks to Bjorn Carlin for sending me the secret to the 14 missing data members. Thank you also to John Bester from South Africa and Juan C. Valverde from ArtInSoft in Costa Rica for sending me their ideas.
The limit on the fields is actually the limit in the constant pool where the names of the fields are stored. Bjorn told me that the 9th and 10th bytes of the class file tell you how many constant fields are in the class. He also sent me output from a little program he wrote that dumped the constant pool from a class.
Here is a piece of code that tells you the size of the constant pool for a classfile:
import java.io.*; public class ConstantPoolSize { static void skip(InputStream in, int skip) throws IOException { while(skip > 0) { skip -= in.skip(skip); } } public static void main(String[] args) throws IOException { DataInputStream din = new DataInputStream( new FileInputStream(args[0])); skip(din, 8); int count = ((din.readByte() & 0xff) << 8) | (din.readByte() & 0xff); System.out.println(count); din.close(); } }
I'll let you figure out the reason for skip() yourself ;-)
Run it against a small class such as:
public class Small {}
You will get different results depending with which debugging info
options you compiled Small.java. The default compile will tell you
that there are 13 entries in Small.class. If you add one field,
you will have 15 entries, one for the name of the field, and one
for the type of the field. For example, if you add an
int a0;, you will have entries "I" and "a0".
You can compile BigClass with the -g:none option, then you can squeeze more fields in. In addition, if you call one field "I" and another "Code", you can get two more fields into your class. "I" is the type of int defined in the constants table. I don't know where "Code" comes from, but it works. The maximum number of fields I've therefore managed to squeeze in like this was 65526.
Now that's really overrevving Java ;-)
Heinz
P.S. Probably the worst mistake in the newsletter was that I said my rev counter was limited to 6000 revolutions per minute. That of course is nonsense. It is limited to 7000 revs. I checked today. When I wrote the newsletter, I did not feel like going to the garage to look. Besides, at 1:00am that might have made my neighbours unhappy ;-)
Performance Articles
Related Java Course
Would you like to receive our monthly Java newsletter, with lots of interesting tips and tricks that will make you a better Java programmer? | http://www.javaspecialists.eu/archive/Issue059b.html | CC-MAIN-2017-09 | refinedweb | 673 | 70.63 |
If you're using a Firefox version before 48, you'll also need an additional key in
manifest.jsoncalled applications:
"applications": { "gecko": { "id": "[email protected]", "strict_min_version": "42.0", "strict_max_version": "50.*", "update_url": "" } }
Note:.
Status of
WebExtensions:
WebExtensions are currently in an experimental alpha state. From Firefox 46, you can publish WebExtensions to Firefox users, just like any other add-on. We're aiming for a first stable release in Firefox 48.
UPD: Firefox 48 released 02.08.2016.
Links:
API support status - The list of APIs and their status.
WebExtensions - JavaScript APIs, keys of manifest.json, tutorials, etc.
Before talking about porting Firefox extensions from/to, one should know what
WebExtensions is.
WebExtensions - is a platform that represents an API for creating Firefox extensions.
It uses the same architecture of extension as Chromium, as a result, this API is compatible in many ways with API in Google Chrome and Opera (Opera which based on Chromium). In many cases, extensions developed for these browsers will work in Firefox with a few changes or even without them at all.
MDN recommends to use
WebExtension for new extensions:
In the future, WebExtensions will be the recommended way to develop Firefox add-ons, and other systems will be deprecated.
In view of the foregoing, if you want to port extensions to Firefox, you have to know, how the extension was written.
Extensions for Firefox can be based on
WebExtension,
Add-on SDK or
XUL.
When using
WebExtension, one has to look through the list of incompatibilities, because some functions are supported fully or partially, that is in other words, one should check one’s
manifest.json.
It also enables to use the same namespace:
At this time, all APIs are accessible through the chrome.* namespace. When we begin to add our own APIs, we expect to add them to the browser.* namespace. Developers will be able to use feature detection to determine if an API is available in browser.*.
manifest.json:
{ "manifest_version": 2, "name": "StackMirror", "version": "1.0", "description": "Mirror reflection of StackOverflow sites", "icons": { "48": "icon/myIcon-48.png" }, "page_action": { "default_icon": "icon/myIcon-48.png" }, "background": { "scripts" : ["js/background/script.js"], "persistent": false }, "permissions": ["tabs", "*://*.stackoverflow.com/*"] }
background script:
function startScript(tabId, changeInfo, tab) { if (tab.url.indexOf("stackoverflow.com") > -1) { chrome.tabs.executeScript(tabId, {code: 'document.body.style.transform = "scaleX(-1)";'}, function () { if (!chrome.runtime.lastError) { chrome.pageAction.show(tabId); } }); } } chrome.tabs.onUpdated.addListener(startScript);
Pack project as standard
zip file, but with
.xpi extensions.
Then,you have to load the extension in Firefox.
Open the
about:addons page, accessible through Menu > Add-ons.
Click on Tools for all add-ons button.
When the extension is loaded the page
about:addons will look like this:
Directions on loading the extension in Google Chrome is in other topic - Getting started with Chrome Extensions.
The result of extension operation will be same in both browsers (Firefox/Google Chrome):
When extension being ported is based on
Add-on SDK one has to look through the comparison table for
Add-on SDK =>
WebExtensions, because these technologies have similar features, but differ in implementation. Each section of table describes the equivalent of
Add-on SDK for
WebExtension.
Comparison with the Add-on SDK
A similar approach and for XUL extensions.
Comparison with XUL/XPCOM extensions | https://sodocumentation.net/google-chrome-extension/topic/5731/porting-to-from-firefox | CC-MAIN-2021-10 | refinedweb | 547 | 50.33 |
Opened 9 years ago
Closed 12 months ago
Last modified 12 months ago
#3003 closed enhancement (fixed)
IWikiSyntaxProvider with doxygen SEARCH_ENGINE unusable slow for large code-bases
Description
Case:
- search engine is enabled in doxygen
- the doxygen-html-code base is large
- a simple WIKI-page is loaded by the user
--> the WIKI-Syntax-provider of the DoxygenPlugin stalls the whole server for up to 5 seconds with 100% CPU usage when loading any simple wiki-page.
my current workaround (with lost functionality) is:
file: doxygentrac.py
_doxygen_lookup(self, segments): ... # Request for a named object # TODO: # - do something about dirs # - expand with enum, defs, etc. # - this doesn't work well with the CREATE_SUBDIRS Doxygen option path, link = lookup('class%s.html' % file, 'class') if not path: path, link = lookup('struct%s.html' % file, 'struct') if path: return 'view', path, link # Revert to search >>>>>>> return ('search', None, None) # bail out for performance issues <<<<<<<<<< results = self._search_in_documentation(doc, [file]) << this is never called now and he rest of this function can not be used at the moment in our case
It would be nice to have a trac.ini - configuration option to disable the last branch, instead of hard-coding the return. I think optimizing the search_in_documentation function would take more time, and it is not needed that much.
Best Regards
Attachments (0)
Change History (3)
comment:1 Changed 9 years ago by
comment:2 Changed 12 months ago by
Performance issues seem to be solved in version > 0.11.
comment:3 Changed 12 months ago by
That's great news, I'll try to find some time to test all your enhancements.
Note: See TracTickets for help on using tickets.
Sorry for delay, I wasn't notified about this... | https://trac-hacks.org/ticket/3003 | CC-MAIN-2017-09 | refinedweb | 288 | 61.06 |
Home automation using Raspberry Pi, MQTT and Home Assistant
Written by Pranav Chakkarwar on 05 Apr 2021 • 14 minutes to read
HomeAutomation Privacy RaspberryPi
I previously wrote a post on DIY Home automation with Node-Red, but the project was hosted in a cloud server and the communication between the server and devices was dependent on the internet. So, I decided to completely rethink my design and came up with a practical and privacy focused solution that I use everyday.
Before we get started let’s take a look at some GREAT BENEFITS of this approach:
Only surface rewiring will get the work done. No need to purchase new lights, fans and appliances. Any device already setup will work seamlessly with this setup.
A large amount of data generated from smart home devices can be misused if you decide to let your home control depend on a third party server. Therefore this solution respects our privacy.
Low cost hardware with open source and free software makes a great combination for cheap but highly reliable solution.
Security issues about smart CCTVs not using end-to-end encryption or sometimes no encryption (Unbelievable!) were recently in the news. So a minimum attack surface and separating the Home Assistant from the host storage makes it a good choice.
Regular updates, security fixes for the software, thanks to the open source community that maintains these projects.
Easily replaceable and up-gradable hardware.
All communications between devices happen locally but the dashboard can be accessed remotely to control the devices locally.
A network map of the setup will give you a much clearer idea.
Requirements:
Raspberry Pi 3/4 or equivalent hardware that can run Home Assistant directly or on Docker containers. I am using a Pi 4B.
Edge IoT devices like ESP8266, ESP32 or equivalent devices that can communicate via the MQTT protocol.
ESP compatible relay boards
(Optional) WiFi and MQTT compatible clients/devices to control fan speed, light luminosity, etc.
Raspberry Pi OS installed if using a Raspberry Pi.
ESP-01 USB flasher
Setting up the Home Assistant server
There are several ways to install Home assistant on a Raspberry Pi. But, I am gonna go the containerized way because I don’t want my RPi 4 to run only a Home Assistant OS 🙃
I have already setup my Raspberry Pi 4B and use it for self-hosting many services, but that’s a talk for another article. Currently this is my Raspberry Pi setup.
Installing docker on raspberrypi using the convenience script
$ curl -fsSL -o get-docker.sh $ sudo sh get-docker.sh
Installing the Home Assistant docker container
On Raspberry Pi 3
$ docker run --init -d \ --name homeassistant \ --restart=unless-stopped \ -v /etc/localtime:/etc/localtime:ro \ -v /PATH_TO_YOUR_CONFIG:/config \ --network=host \ homeassistant/raspberrypi3-homeassistant:stable
On Raspberry Pi 4
$ docker run --init -d \ --name homeassistant \ --restart=unless-stopped \ -v /etc/localtime:/etc/localtime:ro \ -v /PATH_TO_YOUR_CONFIG:/config \ --network=host \ homeassistant/raspberrypi4-homeassistant:stable
Setting up the Home Assistant
In your browser, visit the ip address of your pi followed by port number :8123 on the local network (for e.g. mine is 192.168.0.119:8123).
Tip: Find your pi’s ip by pinging raspberrypi.local (works most of the time).
Now create a username and password. This process won’t create any online accounts but these details will enable us to log in to our Home Assistant when we visit the next time.
The Home Assistant will automatically detect If you have printers, smart lights, chromecast devices, smart speakers already setup. You can add them to your dashboard if you wish!
Setting up a local MQTT broker and connecting it to your Home assistant
A MQTT broker will allow us to send messages from the Home Assistant to the controlling devices and the device will report their state back. I recommend reading MQTT for dummies to understand the working of the MQTT protocol.
I am going for the Eclipse Mosquitto MQTT broker (without docker)
$ sudo apt update $ sudo apt install -y mosquitto mosquitto-clients
To make mosquitto auto-run on boot
$ sudo systemctl enable mosquitto.service
Connecting to the MQTT server from the Home Assistant integrations page.
- Browse to your Home Assistant instance.
- In the sidebar click on Configuration.
- From the configuration menu select: Integrations.
- In the bottom right, click on the Add Integration button.
- A list will pop up, now search and select “MQTT”.
- Complete the set up by entering the name of your MQTT client and the port. If you are following this tutorial the port will be 1883.
![Home Assistant add integrations]/images/add-integration.webp)
Setting up an ESP-01 Relay board
- Download Arduino IDE for your system and install it.
- Next install ESP8266 package inside the Arduino IDE:
- In your Arduino IDE, go to File > Preferences
- Enter “” into the “Additional Boards Manager URLs” field. Then, click OK.
- Open the Boards Manager. Go to Tools > Board > Boards Manager
- Search for ESP8266 and press install for the “ESP8266 by ESP8266 Community“
- Now go to Tools > Manage libraries
C++ program for the ESP-01 to connect to the WiFi and MQTT server
#include "EspMQTTClient.h" EspMQTTClient client( "WiFi Name", "WiFi Password", "ip address of your raspberrypi", // MQTT Broker server ip "mqtt username", // (Not needed) "mqtt password", // (Not needed) "Fan1", // Client name that uniquely identify your device 1883 // The MQTT port, default to 1883. this line can be omitted ); void setup() { Serial.begin(115200); pinMode(0, OUTPUT); } void onConnectionEstablished() { client.subscribe("livingroom/lights/com", [](const String & payload) { if (payload == "1") {digitalWrite(0, HIGH); client.publish("livingroom/lights/state", "1"); } if (payload == "0") {digitalWrite(0, LOW); client.publish("livingroom/lights/state", "0"); } }); } void loop() { client.loop(); }
Remember the ESP USB Flasher?
To flash the ESP-01, The ESP USB flasher should be modified as described in ESP8266 firmware flasher. After this you can flash the ESP-01 with the above program and connect circuit as shown below!
Changing the configuration.yaml of the Home assistant.
As we are running our Home Assistant in a Docker container we have to ssh into the Home Assistant container by using the command
$ sudo docker exec –it homeassistant /bin/bash $ nano configuration.yaml (If this command doesn't work, you will need to install nano using "apk install nano")
Now insert this below configuration in the configuration.yaml and save it!
light: - platform: mqtt name: "Living Room Lights" state_topic: "livingroom/lights/state" command_topic: "livingroom/lights/com" payload_on: "1" payload_off: "0" - platform: mqtt name: "Lounge Lights" state_topic: "lounge/lights/state" command_topic: "lounge/lights/com" payload_on: "1" payload_off: "0" switch: - platform: mqtt name: "Outlet 1" state_topic: "bedroom/outlet1/state" command_topic: "bderoom/outlet1/com" payload_on: "1" payload_off: "0" - platform: mqtt name: "Outlet 2" state_topic: "bedroom/outlet2/state" command_topic: "bderoom/outlet2/com" payload_on: "1" payload_off: "0" fan: - platform: mqtt name: "Living Room" state_topic: "livingroom/on/state" command_topic: "livingroom/on/com" speed_state_topic: "livingroom/speed/state" speed_command_topic: "livingroom/speed/set" payload_on: "1" payload_off: "0" payload_low_speed: "1" payload_medium_speed: "2" payload_high_speed: "3" speeds: - low - medium - high
This is an example code and you can add more devices and categories as you like. Extended configuration options are explained in the Home Assistant Docs.
Notice how the Home Assistant publishes command to the “bathroom/lights/com” and the ESP-01 is subscribed to the same topic. If you don’t understand feel free to ask me in the comments if you cant understand the config.
Remote access of the Home Assistant Dashboard!
Several options are available to access your dashboard over the internet. I found that most people use Port forwarding and DDNS to access a resource outside a local network. But, I will go for a reverse proxy which is far more secure.
Here are the some good reverse proxy providers to choose from:
- Nabu Casa - This method is recommended in the Home Assistant Docs.
- PageKite - I will use this for a demo.
- Cloudflare Argo tunnels - Best for security and protection.
Setting up Pagekite for remote access is fairly simple and can be done completely from a command line. Just use the commands below.
$ curl -O $ python2 pagekite.py 8123 SUBDOMAIN-THAT-YOU-WANT.pagekite.me
The sign up process will start in your terminal. Once you confirm your details the proxy client will start running and you can now visit SUBDOMAIN-THAT-YOU-WANT.pagekite.me and access your Home Assistant over the Internet!!! This URL can be used when you sign in on the Mobile apps of Home Assistant.
To demonstrate customization I applied a custom theme by using the configuration.yaml file.
# Example configuration.yaml entry frontend: themes: happy: primary-color: white text-primary-color: black background-primary-color: #cefe8e
That’s it! Now my setup looks great and works flawlessly.
cognex 2 June 2021The article was absolutely fantastic! A lot of great information which can be helpful in some or the another way. Keep updating the blog, looking forward for more content.
danieldur on reddit26 Apr 2021Pretty nice! What do you have in other tabs? I am especially interested in the "Day ahead". | https://brainbits.in/blog/raspberrypi-homeassistant-ultimate-setup | CC-MAIN-2021-39 | refinedweb | 1,506 | 56.25 |
#include "ctype.h";byte blinkPin = 13;byte blinkState = 0;byte data = 255;unsigned long blinkStart = 0UL;unsigned long blinkNow = 0UL;unsigned long blinkLen = 1000UL;void setup( void ){ Serial.begin( 115200 ); Serial1.begin( 115200 ); pinMode( blinkPin, OUTPUT ); // should default LOW Serial.println( "\nStartup" );}void loop( void ){ blinkNow = millis(); if ( blinkNow - blinkStart >= blinkLen ) { blinkStart = blinkNow; blinkState ^= 1; digitalWrite( blinkPin, blinkState ); } if ( Serial.available()) { data = Serial.read(); Serial1.print((char) data ); } if ( Serial1.available()) { data = Serial1.read(); if ( isalnum( data )) { Serial.print((char) data ); }// else if (( data == 13 ) || ( data == 10 )) else if ( data == 10 ) { Serial.println(); } else { Serial.print( " 0x" ); Serial.print( data, HEX ); Serial.print( "." ); } }}
#include <SoftwareSerial.h>SoftwareSerial vsSerial(2, 3); // Use Arduino pins 2 and three for VS1000 RX, TXvoid setup(){ vsSerial.begin(115200); vsSerial.print("f"); //switch VS1000 to File Play Mode vsSerial.print("C\n"); //cancel anything that the VS1000 might be playing delay(50); }
vsSerial.print("PMUSIC OGG\n"); //play sound file MUSIC.OGG
vsSerial.print("C\n"); //cancel any current playback
vsSerial.print("p51\n"); //play
I can't get reliable 115200 using software serial.
"HardwareSerial - Best performance. Always use this first, if available!".
" The ATmega168 (328) provides UART TTL serial communication, which is available on digital pins 0 (RX) and 1 (TX). The Arduino software includes a serial monitor which allows simple textual data to be sent to and from the Arduino board via a USB connection."
digital pins 0 and 1 go to rx and tx for serial communication. they can't be used if you use the bootloader, but I would assume you could use them if you get rid of the bootloader.
I can't think of a reason why your peripheral UART and the USB-UART would interfere. You probably want to disconnect you UART peripheral during programming, as it may interfere with programming.
I sent data between 2 UNO's using software serial on both. Some characters corrupted. Yes, I tried more than once and did change jumpers. Soldered, it may be okay. 57600 worked solid as rock. End of story.
I used a MEGA to get the VS1000 playing right. | http://forum.arduino.cc/index.php?topic=175353.msg1310332 | CC-MAIN-2017-34 | refinedweb | 351 | 53.68 |
Request life-cycle
Requirement: This guide expects that you have gone through the introductory guides and got a Phoenix application up and running.
The goal of this guide is to talk about Phoenix's request life-cycle. This guide will take a practical approach where we will learn by doing: we will add two new pages to our Phoenix project and comment on how the pieces fit together along the way.
Let's get on with our first new Phoenix page!
Adding a new page
When your browser accesses, it sends a HTTP request to whatever service is running on that address, in this case our Phoenix application. The HTTP request is made of a verb and a path. For example, the following browser requests translate into:
There are other HTTP verbs. For example, submitting a form typically uses the POST verb.
Web applications typically handle requests by mapping each verb/path pair into a specific part of your application. This matching in Phoenix is done by the router. For example, we may map "/articles" to a portion of our application that shows all articles. Therefore, to add a new page, our first task is to add new route.
A new route
The router maps unique HTTP verb/path pairs to controller/action pairs which will handle them. Controllers in Phoenix are simply Elixir modules. Actions are functions that are defined within these controllers.
Phoenix generates a router file for us in new applications at
lib/hello_web/router.ex. This is where we will be working for this section.
The route for our "Welcome to Phoenix!" page from the previous Up And Running Guide looks like this.
get "/", PageController, :index
Let's digest what this route is telling us. Visiting issues an HTTP
GET request to the root path. All requests like this will be handled by the
index function in the
HelloWeb.PageController module defined in
lib/hello_web/controllers/page_controller.ex.
The page we are going to build will simply say "Hello World, from Phoenix!" when we point our browser to.
The first thing we need to do to create that page is define a route for it. Let's open up
lib/hello_web/router.ex in a text editor. For a brand new application, it looks like this:
defmodule HelloWeb.Router do use HelloWeb, :router pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :api do plug :accepts, ["json"] end scope "/", HelloWeb do pipe_through :browser get "/", PageController, :index end # Other scopes may use custom stacks. # scope "/api", HelloWeb do # pipe_through :api # end end
For now, we'll ignore the pipelines and the use of
scope here and just focus on adding a route. We will discuss those in the Routing guide.
Let's add a new route to the router that maps a
GET request for
/hello to the
index action of a soon-to-be-created
HelloWeb.HelloController inside the
scope "/" do block of the router:
scope "/", HelloWeb do pipe_through :browser get "/", PageController, :index get "/hello", HelloController, :index end
A new Controller
Controllers are Elixir modules, and actions are Elixir functions defined in them. The purpose of actions is to gather any data and perform any tasks needed for rendering. Our route specifies that we need a
HelloWeb.HelloController module with an
index/2 action.
To make that happen, let's create a new
lib/hello_web/controllers/hello_controller.ex file, and make it look like the following:
defmodule HelloWeb.HelloController do use HelloWeb, :controller def index(conn, _params) do render(conn, "index.html") end end
We'll save a discussion of
use HelloWeb, :controller for the Controllers Guide. For now, let's focus on the
index/2 action.
All controller actions take two arguments. The first is
conn, a struct which holds a ton of data about the request. The second is
params, which are the request parameters. Here, we are not using
params, and we avoid compiler warnings by adding the leading
_.
The core of this action is
render(conn, "index.html"). It tells Phoenix to render "index.html". The modules responsible for rendering are views. By default, Phoenix views are named after the controller, so Phoenix is expecting a
HelloWeb.HelloView to exist and handle "index.html" for us.
Note: Using an atom as the template name also works
render(conn, :index). In these cases, the template will be chosen based off the Accept headers, e.g.
"index.html"or
"index.json".
A new View
Phoenix views act as the presentation layer. For example, we expect the output of rendering "index.html" to be a complete HTML page. To make our lives easier, we often use templates for creating those HTML pages.
Let's create a new view. Create
lib/hello_web/views/hello_view.ex and make it look like this:
defmodule HelloWeb.HelloView do use HelloWeb, :view end
Now in order to add templates to this view, we simply need to add files to the
lib/hello_web/templates/hello directory. Note the controller name (
HelloController), the view name (
HelloView), and the template directory (
hello) all follow the same naming convention and are named after each other.
A template file has the following structure:
NAME.FORMAT.TEMPLATING_LANGUAGE. In our case, we will create a "index.html.eex" file at "lib/hello_web/templates/hello/index.html.eex". ".eex" stands for
EEx, which is a library for embedding Elixir that ships as part of Elixir itself. Phoenix enhances EEx to include automatic escaping of values. This protects you from security vulnerabilities like Cross-Site-Scripting with no extra work on your part.
Create
lib/hello_web/templates/hello/index.html.eex and make it look like this:
<div class="phx-hero"> <h2>Hello World, from Phoenix!</h2> </div>
Now that we've got the route, controller, view, and template, we should be able to point our browsers at and see our greeting from Phoenix! (In case you stopped the server along the way, the task to restart it is
mix phx.server.)
There are a couple of interesting things to notice about what we just did. We didn't need to stop and re-start the server while we made these changes. Yes, Phoenix has hot code reloading! Also, even though our
index.html.eex file consisted of only a single
div tag, the page we get is a full HTML document. Our index template is rendered into the application layout -
lib/hello_web/templates/layout/app.html.eex. If you open it, you'll see a line that looks like this:
<%= @inner_content %>
which injects our template into the layout before the HTML is sent off to the browser.
A note on hot code reloading: Some editors with their automatic linters may prevent hot code reloading from working. If it's not working for you, please see the discussion in this issue.
From endpoint to views
As we built our first page, we could start to understand how the request life-cycle is put together. Now let's take a more holistic look at it.
All HTTP requests start in our application endpoint. You can find it as a module named
HelloWeb.Endpoint in
lib/hello_web/endpoint.ex. Once you open up the endpoint file, you will see that, similar to the router, the endpoint has many calls to
plug.
Plug is a library and specification for stitching web applications together. It is an essential part of how Phoenix handles requests and we will discuss it in detail in the Plug guide coming next.
For now, it suffices to say that each Plug defines a slice of request processing. In the endpoint you will find a skeleton roughly like this:
defmodule HelloWeb.Endpoint do use Phoenix.Endpoint, otp_app: :demo plug Plug.Static, ... plug Plug.RequestId plug Plug.Telemetry, ... plug Plug.Parsers, ... plug Plug.MethodOverride plug Plug.Head plug Plug.Session, ... plug HelloWeb.Router end
Each of these plugs have a specific responsibility that we will learn later. The last plug is precisely the
HelloWeb.Router module. This allows the endpoint to delegate all further request processing to the router. As we now know, its main responsibility is to map verb/path pairs to controllers. The controller then tells a view to render a template.
At this moment, you may be thinking this can be a lot of steps to simply render a page. However, as our application grows in complexity, we will see that each layer serves a distinct purpose:
endpoint (
Phoenix.Endpoint) - the endpoint contains the common and initial path that all requests go through. If you want something to happen on all requests, it goes to the endpoint
router (
Phoenix.Router) - the router is responsible for dispatching verb/path to controllers. The router also allows us to scope functionality. For example, some pages in your application may require user authentication, others may not
controller (
Phoenix.Controller) - the job of the controller is to retrieve request information, talk to your business domain, and prepare data for the presentation layer
view (
Phoenix.View) - the view handles the structured data from the controller and converts it to a presentation to be shown to users
Let's do a quick recap and how the last three components work together by adding another page.
Another New Page
Let's add just a little complexity to our application. We're going to add a new page that will recognize a piece of the URL, label it as a "messenger" and pass it through the controller into the template so our messenger can say hello.
As we did last time, the first thing we'll do is create a new route.
Another new Route
For this exercise, we're going to re-use the
HelloController we just created and just add a new
show action. We'll add a line just below our last route, like this:
scope "/", HelloWeb do pipe_through :browser get "/", PageController, :index get "/hello", HelloController, :index get "/hello/:messenger", HelloController, :show end
Notice that we use the
:messenger syntax in the path. Phoenix will take whatever value that appears in that position in the URL and convert it into a parameter. For example, if we point the browser at:, the value of "messenger" will be "Frank".
Another new Action
Requests to our new route will be handled by the
HelloWeb.HelloController
show action. We already have the controller at
lib/hello_web/controllers/hello_controller.ex, so all we need to do is edit that file and add a
show action to it. This time, we'll need to extract the messenger from the parameters so that we can pass it (the messenger) to the template. To do that, we add this show function to the controller:
def show(conn, %{"messenger" => messenger}) do render(conn, "show.html", messenger: messenger) end
Within the body of the
show action, we also pass a third argument into the render function, a key/value pair where
:messenger is the key, and the
messenger variable is passed as the value.
If the body of the action needs access to the full map of parameters bound to the params variable in addition to the bound messenger variable, we could define
show/2 like this:
def show(conn, %{"messenger" => messenger} = params) do ... end
It's good to remember that the keys to the
params map will always be strings, and that the equals sign does not represent assignment, but is instead a pattern match assertion.
Another new Template
For the last piece of this puzzle, we'll need a new template. Since it is for the
show action of the
HelloController, it will go into the
lib/hello_web/templates/hello directory and be called
show.html.eex. It will look surprisingly like our
index.html.eex template, except that we will need to display the name of our messenger.
To do that, we'll use the special EEx tags for executing Elixir expressions -
<%= %>. Notice that the initial tag has an equals sign like this:
<%= . That means that any Elixir code that goes between those tags will be executed, and the resulting value will replace the tag. If the equals sign were missing, the code would still be executed, but the value would not appear on the page.
And this is what the template should look like:
<div class="phx-hero"> <h2>Hello World, from <%= @messenger %>!</h2> </div>
Our messenger appears as
@messenger. We call "assigns" the values passed from the controller to views. It is a special bit of metaprogrammed syntax which stands in for
assigns.messenger. The result is much nicer on the eyes and much easier to work with in a template.
We're done. If you point your browser here:, you should see a page that looks like this:
Play around a bit. Whatever you put after
/hello/ will appear on the page as your messenger. | https://hexdocs.pm/phoenix/request_lifecycle.html | CC-MAIN-2020-45 | refinedweb | 2,136 | 65.52 |
Predictive Models: Build once, Run Anywhere
We have released a new version of our open source Python bindings. This new version aims at showing how the BigML API can be used to build predictive models capable of generating predictions locally or remotely. You can get full access to the code at Github and read the full documentation at Read the Docs.
The complete list of updates includes (drum roll, please):
Development Mode
We recently introduced a free sandbox to help developers play with BigML on smaller datasets without being concerned about credits. In the new Python bindings you can use BigML in development mode, and all dataset and models smaller than 1MB can be created for free:
from bigml.api import BigML api = BigML(dev_mode=True)
Remote Sources
You can now create new “remote” sources using URLs. For example, the following snippet would allow you to create a new source using loan funding data from Lending Club.
source = api.create_source("")
The URLs to create remote sources can be http or https with basic realm authentication (e.g.,) or Amazon S3 buckets (e.g., s3://bigml-public/csv/iris.csv) or even Microsoft Azure blobs (e.g., azure://csv/iris.csv?AccountName=bigmlpublic)
Bigger files streamed with Poster
In the first version we were using the fabulous Python request HTTP library to fulfill all the HTTPS communications with BigML. However, we realized that Poster was better suited for streaming large files, mainly due to the fact that it does not need to load the entire file into memory before sending it. Due to the lengthy transmission times, we’ve also added a text progress bar that lets yous see how many bytes have been uploaded so far.
Asynchronous Uploading
Uploading big file might take a while depending on your available bandwidth. We’ve added an
async flag to enable asynchronous creation of new sources.
source = api.create_source("sales2012.csv", async=True)
You can then monitor that source to check the progress. Once the upload is finished the variable will contain the BigML resource.
>>> source {'code': 202, 'resource': None, 'location': None, 'object': {'status': {'progress': 0.48, 'message': 'The upload is in progress', 'code': 6}}, 'error': None}
Local Models
If you import the new
Model class you will be able to create a local version of a BigML model that you can use to make predictions locally, generate an IF-THEN rule version of your model, or even a Python function that implements the model. This is as easy as:
from bigml.api import BigML from bigml.model import Model api = BigML(dev_mode=True) source = api.create_source('') dataset = api.create_dataset(source) model = api.create_model(dataset) model = api.get_model(model) local_model = Model(model)
This code not only will generate a model like the one depicted below in your dashboard at BigML.com but also a local model that would be able to use to generate local predictions or to translate into a set of IF-THEN rules or even into Python code.
Local Predictions
Using local models for predictions has a big advantage: they won’t cost you anything. They are also a good idea for situations where extreme low latency is required, or a network connection is not available. The trade off is that you will lose the ability for BigML to track or improve the performance of your models.
>>>local_model.predict({"petal length": 3, "petal width": 1}) petal length > 2.45 AND petal width <= 1.65 AND petal length <= 4.95 => Iris-versicolor
Rule Generation
Many organizations use rule engines to implement certain business logic. IF-THEN rules are a great way of capturing a white-box predictive model, as they are a human-readable language common to any actor in the organization. That’s a big advantage when you need to share it with, let’s say, the marketing department to adapt their strategies or the CEO to approve it. You can easily get the rules that implement a BigML predictive model as follows:
>>> Generation
Local models can also be used to generate a Python function that implements the predictive model as a sequence of IF statements. For example:
>>> local_model.python() def predict_species(sepal_length=5.77889, sepal_width=3.02044, petal_length=4.34142, petal_width=1.32848): if (petal_length > 2.45): if (petal_width > 1.65): if (petal_length > 5.05): return 'Iris-virginica' if (petal_length <= 5.05): if (sepal_width > 2.9): if (sepal_length > 5.95): if (petal_length > 4.95): return 'Iris-versicolor' if (petal_length <= 4.95): return 'Iris-virginica' if (sepal_length <= 5.95): return 'Iris-versicolor' if (sepal_width <= 2.9): return 'Iris-virginica' if (petal_width <= 1.65): if (petal_length > 4.95): if (sepal_length > 6.05): return 'Iris-virginica' if (sepal_length <= 6.05): if (sepal_width > 2.45): return 'Iris-versicolor' if (sepal_width <= 2.45): return 'Iris-virginica' if (petal_length <= 4.95): return 'Iris-versicolor' if (petal_length <= 2.45): return 'Iris-setosa'
So with this new binding for the BigML API and only a few lines of Python you can upload a big dataset, create a predictive model, and then auto-generate the Python code that will implement the predictive model in your own application. How cool is that? Remember, you can clone the bindings from Github and read the full documentation at Read the Docs.
Trackbacks & Pingbacks | http://blog.bigml.com/2012/08/20/predictive-models-build-once-run-anywhere/ | CC-MAIN-2015-32 | refinedweb | 872 | 66.74 |
I wrote a blog about generating Mac-compatible zip files with SharpZipLib, the conclusion of which was to disable Zip64 compatibility. It was wrong, wrong I tell you.
The better solution is to just set the size of each file you add to the archive. That way you can keep Zip64 compatibility and Mac compatibility.
I owe this solution to the excellent SharpZipLib forum, which covered this problem a while ago, but which I missed when I wrote the earlier blog.
Here’s an updated version of the zip tool in C# that makes Macs happy without annoying anyone else:
using System; using System.IO; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Zip; public class ZipTool { public static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: ziptool <input file> <output file>"); return; } using (ZipOutputStream zipout = new ZipOutputStream(File.Create(args[1]))) { byte[] buffer = new byte[4096]; string filename = args[0]; zipout.SetLevel(9); // Set the size before adding it to the archive, to make your // Mac-loving hippy friends happy. ZipEntry entry = new ZipEntry(Path.GetFileName(filename)); FileInfo info = new FileInfo(filename); entry.DateTime = info.LastWriteTime; entry.Size = info.Length; zipout.PutNextEntry(entry); using (FileStream fs = File.OpenRead(filename)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); zipout.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } zipout.Finish(); zipout.Close(); } } }
Pingback: Reliably Broken » SharpZipLib and Mac OS X | https://buxty.com/b/2011/12/sharpziplib-and-mac-redux/ | CC-MAIN-2019-22 | refinedweb | 232 | 52.66 |
Hi,
How to globlize the form.
Hi,
How to globlize the form.
Ok, before all the Gods here jump on you (someone has already dinged your post's rating, and it wasn't me) ... you need to explain why you would want to make a form global?
There is a rule in C# that is golden and almost always true: If you have to make it global, you probably aren't doing it right.
And take it from someone that came from languages that allowed all the global objects you wanted to create ... as frustrating as it can be to try to figure out how to move data around ... making things global in C# can (and usually will) introduce as many problems as it solves.
That said, you can instance classes before Application.Run() in your Main() ... see program.cs in your solution manager.
Edited 7 Years Ago
by Zinderin: n/a
I Know that some changes have to perform to do so,
Steps:
set forms Localizable property to true.
set Language property to as per we want to globalize the controls in language.
It will create a separate resource file of that particular language.
I have used these steps but not work for me. It display the default language at run time.I dont know waht is going wrong why i cant get the proper output.Is I have to perform the coding on that....
Hi
How do I globlize the windows form in C#.
I have create three resource file in english and second is in other language and write some code on form as bellow
using System.Globalization;
using System.Threading;
[B]On form load[/B]
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("English");
comboBox1.Items.Add("Spanish");
comboBox1.Items.Add("French");
comboBox1.SelectedIndex = 0;
}
[B]On comboBox[/B]
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "English")
{
ChangeLanguage("en");
}
else if (comboBox1.SelectedItem.ToString() == "Spanish")
{
ChangeLanguage("es-ES");
}
else
{
ChangeLanguage("fr-FR");
}
}
private void ChangeLanguage(string lang)
{
foreach (Control c in this.Controls)
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
resources.ApplyResources(c, c.Name, new CultureInfo(lang));
}
}
This code run withpou any error but not displaing any output
Can you help me to solve this problem
Edited 7 Years Ago
by virusisfound: n/a
Curious...
Was there a reason why you had to create another thread instead of simply adding to the one you created before for the same topic?
Just seems like you decided that, since you didn't get the answer you wanted 5 days ago, you were going to re-post the question again rather than adding your new info to the existing thread where it belonged.
As you are using Form1 for the base type of the ComponentResourceManager,
it is looking for resource starting with Form1..
Check that your resource files are named like this Form1.en.resx, Form1.es.resx, and Form1.fr.resx.
Sorry for posting new thread. I don’t remember that I should make the changes in my first post but next time I will remember that think. Thank you for make me correct all time. Lusiphur and daniweb
Thank nick.carne for reply.I tried to get Form1.fr-FR.recx but that form is not accessable in ComponentResourceManager. How to access that form can you tell me. Please ... | https://www.daniweb.com/programming/software-development/threads/302739/globlization | CC-MAIN-2017-51 | refinedweb | 558 | 67.25 |
Once you’ve created strings, it’s often useful to know how long they are. This is where length and capacity operations come into play. We’ll also discuss various ways to convert std::string back into C-style strings, so you can use them with functions that expect strings of type char*.
Length of a string
The length of the string is quite simple — it’s the number of characters in the string. There are two identical functions for determining string length:
Sample code:
string sSource("012345678");
cout << sSource.length() << endl;
Output:
9
Although it’s possible to use length() to determine whether a string has any characters or not, it’s more efficient to use the empty() function:
string sString1("Not Empty");
cout << (sString1.empty() ? "true" : "false") << endl;
string sString2; // empty
cout << (sString2.empty() ? "true" : "false") << endl;
false
true
There is one more size-related function that you will probably never use, but we’ll include it here for completeness:
string sString("MyString");
cout << sString.max_size() << endl;
4294967294
Capacity of a string
The capacity of a string reflects how much memory the string allocated to hold it’s contents. This value is measured in string characters, excluding the NULL terminator. For example, a string with capacity 8 could hold 8 characters.
string sString("01234567");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
Length: 8
Capacity: 15
Note that the capacity is higher than the length of the string! Although our string was length 8, the string actually allocated enough memory for 15 characters! Why was this done?
The important thing to recognize here is that if a user wants to put more characters into a string than the string has capacity for, the string has to be reallocated to a larger capacity. For example, if a string had both length and capacity of 8, then adding any characters to the string would force a reallocation. By making the capacity larger than the actual string, this gives the user some buffer room to expand the string before reallocation needs to be done.
As it turns out, reallocation is bad for several reasons:
First, reallocating a string is comparatively expensive. First, new memory has to be allocated. Then each character in the string has to be copied to the new memory. This can take a long time if the string is big. Finally, the old memory has to be deallocated. If you are doing many reallocations, this process can slow your program down significantly.
Second, whenever a string is reallocated, the contents of the string change to a new memory address. This means all references, pointers, and iterators to the string become invalid!
Note that it’s not always the case that strings will be allocated with capacity greater than length. Consider the following program:
string sString("0123456789abcde");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
This program outputs:
Length: 15
Capacity: 15
(Results may vary depending on compiler).
Let’s add one character to the string and watch the capacity change:
string sString("0123456789abcde");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
// Now add a new character
sString += "f";
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
This produces the result:
Length: 15
Capacity: 15
Length: 16
Capacity: 31;
Length: 8
Capacity: 15
Length: 8
Capacity: 207
Length: 8
Capacity: 207
This example shows two interesting things. First, although we requested a capacity of 200, we actually got a capacity of 207. The capacity is always guaranteed to be at least as large as your request, but may be larger. We then requested the capacity change to fit the string. This request was ignored, as the capacity did not change.
If you know in advance that you’re going to be constructing a large string by doing lots of string operations that will add to the size of the string, you can avoid having the string reallocated multiple times by immediately setting the string to it’s final capacity:
#include <iostream>
#include <string>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;
int main()
{
srand(time(0)); // seed random number generator
string sString; // length 0
sString.reserve(64); // reserve 64 characters
// Fill string up with random lower case characters
for (int nCount=0; nCount < 64; ++nCount)
sString += 'a' + rand() % 26;
cout << sString;
}
The result of this program will change each time, but here’s the output from one execution:
wzpzujwuaokbakgijqdawvzjqlgcipiiuuxhyfkdppxpyycvytvyxwqsbtielxpy
Rather than having to reallocate sString multiple times, we set the capacity once and then fill the string up. This can make a huge difference in performance when constructing large strings via concatenation.
[...] 17.3 — std::string length and capacity [...]
[...] 17.3 std::string length and capacity [...]
[...] capacity() empty() length(), size() max_size() reserve() [...]
Copyright © 2013 Learn C++ - All Rights ReservedPowered by WordPress & the Atahualpa Theme by BytesForAll. Discuss on our WP Forum | http://www.learncpp.com/cpp-tutorial/17-3-stdstring-length-and-capacity/ | CC-MAIN-2013-20 | refinedweb | 815 | 55.13 |
Captcha in forms
Use CAPTCHA on Forms
A CAPTCHA is one of the most common tests used on the Web to tell a human from a computer in interactions such as filling out web forms. The user is supposed type characters from a distorted image that appears on the screen. The input is evaluated and if correct, the user is presumed to be human.
Starting from SP 3 for Version 1.2, C1 CMS has the built-in CAPTCHA functionality, which you can use with web forms rendered by XSLT functions or created on ASP.NET pages.
How to use the C1 CMS CAPTCHA functionality in XSLT functions
Let’s start with the sample XSLT function that implements the C1 CMS CAPTCHA functionality and renders a form on a page.
Following the sample, you will learn the CAPTCHA functions used in the sample in more detail.
Sample XSLT Function
Let’s see the sample of the XSLT function that renders an input web form.
Using this form, the user can submit his/her contact information by filling out the corresponding input fields and the CAPTCHA.
<xsl:stylesheet <xsl:template <html> <head></head> <body> <!-- Captcha --> <xsl:variable <xsl:variable <xsl:variable <xsl:variable <xsl:choose> <xsl:whenSubmitted! <xsl:value-of </xsl:when> <xsl:otherwise> <form method="post"> <br /> Name: <br /> <input type="text" name="txtName" value="{c1:GetFormData('txtName')}" /> <br /> Email: <br /> <input type="text" name="txtEmail" value="{c1:GetFormData('txtEmail')}" /> <br /> Type the characters you see in the picture below: <br /> <img src="{captcha:GetImageUrl($captcha_encryptedValue)}" /> <br /> <input name="captcha" type="hidden" value="{$captcha_encryptedValue}" /> <input type="text" name="txtCaptcha" value="{$captcha_value}" /> <xsl:if<label style="color:Red"> Not valid</label></xsl:if> <br /> <input type="submit" value="Submit" /> </form> </xsl:otherwise> </xsl:choose> </body> </html> </xsl:template> </xsl:stylesheet>
Important: To ensure that the same encrypted value is not used more than once, always use the
RegisterUsage function. It registers the used encrypted value so that the next time a web form tries to commit it, this value will not be accepted (see the sampe code above).
In the above example:
- We have 3 text input elements:
txtName,
txtEmail,
txtCaptcha. The latter gets the user’s CAPTCHA input. We also have 1 hidden input element to hold the encrypted value for our CAPTCHA called captcha.
- The
<img>element is set to the URL returned by
captcha:GetImageUrl.
- The form with these fields and elements is placed within the code block that executes if the form has not been posted back (just loaded) or if the CAPTCHA has not been validated.
- We have two variables for the value of the CAPTCHA cipher used on the form and the value entered by the user for the CAPTCHA:
captcha_encryptedValueand
captcha_value.
- We also have to two status variables that indicate whether the CAPTCHA value has been posted back (
GetFormData('…')) and whether the user’s input has been valid (
IsValid). Based on these two values parts of the XSLT code are executed or not.
- In the block that executes on a postback provided that the user’s input valid for the CAPTCHA, we output a success message and register the CAPTCHA value as used with
RegisterUsage.
- If the user’s input is invalid for the CAPTCHA, the user is informed of that (via the corresponding label element).
Now let’s examine the used functionality a bit closer.
Function Overview
Before using the C1 CMS CAPTCHA, you should first add two required XML namespaces to your XSL file to be able to use required functions:
xmlns:captcha=""
xmlns:c1=""
As its name suggests, the
captcha namespace contains the function necessary to implement CAPTCHA functionality on a web form. The
c1 namespace contains the C1 CMS standard functions, one of which we use in our sample.
Now let’s have an overview of the functions that implement the CAPTCHA functionality on a web form.
C1 CMS CAPTCHA Functions
GetEncryptedValue
This function returns the encrypted value ("CAPTCHA cipher") to be used within the form when getting the CAPTCHA image URL (
GetImageUrl) and validating the user’s input (
IsValid). If its input parameter is an empty string (which is the case when accessed for the first time) or invalid, the function returns a new CAPTCHA cipher; otherwise, the function simply returns the CAPTCHA cipher passed as its input parameter (which is the case on postbacks).
This value is assigned to the hidden CAPTCHA field on the form and initially is empty.
If the encrypted value has not been used within 30 minutes, it becomes invalid - and a new value must be generated.
GetImageUrl
This function returns an URL to a CAPTCHA image to present to the user. It is based on the CAPTCHA cipher (encrypted value) passed as an input parameter.
This image URL is then specified in the
<img> element on the form.
IsValid
This function test the user’s input against the CAPTCHA image for match. It returns true if they match; otherwise, false. The return value is evaluated for selecting the proper course of action – accepting or rejecting the form submission.
RegisterUsage
This function registers ("remembers") the used encrypted value so that the next time a web form tries to commit it, this value will not be accepted. By keeping track of used encrypted values, we ensure that the same encrypted value is not allowed to be used more than once.
C1 CMS Standard Functions
GetFormData
This function gets one of the form’s values sent within an HTTP POST request. The value might be further used as input parameters for CAPTCHA or as field values passed when posting a form.
Adding Fields and Variable
As you can see in the sample above, you should first add a number of fields and other elements to your web form, which must include, amongst others:
- A hidden input control that will hold the CAPTCHA cipher used within the from
- An image element that will present the generated CAPTCHA image
- A text box field element that will get the user’s input for the CAPTCHA image
For better code "readability”, you can define a few XSLT variables:
- A variable that contains a CAPTCHA cipher, obtained by calling the
captcha:GetEnriptedValuefunction
- A variable that contains the value user has filled the CAPTCHA text box with
- A variable that indicates whether the CAPTCHA value has been posted back, obtained by checking whether the CAPTCHA cipher field’s value is empty
- A variable that indicates whether the user’s input for the CAPTCHA image has been valid, obtained by calling the
captcha:IsValidfunction and passing the user’s input and the CAPTCHA cipher in
Putting Things Together
When the user opens the form for the first time:
- It calls the
captcha:GetEncryptedValuefunction by passing the hidden CAPTCHA cipher field value in, initially empty. The function returns the CAPTCHA cipher and initialized the corresponding variable with it.
- As the form has not been posted back yet and the user’s input (no input actually) can’t possibly validate, a new CAPTCHA cipher will be created here.
- Besides, based on the CAPTCHA cipher value, the image URL is returned by the
captcha:GetImageUrland used to present the CAPTCHA image to the user.
When the user fills out the fields as well as supplies the characters from the CAPTCHA image and submits the form:
- The user’s input for the CAPTCHA image is validated by the
captcha:IsValidfunction.
- As the form has been posted, the postback status is set to true.
- The form refreshes and based on the result returned by
captcha:IsValid, one of the following scenarios starts:
- If the user’s input is valid, a "success" message is displayed and the encrypted value is registered as used with
captcha:RegisterUsage
- If the user’s input is invalid, the fields keep their values and a validation error message is displayed at the CAPTCHA input field | http://docs.c1.orckestra.com/Functions/XSLT/Captcha-in-forms | CC-MAIN-2017-17 | refinedweb | 1,311 | 53.95 |
Programming UrhoSharp with F#
- PDF for offline use
-
- Sample Code:
-
Let us know how you feel about this
Translation Quality
0/250
How to create a simple UrhoSharp application using F# in Xamarin Studio
UrhoSharp can be programmed with F# using the same libraries and concepts used by C# programmers. The Using UrhoSharp article gives an overview of the UrhoSharp engine and should be read prior to this article.
Like many libraries that originated in the C++ world, many UrhoSharp functions return booleans or integers indicating success or failure. You should use
|> ignore to ignore these values.
The sample program is a "Hello World" for UrhoSharp from F#.
Creating an empty project
There are no F# templates for UrhoSharp yet available, so to create your own UrhoSharp project you can either start with the sample or follow these steps:
- From Xamarin Studio, create a new Solution. Choose iOS > App > Single View App and select F# as the implementation language.
- Delete the Main.storyboard file. Open the Info.plist file and in the iPhone / iPod Deployment Info pane, delete the
Mainstring in the Main Interface dropdown.
- Delete the ViewController.fs file as well.
Building Hello World in Urho
You are now ready to begin defining your game's classes. At a minimum, you will need to define a subclass of
Urho.Application and override its
Start method. To create this file, right-click on your F# project, choose Add new file... and add an empty F# class to your project. The new file will be added to the end of the list of files in your project, but you must drag it so that it appears before it is used in AppDelegate.fs.
- Add a reference to the Urho NuGet package.
- From an existing Urho project, copy the (large) directories CoreData/ and Data/ into your project's Resources/ directory. In your F# project, right-click on the Resources folder and use Add / Add Existing Folder to add all of these files to your project.
Your project structure should now look like:
Define your newly-created class as a subtype of
Urho.Application and override its
Start method:
namespace HelloWorldUrho1 open Urho open Urho.Gui open Urho.iOS type HelloWorld(o : ApplicationOptions) = inherit Urho.Application(o) override this.Start() = let cache = this.ResourceCache let helloText = new Text() helloText.Value <- "Hello World from Urho3D, Mono, and F#" helloText.HorizontalAlignment <- HorizontalAlignment.Center helloText.VerticalAlignment <- VerticalAlignment.Center helloText.SetColor (new Color(0.f, 1.f, 0.f)) let f = cache.GetFont("Fonts/Anonymous Pro.ttf") helloText.SetFont(f, 30) |> ignore this.UI.Root.AddChild(helloText)
The code is very straightforward. It uses the
Urho.Gui.Text class to display a center-aligned string with a certain font and color size.
Before this code can run, though, UrhoSharp must be initialized.
Open the AppDelegate.fs file and modify the
FinishedLaunching method as follows:
namespace HelloWorldUrho1 open System open UIKit open Foundation open Urho open Urho.iOS [<Register ("AppDelegate")>] type AppDelegate () = inherit UIApplicationDelegate () override this.FinishedLaunching (app, options) = let o = ApplicationOptions.Default let g = new HelloWorld(o) g.Run() |> ignore true
The
ApplicationOptions.Default provides the default options for a landscape-mode application. Pass these
ApplicationOptions to the default constructor for your
Application subclass (note that when you defined the
HelloWorld class, the line
inherit Application(o) calls the base-class constructor).
The
Run method of your
Application initiates the program. It is defined as returning an
int, which can be piped to
ignore.
The resulting program should look like:
>>IMAGE. | https://developer.xamarin.com/guides/cross-platform/urho/fsharp-and-urhosharp/ | CC-MAIN-2017-30 | refinedweb | 584 | 60.01 |
C++ else..if ladderPritesh
In the previous chapters we have seen different tutorials on if statement and if-else statement.
When we need to list multiple else if…else statement blocks. We can check the various conditions using the following syntax –
Syntax : C++ Else if ladder
if(boolean_expression 1) { // When expression 1 is true } else if( boolean_expression 2) { // When expression 2 is true } else if( boolean_expression 3) { // When expression 3 is true } else { // When none of expression is true }
When the first Boolean condition becomes true then first block gets executed.
When first condition becomes false then second block is checked against the condition. If second condition becomes true then second block gets executed.
Example : Else if ladder
#include <iostream> using namespace std; int main () { // declare local variable int marks = 55; // check the boolean condition if( marks >= 80 ) { // if 1st condition is true cout << "U are 1st class !!" << endl; } else if( marks >= 60 && marks < 80) { // if 2nd condition is false cout << "U are 2nd class !!" << endl; } else if( marks >= 40 && marks < 60) { // if 3rd condition is false cout << "U are 3rd class !!" << endl; } else { // none of condition is true cout << "U are fail !!" << endl; } return 0; }
Output :
U are 3rd class !!
Explanation :
- Firstly condition 1 specified in the if statement is checked. In this case the condition becomes false so it will check the 2nd condition in the else if block.
- Now 2nd block condition also evaluates to be false then again the 2nd block will be skipped and 3rd block condition is checked.
- In the above example the condition specified in the 3rd block evaluates to be true so the third block gets executed.
Flowchart diagram :
Some rules of using else if ladder in C++ :
Keep some important things in mind –
- if block can have zero or one else block and it must come after else-if blocks.
- if block can have zero to many else-if blocks and they must come before the else.
- After the execution of any else-if block none of the remaining else-if block condition is checked. | http://www.c4learn.com/cplusplus/cpp-else-if-ladder/ | CC-MAIN-2019-39 | refinedweb | 344 | 68.3 |
> AVChat1.rar > UNetwork.cpp
// // UNetwork.cpp // /*-----------------------------------------------------*\ HQ Tech, Make Technology Easy! More information, please go to. /*-----------------------------------------------------*/ #include "stdafx.h" #include "UNetwork.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// BOOL UNetwork::GetHostInfo(char * outIP, char * outName) { char name[300]; if (gethostname(name, 300) == 0) { if (outName) { strcpy(outName, name); } PHOSTENT hostinfo; if ((hostinfo = gethostbyname(name)) != NULL) { LPCSTR pIP = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list); strcpy(outIP, pIP); return TRUE; } } return FALSE; } void UNetwork::DumpSocketError(void) { switch (WSAGetLastError()) { case WSANOTINITIALISED: TRACE("A successful WSAStartup call must occur before using this function. "); break; case WSAENETDOWN: TRACE("The network subsystem has failed. "); break; case WSAEACCES: TRACE("The requested address is a broadcast address, but the appropriate flag was not set. Call setsockopt with the SO_BROADCAST parameter to allow the use of the broadcast address. "); break; case WSAEINVAL: TRACE("An unknown flag was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled. "); break; case WSAEINTR: TRACE("A blocking Windows Sockets 1.1 call was canceled through WSACancelBlockingCall. "); break; case WSAEINPROGRESS: TRACE("A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. "); break; case WSAEFAULT: TRACE("The buf or to parameters are not part of the user address space, or the tolen parameter is too small. "); break; case WSAENETRESET: TRACE("The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. "); break; case WSAENOBUFS: TRACE("No buffer space is available. "); break; case WSAENOTCONN: TRACE("The socket is not connected (connection-oriented sockets only). "); break; case WSAENOTSOCK: TRACE("The descriptor is not a socket. "); break; case WSAEOPNOTSUPP: TRACE("MSG_OOB was specified, but the socket is not stream-style such as type SOCK_STREAM, OOB data is not supported in the communication domain associated with this socket, or the socket is unidirectional and supports only receive operations. "); break; case WSAESHUTDOWN: TRACE("The socket has been shut down; it is not possible to sendto on a socket after shutdown has been invoked with how set to SD_SEND or SD_BOTH. "); break; case WSAEWOULDBLOCK: TRACE("The socket is marked as nonblocking and the requested operation would block. "); break; case WSAEMSGSIZE: TRACE("The socket is message oriented, and the message is larger than the maximum supported by the underlying transport. "); break; case WSAEHOSTUNREACH: TRACE("The remote host cannot be reached from this host at this time. "); break; case WSAECONNABORTED: TRACE("The virtual circuit was terminated due to a time-out or other failure. The application should close the socket as it is no longer usable. "); break; case WSAECONNRESET: TRACE( usable. "); break; case WSAEADDRNOTAVAIL: TRACE("The remote address is not a valid address, for example, ADDR_ANY. "); break; case WSAEAFNOSUPPORT: TRACE("Addresses in the specified family cannot be used with this socket. "); break; case WSAEDESTADDRREQ: TRACE("A destination address is required. "); break; case WSAENETUNREACH: TRACE("The network cannot be reached from this host at this time. "); break; case WSAETIMEDOUT: TRACE("The connection has been dropped, because of a network failure or because the system on the other end went down without notice. "); break; default: TRACE("Unknown socket error. "); break; } } | http://read.pudn.com/downloads46/sourcecode/windows/directx/153807/AVChat/Network/UNetwork.cpp__.htm | crawl-002 | refinedweb | 519 | 56.45 |
Table of Contents
About
go-try is a package that allows you to use
try/catch block in Go.
This project is still in its early stages, so any thoughts and feedback are very
Why
go-try?
Many Go developers get tired of dealing with errors because there are too many
errors to handle one by one, which is intuitive and effective, but really
annoying.
I’ve been trying to find out if Go has an error handling method like
try/catch, I think that would probably be a lot easier, but unfortunately, I
couldn’t find any package that’s easy to use.
So I tried to make one myself, taking inspiration from the
try/catch syntax,
then
go-try was born!
Getting Started
Installation
go get github.com/ez4o/go-try
Usage
Try(func () { ... ThrowOnError(ce) ... ThrowOnError(err) ... }).Catch(func (ce CustomError) { ... }).Catch(func (e error, st *StackTrace) { ... st.Print() })
Functions
Example
Let’s say you want to fetch JSON from a url and unmarshal it, you can simply
write it like this:
import ( "encoding/json" "fmt" "io/ioutil" "net/http" . "github.com/ez4o/go-try" ) func main() { Try(func() { resp, err := http.Get("") ThrowOnError(err) defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) ThrowOnError(err) var data []map[string]interface{} err = json.Unmarshal(b, &data) ThrowOnError(err) fmt.Println(data) }).Catch(func(e error, st *StackTrace) { fmt.Println(e) st.Print() }) }
For more examples, head over to!
Roadmap
- Implement catching errors of different types.
- Tests
- CI
See the open issues for a full list of
proposed features (and known issues).
Contributing feat/amazing-feature)
- Commit your Changes with
Conventional Commits
- Push to the Branch (
git push origin feat/amazing-feature)
- Open a Pull Request
License
Distributed under the MIT License. See
LICENSE for more
information.
Author
- HSING-HAN, WU (Xyphuz)
- Mail me: [email protected]
- About me:
- GitHub: | https://golangexample.com/a-package-that-allows-you-to-use-try-catch-block-in-go/ | CC-MAIN-2022-05 | refinedweb | 312 | 59.5 |
7973/hyperledger-fabric-no-go-in-path-error
Hi. I'm new to Hyperledger and following this tutorial:
When I run the make native command,
I recived following error:
Makefile:71: *** "No go in PATH: Check dependencies". Arresto.
What should I do to solve this error?
The error is because the go path is not set.
To solve this error, you can do the following
1. Find where you have installed go lang.
whereis go
2. Export using the following command:
export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin
3. Add GOROOT/bin to your PATH
This should solve the error.
The solution to this problem is as ...READ MORE
My docker version was 1.7. And its ...READ MORE
For chaincode to properly run on your ...READ MORE
Hyperledger uses a timeout mechanism for chaincode ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
Do this:
$go get -u github.com/golang/protobuf/protoc-gen-go
$ cp $GOPATH/bin/protoc-gen-go build/docker/gotools/bin/
Now ...READ MORE
Try defining or referencing the application in ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/7973/hyperledger-fabric-no-go-in-path-error?show=7977 | CC-MAIN-2020-24 | refinedweb | 214 | 62.34 |
Content-type: text/html
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
int res_mkquery (
int query_type,
char *domain_name,
int class,
int type,
char *data,
int data_length,
struct rrec *reserved,
char *buffer,
int buf_length );
The res_mkquery() function makes packets for name servers in the Internet domain. The res_mkquery() function makes a standard query message and places it in the location pointed to by the buffer parameter.
The res_mkquery() function is one of a set of subroutines that form the resolver, a set of functions that resolve domain names. Global information that is used by the resolver functions is kept in the _res data structure. The /include/resolv.h file contains the _res data structure definition.
Upon successful completion, the res_mkquery() function returns the size of the query. If the query is larger than the value of the buf_length parameter, the function fails and returns a value of -1.
Functions: dn_comp(3), dn_expand(3), dn_find(3), dn_skipname(3), _getlong(3), _getshort(3), putlong(3), putshort(3), res_init(3), res_send(3) delim off | http://backdrift.org/man/tru64/man3/res_mkquery.3.html | CC-MAIN-2017-04 | refinedweb | 173 | 57.27 |
I have a new compiler along my Dev C++ it is called Mircrosoft Visual Beta 2005. It looks sl much more professional too!!
Anyway, This is my first working program, but when I debugged and ran it, it worked ok, but I got a unfamiluar warning up it said:
" 'getch' was declared deprecated :: see declaration of 'getch'
I do not understand what the warning is saying, as I delcared getch as part of conio.h
I use getch so I do not have to use system("pause");
here is the code:
Code:
#include "stdafx.h" // this header is for ALL USE
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
string myname;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "What is your name?" << endl;
cout << "\n\n";
cout << "My name is ";
cin >> myname;
cout << "So your name is " << myname;
cout << "\n\n";
getch();
return 0;
} | http://cboard.cprogramming.com/cplusplus-programming/67062-simple-error-%3D-difficult-problem-printable-thread.html | CC-MAIN-2014-35 | refinedweb | 146 | 76.66 |
I implemented a code that takes input file from command line. Then, sorts this input. Then write output to current directory. My code works but I am wondering that type of file.
My input.txt type is dos\Windows as seen in the picture.
My generated output.txt type is UNIX. Also their sizes are different. Why are they stored in different format? I used, bufferedReader, fileWriter to implement this code.
code.java:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.FileWriter;
public class code{
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(args[0])))
{
int lines = 0;
while (br.readLine() != null) lines++; // to get text's number of lines
String sCurrentLine;
BufferedReader br2 = new BufferedReader(new FileReader(args[0])); //to read and sort the text
String[] array; //create a new array
array = new String[lines];
int i=0;
while ((sCurrentLine = br2.readLine()) != null) {//fill array with text content
array[i] = sCurrentLine;
i++;
}
Arrays.sort(array); //sort array
FileWriter fw = new FileWriter("output.txt");
for (i = 0; i < array.length; i++) { //write content of the array to file
fw.write(array[i] + "\n");
}
fw.close();
System.out.println("Process is finished.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
x a t f a s f g h j n v x z s d f g b s c d e d d
a a b c d d d d e f f f g g h j n s s s t v x x z
The phenomenon you are experiencing is a difference in end-of-line characters between UN*X systems and Microsoft Windows systems. These systems prefer to use different sequences of characters to signal a end of line.
\n, 0x0A in ASCII)
\r\n, 0x0D and 0x0A in ASCII)
You state that you want to use the Windows variant. In that case, you should not be appending
"\n" to every line in the new file. The naive approach would be to use
"\r\n\", but there is a better way:
Java provides you with the ability to get your current platform's preferred end-of-line character sequence. You can get your platform's end-of-line character sequence by calling
System.getProperty("line.separator") (< Java 7) or
System.lineSeparator() (≥ Java 7).
So, to sum this up, you should change the following line:
fw.write(array[i] + "\n");
to
fw.write(array[i] + System.lineSeparator()); | https://codedump.io/share/Nm1OAfAoOlDB/1/file-type-in-java-windowsunix | CC-MAIN-2017-13 | refinedweb | 415 | 69.38 |
#include <db_cxx.h> int DbTxn::prepare(u_int8_t gid[DB_GID_SIZE]);
The
DbTxTx.
All open cursors in the transaction are closed and the first cursor close error will be returned.
The
DbTxn::prepare()
method either returns a non-zero error value or throws an
exception that encapsulates a non-zero error value on
failure, and returns 0 on success.
The errors that this method returns include the error values of
Dbc::close() and the following:.
The gid parameter specifies the global transaction ID by which this transaction will be known. This global transaction ID will be returned in calls to DbEnv::txn_recover() telling the application which global transactions must be resolved. | http://idlebox.net/2011/apidocs/db-5.2.28.zip/api_reference/CXX/txnprepare.html | CC-MAIN-2014-10 | refinedweb | 109 | 54.52 |
COMMENTARY
INTERVIEW
SPECIALS
CHAT
ARCHIVES
The Indian rupee slid by Re 0.45 to
close at Rs 39.45-50 as against yesterday's close of
Rs 38.99-39.01 on hectic demand from corporate sectors and
banks and the absence of the Reserve Bank of India in the interbank
foreign exchange market in Bombay today.
Outside, the rupee quoted at previous closing level. Due to heavy
demand from institutions and banks on behalf of their client to pay
import remittances, the rupee breached the Rs 39.40 barrier during intraday
trading and was quoted at Rs 39.48-52.
Dealers said that for most of the day the rupee quoted in the range of Rs 39.40-50.
The currency moved in a single direction as import covering
continued till the fag end of the day. Exporters have
already covered their position but were still hoping for higher
prices, a dealer added.
The apex bank remained away from the market. The State
Bank of India was doing transactions both ways. During
the day, SBI started making profits at higher prices, which
reflected in the market and the rupee came down to Rs 39.39-42.
In the last phase of trading, the SBI started buying dollars which
pushed it up to Rs 38.45-50.
In the overseas market, the US dollar weakened against the
yen and other currencies were more or less the same, dealers
said.
The annualised premium shot by 10.20 per cent in a single
trading day following heavy paying pressure. The month of
January and March will witness higher paying pressure.
The forward premium quoted higher, the cash to spot dollar
traded at 2.25 to 2.50 paise premium, spot to December
was quoted at 19.00--20.00 paise premium and spot to September
traded at 274.00--284.00 paise premium.
Meanwhile, the RBI fixed the reference
rate at Rs 39.42 as against Rs 39.05 on the last working day.
UNI | http://inhome.rediff.com/money/dec/11forex.htm | crawl-003 | refinedweb | 333 | 76.42 |
The WinFS Files: Divide et Impera
Sean Grimaldi
Microsoft Corporation
December 2005
Summary: WinFS enables developers to think about data as data, not as specific data formats. Sean Grimaldi explores the implications of being able to unify your data.
Divide and conquer, or unify?
I wasn't immediately sure how to approach this column, because it deals with an abstract architectural problem. The problem is that data is not unified, which denies programmers and end users the ability to use most of their data the way they can use data in a database.
Often, you can solve a difficult problem by dividing it into two or more simpler problems. You then solve the sub-problems and combine the solution to solve the original problem. For example, merge sort is an old sorting algorithm, and like binary search it uses a divide-and-conquer approach. The merge sort algorithm splits a list into halves. You sort each half and then combine them. The result is a sorted list. This approach generally takes less time than sorting the list all at once, depending on how you implement it and the data you sort.
Divide and conquer is such a natural way of problem solving that I suspect most people seldom reflect on it. For me, the difficulty with this approach seems to be in finding a way to divide the problem orthogonally, rather than with the general approach.
Data has been divided.
It seems this divide-and-conquer approach is what we've done with data. Data is a rich concept. By data, I mean numbers, characters, and other artifacts, like images, on which programs operate. Note that this definition of data encompasses the data in file system files as well as the data in relational databases.
A huge amount of data is stored in files. The computer I am writing on has 608,903 files on it, including vacation photos, C# files, Excel workbooks, and many file types for which I don't even recognize the extension.
I also have some SQL Server database files, like Northwnd.mdf. A lot of data is stored in these database files, but by database standards the largest database on this computer is tiny: less than 1 GB.
There are other ways to store data, but the bulk of the data I am interested in manipulating programmatically is either in files or in databases.
Divided data is bad.
Although dividing data into these many formats, each with different expectations and behaviors, has enabled programs and end users to manipulate data, diving data also has negative effects.
One negative effect is the amazing variety of data types and data formats. I like to think of this as the full name problem. The concept of a person is simple. Babies can distinguish between people and non-people shortly after birth. People have names. These concepts are about as simple and fundamental as it gets, and yet there are literally thousands of formats to express person and name in data structures. For example, you can define full name as first name plus surname with an optional middle initial. Some programs use this data structure, but others do not. In many cases, full name is a single string property unrelated to any first name or surname property. Sometimes a person can have multiple full names. For example, my friend has a given name and a nickname he uses with the surname under which he operates his business. Both identifiers refer to the same person in different contexts. Can't we just agree that people have a first name and a surname and that some people have nicknames and zero or more middle names? Do we really need hundreds of ways of representing a person's name as a data structure? There is a cost to redefining the full name concept so many times.
Querying is another problem with diverse data structures. Because a lot of data is stored in files and a lot of data is stored in databases, to query your data you often need a query engine that can return results for data stored as a file or in the database. But this is not a common feature. So, without WinFS, you often have to query and merge the result sets from the file system, databases, and other data stores. This in itself can be a tough programming task. Consider one example of how this affects me. I use Word as my e-mail editor and Outlook as my e-mail client, so sometimes I forget whether I wrote something directly in Word or indirectly through Word in an e-mail. If I used Word, it is probably in a file, but if I used Outlook it is stored in the Exchange server database. This matters, because Exchange and Outlook and the Search Companion toolbar do not search the same things and do not support the same query capabilities.
Even if you can query across physical data stores, it is unfeasible to write meaningful queries without understanding the semantics of each data structure. You need to know how to write a query for a name that can be null, and you need to understand what it means to retrieve a person's name that has a null value. Otherwise, you don't understand the data returned from the query.
A necessary condition for rich query capabilities is that the data must have some semantically equivalent attributes. For example, if a person does not have a name, birth date, gender, mother, location, or other attributes, it becomes very difficult to write a meaningful query for persons. Usually the data needs to be evaluated and, if feasible, transformed and mapped to enable programmers to identify and manipulate equivalent attributes.
There is a cost in transforming among this huge variety of data structures. In perhaps the simplest scenario, it takes some code to transform a full name property to a string and some more code to transform a string to a full name property. In some cases, even this simple transform is impossible without data loss. For example, if full name is a collection of full name structs, there is no way to convert them to a string full name without the possible loss of some of the items in the collection. Full name might be in one table and the person it applies to in another table, so you have to join to get the one or more full names for a given person. For each format, this bridging code has to be specified, coded, tested, and documented, and sometimes it comes out wrong—for example, when the specification did not anticipate that a person does not have a middle name. Between data loss and a high cost of bridging, the variety of data structures is a real problem.
Perhaps the largest cost, though, is in rewriting behaviors for each data structure. Consider the save concept, for example. The concept is straightforward: You want to persist some data to disk for possible use later. The data could be an object, a file, or a database row—all data. For example:
In each of these cases, the code for the save operation is different code.
Even if you want to represent full name in a common way across these different data manifestations, you still have to write code for the save operation in different ways. Word is an example of an application in which the same data in the same application can be saved in multiple formats. In Word, you can save a document as .doc, .xml, .html, .txt, etc. This affects end users, because save means something different to most applications; but it particularly affects developers. Because data is divided into so many manifestations, you have to specify, code, test, and document the save operation multiple times. This is expensive even under the best-case scenario that the applications that perform this save operation all agree on what a full name looks like. Usually they don't, even at the same company.
So let's review. So far, I've said that data is divided and that there are some negatives to this situation. The data is divided into file, database, and other data. The negatives are that programmers have to recreate data types, bridge between data types, and rewrite behaviors repeatedly. If this seems normal to you, it may be because you have operated in this fractured data environment for years and have come to expect nothing more.
WinFS unifies data, solving the problem of divided data.
Until I started working on the WinFS team, I had forgotten the splendor that is data—data that you can search, save, update, share, synchronize, respond to notifications on, treat as, well, data. Some people call this unified data, and it might seem abstract.
Once you begin treating data as data, and not as these various formats, you can do some interesting things. For example, you can think about information in new ways. You could write code that shows a picture of a person, his role, and his contact information for everyone attending a given meeting and every document that they contributed to that you have not already read, and on a personal note, if they have already given you some money for the charity bicycle race you are participating in next month. Today, I have all this data available to my computer, but no feasible way to query it without WinFS. I plainly can't get at a lot of my data.
How WinFS solves this problem:
WinFS resolves this issue by defining common item types. For example, think about never having to recreate a data type for common concepts such as audio record, meeting, contact, person, document, photo, message, video clip, etc.
The following are the WinFS namespaces in which these common entity types reside:
- System.Storage.Audio
- System.Storage.Calendar
- System.Storage.Contacts
- System.Storage.Documents
- System.Storage.Image
- System.Storage.Media
- System.Storage.Messages
- System.Storage.Video
A person is a person is a person, no matter where it comes from with WinFS. Think of all the time you have spent coming up with various objects to represent a person. I can recall defining about 10 variations of person as I moved from one team to another. In almost all of these cases, the person type varied in trivial ways. WinFS does not require one schema to rule them all, however. You can choose to extend the WinFS types to suit your goals using either subclassing or an extension mechanism. Let me know if you are interested in an article about extending WinFS types.
Once you have a definition for item types, like person, you don't need to write so much code to bridge between types. For example, if your application and my application both use the WinFS person type, no transformation is necessary. Even if I extend the WinFS person type, we may be able to share the data without transforming it. For example, if I write an extension to the person type that adds a property for their medical insurance member ID, and your application is a greeting card application, I can pass a person between our applications with just a cast to person.
By far the biggest advantage is common behaviors. Think about this in relation to the save operation. You can save a person instance with a line of code, as in the following snippet:
C#
The save operation is a part of the WinFS API, so you don't need to rewrite it. It applies to all common entity types.
C#
It doesn't matter if this is a special sort of document, such as one I derive from Document; the pattern is the same. Here I derive a Gift type of document from the Document type.
Figure 1. Deriving a Gift type from the Document type.
The usage pattern is the same as it is for Person and Document, because they are all data.
C#
Actually, I want to do all the typical things one does with data, such as create, retrieve, update, delete, save, share, synchronize, copy, move, restrict access, respond to notifications, etc. Well, with WinFS you get these common behaviors by using the WinFS API.
Unifying data has big payback to programmers!
Because applications can build on WinFS-defined data types, applications can share data—assuming the correct permissions. This is good for you as a programmer, as well as for the end user of your application.
As a programmer, you can reuse data the end user already has in the WinFS store. For example, assume your application presents advertisements to a user of events they could attend, like a bike race or a rodeo.
Before presenting an event to the user, your application can check the user's calendar and display the event differently if the user already has a meeting scheduled that would conflict with the event, such as making the border of the invitation red.
You can also populate data into the WinFS store to be used by other programs. For example, if the end user accepts the invitation to the bicycle race, their personal information manager (PIM) application, such as their e-mail client, could show that date as reserved in their calendar. This also gives the end user a rich user experience in both applications.
Programmers are tired of recreating the same types, like full name, and users are tired of populating the data into each variation of full name. For example, the Human Resources enterprise resource planning (ERP) software at work tracks my emergency contact, but I have to enter this into the eCommerce site I use when I register for events, like a bicycle race. In addition, I had to enter the same information again as my financial beneficiary field at my stock trading site. This is a pain point for end users, and often when you are designing an application, you request less information than you would like so that your application does not burden the user with data input. This comes up all the time with registration forms, which often end up with an address of "asdf".
As a developer, from a data mining point of view, it is annoying when the user types slightly different names and there is no way to know if these refer to the same person or not.
Once you stop thinking of data as all these formats, and just think of it as data, you begin to have higher expectations of it. With WinFS you can just think of this as data, and manipulate it as you would with any data, such as putting it on a USB drive to take with you.
Complex software generally has many settings. Windows, for example, enables you to view a folder's contents in several ways, such as thumbnails, tiles, icons, lists, or detail views. You can select the view you prefer and this setting is persisted from one session to the next. With WinFS, organization can be persisted from one application to the next. For example, if I store person objects in WinFS representing my family members and college friends, an e-mail application should be able to present information from my family members differently than information from my college friends. I would prefer that if I synchronize data, the e-mail from my family members is prioritized higher than e-mail from my college friends, so that if disk space is limited the family e-mail gets synchronized first.
Common behaviors enable new scenarios. One that occurs to me is a cached mode. Outlook has a cached mode where you don't need to be connected to the network to work with e-mail. Many network-based applications, like eCommerce sites, don't have this facility. When I travel, I'd like to shop at an eCommerce site without a network connection. If these eCommerce sites stored data in WinFS, it would be simple to write a local cache manager application that synchronized the results to the eCommerce site when the network connection was restored. This is because the WinFS API includes sync functionality. There is also a performance aspect of caching. Caching data locally enables the great hardware available in PCs, such as multi-core processors, to manipulate the data rather than performing the crunching on a remote server. For example, when you perform a complex group-by operation or large sort, doing this locally can be significantly more responsive than performing the manipulation on a remote server and then moving the sorted data locally.
Once you store data in WinFS and work with WinFS types, you don't have to rewrite code for each type of data.
Right now, most data is owned by the application, not the user. Once data is freed from the format, the user can get at a lot more data. Users need richer ways to organize, manage, share, synchronize, and generally work with their data. WinFS provides these facilities as well. The next column in this series will cover various ways of organizing data with WinFS. Stay tuned as the WinFS adventure continues!
Summary
This article covers the idea of unifying data. It describes how data is not unified today and some of the issues with this. Although a few aspects of WinFS are undocumented, you can read more about it here:
- Newsgroup:
The WinFS Files:
Sean Grimaldi is currently most interested in data access, WinFS, and racing cyclocross. Sean has worked on WinFS since 2002. You can reach Sean at sgrimald@microsoft.com. | http://msdn.microsoft.com/en-us/library/aa480690.aspx | CC-MAIN-2013-48 | refinedweb | 2,938 | 61.36 |
Is it possible to fold a block just from placing your cursor over it and hitting a hotkey? (is there a command yet for that?)
Currently I can only do that by clicking on the icon:
Go to Edit > Code Folding. It will list all the coding options and keyboard shortcuts.
I just tried those, but it won't work unless I select code.
What I want is to actually just fold whatever block the cursor is on.
From the command on the toolbar it still won't work..Help please?
I guess I'll make a plugin for you...
The key bindings listed in the Edit / Code Folding menu will fold the block the caret is on if no text is selected, or if there's a selection, they'll fold the selected text.
I can get the second option to work ( select text + folding command )
But the first one is not working, at least not as expected.
I think this is a bug.
I have the following code:
.pagination {
@include pagination;
}
I'm expecting that placing the cursor anywhere near those 3 lines and doing fold, will actually fold that given block. However it won't work if I place the cursor anywhere on the first or third line, it'll only work on the second line.
I'm also trying to make the fold / unfold hotkeys work with one single key with a plugin sublimator wrote for me, but it seems it won't work the same way:
import sublime_plugin
[code]class ToggleFold(sublime_plugin.TextCommand): '{"keys": "f1"], "command": "toggle_fold"}' def run(self, edit): view = self.view
if any(not view.fold(sel) for sel in view.sel()):
map(view.unfold, view.sel())[/code] | https://forum.sublimetext.com/t/folding-via-hotkey-rather-than-clicking/3195/4 | CC-MAIN-2016-18 | refinedweb | 286 | 73.58 |
Difference between revisions of "Gitlab"
Revision as of 11:45, 8 ...
Database backend
A Database backend will be required before Gitlab can be run. Currently GitLab supports MariaDB and PostgreSQL. By default, GitLab assumes you will use MySQL. Extra work is needed if you plan to use PostgreSQL.
your_username_hereand
MariaDB
To set up MySQL (MariaDB) you need to create a database called
gitlabhq_production along with a user who has full priviledges to the database. You might do it via command line as in the following example.
mysql -u root -p
mysql> CREATE DATABASE IF NOT EXISTS `gitlabhq_production`; mysql> CREATE USER 'your_username_here'@'localhost' IDENTIFIED BY 'your_password_here'; mysql> GRANT SELECT, LOCK TABLES, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON `gitlabhq_production`.* TO 'your_username_here'@'localhost'; mysql> \q
Now try connecting to the new database with the new user to verify you did it correctly:
mysql -u your_username_here -p -D gitlabhq_production
Next you'll need to open up
/etc/webapps/gitlab/database.yml and set
username: and
password: for the
gitlabhq_production database to
your_username_here and
your_password_here, respectively. You need not worry about the info for the
gitlabhq_here create the
gitlabhq_production database with along with it's user. Remember to change
your_username_here and
psql -d template1
template1=# CREATE USER your_username_here WITH PASSWORD 'your_password_here'; up the new
/etc/webapps/gitlab/database.yml and set the values for
username: and
password:. For example:
Snippet from the new 're doing), you don't need to worry about configuring the other databases listed in
/etc/webapps/gitlab/database.yml. We only need to set up the production database to get GitLab working.
Finally, open up
/usr/lib/systemd/system/gitlab.target change all instances of
mysql.service to
postgresql.service. For example:
Snippet from /usr/lib/systemd/system/gitlab.target
... [Unit] Description=GitLab - Self Hosted Git Management Requires=redis.service postgresql.service After=redis.service postgresql.service syslog.target network.target [Install] WantedBy=multi-user.target
Initialize Gitlab database
Finally, initialize the sudo -u gitlab bundle exec rake gitlab:env:info RAILS_ENV=production
fatal: Not a git repository (or any of the parent directories): .git's systemd to manage server start during boot (which GitLab does not recognize).
Example output of sudo -u gitlab bundle exec rake gitlab:check RAILS_ENV=production
fatal: Not a git repository (or any of the parent directories): .git Checking Environment ... Git configured for gitlab user? ... yes Has python2? ... yes python2 is supported version? ... yes Checking Environment ... Finished Checking GitLab Shell ... GitLab Shell version >= 1.7.9 ? ... OK (1.8.0) Repo base directory exists? ... yes Repo base directory is a symlink? ... no Repo base owned by gitlab:gitlab? ... yes Repo base access is drwxrws---? ... yes update hook up-to-date? ... yes update hooks in repos are links: ... can't check, you have no projects Running /srv/gitlab/gitlab-shell/bin/check Check GitLab API access: OK Check directories and files: /srv/gitlab/repositories: OK /srv/gitlab/.ssh/authorized_keys: OK Test redis-cli executable: redis-cli 2.8.4 Send ping to redis server: PONG gitlab-shell self-check successful Checking GitLab Shell ... Finished Checking Sidekiq ... Running? ... yes Number of Sidekiq processes ... 1 Checking Sidekiq ... Finished Checking LDAP ... LDAP is disabled in config/gitlab.yml Checking LDAP ... Finished Checking GitLab ... Database config exists? ... yes Database is SQLite ... no All migrations up? ... fatal: Not a git repository (or any of the parent directories): .git yes GitLab config exists? ... yes GitLab config outdated? ... no Log directory writable? ... yes Tmp directory writable? ... yes Init script exists? ... no Try fixing it: Install the init script For more information see: doc/install/installation.md in section "Install Init Script" Please fix the error above and rerun the checks. Init script up-to-date? ... can't check because of previous errors projects have namespace: ... can't check, you have no projects Projects have satellites? ... can't check, you have no projects Redis version >= 2.0.0? ... yes Your git bin path is "/usr/bin/git" Git version >= 1.7.10 ? ... yes (1.8.5) Checking GitLab ... Finished
Make systemd see your new daemon unit files:
$ systemctl daemon-reload
After starting the database backend (in this case MySQL), we can start Gitlab with its webserver (Unicorn):
$ systemctl start redis mysqld gitlab-sidekiq gitlab-unicorn
Replace
mysqld with
postgresql in the above command if you're using PostgreSQL.
To automatically launch GitLab at startup, run:
$ systemctl enable gitlab.target gitlab-sidekiq gitlab-unicorn
Now test your Gitlab instance by visiting or and login with the default credentials:
username:
admin@local.hostpassword:
5iveL!fe
That's it. GitLab should now be up and running.
Advanced Configuration
HTTPS/SSL
Change GitLab configs
Modify
/etc/webapps/gitlab/shell.yml so the url to your GitLab site starts with
https://.
Modify
/etc/webapps/gitlab/gitlab.yml so that
https: setting is set to
true.
Configure HTTPS server of choice
Apache
Node.js
You can easily set up an http proxy on port 443 to proxy traffic to the GitLab application on port 8080 using http-master for Node.js. After you've creates your domain's OpenSSL keys and have gotten you CA certificate (or self signed it), then go to to learn how easy it is to proxy requests to GitLab using HTTPS. http-master is built on top of node-http-proxy..
HTTPS is not green (gravatar not using https)
Redis caches gravatar images, so if you've visited your GitLab with http, then enabled https, gravatar will load up the non-secure images. You can clear the cache by doing
cd /usr/share/webapps/gitlab; bundle exec rake cache:clear
as the gitlab user. | https://wiki.archlinux.org/index.php?title=Gitlab&curid=15019&diff=296585&oldid=296584 | CC-MAIN-2018-13 | refinedweb | 930 | 52.56 |
What).
An MVar is an object with two methods, put and take. The sender calls put with a message and continues (it doesn’t block–that’s why this message-passing model is called “asynchronous”). The receiver, in another thread, calls take to remove the message from MVar. If there is no message, the receiver blocks until there is one.
An MVar can store a maximum of one message, so it’s an error to call put when there is an unclaimed message inside it. An MVar can thus be only in one of two states: empty or full.
Here’s a simple-minded implementation of MVar written in Java. (A lock-free implementation is possible–and closer to how Haskell implements it–but it’s harder to reason about.)
public class MVar<T> { private T _obj; private boolean _full; public MVar(){ _full = false; } // put: asynchronous (non-blocking) // Precondition: MVar must be empty public synchronized void put(T obj) { assert !_full; assert _obj == null; _obj = obj; _full = true; notify(); } // take: if empty, blocks until full. // Removes the object and switches to empty public synchronized T take() throws InterruptedException { while (!_full) wait(); // may throw! T ret = _obj; _obj = null; _full = false; return ret; } }
You might think that it would be difficult to implement anything useful with MVars. After all it looks like a message queue of length one, which bombs when you try to put a second message in. Yet it is the simplest building block for more sophisticated structures. It is the atom of asynchronous message passing.
We’ve seen before how to implement asynchronous message passing using synchronous building blocks by spawning a thread. Now let’s see how we can implement a simple synchronous channel variable using asynchronous MVars. Remember, in a synchronous channel, if there is no receiver already waiting on the other side, a call to send (or write, in this example) will block.
The basic channel variable, or a channel of length one, is called a CVar in Haskell, and it contains two MVars, one to store the message, and the other for the acknowledgment. The acknowledgment MVar doesn’t really have to store anything–we are only interested in its state: empty or full. The reader will acknowledge the receipt of the message by setting it to full.
public class CVar<T> { private MVar<T> _data; private MVar<Object> _ack; public CVar(){ _data = new MVar<T>(); _ack = new MVar<Object>(); _ack.put(null); // make _ack full } public void write(T obj) throws InterruptedException { _ack.take(); // make _ack empty _data.put(obj); } public T read() throws InterruptedException { T data = _data.take(); _ack.put(null); // make _ack full return data; } }
MVars can also be used to build a more useful asynchronous buffered channel that can store more than one message at a time. I will show you the construction, but it’s far from trivial. You might notice that it resembles a lot a lock-free FIFO queue (although I chose to use locks to implement the MVar). As with all lock-free data structures, one has to be very careful when reasoning about their correctness. I’ll leave it as an exercise to the reader 😉 .
Item and Stream are mutually recursive data structures forming a linked list. An Item points to a Stream–the tail of the list. A Stream is an MVar containing an Item. You may look at a Stream as a sequence of alternating MVars and Items. An empty MVar may serve as a sentinel.
class Item<T> { private T _val; private Stream<T> _tail; public Item(T val, Stream<T> tail){ _val = val; _tail = tail; } T value(){ return _val; } Stream<T> tail(){ return _tail; } } // It's just a typedef for an MVar that stores an Item class Stream<T> extends MVar<Item<T>> {}
A Channel contains the Stream linked list stored in an MVar, which is called _read because the head of the list is where we read messages. The other MVar points to the end of the list (really an empty sentinel Stream). This is the write end of the list. The methods put and get (which are not synchronized!) perform some intricate manipulations characteristic of lock-free algorithms, making sure that at every step the queue is in a consistent state for concurrent access. Notice that put will only block if another put is in progress. Otherwise it’s asynchronous–there is no waiting for a receiver.
public class Channel<T> { private MVar<Stream<T>> _read; private MVar<Stream<T>> _write; public Channel() { _read = new MVar<Stream<T>>(); _write = new MVar<Stream<T>>(); Stream<T> hole = new Stream<T>(); _read.put(hole); _write.put(hole); } public void put(T val)throws InterruptedException { Stream<T> newHole = new Stream<T>(); Stream<T> oldHole = _write.take(); _write.put(newHole); oldHole.put(new Item<T>(val, newHole)); } public T get()throws InterruptedException { Stream<T> cts = _read.take(); Item<T> item = cts.take(); _read.put(item.tail()); return item.value(); } }
In the next few installments I’m planning to talk a little about “choice” and then tackle the actor-based message-passing paradigm (Erlang and Scala). | https://bartoszmilewski.com/2009/02/ | CC-MAIN-2017-09 | refinedweb | 852 | 64.1 |
Applets in Java using NetBeans as an IDE (Part 1)
C.W. David
Department of Chemistry
University of Connecticut
Storrs, CT 06269-3060
Carl.David@uconn.edu
We are interested in creating a teaching/testing tool for the WWW using applet
technology implemented using Java. You can see from Illustration 1 what we are aiming
at:
Clearly, we are aiming for what is called a constructed response, not a multiple choice,
method for answering. Notice that the text contains 90
o
C which failed (using LaTeX
notation), and 90<sup>o</sup> fails also. This means that whatever we've done,
vide
ante
, we are not interpreting HTML properly (more on this later). In all that follows, we
Illustration
1
: An applet showing constructed responses in an intuitive mode. Note the misprint!
will be using NetBeans 1.5, and Java 1.5. There are other IDE's available, but this one has
freeform GUI construction, which turns out to be incredibly intuitive.
If you find any errors or omissions, or want
clarifications
added, please e-mail me
at
Carl.David@uconn.edu
, and I will make the appropriate adjustments.
Criteria for the Project:
Our criterion for ultimate success in this project is to use HTML properly, so that
chemical subscripts and superscripts can be included (as well as the degree symbol, etc.).
In this first example, the text is embedded in the question, and our second goal is to
obtain the text from a web site in a public_html directory accessible to teachers who are
willing to edit HTML text for their questions. Of course, we need to know (or generate)
the correct answer, and compare it to the student answer, and we need to create a strategy
for what to do when the student submits an incorrect answer. But first, we analyze this
example as best we can.
Creating an Applet:
We start with creating an applet:
we've started with an existing Project, and found the sources folder, and right clicked
there to get choice, and as novices, we try new, which allows us to see a Description field
Illustration
2
: Creating a new JApplet
for any choice to be made, helping us.
We choose a JApplet, and give it a name, i.e., follow the menus and choices as
they appear. IN the code snippets which follow, lots will have been removed for the sake
of clarity. It is most important, when a symbol from the API's can't be found, that you
check the import statements, which, for me, grow as I work, i.e., I don't start with
import javax.swing.JTextArea;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.*;
import java.util.Formatter;
but this is what I ended up with after coding (there is a clean up of imports in the IDE,
which one can employ later.
To continue,
we go to the Design menu and start adding components from the
Palette.
This generates code which occurs in the hidden, uneditable, part of the source,
and most of the time you needn't look at
it. We
start with the
±
symbol (we will need two
of these, one for the 3 digit part and one for the power of ten part).
First, we have to set up the layout, and the easiest in NetBeans1.5 is the
free
form
one. Right clicking on the brown form in the design mode one gets:
and we choose Free Design, which is superb!
Next, we click on a JComboBox in the
palette
and then click on the emerging
form. Lo and behold, a JComboBox appears; its temporary name is jComboBox1. We
Illustration
3
: Choosing the FreeForm scheme for laying out our GUI
see:
and a little experimentation will yield that we can move this
around
to where we want it.
Right click on it, and choose Properties (at the bottom of the pop-up menu). You will see:
which allows you to edit its
model
“Item 1, Item 2, Item 3, Item 4” into “+ -”.
Wonderful.
We
repeat the procedure, adding a second JComboBox, obtaining:
Notice that we've
aligned
the second JComboBox with the first, and we can not edit it's
model
to read :1,2,3,4,5,6,7,8,9. Notice that we've omitted zero, since we want to force
the student to use scientific notation, where the first digit must be non-zero.
Next, we add a label, whose text is “.”, and then two more JComboBoxes so that a
3 significant figure result can be seen. Continuing with the rest of the boxes and such is
obvious, and omitted here.
When we're all said and done, we've got these JComboBoxes and Labels, and we
can align them together using point and click, and we can group them and move them
where we like. The entire process is just plain incredible.
We need to add a JeditorPane, sized to fill the upper part of the form, and a submit
button which will tell the computer to grade the student's answer once it is completely
entered. Notice that we do not want to process the individual JComboBox changes as
they occur, we want to process them when the appropriate time comes.
To enter the question, we are forced to code under the properties of the
JEditorPane ,which shows up in the compressed code as:
Illustration
4
: Creating a graphic
element from the
Palette
Illustration
5
: Editing the items to be shown in the JComboBox
Illustration
6
: Adding a second element
after editing the first element
jTextArea1.setText("When 215 grams of potassium nitrate, 0.35 grams of sodium
chloride, and 500 grams of water are mixed at about 90^oC, the volume of the resultant
solution is found to be 585.3 milliliters. What is the density of the solution?");
This means that we are going to have a major problem with this kind of implementation,
since we don't want our teachers editing Java code!
So, for the time being, we will live with this implementation, and try a different
scheme later. Right now, we want to focus on how to grade the student's response!
In the design view, we now right click on the submit button, and look at its Events. Just
clicking on the
empty
field next to “Action Performed” leads to insertion of code into our
source
, which we add to under the TODO rubric.
We start with the plus/minus sign, and write
JComboBox pm = (JComboBox)getContentPane().getComponent(2);
String pm_s = (String)pm.getSelectedItem();
You may ask, how did I know that it was component #2, and I will tell you, pure and
simple trial and error. Phooey! We will return to this inadequate method after we've
finished. Any way, we obtain pm, and then convert it to a string so that we can do other
things with it in a little while.
After retrieving the contents of the other JComboBoxes, items 3, 5 and 6, we
execute the most important statement:
String mantissa = (String)pm_s+i1.getSelectedItem()+"."+i2.getSelectedItem()
+i3.getSelectedItem();
which creates a number of the kind “3.14” with the appropriate sign pre-pended. Next we
convert this string to a number (double in our case):
double mant = Double.valueOf(mantissa).doubleValue();
//we have just gotten the x.yz (signed) part of a student's answer!
We then repeat the coding for the power of ten. After obtaining the power of ten, we
create the final student answer:
student_answer = Math.pow(10,exponent)*mant;
which we report by changing the label which asked for the student's answer to contain
his/her last answer as well, i.e.,
String answer_formatted = String.format(Double.toString(student_answer),"%9.2g");
myLabel1.setText("Enter your answer in scientific notation here; your prior answer
was:"+answer_formatted);
Here is the code in its entirety:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JComboBox pm = (JComboBox)getContentPane().getComponent(2);
String pm_s = (String)pm.getSelectedItem();
JComboBox i1 = (JComboBox)getContentPane().getComponent(3);
JComboBox i2 = (JComboBox)getContentPane().getComponent(5);
JComboBox i3 = (JComboBox)getContentPane().getComponent(6);
String mantissa = (String)pm_s+i1.getSelectedItem()+"."+i2.getSelectedItem()
+i3.getSelectedItem();
double mant = Double.valueOf(mantissa).doubleValue();
//we have just gotten the x.yz (signed) part of a student's answer!
JComboBox pm2 = (JComboBox)getContentPane().getComponent(8);
String pm_s2 = (String)pm2.getSelectedItem();
JComboBox i4 = (JComboBox)getContentPane().getComponent(9);
JComboBox i5 = (JComboBox)getContentPane().getComponent(10);
String exp = (String)pm_s2+i4.getSelectedItem()+i5.getSelectedItem();
double exponent = Double.valueOf(exp).doubleValue();
//we have just gotten the exponent of the power of ten.
student_answer = Math.pow(10,exponent)*mant;
JLabel myLabel1 = (JLabel)getContentPane().getComponent(1);
String answer_formatted = String.format(Double.toString(student_answer),"%
9.2g");
myLabel1.setText("Enter your answer in scientific notation here; your prior answer
was:"+answer_formatted);
}
In order to test our method of judging the student response, we here give some
pseudo code which illustrates our attack:
correct_answer = 1.22;// this is just for testing purposes!
if(answer_formatted.equals(correct_formatted)){
myLabel.setForeground(java.awt.Color.GREEN);
myLabel.setText("Enter your answer in scientific notation here; your prior
answer,"+answer_formatted+", was RIGHT!");
}else{
myLabel.setForeground(java.awt.Color.RED);
myLabel.setText("Enter your answer in scientific notation here; your prior
answer,"+answer_formatted+", was WRONG!");
}
so that we can compare the student's answer to our own (locally coded for the time
being). We can (and perhaps will) tell the student if his last digit is off, i.e., that he is
approximately right, but that is another subject, and we will defer that for the time being.
The Next Step:
We have several alternatives now, which we need to address. Here is a list of
them:
1.
How to get HTML interpreted correctly.
2.
How to get the HTML to contain the answer desired (
vide infra
),
3.
How to get random numbers into the question's HTML so that each student gets a
different version.
4.
How to include SureMath in the HTML so that a SureMath presentation can be
included in each question for
those
who need help.
We will answer these an other questions in succeeding sections of this presentation.
Log in to post a comment | https://www.techylib.com/en/view/cabbagepatchtexas/applets_in_java_using_netbeans_as_an_ide_part_1 | CC-MAIN-2018-09 | refinedweb | 1,703 | 56.45 |
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 19.1, “How to create Scala classes that use generic types (cookbook examples).”
Problem
You want to create a Scala class (and associated methods) that uses a generic type.
Solution
As a library writer, creating a class (and methods) that takes a generic type is similar to Java. For instance, if Scala didn’t have a linked-list class and you wanted to write your own, you could write the basic functionality like this:
class LinkedList[A] { private class Node[A] (elem: A) { var next: Node[A] = _ override def toString = elem.toString } private var head: Node[A] = _ def add(elem: A) { val n = new Node(elem) n.next = head head = n } private def printNodes(n: Node[A]) { if (n != null) { println(n) printNodes(n.next) } } def printAll() { printNodes(head) } }
Notice how the generic type
A is sprinkled throughout the class definition. This is similar to Java, but Scala uses
[A] everywhere, instead of
<T> as Java does. (More on the characters
A versus
T shortly.)
To create a list of integers with this class, first create an instance of it, declaring its type as
Int:
val ints = new LinkedList[Int]()
Then populate it with
Int values:
ints.add(1) ints.add(2)
Because the class uses a generic type, you can also create a
LinkedList of
String:
val strings = new LinkedList[String]() strings.add("Nacho") strings.add("Libre") strings.printAll()
Or any other type you want to use:
val doubles = new LinkedList[Double]() val frogs = new LinkedList[Frog]()
At this basic level, creating a generic class in Scala is just like creating a generic class in Java, with the exception of the brackets.
Discussion
When using generics like this, the container can take subtypes of the base type you specify in your code. For instance, given this class hierarchy:
trait Animal class Dog extends Animal { override def toString = "Dog" } class SuperDog extends Dog { override def toString = "SuperDog" } class FunnyDog extends Dog { override def toString = "FunnyDog" }
you can define a
LinkedList that holds
Dog instances:
val dogs = new LinkedList[Dog]
You can then add
Dog subtypes to the list:
val fido = new Dog val wonderDog = new SuperDog val scooby = new FunnyDog dogs.add(fido) dogs.add(wonderDog) dogs.add(scooby)
So far, so good: you can add
Dog subtypes to a
LinkedList[Dog]. Where you might run into a problem is when you define a method like this:
def printDogTypes(dogs: LinkedList[Dog]) { dogs.printAll() }
You can pass your current
dogs instance into this method, but you won’t be able to pass the following
superDogs collection into
makeDogsSpeak:
val superDogs = new LinkedList[SuperDog] superDogs.add(wonderDog) // error: this line won't compile printDogTypes(superDogs)
The last line won’t compile because (a)
makeDogsSpeak wants a
LinkedList[Dog], (b)
LinkedList elements are mutable, and (c)
superDogs is a
LinkedList[SuperDog]. This creates a conflict the compiler can’t resolve. This situation is discussed in detail in Recipe 19.5, “Make Immutable Collections Covariant”.
In Scala 2.10, the compiler is even nice enough to tell you what’s wrong in this situation, and points you toward a solution:
[error] Note: SuperDog <: Dog, but class LinkedList is invariant in type A. [error] You may wish to define A as +A instead. (SLS 4.5)
Type parameter symbols (naming conventions)
If a class requires more than one type parameter, use the symbols shown in Table 19-3. For instance, in the official Java Generics documentation, Oracle shows an interface named
Pair, which takes two types:
// from public interface Pair<K, V> { public K getKey(); public V getValue(); }
You can port that interface to a Scala trait, as follows:
trait Pair[A, B] { def getKey: A def getValue: B }
If you were to take this further and implement the body of a
Pair class (or trait), the type parameters
A and
B would be spread throughout your class, just as the symbol
A was used in the
LinkedList example.
Scala generic type parameter naming conventions
The same Oracle document lists the Java type parameter naming conventions. These are mostly the same in Scala, except that Java starts naming simple type parameters with the letter
T, and then uses the characters
U and
V for subsequent types. The Scala standard is that simple types should be declared as
A, the next with
B, and so on. This is shown in Table 19-3.
Table 19-3. Standard symbols for generic type parameters
See Also
- Oracle’s Java “Generic Types” documentation
- Recipe 19.4, “Make Mutable Collections Invariant”
- Recipe 19.5, “Make Immutable Collections Covariant”
- You can find a little more information on Scala’s generic type naming conventions at the Scala Style Guide’s Naming Conventions page
The Scala Cookbook
This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:
You can find the Scala Cookbook at these locations:
Add new comment | https://alvinalexander.com/scala/scala-classes-using-generic-types-examples | CC-MAIN-2017-39 | refinedweb | 829 | 58.42 |
Dear all;
I dont want to use AutoBean with Grids. I want to JSON and ModelData as GXT 2.5. but i dont want migration mode.
How do make a solutions?
Printable View
Dear all;
I dont want to use AutoBean with Grids. I want to JSON and ModelData as GXT 2.5. but i dont want migration mode.
How do make a solutions?
One of the fundamental difference between 2.5 and 3.x is that 3.x makes heavy use of Java generics. Grid was one of the things changed such that grid records are just Java beans. IMO this is actually a VERY good thing because now the model is not tightly coupled to the view framework and thus makes for great code reuse without sucking in unnecessary dependencies.
If you want to use JSON instead of RPC, there is a JsonReader class, but AFAIK, there is no way to use JSON without an auto bean factory, or in fact, converting from JSON to Java beans without one.
Thanx for reply. Icfantv.
I very like Java Bean System but as you know, more than one table in the real world. I like Java Bean for insert or update with method but Java bean need per grid by per bean.
Example.
x.col1,
x.col2,
x.col3,
.....
y.col1,
y.col2,
y.col3,
y.col4,
........
FROM x INNER JOIN y ON (x.col5=y.col5)
This Query have Two Table. And Two Bean;
I want to JSON and ModelData for this condition. Java bean need XBean and YBean Merge.
What do you recommend for use in this kind of. With bean or Without bean on GWT,GXT
If I understand you correctly, what you are talking about is beyond the scope of GXT. Current ORM frameworks can easily map multiple table data into one Java bean with no additional steps from the user. We are currently doing this in one of our web applications.
What I suspect you're saying is that your server side-code is already serving up JSON and you don't want to modify it. This is fine, but you will need someway to marshall that JSON into another object form and the way this is done in GXT 3.x is with the JsonReader object and auto beans.
I can understand and appreciate not wanting to do a code migration, but GXT 3.x was over a year of development work and a significant portion of the API was a ground up rewrite.
The answer to your question depends on several factors:
- What is your time frame? If short, you may want to reuse existing code as much as possible.
- What does your server-side interface look like? If it returns JSON, you don't have to change it, but you will need to marshall that back into Java form and the easiest way to do this is via auto beans.
First thanks for this brain strom and Sorry for my English.
I have been using GXT 2 since 2 years ago and i developed two project with that.
as you know GXT 2 is ModelData base for data connection. I developed my custom library for database comunication process. This library has Java Bean Support and JSON support. I think insert and update method with JavaBean; select method with JSON. GXT 3 will be my new UI Framework.
I will add multiple table support in my database library's java bean mode.
My bean is now Structure
I think add a field that model structure. (Map<String,Model> Relations;). then My QueryManager will fill relational table on this field.I think add a field that model structure. (Map<String,Model> Relations;). then My QueryManager will fill relational table on this field.Code:
public class ModulesModel implements Model {
public static final List<Index> PrimaryKeys;
public static final List<Index> ForeginKeys;
public static final List<Index> Indexes;
public static final List<Column> Columns;
public static final String Database;
public static final String Table;
static {
Database = "";
Table = "modules";
PrimaryKeys = new ArrayList<Index>();
Index pkmodule_guid = new Index();
pkmodule_guid.setTable("modules");
pkmodule_guid.setField("module_guid");
pkmodule_guid.setName("null");
pkmodule_guid.setAutoIncrement(false);
pkmodule_guid.setNullable(false);
pkmodule_guid.setType(IndexType.PK);
PrimaryKeys.add(pkmodule_guid);
ForeginKeys = new ArrayList<Index>();
Index fkprogram_guid = new Index();
fkprogram_guid.setTable("program_guid");
fkprogram_guid.setField("program_guid");
fkprogram_guid.setName("fk_modules_program_guid");
fkprogram_guid.setAutoIncrement(false);
fkprogram_guid.setNullable(false);
fkprogram_guid.setType(IndexType.FK);
fkprogram_guid.setForeginTable("program");
fkprogram_guid.setForeginField("program_guid");
fkprogram_guid
.setUpdateRule(IndexRule.NO_ACTION);
fkprogram_guid
.setDeleteRule(IndexRule.NO_ACTION);
ForeginKeys.add(fkprogram_guid);
Indexes = new ArrayList<Index>();
Columns = new ArrayList<Column>();
Column colmodule_key = new Column();
colmodule_key.setDecimalDigits(0);
colmodule_key.setDefault("null");
colmodule_key.setName("module_key");
colmodule_key.setTable("modules");
colmodule_key.setSize(250);
colmodule_key.setType(12);
Columns.add(colmodule_key);
Column colmodule_adi = new Column();
colmodule_adi.setDecimalDigits(0);
colmodule_adi.setDefault("null");
colmodule_adi.setName("module_adi");
colmodule_adi.setTable("modules");
colmodule_adi.setSize(250);
colmodule_adi.setType(12);
Columns.add(colmodule_adi);
Column colprogram_guid = new Column();
colprogram_guid.setDecimalDigits(0);
colprogram_guid.setDefault("null");
colprogram_guid.setName("program_guid");
colprogram_guid.setTable("modules");
colprogram_guid.setSize(100);
colprogram_guid.setType(12);
Columns.add(colprogram_guid);
Column colmodule_guid = new Column();
colmodule_guid.setDecimalDigits(0);
colmodule_guid.setDefault("null");
colmodule_guid.setName("module_guid");
colmodule_guid.setTable("modules");
colmodule_guid.setSize(100);
colmodule_guid.setType(12);
Columns.add(colmodule_guid);
Column colmodule_type = new Column();
colmodule_type.setDecimalDigits(0);
colmodule_type.setDefault("null");
colmodule_type.setName("module_type");
colmodule_type.setTable("modules");
colmodule_type.setSize(10);
colmodule_type.setType(4);
Columns.add(colmodule_type);
}
public ModulesModel() {
}
private String module_key;
public void setModule_key(String module_key) {
this.module_key = module_key;
}
public String getModule_key() {
return this.module_key;
}
private String module_adi;
public void setModule_adi(String module_adi) {
this.module_adi = module_adi;
}
public String getModule_adi() {
return this.module_adi;
}
private String program_guid;
public void setProgram_guid(String program_guid) {
this.program_guid = program_guid;
}
public String getProgram_guid() {
return this.program_guid;
}
private String module_guid;
public void setModule_guid(String module_guid) {
this.module_guid = module_guid;
}
public String getModule_guid() {
return this.module_guid;
}
private int module_type = -1;
public void setModule_type(int module_type) {
this.module_type = module_type;
}
public int getModule_type() {
return this.module_type;
}
@Override
public List<Index> getPrimaryKeys() {
return ModulesModel.PrimaryKeys;
}
@Override
public List<Index> getForeginKeys() {
return ModulesModel.ForeginKeys;
}
@Override
public List<Index> getIndexes() {
return ModulesModel.Indexes;
}
@Override
public List<Column> getColumns() {
return ModulesModel.Columns;
}
@Override
public String getDatabase() {
return ModulesModel.Database;
}
@Override
public String getTable() {
return ModulesModel.Table;
}
}
What do you think about and how can i use this model with GXT PropertyAccess? or do you have another offer.
Best Regards
I'm not sure I follow completely, but to answer your question about property access, as long as your model object adheres to the JavaBean contract then you're fine - you can call any getXXX or isXXX property methods on your bean.
Just a heads up however, that bean is referenced from the client-side which means the GWT compiler will need the source code for EVERYTHING in that class whether or not you actually need or use it.
Then there are 3 ways in front of me
1- use a ORM Framework as OpenJPA (I think performance cost is expesive. Too hard for my project)
2- Dynamical create model class. ( I dont know its possible)
3- Create a class for each grid (I thing not flexible coding)
I finded a Class in GXT
Do you know how to use this class?
Addressing your items:.
- There are other, probably more prominent, ORM frameworks out there. Hibernate is probably by far the most ubiquitous but it's a little esoteric. The other is myBatis (previously iBatis).
I could go into a long diatribe about one vs. the other, but in general Hibernate is good if you haven't written your schema yet or you completely control the schema. It really forces you to get your schema and relationships correct. myBatis is good if you want to reuse your existing SQL. And if you're using Spring it's even easier still with their mybatis-spring project.
Ultimately though, they both do the same things: take SQL queries and create Java objects for you.
- You can use auto beans to convert your JSON back into a Java object, you just need to provide the factory If you look at the Javadoc for JsonReader (), you will see almost a full working example. Plus, there's a JSON Grid demo here:
- I can understand how one might think that the 1:1 relationship between a grid and it's records is not flexible, but I disagree. A model can be anything and can include containing other models. All you need to do is provide a cell implementation for how to render a cell that makes use of the nested models. You will also ultimately have this restriction with JSON. Personally, trying to create a dynamic grid whose columns change with the data might be more work than it is worth.
I had posted a similar question which appears to be getting ignored.
I am looking for two things at this point.
The ability to dynamically create fields/properties within the bean and then apply that to a grid and please tell me how I might shed the much of the Sencha example code I don't need. I am hoping that the RPC is not a necessary part of Sencha Grids but so far its looking like the servlets are part of what is needed to display the Grids and Charts.
I would be most greatful if someone could address that issue. So far it seems I am stuck with the need to use RPC and bean models to display grids which limits the developer to a specific bean of N fields
I can not specify as it appears a bean that can grow dynamically in fields or perhaps I am missing something here could anyone comment on this? The closest I had come to dynamic column grids is
a bean with many columns statically defined and availablility ArrayList<MyModel> myModel=new ArrayList<MyModel>(); and adding references to each field I could use for a dynamic columnConfig set.
If I ever find my previous posting I will post the contents here. Perhaps it will help others
Here is what I had written:
When using Sencha Grids I find I have to create a fixed model SGrid class and SGridProperties interface such that
I have to N columns up to as many as I add to my List of ColumnConfig
as well as SGrid and SGridProperties interface.
private ArrayList<ColumnConfig<SGrid, String>> availGridColumns=new ArrayList<ColumnConfig<SGrid, String>>();
private void setup_availGridColumns()
{
this.availGridColumns.add(new ColumnConfig<SGrid, String>(props.n1(1), 50, " "));
this.availGridColumns.add(new ColumnConfig<SGrid, String>(props.n2(2), 50, " "));
: :
this.availGridColumns.add(new ColumnConfig<SGrid, String>(props.nZ(), 50, " "));
}
Note other than this part the grids are working. I do have some sizing issues but the bottom line here is that I need a more dynamic way to do this and I am in need of some basic understanding here of how I might do this more dynamically. Anyone got a good suggestion regarding this??
Now this approach means that for a complete grid of strings and nothing but strings I need my model SGrid to have as many n... properties e.g n200 for 200 columns. So its still limited and not dynamic. The guy I am working with on a project wants it completely dynamic. How might that be accomplished??
How might this be done so it is completely dynamic? Is there another way to do this without the ColumnModel object??
Rather than have to make up a set of availableGridColumns I would perfer
simply a new GridColumnx.add(new ColumnConfig<SGrid, String>(props.n(0), 50, " "));
simply a new GridColumnx.add(new ColumnConfig<SGrid, String>(props.n(1), 50, " "));
simply a new GridColumnx.add(new ColumnConfig<SGrid, String>(props.n(2), 50, " "));
which would mean I could create a basic loop and expand the number of fields to display at will without having to update two files SGrid.java(Model Bean class) and SProperties.java (interface)
As far as dynamic columns are concerned, I can't help you because I don't have experience in that area. I do, however, see that you are a premium member. Can you not post something in the premium forums? Sven is usually very good about getting back to the poster.
Also, to be clear, grids are not tied to RPC. Grids have a ListLoader and the ListLoader is responsible for loading data. ListLoaders are not tied to RPC either as the constructor for the ListLoader takes in either just a DataProxy or a DataProxy and a DataReader. You'll happily note that both JsonReader and XmlReader extend DataReader allowing you to not have to use RPC if you don't want to. | http://www.sencha.com/forum/printthread.php?t=244047&pp=10&page=1 | CC-MAIN-2014-10 | refinedweb | 2,087 | 57.47 |
<<
Brant Faulkner7,921 Points
[solved] Build a Grocery List Program challenge.
I am stuck on this challenge, any tips on where I am going wrong would be appreciated.
I have also noticed that through these Ruby challenges the instructors use of single vs double quotes appears random much of the time. My current understanding is that one should use double quotes when the string needs to be interpolated.
But I am not sure when we should be using single quotes, or no quotes. Any guidance on that would be awesome too.
def create_shopping_list hash = { 'title' = "Grocery List", 'items' => Array.new} return hash end
Geoff Parsons11,667 Points
Brant Faulkner I added "[solved]" to your title since Ryan Trimble's suggestion should solve the issue you're having. Next time post your response as an answer Ryan so we can give you some points for it! :)
Brant Faulkner7,921 Points
Thanks Ryan. That was it.
Funny how a typo can create doubt in my understanding of the material. Will keep that in mind going forward.
1 Answer
J.D. Sandifer18,813 Points
Reposting the solution above as an answer so it doesn't show up as unanswered:
To assign a value to a key in a hash, you need to use the => symbol. You have it on your "Items" key, but the "title" key only has an = symbol.
Ryan Trimble15,559 Points
Ryan Trimble15,559 Points
Hi there Brant,
To assign a value to a key in a hash, you need to use the => symbol. You have it on your "Items" key, but the "title" key only has an = symbol.
should be:
Looks OK otherwise!
As for the single vs. double quotes question, you seem to have an understanding for it. Double quotes are used when an variable needs to be interpolated. | https://teamtreehouse.com/community/solved-build-a-grocery-list-program-challenge | CC-MAIN-2022-33 | refinedweb | 301 | 83.46 |
Hi
Here we covered the better solution to code, so that it cannot lead the any kind of code styling or formatting errors behind. Provided the way to use scala properties and collections in a better way according to their behaviour.
Effective Programming In Scala – Part 2 : Monads as a way for abstract computations in Scala
Here we provided short hand solutions to the long and lengthy writing of code to perform some task in a predefined sequence. Provided the better use of comprehensions so that functionality depending upon Monads can be easily performed.
Now in this blog we continue to explain the concepts that can be used to tell the scala to use the desired value types and generate the monkey patches in way of Scala.
Type Annotations versus Ascription
In Scala we know that if we do not define the type of a variable, then it takes its type itself,
However we can control the type of a value to be a byte, int or string as well,
If we make the code to use the desired form, we type the following,
As we can see that compiler provides the definition to the type as we need, but when we want to provide own definition or override the type of value, then we can use type annotations as well.
Ascription
Scala Ascription is same approach as compared with the annotations, but with a slight difference. Sometimes a new developer of Scala can be confused with both annotations and ascriptions. Ascription can be taken as a process of up-casting of a type and annotations as simple way of defining the result, we want from an expression after its execution.
In the following examples, we can show the ascription clearly.
We have bonus as of Double type and salary of object type. As you can see here, we want the salary to be of an Object type, otherwise it must not be compiled with String or unmatching type.
Now have a look at the below example, where the Ascription can be applied in another way,
In above code we used the (Nil: List[Int]) and (Left(“List is empty”): Either[String, Int]) are another examples of ascriptions.
Adding methods to class in implicit way
In functional programming, we often desire to add some cool functionalities to the existing classes in our project. A class plays a very important role in project development. The class is defined to hold the a huge part of the project’s functions. If we want some cool thing to our class, we should go with the following.
Here we define a class BetterWay having a methods, which returns next positioned character from ASCII standards, for every single character of the input word.
Now we define the magic below,
Here we defined a method stringToString which takes an input string, and passes it to the BetterWay class for further processing. Now we provide some data to test it,
Finally we put the word hal and got all the characters of this incremented by one and resulting into ASCII values ibm.
Lets see whats happening here…
Method stringToString is a simple methods defined in Scala. But as it is defined along the keyword implicit, then it has something more. The implicit does the magic here,
A method defined as implicit, stringToString in our case, takes a string and looks up the BetterWay class and searches for every method which accepts a string as its parameter.
Methods increment defined in class processes the string, iterates over each of its character and then gets the character next to it from ASCII values.
It does not matter whatever name you are providing for the method name for stringToString.
Monkey Patching
Now as we have the idea of implicits and how they work and perform their task, we take a similar concept under control as Monkey Patching. If a user comes from the Ruby’s background, then he always finds the implicits as another way for monkey patching. Monkey Patching in ruby is used to extend the existing class without creating a new class. Now have a look at the below example,
Here we defined an implicit DefinitionHelper class to that accepts a value to be of Int type, which leads the class to inherit all Int members and convert any Int in scope to DefinitionHelper.
The big difference between Ruby and Scala is that Scala applies the implicit in the current scope. We can call and import the implicits anywhere without littering the global namespace resulting into less collisions and more compact DSLs.
Following points must be remembered while declaring implicits in Scala,
- Implicits must be defined inside of another trait, class or any object,
- We can have only one non-implicit parameter in constructor,
- Scala defines the same name as of class for an object as companion object. Keeping this point in mind, We cannot have another object or member with same name as of class in scope.
So i think this blog will help you a lot in enhancing the power of scala by type system and implicits.
Happy Blogging!!!
2 thoughts on “Effective Programming In Scala – Part 3 : Powering Up your code implicitly in Scala”
When using implicit classes, would it not be better to have the classes extend AnyVal to avoid unnecessary object allocations? Of course this can’t always be done if your extensions require extra state, but for simple convenience methods like you have used here, would it not be better? Or do newer versions of Scala automatically do this?
Reblogged this on Play!ng with Scala and commented:
Discover type annotations versus ascriptions, adding methods to class in implicit way and monkey patching. | https://blog.knoldus.com/effective-programming-in-scala-part-3-powering-up-your-code-implicitly-in-scala/ | CC-MAIN-2019-22 | refinedweb | 951 | 55.37 |
Responsive web design -media queriespublished on: | by In category: Web Development Tools
With so many devices available in the market today, It goes without saying that designers should think responsiveness. Building sites that can be accessed across devices cannot be stressed enough. It is a good practice to build mobile-first responsive sites then adjust for bigger screens.
Viewport
Viewport defines the area of the screen that the browser can render content to.To achieve responsiveness, we include meta viewport in the head section of the document
<meta name="viewport" content="width=device-width, initial-scale=1">
Breakdown of the
- The
meta name="viewport"instructs the browser how to controls the width and scaling.
- The
width = device-widthsets the width of the page to follow the screen-width of the device
- include
initial-scale = 1to establish the 1:1 relationship between CSS pixels and device independent pixels.
Media queries
Media Queries are definitely buddies when talking responsiveness. They enable designers to define breakpoints: The point at which the site adapts according to the best possible layout. Media Queries can be used to check the width and height of the viewport, device width and height, resolution and screen orientation.
Ways to apply media queries
- Linked css A separate stylesheet is ideal if there is a need to completely separate different styles for different devices such as desktop, laptop. Linked stylesheet makes many but small http requests. They are referenced as
- Embedded with an @import tag. @import rule is expensive and should be avoided for performance reasons.It can prevent stylesheets from being downloaded concurrently negatively impacting performance.However, the rule can be beneficial if a stylesheet depends on another.
This rule should be used sparingly.
import url("mail.css") only screen and (min-width:500px);
- Embeded with @media tag
Breakpoints
Many different devices will be available in the market over a period of time so Avoid defining breakpoints based on devices for obvious reasons.Who knows which new device will be in the market tomorrow. It is good practice to find breakpoints using your content as a guide. Furthermore, the content is the important stuff and the design should display the content right?
Width vs device-width
Understanding the difference between media queries based on width and device-width is vital.width is the size of the browser window while device-width is the device actual screen size. In other words, the screen resolution of the device
It is not a good idea to use device-width because:
- They don't always match the layout viewport.C a prevent content from adapting on desktops or other devices that allow the window to be resized and this is because the query is based on the actual device size and not the browser window.
- Some browsers such as Legacy Android browser may report the wrong value
My thoughts on good design Practices.
- Use @import rule sparingly, it can prevent your stylesheets from downloading concurrently
- Device-Width dot always match the layout viewport
- Don't base your breakpoints on device size instead prioritize content
- @media rule makes few big http requests | https://achiengcindy.com/blog/2018/07/30/responsive-web-design-media-queries/ | CC-MAIN-2019-30 | refinedweb | 517 | 52.49 |
In Scala, we could use object to override val / 0-arity defs:
object
object emptyProduct extends Grad[HNil] {
...
}
However, this does not extend to case classes. I would like that case classes could override defs with arity > 1 like this:
case class product[H, T <: HList](H: Grad[H], T: Grad[T]) extends Grad[H :: T] {
...
}
instead of
def product[H, T <: HList](H: Grad[H], T: Grad[T]): Grad[H :: T] = new Grad[H :: T] {
...
}
I would argue that the case class form looks better.
case class
FYI: implicit classes can override defs.
implicit class
def
Is this not because the case class itself extends Grad[H :: T], not its companion object? Presumably it doesn’t work for the same reason a (regular) class does not override a val.
Grad[H :: T]
val
I think this is an implementation detail, and it’s not defined in the spec. The fact that implicit classes are internally implemented with classes + implicit defs makes the synthesized implicit conversions override whatever was defined in the super class.
In my opinion, it looks really weird. Classes are not methods. I don’t want to override a method with a class, it looks like a first good step towards chaos!
However, I appreciate seeing suggestions from the Community, it’s been a while since we don’t get them .
The thing is that an object is a class and a value containing the singleton instance of that class. A case class is not a class and a method returning an instance of that class. It’s a class and a function returning an instance of that class.
This suggestion would actually make a lot of sense (or probably: would already be implemented) if functions and methods in Scala were unified.
I wouldn’t say so. An object, language-wise, is a term. A class is a type (an entity to be more precise?). I don’t see how you can unify these two without breaking everyone’s mental model…
I would say an object defines a term as well as a type. But I agree you probably shouldn’t enable implementing methods with case classes. But I can see where he’s coming from.
For what it’s worth, this currently works for the reason pointed out by @Jasper-M:
trait A { type Foo; def Foo: Int => Foo }
object B extends A { case class Foo(x: Int) }
It breaks when type parameters are introduced, because the companion object to Foo no longer extends a function type (it would need to be a polymorphic function type).
Foo
Agreed—also, those two things aren’t equivalent. But I’m happy with writing case class Product and a forwarder override def product ... = Product(...).
Product
override def product ... = Product(...)
In practice, this happens because case classes have the same meaning at the top-level and elsewhere, so the generated constructor can’t be (on the JVM) a top-level function, but must be a method on the companion object.
On the principle
But a case class isn’t just a type, it’s a type + a constructor method. In the spec, they’re classes and methods are both “templates”. That comes (IIUC) from the Beta family of languages, where classes and methods are unified more fully. There, the activation record of a method is nothing but a class, whose members are local definitions of the method, and the body of a constructor is a definition of the members of that class. The second part survives in Scala constructors, the rest is gone thanks to the JVM. | https://contributors.scala-lang.org/t/case-classes-overriding-defs/1181 | CC-MAIN-2017-43 | refinedweb | 597 | 71.75 |
How to Test Your Vue Project with Jest and Nightwatch
published a story
Testing is a vital part of the development cycle and a part of life for programmers and developers. Nobody likes bugs in their code, but they're incredibly annoying when you think your project is done and ready for deployment. But inevitably, someone will find a way to break your code: a certain function has an unforeseen edge case that doesn't work, going to pages in an unpredicted sequence can result in weird outputs, etc.
Of course, one of the best ways to unearth bugs in your code is to get people to test it over and over again, but even before that phase, there are a lot of ways to find problems in your project. That's what I'll be talking about in this article.
For this article, I'll assume that you have some familiarity with Vue.js or any other MVC like React. If you don't, you can easily learn more about components and other things on the Vue website. In this tutorial, I'm going to demonstrate how you can test your Vue project with Jest and Nightwatch.
Table of Contents
Alright. Let's finally get into it.
Unit Testing in Vue with Jest
Unit testing, simply put, is the method of isolating individual parts of your code and seeing if they work as expected.
For example, if we have a method that takes an array and returns the lowest value, then our unit test will pass it a hard-coded array and expect a certain value to be returned. Unit testing is a good way to catch corner cases and bugs.
In Vue.js, there are several things we might want to unit test like:
- Components requiring certain lifecycle hooks
- Components passing/accessing props
- The text output of components
- The value of a component's data
To conduct these tests, Vue has great built-in options for working with Jest - a popular JS unit testing software.
Jest uses assertions that expect a certain response. For example, with Jest, if we wanted to test a
sum(int a, int b) function, we would write.
expect(sum(1, 2)).toBe(3);
However, testing entire components can get a lot tricker. First, we have to wrap our tests in a
describe test runner (you can learn more about this in the Jest docs).
Then, we can start declaring our tests. The following is an example of a test that ensures that a Vue component,
Component.vue renders what we expect it to.
Our component
Component.vue is going to look like this:
<template> <div> <h1>Hello World!</h1> </div> </template>
To be able to test it, we'll have to write the following test:
import Vue from 'vue' import Component from "@/components/Component.vue" describe("Component.vue", () => { it("renders the proper default message", () => { const Constructor = Vue.extend(Component) const vm = new Constructor().$mount() // we expect the default output to be "Hello World!" expect(vm.$el.textContent).toBe('Hello World!') }) })
We can do similar operations for a lot of other tests such as checking styles, computed properties, data values, etc. I won't go into too much detail because a lot of these are easily found with a quick Google Search. Just remember the following format for Jest unit tests.
- Import Vue and the components you are testing
- Use a
describeto wrap your unit tests for each component
- Describe each test with an
itfunction that describes the test and performs it.
- Use
expectand
toBeto determine if you get the right output for your services.
To run your Jest test, first, we have to make sure that Jest is installed in your project. Run the following command:
npm install --save-dev jest
Then, in your
package.json file, add the following script:
{ "scripts": { "test": "jest" } }
Now that we're all set up, we can run the tests using the line
npm test - this will call jest and run all of your tests.
That's the basics of unit testing in Vue, if you want to know a little bit more about it, the Vue docs are a great resource for all developers.
Snapshot Tests with Jest
Another great use for Jest is to do snapshot tests - making sure your UI does not change unexpectedly. The way they work is simple: store a snapshot file that contains the expected UI component, and when you run the test, it will compare the current build of your project to that snapshot.
If they're not equal, either something went wrong or you need to update the snapshot of your project to the current version.
The syntax for snapshot tests, since they also are built-in with Jest, is similar to unit tests. Let's get into an example.
Let's say we have a component called
HelloWorld.vue that we don't want to unexpectedly change. This can be anything, but let's just use the following example.
<template> <div> {{Hello World!}} </div> </template> <script> export default { data () { return { msg: 'Hello World!' } } } </script>
Our test file will look like this. Note that this can be incorporated into the same file as our unit tests from the previous section.
import Vue from 'vue' import HelloWorld from "@/components/HelloWorld.vue" const Constructor = Vue.extend(HelloWorld) const vm = new Constructor().$mount() describe("HelloWorld.vue", () => { it('should match the snapshot', () => { expect(vm.$el).toMatchSnapshot() }) })
This creates and mounts a component, which gives us access to its HTML via the
$el property.
The first time we run the test, Jest sees that we don't have a snapshot yet, so it creates one. Then, on any future tests, it will compare the current build to the snapshot that we have stored.
If they match, they test passes; if they don't, the test fails and you'll see the differences between the two.
Sometimes, however, we'll need to update the snapshot to include a more recent version of our file. There are two ways to do this.
- We can run the command
jest --updateSnapshot
- In watch mode, we can use the inline commands and press 'U' to update failed screenshot tests.
Using Nightwatch for E2E Test in Vue
First off, what are E2E tests? End to End tests check on an application's entire flow from, you guessed it, end to end/start to finish.
They encompass all of the actions a user might perform on a website: clicking, typing, everything. The purpose of E2E tests is to simulate actions a real user might perform.
E2E tests are useful when you have multiple features that were developed independently but are dependent on each other to run properly. When unit tests simply aren't enough to test your project, E2E tests come to the rescue.
Tools like Nightwatch, which we'll be using here, help mimic a user's typing and clicking on a website to ensure that things are happening as expected. While Nightwatch is not Vue specific (it runs on Node.js) - it's still a great tool for testing Vue apps.
Writing E2E tests is a lot more time consuming because we have to get into the mind of a user and what steps (in order) they'll take to navigate our project.
At the end, similar to in Jest, we use an
assert to make sure the output is what it should be.
To add Nightwatch to your project, use the command
npm install. Then, you can find the tests are located in a subdirectory within your project.
I think a great example of a test file comes from Nightwatch docs themselves. The following goes to Google, runs a search, and checks if the search bar has the correct input (which should be the text input).
module.exports = { 'step one: navigate to google' : function (browser) { browser .url('') .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('input[name=btnK]', 1000) }, 'step two: click input' : function (browser) { browser .click('input[name=btnK]') .pause(1000) .assert.containsText('#main', 'Night Watch') .end(); } };
Now that we have a test, to run your test, just simply call
nightwatch path/to/test.js in your Terminal.
As you can see, Nightwatch uses CSS selectors in order to interact with your site. This is a great way of seeing what will happen in different scenarios.
One benefit of running E2E tests is that it forces you to think about how people will use your site. Overall it's just a helpful tool for developers to think about their site from an end user's perspective.
Another nice thing about Nightwatch is that you can change the URLs to run on so you don't have to upload your project to a dedicated server to conduct these tests.
Conclusion
Testing is a vital part of every development cycle. It helps catch bugs, gives developers more confidence in their code, and helps create a better product.
In this article, we've learned the basics of testing Vue components with unit, snapshot, and E2E testing. While this is only the basics of testing, it should be enough to get you started and you should also know where to go to find more (the docs).
Let me know if you have any questions and please share this tutorial with your Vue friends! | https://hashnode.com/post/how-to-test-your-vue-project-with-jest-and-nightwatch-cjskmturk00665ss1gauawb84 | CC-MAIN-2020-24 | refinedweb | 1,553 | 71.95 |
In this Program, you’ll learn how to Check Prime Number By Creating a Function or check prime numbers creating function.
To nicely understand this example to check prime numbers creating
- for Loop
- break and continue Statement
- if, if…else and Nested if…else
- Functions
- Types of User-defined Functions
Program to Check weather number is Prime or Not
#include <iostream> using namespace std; int checkPrimeNumber(int); int main() { int n; cout << "Enter a positive integer: "; cin >> n; if(checkPrimeNumber(n) == 0) cout << n << " is a prime number."; else cout << n << " is not a prime number."; return 0; } int checkPrimeNumber(int n) { bool flag = false; for(int i = 2; i <= n/2; ++i) { if(n%i == 0) { flag = true; break; } } return flag; }
Output
Enter a positive integer: 23 23 is a prime number.
In this example, the number entered by the user is passed to the
checkPrimeNumber()function.
This function returns
true if the number passed to the function is a prime number, and returns
false if the number passed is not a prime number.
Finally, the appropriate message is printed from the
main() function
Ask your questions and clarify your/others doubts on Program to check prime numbers creating the function by commenting. Documentation
Related Programs
- C++ “Hello, World!” Program
- C++ Program to Print Number Entered by User
- C++ Program to Find Quotient and Remainder
- C++ Program to Find Size of int, float, double and char in Your System
- C++ Program to Swap Two Numbers
- C++ Program to Find ASCII Value of a Character
- C++ Program to Multiply two Numbers | https://coderforevers.com/cpp/cpp-program/prime-function/ | CC-MAIN-2020-16 | refinedweb | 261 | 52.12 |
,
Thanks for the answers!
Thomas Moenicke wrote:
> Ferenc Veres wrote on Dienstag, 17. Januar 2006 02:12:
>=20
>>Then what is the input encoding?=20
..
> Trolls wrote:
> "Constructs a string initialized with the ASCII string str."
> And next
> "str is converted to Unicode using fromAscii()."
I did some tests, with Tutorial 1 in both PHP_QT and C++, and I think it
can accept iso-8859-1 encoded characters too. Not only the first 127
ASCII characters display right on the Tutorial 1 button, but if you use
127 to 255 byte values, they display like those byte codes look in
iso-8859-1 character set! (latin1)
Fine. Not useful for Hungarian, but an acceptable extra feature. ;-)
> Lets finish QString and test all functions there. All I have seen in ph=
p=20
> internals stores strings binary. Maybe, we have luck.
For example entering "=C5=B1" in iso-8859-2 edited source code will displ=
ay
"=C3=BB" on a button, as that is the same BYTE VALUE in iso-8859-1.
It's okay. I just needed to know, it expects Latin1 characters. Now I
can also test toUtf8(). :-)
> We will see. There are
> toAscii()
> toLatin1
> toUtf8
My test results confirm that everything is alright! ;-) From
tests/unicode.php, changing the input string to > 127 characters,
->toUtf8() displays characters right on my Konsole, so I think, the
latin1 to utf-8 conversion is done.
(Of course if I edit in Latin1 or Latin2, I can see different characters
on the same byte code, but both the characters display as their latin1
value on the button label or console. KWrite is a very good editor to
test this.)
Printing the string with echo, prints binary dirt, that's also correct,
because the byte sequence of the latin-1 characters have no meaning if
for my utf-8 console. Displaying on and inside widgets, will be up to
Qt, when we can pass QString to them.
I'll have my input data in utf-8, so I think fromUtf8 could be used, but
currently I cannot call that method on QString. Will it be implemented
as static method like the C++? (If yes, I think I will need an example
on how to call. :-) )
Many thanks and keep up the good work! ;-)
Ferenc
ps: may I report problems with any widgets appearing in the source? If
yes, then I think QLabel is completely broken. :-)
Hi all,
Thomas Moenicke wrote:
>
> It runs if I create the Slider but omit it from the layout.
>
> /* LCD only */
>
I checked out the latest version and runs perfect with adding QLineEdit
and QPushButton controls to the grid. Great! :-)
In my code I have public arrays for all those controls. In tutorial 6, I
think the LCDRange() has no public class member variable assigned. (Same
in C++ original tutorial.) I don't know if this difference causes
changing the line in t6/main.php:
$this->grid->addWidget(new QPushButton("a",$this), $row, $column, 0);
or
$this->grid->addWidget(new QLineEdit("a",$this), $row, $column, 0);
to segfault. (Garbage collector kills the referenced QLineEdit?)
(I have the same controls in my program and they work well. Anyway, I
don't think anyone would create a control without some way to access it
(i.e. a class member object). Then I just wonder why the original T6
works. :-) )
Ferenc
piotr mali=C5=84ski wrote on Freitag, 20. Januar 2006 17:41:
> In some lines in the configure there is:
> qt/classes/qpainter.cpp \TAB HERE (or space)
> the TAB has to be removed.... kate even highlights the \ in different col=
or
> :)
I fixed that yesterday ;-) Updating your svn copy should help, then run php=
ize=20
again.
> second thing is -laudio. I still have problem with it. If -laudio flag
> is set in configure it will die - "can't create executables". When I
> remove it it compiles and work :) Is it something from QT?
I copied it from the Makefile generated by qmake. I know this way is not ve=
ry=20
specific. Hope I will have the time to write a more specific automake file.
=2D-=20
Thomas
In some lines in the configure there is:
qt/classes/qpainter.cpp \TAB HERE (or space)
the TAB has to be removed.... kate even highlights the \ in different color=
:)
second thing is -laudio. I still have problem with it. If -laudio flag
is set in configure it will die - "can't create executables". When I
remove it it compiles and work :) Is it something from QT?
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/php-qt/mailman/php-qt-users/?viewmonth=200601&viewday=20 | CC-MAIN-2017-09 | refinedweb | 798 | 75.81 |
This document demonstrates how to set up a connection to Sun's
Java DB
(which is based on the Apache Derby
database) in NetBeans IDE. Once a connection is made, you can begin working
with the database in the IDE, allowing you to create tables, populate
them with data, run SQL
Sun Java
System Application Server 9.0, Platform Edition, and is now included in
JDK 6 as well.
Note: If you are using NetBeans 6.x, see the
updated version of this tutorial.
Expected duration: 25 minutes
The following topics are covered below:
Before you start this tutorial, you must make sure you have the following
software installed on your computer:
Note: If you are downloading JDK 6, the Java DB database will be included
in your installation. You can also download the
Sun
Java System Application Server, which includes Java DB. When registering
the application server in NetBeans IDE, Java DB will be automatically registered
as well. Alternatively, consider downloading the
Java EE 5 Tools Bundle,
which includes both NetBeans IDE and Sun Java System Application Server.
If you have the Sun Java System Application Server registered in NetBeans IDE, the Java DB
will already be registered for you. You can skip ahead to Starting
the Server and Creating a Database. If you downloaded the Application Server and
need help registering it in NetBeans IDE, see Registering a Sun Java System Application
Server Instance in the IDE's Help Contents (F1). If you just downloaded Java DB on
its own, do the following:
Before continuing further, it is important to understand the components found in Java DB's
root directory:
Now that the database is configured, you can register it in the IDE:
Once your database is registered with the IDE, the Java DB Database menu item appears
under Tools in the main menu. This menu item allows you to start and stop the
database server, as well as create a new database. To start the database server:
So far, you have successfully started the the database server and created a database
in NetBeans IDE. However, in order to start working with the new database in the IDE, you
need to create a connection. To connect to contact_database:
Because you just created contact_database, it obviously does not yet contain
any tables or data. In NetBeans IDE you can add a database table by either
using the Create Table dialog, or by inputing an SQL query and running it directly
from the SQL editor. You can explore both methods:
CREATE TABLE "CONTACTS" (
"ID" INTEGER not null primary key,
"FIRST_NAME" VARCHAR(50),
"LAST_NAME" VARCHAR(50),
"TITLE" VARCHAR(50),
"NICKNAME" VARCHAR(50),
"DISPLAY_FORMAT" SMALLINT,
"MAIL_FORMAT" SMALLINT,
);
Now that you have created your first table in the contact_database, you can start
populating it with data. In order to add a complete record (row) to the CONTACTS table,
you need to supply a value for every field present in the table. You can use the SQL
Editor to formulate a simple query to add a new contact record:
insert into "NBUSER"."CONTACTS" values (1,'Monty','Python','Mr.','Bruiser',3,10,'monty.python@flyingcircus.com')
Issuing commands from an external SQL script is a popular way to manage your
database. You may have already created an SQL script elsewhere, and want to
import it into NetBeans IDE to run it on a specified database.
For demonstrative purposes, download
friends.sql
and save it to a location on your computer. This script creates a new table named
Friends and populates it with data. To run this script on our
contact_database:. Use the sample database that
comes packaged with Java DB when you download the
Sun Java System
Application Server. This process is essentially carried out in two steps: You
must first grab the table definition of the selected table, then you can recreate
the table in your chosen database.
This concludes the Working with the Java DB (Derby) Database in NetBeans IDE tutorial. This
tutorial demonstrated how to set up a connection to the Java DB database in NetBeans IDE.
It then demonstrated how to create, view and modify tables, as well as run SQL queries on tabular
data while using NetBeans IDE.
For related and more advanced tutorials, see the following resources:
top
Bookmark this page | http://www.netbeans.org/kb/55/derby-demo.html | crawl-002 | refinedweb | 712 | 50.87 |
Alright, I know that this might be really easy for some people, but I am having one heck of a time figuring this out! I was wondering if someone could please help me figure this out...I am in need and this code needs to be done by tomorrow evening, so i was wondering if I could get some straight answers here. :P I am using Dev C++, and here is my code.
If someone could please lead me in the right direction for sorting my employee struct after the data is entered, then I would be so happy!!! Thank you so much in advance!If someone could please lead me in the right direction for sorting my employee struct after the data is entered, then I would be so happy!!! Thank you so much in advance!Code:#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> using namespace std; #define ePos 3 // Define the amount of employees // Create the structure for the employees struct Employee_t { string eFName, eLName, eStreetName, eCity, eState; int eStreetNum, eZip, eID; }employee [ePos]; // Set a default array to store employees // Declare the fuctions before main process for use void printEmployee (Employee_t Employee); void employeeSort(string array[], int len); // Start main int main() { // Define the position of the array for employee int pos; // Ask for input of employees using a for statement to fill the array for (pos = 0; pos < ePos; pos++) { cout << "\nEnter employee's -\n"; // Ask and store employee's name cout << "First Name: "; cin >> employee[pos].eFName; // Ask and store employee's last name cout << "Last Name: "; cin >> employee[pos].eLName; // Ask and store employee's street number cout << "Street Number: "; cin >> employee[pos].eStreetNum; // Ask and store employee's street number cout << "Street Name: "; cin >> employee[pos].eStreetName; // Ask and store employee's city cout << "City: "; cin >> employee[pos].eCity; // Ask and store employee's state cout << "State: "; cin >> employee[pos].eState; // Ask and store employee's zip code cout << "Zip Code: "; cin >> employee[pos].eZip; // Ask and store employee's customer ID cout << "Customer ID: "; cin >> employee[pos].eID; } // Display the entered employees cout << "\nYou have entered these employees: \n"; // Used to display employee's information for (pos = 0; pos < ePos; pos++) { printEmployee (employee[pos]); } employeeSort(employee[pos], 4); // Pause before safe shutdown of program system("PAUSE"); return EXIT_SUCCESS; } // Print the employee's information void printEmployee (Employee_t Employee) { cout << "\n" << Employee.eLName << ", " << Employee.eFName << endl; cout << Employee.eStreetNum << " " << Employee.eStreetName << endl; cout << Employee.eCity << ", " << Employee.eState << " " << Employee.eZip << endl; } // Sorting function for employees void employeeSort(string array[], int len) { int i, j; string check; for(i=1; i<len; i++) { check = array[i]; for(j=i; j>=1 && (check < array[j-1]); j--) { array[j] = array[j-1]; array[j-1] = check; } } } | http://cboard.cprogramming.com/cplusplus-programming/126837-struct-array-sorting-frustrating.html | CC-MAIN-2015-35 | refinedweb | 465 | 53.61 |
The hook() decorator accepts two parameters: object, and method. The object parameter specifies the object in which defines the method to be hooked. The method parameter specifies the method to be hooked. The decorated function, the actual hook, must specify the same operation signature as the original method invocation.
For instance, lets say we want to hook the Package.get_name() method. We would define the hook as follows.
Obviously not the most useful hook in the world, we replace the package name that would have been retrieved with a static string. In fact, the original Package.get_name() call is never actually invoked. It is replaced entirely.
#ECP hook demonstration
from enomalism2.model import Package, hook
@hook(Package, Package.get_name)
def hook_get_name(fn, self):
"""Hook into the Package.get_name() method."""
return 'My Package'
Hooks can also be modeled as event subscriptions, where in the system, each method invocation can be considered a published event. Each defined hook can be considered an event subscription. For example, lets modify the previous example to simulate a pre and post event situation.
Here, our pre-event functionality logs the fact that we are attempting to retrieve the package name. Our post-event functionality logs the fact that the package name retrieval was successful. To contract the first example, the original method is invoked here. We are simply extending the functionality. What is interesting is the fact that we can do so in any direction. We can add pre-invocation functionality, post-invocation functionality; we can replace the invocation entirely if need be.
#ECP hook pre/post event demonstration
import logging
from enomalism2.model import Package, hook
@hook(Package, Package.get_name)
def hook_get_name(fn, self):
"""Hook into the Package.get_name() method."""
logging.info("Attempting to get the package name...")
result=fn(self)
logging.info("Success.")
return result | http://www.boduch.ca/2009/01/understanding-hooks-in-ecp.html | CC-MAIN-2017-43 | refinedweb | 301 | 52.15 |
I’m pleased to announce my new Bundling and Minification tutorial. Bundling and Minification (B/M) can significantly improve your first page hit download time – something that is very critical for mobile targeted applications.
B/M was introduced in ASP.NET 4.5 Beta, but the RC version has significant improvements. For a good overview of the changes between Beta and RC, see super PM Howard Dierking’s blog entry Web Optimization in Visual Studio 2012 RC.
Although this tutorial is specifically aimed at ASP.NET MVC 4, you can use B/M with Web Forms and Web Pages.
The RC version of B/M doesn’t work with Azure caching providers, but that has been fixed and the RTM version will work with Azure caching providers.
The ASP.NET B/M framework is contained in System.Web.Optimization namespace. There are other B/M frameworks such as Matt Wrock’s popular RequestReduce.
We haven’t stopped working on B/M. Let me know what features we should consider in the future.
In addition to blogging, I use Twitter to make quick posts and share links. My Twitter handle is: @RickAndMSFT
(no need to publish this comment)
B/M… heh.
Hi Rick,
I wonder if a feature like the one described here stackoverflow.com/…/a-localized-scriptbundle-solution in stackoverflow, would be possible through the ASP.NET B/M framework.
I would need to conditionaly devide which script to bundle depending on localization.
Thanks
Hi Indice – Thanks for pointing out the SO question. Hao Kung (the lead developer on B/M) answered it.
Pardon, if very basic question – How do we add a Bundle.config to an MVC 4 web application? and where? | https://blogs.msdn.microsoft.com/rickandy/2012/06/13/asp-net-bundling-and-minification/ | CC-MAIN-2017-04 | refinedweb | 283 | 68.16 |
This action might not be possible to undo. Are you sure you want to continue?
2 User’s Guide
December 2003
This manual copyright 1997-2003 Perforce Software. All rights reserved..
Table of Contents
Preface
About This Manual ..................................................... 11
Administering Perforce?..................................................................................11 Please Give Us Feedback .................................................................................11
Chapter 1
Product Overview....................................................... 13
Perforce Server and Perforce Client Programs.............................................14 Moving files between the clients and the server......................................14 File conflicts...................................................................................................15 Labeling groups of files ...............................................................................15 Branching files ..............................................................................................15 Job tracking ...................................................................................................16 Change notification ......................................................................................16 Protections .....................................................................................................17 Other Perforce Clients......................................................................................17 P4Win .............................................................................................................17 P4Web.............................................................................................................17 Merge Tools .......................................................................................................17 P4 resolve.......................................................................................................18 P4WinMerge..................................................................................................18 Other merge utilities ....................................................................................18 Defect Tracking Systems ..................................................................................18 Perforce jobs ..................................................................................................18 P4DTI integrations with third-party defect trackers...............................19 Plug-Ins, reporting and tool integrations......................................................19 IDE Plug-ins ..................................................................................................19 P4Report and P4SQL ...................................................................................20 P4OFC ............................................................................................................20
Chapter 2
Connecting to the Perforce Server............................................................. 21
Before you begin ...............................................................................................21 Setting up your environment to use Perforce...............................................21
Perforce 2003.2 User’s Guide
3
.............................................. 41 Editing Existing Client Specifications................................................. 23 Chapter 3 Perforce Basics: Quick Start. 30 Editing files in the depot ............................................................................................................................................. 26 Naming the client workspace ........ 39 Using views ................................................................Table of Contents Telling Perforce clients where the server is..................... 37 Wildcards .......................................................... 25 File configurations used in the examples........................................... 22 Verifying the connection to the Perforce server ..... 26 Describing the client workspace to the Perforce server............................. 34 Basic reporting commands ........ 45 Multiple workspace roots for cross-platform work...... 39 Wildcards in views ................................... 44 Deleting an existing client specification............... 38 Mapping the Depot to the Client Workspace ..................................................................................... 47 Referring to Files on the Command Line .............................................. 28 Updating the depot with files from your workspace ........................................................................................................................................................................................................................................................................................................................................................................................................................................... 41 Types of mappings ...................................... 48 Local syntax.............................................................................................................. 29 Adding files to the depot................... 26 Copying depot files into your workspace ................................. 37 Description of the Client Workspace........................................................................................................................................... 45 Client specification options.... 48 4 Perforce 2003........................................................................... 25 Underlying concepts ...................................................................................................... 33 Backing out: reverting files to their unopened states .... 31 Deleting files from the depot ............................... 38 Wildcards and “p4 add” ............................................................................. 38 Multiple depots..................................................................................... 34 Chapter 4 Perforce Basics: The Details.................................................................................................... 25 Setting up a client workspace ... 32 Submitting with multiple operations .........................2 User’s Guide ................................................... 47 Line-ending conventions (CR/LF translation)....................................................................
.61 Chapter 5 Perforce Basics: Resolving File Conflicts....................................................66 Performing Resolves of Conflicting Files ........73 Preventing multiple checkouts with +l files.......................2 User’s Guide 5 ............................................................................73 Resolves and Branching................................................................................48 Providing files as arguments to commands ..............................................................74 Resolve Reporting.....................................................50 Name and String Limitations......................................................................................................61 General Reporting Commands..........................................................................................56 Forms and Perforce Commands ..................66 File revisions used and generated by “p4 resolve” ........Table of Contents Perforce syntax.........................51 Using revision specifications without filenames .......................67 Types of conflicts between file revisions ..............................................49 Wildcards and Perforce syntax............. Writing forms to standard output....................65 How Do I Know When a Resolve is Needed?....55 Base file types........................................................68 Using Flags with Resolve to Automatically Accept Particular Revisions .......................................................................................................72 Preventing multiple resolves with p4 lock ..........................60 Reading forms from standard input........................................................72 Locking Files to Minimize File Conflicts................................ 63 RCS Format: How Perforce Stores File Revisions .................................54 Revision Ranges.........................................................................................................................................................................................................................................................................68 The “p4 resolve” options...........................................................................................................................................................51 Specifying Older File Revisions.................................50 Illegal characters in filenames and Perforce objects ................................................................................................................................................................................63 Use of “diff” to determine file revision differences.....................74 Perforce 2003.............65 Scheduling Resolves of Conflicting Files ..................................................................................................65 Why “p4 sync” to Schedule a Resolve? .........................71 Binary files and “p4 resolve” .............................................................50 Name and description lengths .....................................................67 How the merge file is generated ....................63 Only the differences between revisions are stored..............................................................................54 File Types ......
....................................... 92 Tagging specific files and revisions with p4 labelsync........ 88 When submit of the default changelist fails..................................................... 94 Using label views........................ the changelist is assigned a number ............................................................................................................................................................................................................. 79 Working Detached .... 89 Deleting Changelists................................................................................................................................................................ 92 Labeling all revisions in your workspace .................................................... 91 Creating a new label.............................. 85 Working with the Default Changelist ................................................. 90 Chapter 8 Labels ................................................................................................................................. 93 Listing files tagged by a label ....................... 91 Using labels............................... 94 Referring to files using a label ......................................... 87 Working With Numbered Changelists ......................................................................... 83 Revision histories and renamed files ................................................................. 88 Perforce May Renumber a Changelist upon Submission ........................... 77 Reconfiguring the Perforce Environment with $P4CONFIG ..... 82 Renaming Files .................... 93 Previewing labelsync’s results.................................................................................... 81 Refreshing files ..................................................................................................................................................... 86 Creating Numbered Changelists Manually ............................................................................................................................................................................... 78 Command-Line Flags Common to All Perforce Commands . 95 6 Perforce 2003......... 93 Preventing inadvertent tagging and untagging of files .....Table of Contents Chapter 6 Perforce Basics: Miscellaneous Topics ...................................................... 82 Recommendations for Organizing the Depot........................................................ 77 Perforce Passwords................................... 91 Why not just use changelist numbers? ..................................................................................................................2 User’s Guide .................... 81 Finding changed files with “p4 diff” ................................................ 83 Chapter 7 Changelists ....................................................................................................... 81 Using “p4 diff” to update the depot . 89 Changelist Reporting.................................................... 93 Untagging files with p4 labelsync. 87 Automatic Creation and Renumbering of Changelists ..............................
..110 For More Information ................................................115 Using and escaping wildcards in jobviews ..............................................................................................................................................................................................................................................................103 Branch Specification Usage Notes...................................................113 Viewing jobs by content with jobviews.......... 111 Creating and editing jobs using the default job specification...................107 Integrating specific file revisions ....................108 The integration algorithm .........................................................................107 Re-integrating and re-resolving files ...................................111 Job Usage Overview.......................115 Negating the sense of a query ...................................................................................108 The yours......114 Finding jobs by field values ...................................100 Branching and Merging..................................... and base files ....................................................................114 Finding jobs containing particular words..............2 User’s Guide 7 ..................................................112 Creating and editing jobs with custom job specifications .110 Chapter 10 Job Tracking .......................................................................................................99 When to Create a Branch .........................................................103 Branching and Merging....108 Integrate’s actions................................................................................105 Integration Usage Notes ....................................109 Integration Reporting............................................96 Label Reporting............................. Method 2: Branching with Branch Specifications...........................95 Details: How p4 labelsync works ..............................................................................................Table of Contents Deleting labels..............................................................102 Propagating changes from branched files to the original files ............................................... 99 What is Branching?..........................................................108 How Integrate Works .....................................................................107 Advanced Integration Functions... Method 1: Branching with File Specifications ..........................97 Chapter 9 Branching ............99 Perforce’s Branching Mechanisms: Introduction ..................................... theirs......115 Perforce 2003..............................................................................................................................................................106 Deleting Branches ......................................................101 Propagating changes between branched files ........................................................................................................................................................................................................................................................101 Creating branched files..................................................................
.................................................................................. 132 Branch and Integration Reporting. 137 Appendix A Installing Perforce ......................................................................................... fixes............... 140 Creating a Perforce server root directory............................................................................................................................................................................................................................................................................................................................................ 123 File metadata .............118 Automatic update of job status ................................................................................ 139 Download the files and make them executable ..................................................................................................................................117 Linking jobs to changelists with the JobView: field.................................................................................................................................... 133 Job Reporting.............................................. 120 Chapter 11 Reporting and Data Mining............................................. 136 Comparing the change content of two file sets .................................................. and changelists .........................116 Linking Jobs to Changelists.. 125 File contents............. 140 8 Perforce 2003................................................................................................................................................................119 What if there’s no status field? ........................................ 131 Labels........................................................................................................................... 139 Getting Perforce ........................................ 135 System Configuration........................................................................................................................................................2 User’s Guide ........ 133 Jobs.............................................117 Linking jobs to changelists with p4 fix ... 133 Basic job information ............ 130 Viewing changelists that meet particular criteria ........ 136 Reporting with Scripting ............................................................................ 139 Installing Perforce on UNIX ..........Table of Contents Using dates in jobviews........................... 120 Integrating with External Defect Tracking Systems ..................................................................... 123 Files ................................................ 130 Files and jobs affected by changelists ........................................................................... 123 Relationships between client and depot files ........... 140 Telling the Perforce server which port to listen to................................................................ 134 Reporting for Daemons.......................................................................118 Linking jobs to changelists from within the submit form ...............116 Comparison operators and field types ........................................ 120 Job Reporting Commands ............................................ 126 Changelists...................................... 120 Deleting Jobs......... 135 Special Reporting Flags...........................................................................................
Table of Contents
Starting the Perforce server.......................................................................140 Stopping the Perforce server.....................................................................141 Telling Perforce clients which port to talk to..........................................141 Installing Perforce on Windows ...................................................................141 Terminology note: Windows services and servers ................................142 Starting and stopping Perforce on Windows .........................................142
Appendix B
Environment Variables ............................................. 143
Setting and viewing environment variables...............................................144
Appendix C
Glossary ...................................................................... 145 Index ........................................................................... 155
Perforce 2003.2 User’s Guide
9
Table of Contents
10
Perforce 2003.2 User’s Guide
Preface
About This Manual
This is the Perforce 2003.2 User’s Guide. It teaches the use of Perforce’s Command-Line Client. Other Perforce clients such as P4Win (the Perforce Windows Client) are not discussed here. If you’d like documentation on other Perforce client programs, please see our documentation pages, available from our web site at. Although you can use this guide as a reference manual, we intend it primarily as a guide/tutorial on using Perforce. The full syntax of most of the Perforce commands is explicitly not provided here; in particular, only a subset of the available flags are mentioned. For a complete guide to Perforce, please see the Perforce Command Reference, or the on-line help system. If you will be using Perforce on any operating system other than UNIX, please consult the Perforce platform notes for that OS. Chapters 2 through 4 of this manual comprise our Getting Started guide. Newcomers to Perforce should start there, and move to subsequent chapters as needed.
Administering Perforce?
If you’re administering a Perforce server, you’ll need the Perforce System Administrator’s Guide, which contains all the system administration material formerly found in this manual. If you’re installing Perforce, the Perforce System Administrator’s Guide is also the place to start.
Please Give Us Feedback.
Perforce 2003.2 User’s Guide
11
Preface: About This Manual 12 Perforce 2003.2 User’s Guide .
but software configuration management (SCM) has been defined in many different ways. • Some release management facilities are offered. development branches. it can manage any sort of on-line documents. Perforce can be used to store revisions of a manual. multiple users can edit their own copies of the same file.Chapter 1 Product Overview Perforce facilitates the sharing of files among multiple users. and a few other things. defect tracking.2 User’s Guide 13 . or in any sort of needed file set. release management. this capability is known as defect tracking or change management. source files managed by Perforce are easily built by Jam. file sharing. The Jam tool and Perforce meet at the file system. It is a software configuration management tool. • Perforce supplies some lifecycle management functionality. files can be kept in release branches. Perforce 2003. users can work with files stored on a central server or with files replicated on a proxy server. to manage Web pages. • Change review functionality is provided by Perforce. SCM has been described as providing version control. • Perforce provides facilities for concurrent development. • Perforce supports distributed development. Although Perforce was built to manage source files. • Although a build management tool is not built into Perforce. we do offer a companion open source product called Jam. Perforce can track the file revisions that are part of a particular release. It’s worth looking at exactly what Perforce does and doesn’t do: • Perforce offers version control: multiple revisions of the same file are stored and older revisions are always accessible. build management. • Bugs and system improvement requests can be tracked from entry to fix. or to store old versions of operating system administration files. this functionality allows users to be notified by email when particular files are changed. depending on who’s giving the definition.
Each user works on a client machine. Perforce users can retrieve files from the depot into their own client workspaces. This manual assumes that you or your system administrator have already installed both p4 and p4d. Linux. This approach allows users to simultaneously update all files related to a bug fix or a new feature. The p4d program must be run on a UNIX or Windows machine. these directories are called client workspaces. and keeps track of users. Macintosh. These file changes can be sent to the depot in a single changelist. It manages the shared file repository. For example. The Perforce clients can be distributed around a local area network. • Perforce client programs (for instance. and other Perforce metadata. and communicate with p4d using TCP/IP. Perforce client programs can be run on many platforms. edit. You’ll find installation instructions in the Perforce System Administrator’s Guide. Moving files between the clients and the server Users create. also available at our Web site.Chapter 1: Product Overview Perforce Server and Perforce Client Programs Perforce has a client/server architecture. Windows. workspaces. Client programs send users’ requests to the Perforce Server (p4d) for processing. VMS. The client programs communicate with the server using TCP/IP. dialup network. at their command. edited. and resubmitted to the depot for other users to access. 14 Perforce 2003. When a new revision of a file is stored in the depot. Files that have been edited within a client workspace are sent to the depot using a changelist.2 User’s Guide . another added. and NeXT hosts. The following programs do the bulk of Perforce’s work: • The Perforce Server (p4d) runs on the Perforce server machine. and another deleted. and delete files in their own directories on client machines. Perforce clients can also reside on the same host as the server. or any combination of these topologies. the server. in which users at other computers are connected to one central machine. a Perforce client program transfers files to and from the Perforce server. the old revisions are kept and are still accessible. p4) run on Perforce client machines. including UNIX. wide area network. which is a list of files and instructions that tell the depot what to do with those files. one file might have been changed in the client workspace. or none of them are. which is processed atomically: either all the changes are made to the depot at once. Perforce commands are used to move files to and from a shared file repository on the server known as the depot. BeOS. where they can be read.
This process generates a merge file from the conflicting files. and then the second user tries to do the same thing. Labeling groups of files It is often useful to mark a particular set of file revisions for later access. Labels. this name is a label for the user-determined list of files. For example. This list of files can be assigned a name. Suppose that one source file needs to evolve in two separate directions. suppose two users copy the same file from the depot into their workspaces. File conflicts When two users edit the same file. For details about labels. their changes can conflict. but this is not always the case. see Chapter 8.1. Perforce Basics: Quick Start and Chapter 4. If Perforce were to unquestioningly accept the second user’s file into the depot. and Perforce 2003. The Perforce Server is responsible for tracking the state of the client workspace. see Chapter 5. For example. it has been assumed that all changes to files happen linearly. which determines which files in the depot can be accessed by that client workspace. When a file conflict is detected. One client workspace might be able to access all the files in the depot. The first user sends his version of the file back to the depot. the release engineers might want to keep a list of all the file revisions that comprise a particular release of their program. Branching files Thus far. while another client workspace might access only a single file. For basic information about using Perforce. Perforce allows the user experiencing the conflict to perform a resolve of the conflicting files. Perforce knows which files a client workspace has. which contains all the changes from both conflicting versions.2 User’s Guide 15 . and which files have write permission turned on. Perforce Basics: The Details. the first user’s changes would not be included in the latest revision of the file (known as the head revision). the label can be used to copy its revisions into a client workspace.0. see Chapter 3. The resolve process allows the user to decide what needs to be done: should his file overwrite the other user’s? Should his own file be thrown away? Or should the two conflicting files be merged into one? At the user’s request. and each edits his copy of the file in different ways. At any subsequent time. To learn how to resolve file conflicts.Chapter 1: Product Overview Each client workspace has its own client view. where they are. Perforce Basics: Resolving File Conflicts. Perforce will perform a three-way merge between the two conflicting files and the single file that both were based on. such as release2. This file can be edited and then submitted to the depot. perhaps one set of upcoming changes will allow the program to run under VMS.
see Chapter 9.2 User’s Guide . Change notification Perforce’s change review mechanism allows users to receive email notifying them when particular files have been updated in the depot. The fields contained in your system’s jobs can be defined by the Perforce system administrator. or daemon. or write your own daemons. For details about branching. Perforce’s job tracking mechanism does not implement all the functionality that is normally supplied by full-scale defect tracking systems. please see Chapter 10. and whether the fix has been propagated to other codelines. allow changelists to be validated before they’re submitted to the depot. By default. what files were modified to implement the fix. The files for which a particular user receives notification are determined by that user. Clearly. Its simple functionality can be used as is. like “please make the program run faster. Perforce’s Inter-File Branching™ mechanism allows any set of files to be copied within the depot. integrate Perforce with third-party defect tracking systems.Chapter 1: Product Overview another set will make it a Mac program. Job Tracking. or it might be a system improvement request. a changelist represents work actually done. To read more about jobs. 16 Perforce 2003. like “the system crashes when I press return”. but changes in either codeline can be propagated to the other. Perforce’s job tracking mechanism allows jobs to be linked to the changelists that implement the work requested by the job. called triggers. A job might be a bug description. the new file set. or it can be integrated with third-party job tracking systems through P4DTI Perforce Defect Tracking and Integration.” Whereas a job represents work that is intended to be performed. Change review is implemented by an external program. which can be customized. who fixed it. A job can later be looked up to determine if and when it was fixed. consult the Perforce System Administrator’s Guide. Perforce can be made to run external scripts whenever changelists are submitted. These scripts. or codeline. two separately-evolving copies of the same files are necessary. Job tracking A Job is a generic term for a plain-text description of some change that needs to be made to the source code. Branching. To learn how to set up the change review daemon. evolves separately from the original files.
Macintosh.perforce.Chapter 1: Product Overview Protections Perforce provides a protection scheme to prevent unauthorized or inadvertent access to the depot.com/perforce/products/p4win.2 or newer. Merge tools often use color-coding to highlight differences and some even include the option to automatically merge non-conflicting changes. click. Protections at the IP address level are as secure as the host itself.com/perforce/products/p4web.html P4Web The Perforce web client turns most any Web browser into a complete SCM tool. see the product page at:. and runs on Unix. drag. Other Perforce client programs. simplifying the process of resolving conflicts that result from parallel or concurrent development efforts. For more about P4Web. and drop your way through Perforce tasks. Other Perforce Clients The Perforce Command-Line Client (p4) is not the only Perforce client program. Because Perforce usernames are easily changed.html Merge Tools Interactive merge tools allow you to display the differences between file versions. Perforce 2003. P4Web will work with a Perforce Server at Release 99.2 User’s Guide 17 . may be downloaded from the Perforce web site. Permissions can be granted or denied based on users’ usernames and IP addresses. see the product page at:. not security. We discuss protections in the Perforce System Administrator’s Guide. it shows you your work in progress at a glance and lets you point. P4Win The Perforce Windows Client provides a native Microsoft Windows user interface for all SCM tasks. and Windows. the Perforce Windows Client. including P4Win. The protection mechanism determines exactly which Perforce commands are allowed to be run by any particular client. Using the familiar Windows® Explorer look and feel. For more about P4Win. or can be granted or denied to entire groups of users.perforce. protections at the user level provide safety.
perforce. P4WinMerge P4WinMerge is Perforce’s graphical three-way merge and conflict resolution tool for Windows. Conversely. a Perforce Server is necessary.perforce. management of digital assets in environments where concurrent development is not encouraged).html Other merge utilities Perforce is easily integrated with third-party merge tools and diff utilities. In addition to providing basic built-in defect tracking. P4WinMerge is a stand-alone Windows application.com/perforce/products/p4winmerge. P4 resolve Perforce’s “p4 resolve” command includes built-in merge capability for the console environment. issues and status entered into your defect tracking system can be accessed by Perforce users. or P4Web. In situations where concurrent file check-out is not desirable. Perforce can be configured to restrict this capability to specific file types or file locations (for instance. see:. Users need only change an environment variable (such as P4MERGE or P4DIFF) to point to their merge tool of choice.com/perforce/products/merge. it does not require a Perforce Server when used by itself. see:. For more about P4WinMerge. 18 Perforce 2003. P4Win.Chapter 1: Product Overview Perforce offers full support for both parallel and concurrent development environments. Perforce jobs Perforce’s built-in defect tracking and reporting features are available to all Perforce users. However. when invoked from within a Perforce client program like the Perforce Command-Line Client. Perforce is integrated with several leading defect tracking systems.2 User’s Guide . P4WinMerge uses the “3-pane” approach to display and edit files during the merge process. For more about using third-party merge tools with Perforce. Activity performed by Perforce users can be automatically sent to your defect tracking system.html Defect Tracking Systems Perforce provides a number of options for defect tracking.
For more about Perforce IDE Plug-ins. or generate reports relating issues to files or codelines.html Perforce 2003. so that you don’t have to switch between your defect tracker and SCM tool and enter duplicate information about your work. including a list of defect tracking systems for which P4DTI integrations have already been built. see: be automatically entered into your defect tracking system by P4DTI. find the work that was done to resolve an issue.com/perforce/products/defecttracking.perforce. reporting tools.2 or newer. some companies prefer to use the defect tracking system they’ve already got in place. P4DTI runs on Unix and Windows. can be converted automatically to Perforce metadata for access by Perforce users.Chapter 1: Product Overview P4DTI integrations with third-party defect trackers Although Perforce provides built-in defect tracking. and workflow rules to manage complex processes. Perforce Defect Tracking Integration (P4DTI) is an open source project specifically designed to integrate Perforce with other defect tracking systems by replicating Perforce jobs and changelist numbers to their equivalents in the other system.html Plug-Ins.com/perforce/products/plugins-ide. Conversely. see:. propagation of changes into release branches. P4DTI lets you take advantage of third-party user interfaces. While Perforce jobs can be used without additional software for straightforward issue tracking. databases. P4DTI also links changes made in Perforce with defect tracker issues.perforce. and so on.2 User’s Guide 19 . and Metrowerks CodeWarrior. For more about using third-party defect tracking systems with Perforce. Borland JBuilder. you can integrate Perforce with any third-party defect tracking or process management software. P4DTI uses Perforce’s built-in “jobs” feature to mirror data in defect tracking systems. and so forth . change orders. P4DTI connects your defect tracking system to Perforce. It can be used with a Perforce Server on any platform at Release 2000. bug fixes. reporting and tool integrations IDE Plug-ins Perforce IDE Plug-ins allow developers to work with Perforce from within integrated development environments (IDEs) such as Microsoft Developer Studio. issues and status entered into your defect tracking system bug reports. With P4DTI. or want to install a different defect tracker for use with Perforce.enhancements. Activity in your Perforce depot . making it easy to find out why a change was made. work assignments.
the Perforce ODBC Data Source. This menu provide easy access to common Perforce SCM commands.2 User’s Guide .com/perforce/products/p4report.perforce. For more about P4Report and P4SQL. Microsoft® Access® and Excel®. P4Report can also be integrated with some defect tracking systems.Chapter 1: Product Overview P4Report and P4SQL The Perforce Reporting System (P4Report) offers query and reporting capability for Perforce depots. Based on P4ODBC. and Microsoft Powerpoint. P4Report also includes the Perforce SQL Command-Line Client (P4SQL).perforce. so that users never have to leave familiar office applications to work with documents under Perforce control.html P4OFC The Perforce Plug-in for Microsoft Office (P4OFC) adds a “Perforce” menu to Microsoft Word. P4Report can be used by ODBCcompliant reporting tools including Crystal Reports®.html 20 Perforce 2003. see:. For more about P4OFC. Microsoft Excel. see:. P4SQL can be used to execute SQL statements either interactively or using scripts.
• The p4 program runs on each Perforce client. clients.Chapter 2 Connecting to the Perforce Server Perforce uses a client/server architecture. and communicates with p4d via TCP/IP.2 User’s Guide 21 . Every running Perforce system uses a single server and can have many clients. Setting up your environment to use Perforce A Perforce client program needs to know two things in order to talk to a Perforce server: • the name of the host on which p4d is running. we strongly encourage you to read the full installation instructions in the Perforce System Administrator’s Guide. and • the port on which p4d is listening Perforce 2003. if you’re installing Perforce from scratch). you’ll also have to install the Perforce server before continuing. If you’re installing a production server. See the appendix. Before you begin This chapter assumes that your system administrator has already set up a Perforce server (p4d) for you. these files are transferred to and from a shared file repository located on a Perforce server. This address is stored in the P4PORT environment variable. As mentioned earlier. “Installing Perforce” on page 139. and that it is already up and running. and other Perforce metadata. It manages the shared file repository. protections. or are planning on extensive testing of your evaluation server. If this is not the case (for instance. for information on how to install the server. and keeps track of users. two programs do the bulk of Perforce’s work: • The p4d program runs on the Perforce server. The information in the appendix is intended to help you install a server for evaluation purposes. Each Perforce client program needs to know the address and port of the Perforce server with which it communicates. Files are created and edited by users on their own client hosts. It sends the users’ requests to the p4d server program for processing.
For example: If the server is running on.. • If you’ve just installed the Perforce server yourself. Once this has been done. listening on port 1666.2 User’s Guide . having configured the server on a specific host to listen to a specific port.com:1818 The definition of P4PORT can be shortened if the Perforce client is running on the same host as the server.com and is listening to port. you’ll need to know the name of the host where p4d is located. if not. you’ll need to set it yourself.Chapter 2: Connecting to the Perforce Server These are set via a single environment variable.. Once you’ve obtained the host and port information. it’s possible that your system administrator has already set P4PORT for you. only the port number need be provided to p4. 22 Perforce 2003. If your site is already using Perforce. 3435 1818 set P4PORT to: dogs:3435 x. you already know this.. Either way. you should re-verify the connection with p4 info.. For example: If the server is running on. In this case. dogs x. you should verify your client’s connection to the Perforce server with the p4 info command... the definition of P4PORT for the p4 client can be dispensed with altogether. If p4d is running on a host named or aliased perforce.. as described below. <same host as the p4 client> perforce and is listening to port. • If you’re connecting to an existing Perforce installation. Perforce is ready to use. 1543 1666 set P4PORT to: 1543 <no value needed> When P4PORT has been set. where host is the name of the host on which p4d is running. after setting P4PORT to point to your server. Note See “Setting and viewing environment variables” on page 144 for information about how to set environment variables for most operating systems and shells.. Telling Perforce clients where the server is To use Perforce. you’ll have to ask your system administrator for the host and port of the Perforce server. P4PORT. and the number of the TCP/IP port on which it’s listening. set your P4PORT environment variable to host:portNum. and portNum is the port to which it is listening.
check $P4PORT. Windows On Windows platforms. it displays the host and port number on which p4d is listening. if the value is anything else. Current directory: /usr/edk Client address: 192.Chapter 2: Connecting to the Perforce Server Verifying the connection to the Perforce server To verify the connection. If the P4PORT environment variable is correctly set. you receive a variant of this message: Perforce client error: Connect to server failed. perforce: host unknown. In the above example. everything is fine. then P4PORT has not been set at all. registry variables are preferred over environment variables. If. you’ll need to set the value of P4PORT.168. If the value you see in the third line of the error message is perforce:1666 (as above). you’ll see something like this: User name: edk Client name: wrkstn12 Client host: wrkstn12 Client unknown.123:1818 Server address: p4server:1818 Server root: /usr/depot/p4d Server date: 2000/07/28 12:11:47 -0700 PDT Server version: P4D/FREEBSD/2000.0. and you can set these with command p4 set. type p4 info at the command line.1/16375 (2000/07/25) Server license: P4 Admin <p4adm> 20 users on unix (expires 2001/01/01) The Server address: field shows which Perforce server to which the client has connected. P4PORT has been incorrectly set. In either case. then P4PORT has not been correctly set. TCP connect to perforce:1666 failed. Perforce 2003.2 User’s Guide 23 . however.
2 User’s Guide .Chapter 2: Connecting to the Perforce Server 24 Perforce 2003.
will work with their Elm files in the following locations: User Username edk lisag Client Workspace Name eds_elm lisas_ws Top of own Elm File Tree /usr/edk/elm /usr/lisag/docs Ed Lisa Perforce 2003. You’ll learn how to set up a workspace. Ed and Lisa. The Elm examples used in this manual are set up as follows: • A single depot is used to store the Elm files. Perforce commands are used to move files to and from a shared file repository known as the depot. Perforce Basics: The Details. Perforce commands supplement your normal work actions instead of replacing them. This chapter gives a broad overview of these concepts and commands. The elm files will be shared by storing them under an elm subdirectory within the depot. Perforce users can retrieve files from the depot into their own client workspaces. and the basic Perforce reporting commands. which are called client workspaces. When a new revision of a file is stored in the depot.Chapter 3 Perforce Basics: Quick Start This chapter teaches basic Perforce usage. populate it with files from the common file repository (the depot). Perforce commands are always entered in the form p4 command [arguments]. and perhaps other projects as well. edited. and deleted in the user’s own directories. Underlying concepts The basic ideas behind Perforce are quite simple: files are created. Perforce was written to be as unobtrusive as possible. • Each user will store his or her client workspace Elm files in a different subdirectory. the old revisions are kept and remain accessible. where they can be read. edited.2 User’s Guide 25 . and resubmitted to the depot for other users to access. Files are still created in your own directories with your tool of choice. so that very few changes to your normal work habits are required. edit these files and submit the changes back to the repository. for details. The two users we’ll be following most closely. File configurations used in the examples This manual makes extensive use of examples based on the source code set for a program called Elm. see Chapter 4. back out of any unwanted changes.
or to use a different workspace. See the “Environment Variables” section of the Perforce Command Reference for details.Chapter 3: Perforce Basics: Quick Start Setting up a client workspace To move files between a client workspace and the depot. set the environment variable P4CLIENT to the name of the client workspace Example: Naming the client workspace Ed is working on the code for Elm. once the form is filled in and the editor exited. You can define the editor your client uses through the P4EDITOR environment variable. In the Korn or Bourne shells. 26 Perforce 2003. Naming the client workspace To name your client workspace. export P4CLIENT Each operating system or shell has its own method of defining environment variables. Typing p4 client brings up the client definition form in a standard text editor. the Perforce server requires two pieces of information: • A name that uniquely identifies the client workspace. the Perforce server is able to move files between the depot and the client workspace. including p4 client. He wants to refer to the collection of files he’s working on by the name eds_elm. field names always start in the leftmost column of text. Describing the client workspace to the Perforce server Once the client workspace has been named. and • The top-level directory of this workspace. he’d type: $ P4CLIENT=eds_elm . In the text forms used by Perforce. Note Many p4 commands. display a form for editing in a standard text editor. it must be identified and described to the Perforce server with the p4 client command. and field values are indented with tabs or spaces.2 User’s Guide . Perforce requires that there be at least one space or a tab prior to the contents of a form field.
He therefore changes the values in the Root: and View: fields as follows: Client: eds_elm Owner: ed Description: Created by ed... and all files in the depot would be mapped to Ed’s home directory. Root: /usr/edk/elm Options: nomodtime noclobber View: //depot/elm_proj/.2 User’s Guide 27 .. Root: /usr/edk Options: nomodtime noclobber View: //depot/. With these default settings. Now he types p4 client from his home directory. This specifies that /usr/edk/elm is the top level directory of Ed’s client workspace. and sees the following form: Client: eds_elm Owner: ed Description: Created by ed. likely cluttering it with files Ed has no interest in working with. /usr/edk/elm. //eds_elm/. This should be the lowest-level directory that includes all the files and directories that you’ll be working with. and that the files under this workspace directory are to be mapped to the depot’s elm_proj subtree. the two most important are the Root and View. Perforce 2003. and he would like this directory to contain only files in the elm_proj portion of the depot... He’s set the environment variable P4CLIENT to eds_elm. //eds_elm/. View: Example: Setting the client root and the client view: Ed is working with his Elm files in a setting as described above. Describes which files and directories in the depot are available to the client workspace.. The meanings of these fields are as follows: Field Root: Meaning Identifies the top subdirectory of the client workspace. and where the files in the depot will be located within the client workspace. all files in Ed’s home directory of /usr/edk (including files unrelated to Ed’s work) would be mapped to the depot.. Ed would like to keep all Elm-related material in a subdirectory in his home directory.Chapter 3: Perforce Basics: Quick Start The p4 client form has a number of fields..
Lisa has been assigned to fix bugs in Ed’s code.> 28 Perforce 2003. Copying depot files into your workspace Use p4 sync to retrieve files from the depot into a client workspace. The Description: can be filled with anything at all. and the p4 client command saves his changes. he exits from the editor. If this is the case. See the general platform notes on the Perforce web site for further details. $ cd ~/elm_ws $ p4 sync //depot/elm_proj/doc/elmdoc.0 //depot/elm_proj/doc/elmdoc. and sets up a client workspace. She creates a directory called elm_ws within her own directory. Windows In Windows environments. The View: describes the relationship between files in the depot and files in the client workspace. You’ll also use p4 client to change existing client specifications. Example: Copying files from the depot to a client workspace. The read-only Client: field contains the string stored in the P4CLIENT environment variable. as described in “Adding files to the depot” on page 30.0#2 . p4 sync won’t do anything. The client specification simply indicates where files will be located when subsequent Perforce commands are used. Note If you’re setting up a brand new depot. Views are explained in more detail at the start of the next chapter. since there are no files in the depot to copy to the client workspace yet. Warning! To use Perforce properly.1 <etc.2 User’s Guide . now she wants to copy all the existing elm files from the depot into her workspace.1#2 . Creating a client specification has no immediate visible effect. no files are created when a client specification is created or edited. it is crucial to understand how views work. it’s a place where you can enter text that describes the contents of this client workspace.added as /usr/lisag/elm_ws/doc/elmdoc.added as /usr/lisag/elm_ws/doc/elmdoc.Chapter 3: Perforce Basics: Quick Start When Ed is done. This is described in “Perforce Basics: The Details” on page 37. a single client workspace may span multiple drives by setting the client root to null and including the drive letter in the client view. start by copying files from your client workspace to the depot with p4 add.
edit. This allows a set of files to be updated in the depot all at once: when the changelist is submitted.2 User’s Guide 29 . Note This chapter discusses only the default changelist. the affected file and the corresponding operation are listed in the default changelist. compares the result against the current client contents. but the corresponding changelist has not yet been submitted in the depot. or p4 delete. or deleted from the depot. which is a list of files and operations on those files to be performed in the depot. updates.Chapter 3: Perforce Basics: Quick Start Once the command completes. p4 edit. When these commands are given. thus. updated in. Updating the depot with files from your workspace Any file in a client workspace can be added to. or none of them are. The operations are performed on the files in the changelist when the p4 submit command is given. the directory is created within the client workspace at sync time. Perforce is told the new state of client workspace files with the commands p4 add filenames. p4 sync deletes it from the client workspace. for a full discussion. Perforce 2003. the corresponding files are listed in a Perforce changelist. and then adds. if a file has been deleted from the depot. If a file exists within a particular subdirectory in the depot. and the files in the depot are affected only when this changelist is submitted to the depot with p4 submit. to limit the files it retrieves. with or without wildcards. the most recent revisions of all the files in the depot that are mapped through her client workspace view will be available in her workspace. and p4 delete do not immediately add. The job of p4 sync is to match the state of the client workspace to that of the depot. p4 sync can take filenames as parameters. the file is said to be open in the client workspace. either all of the files in the changelist are affected. The p4 sync command maps depot files through the client view. or deletes files in the client workspace as needed to bring the client contents in sync with the depot. When a file has been opened with p4 add. see Chapter 7. or delete files in the depot. Instead. The commands p4 add. p4 edit. but that directory does not yet exist in the client workspace. p4 edit filenames. which is automatically 2. This is accomplished in two steps: 1. Changelists. or p4 delete filenames. maintained by Perforce. Changelists can also be created by the user.
$ cd ~/elm/doc $ p4 add elmdoc. He types p4 submit and sees the following form in a standard text editor: Change: new Client: edk User: edk Status: new Description: <enter description here> Files: //depot/elm_proj/doc/elmdoc. type p4 add filename(s). He wants to add these files to the depot.2#1 //depot/elm_proj/doc/elmdoc. The files are named elmdoc. any files deleted from this list will carry over to the next default changelist.0#1 //depot/elm_proj/doc/elmdoc. Example: Adding files to a changelist.* //depot/elm_proj/doc/elmdoc.0 through elmdoc.3 # # # # add add add add Ed changes the contents of the Description: field to describe what these file updates do.0 //depot/elm_proj/doc/elmdoc. Ed is ready to submit his added files to the depot. 30 Perforce 2003. the files are not actually stored in the depot until the p4 submit command is given. When he’s done. Ed is writing a help manual for Elm. and they’re sitting in the doc subdirectory of his client workspace root. Lines can be deleted from the Files: field. he quits from the editor.Chapter 3: Perforce Basics: Quick Start Adding files to the depot To add a file or files to the depot. Example: Submitting a changelist to the depot. and will appear again the next time p4 submit is performed.2 //depot/elm_proj/doc/elmdoc.3#1 - opened opened opened opened for for for for add add add add At this point. and the new files are added to the depot. the files he wants to add to the depot have been added to his default changelist. The Description: field contents must be changed. or the depot update won’t be accepted.1 //depot/elm_proj/doc/elmdoc.2 User’s Guide .3. but they won’t be added to the depot until the p4 submit command is given. The p4 add command opens the file(s) for add and lists them in the default changelist.1#1 //depot/elm_proj/doc/elmdoc. However.
as described above. Perforce always displays filenames with a #N suffix. Revision numbers are always assigned sequentially. Editing files in the depot To open a file for edit.opened for add //depot/elm_proj/lib/addrmchusr. Example: Using multiple file arguments on a single command line. which is described below.opened for add <etc. and • The file(s) to be edited are added to the default changelist. $ cd ~ $ p4 add elm/lib/* elm/hdrs/* elm/doc/* //depot/elm_proj/lib/Makefile. it is automatically created within the depot at submit time. This has two effects: • The file(s) write permissions are turned on in the client workspace. the default changelist will be assigned a number. Populating empty depots In Perforce. use p4 edit. populate new. For this reason.opened for add //depot/elm_proj/lib/add_site. and header files to the depot.c#1 . Ed wants to add all of his Elm library. The operating system’s write permission on submitted files is turned off in the client workspace when p4 submit is performed. Perforce Basics: Resolving File Conflicts for instructions on resolving file conflicts. the #N indicates that this is the Nth revision of this file. Please see Chapter 5. The write permissions are turned back on by p4 edit. Ed then does a p4 submit. Perforce 2003. there’s no difference between adding files to an empty depot and adding files to a depot that already contains other files. You might have noticed in the example above that the filenames are displayed as filename#1. This helps ensure that file editing is done with Perforce’s knowledge.Chapter 3: Perforce Basics: Quick Start Adding more than one file at once Multiple file arguments can be provided on the command line.2 User’s Guide 31 . empty depots by adding files from a client workspace with p4 add. Warning! If a submit fails.> After p4 add is finished.c#1 .SH#1 . documentation. If the directory containing a new file does not exist in the depot. and you’ll need to submit that changelist in a slightly different way.
This makes it possible to read older revisions of “deleted” files back into the client workspace. it appears as if the file has been deleted from the depot. The deletion of the file in the depot occurs only after the changelist with the delete operation is submitted.opened for delete The file is deleted from the client workspace immediately. Note Before a file can be opened for edit.opened for edit He then edits the file with any text editor. as described above.3 //depot/elm_proj/doc/elmdoc. it must already have been added to the depot with p4 add.3#1 .3 is no longer needed. use p4 submit. Deleting files from the depot Files are deleted from the depot in a way similar to the way in which they are added and edited. The p4 delete command opens the file for delete in the default changelist.3 //depot/elm_proj/doc/elmdoc. he submits the file to the depot with p4 submit.3#1 . you must give the p4 edit command before attempting to edit the file. old file revisions are never actually removed.2 User’s Guide . however. Once the changelist is submitted. Example: Opening a file for edit: Ed wants to make changes to his elmdoc. To save the new file revision in the depot. When he’s finished. as described above. but it is not deleted from the depot until he gives the p4 submit command. Example: Deleting a file from the depot.Chapter 3: Perforce Basics: Quick Start Since the files must have their write permission turned back on before they can be edited. 32 Perforce 2003. or copied into the client workspace from the depot with p4 sync. He deletes it from both his client workspace and from the depot as follows: $ cd ~/elm/doc $ p4 delete elmdoc. Ed’s file doc/elmdoc. The p4 delete command also deletes the file from the client workspace. and then p4 submit is used to delete the file from the depot. $ cd ~/elm $ p4 edit doc/elmdoc.3 file. this occurs when the p4 delete command is given. He opens the file for edit.
c functionality edit edit edit # edit # add All of his changes supporting multiple mailboxes are grouped together in a single changelist. if the submission fails for any reason.2#2 . and deleting files in a single submit: Ed is writing the portion of Elm that is responsible for multiple folders (multiple mailboxes). or none of them are. Example: Adding. and appear again the next time p4 submit is performed. mailbox” Files: //depot/elm_proj/doc/elmdoc. either all of these files are updated in the depot.Chapter 3: Perforce Basics: Quick Start Submitting with multiple operations Multiple files can be included in any changelist. when Ed quits from the editor.1#1 .1 # //depot/elm_proj/doc/elmdoc. Changelists can be used to keep files together that have a common purpose.2 User’s Guide 33 .0#1 .> $ p4 edit elm/hdrs/s_elm.c //depot/elm_proj/src/newmbox. Files can be deleted from the Files: field.* //depot/elm_proj/hdrs/s_elm. He has a new source file src/newmbox. or. updating. Perforce 2003. and he needs to edit the header file hdrs/s_elm.c.2 # //depot/elm_proj/hdrs/s_elm.0 # //depot/elm_proj/doc/elmdoc.opened for edit //depot/elm_proj/doc/elmdoc.h //depot/elm_proj/src/newmbox. none of them are.h#1 . this is called an atomic change transaction).h doc/elmdoc. these files are moved into the next default changelist. Submitting the changelist to the depot works atomically: either all the files are updated in the depot.c#1 . He adds the new file and prepares to edit the existing files: $ cd ~ $ p4 add elm/src/newmbox.opened for edit He edits the existing files and then performs a p4 submit of the default changelist: Change: new Client: eds_elm User: edk Status: new Description: Changes to Elm’s “mult.opened for add <etc.opened for edit //depot/elm_proj/doc/elmdoc.opened for edit //depot/elm_proj/doc/elmdoc.h and the doc/elmdoc files. (In Perforce’s terminology.
c //depot/elm_proj/src/signals. If p4 add was used to open the file.c is not one of the files he will be working on. Example: Reverting a file back to the last synced version. and any local modifications to the file are lost.c limit. it will appear back in the client workspace immediately.opened for edit //depot/elm_proj/src/limit. Basic reporting commands Perforce provides some 20+ reporting commands. overwriting the newly-edited version of the file.2 User’s Guide 34 . or delete can be removed from its changelist with p4 revert.was edit.opened for edit //depot/elm_proj/src/signals.Chapter 3: Perforce Basics: Quick Start Backing out: reverting files to their unopened states Any file opened for add.opened for edit and then realizes that signals.c. To reduce the risk of overwriting changes by accident. Each chapter in this manual ends with a description of the reporting commands relevant to the chapter topic. Ed wants to edit a set of files in his src directory: leavembox. you may want to preview a revert by using p4 revert -n before running p4 revert. Command p4 help commands p4 help command Meaning Lists all Perforce commands with a brief description of each. limit. For any command provided. reverted If p4 revert is used on a file that had been opened with p4 delete. All the reporting commands are discussed in greater detail in Chapter 11. He opens the files for edit: $ cd ~elm/src $ p4 edit leavembox. but leaves the client workspace file intact.c. This command reverts the file in the client workspace back to its unopened state.c#2 . the last synced version will be written back to the client workspace. He can revert signals. gives detailed help about that command.c.c#1 . edit.c signals. p4 help sync provides detailed information about the p4 sync command. p4 revert removes it from the changelist. and that he didn’t mean to open it.c to its unopened state with p4 revert: $ p4 revert signals.c#1 . Reporting and Data Mining. The most basic reporting commands are p4 help and p4 info.c //depot/elm_proj/src/leavembox. Perforce 2003. If the reverted file was originally opened with p4 edit.c#2 . and signals. For example. The -n option reports what files would be reverted by p4 revert without actually reverting the files.
Reports what files would be updated in the client workspace by p4 sync without actually performing the sync operation. Perforce 2003. and a few other tidbits.2 User’s Guide 35 . Two other reporting commands are used quite often: Command p4 have p4 sync -n Meaning Lists all file revisions that the Perforce server knows you have in the client workspace. user name. Gives a discussion of Perforce view syntax Describes all the arguments that can be given to p4 help. Perforce version. Reports information about the current Perforce system: the server address. client root directory.Chapter 3: Perforce Basics: Quick Start Command p4 help usage p4 help views p4 help p4 info Meaning Describes command-line flags common to all Perforce commands. client name.
2 User’s Guide .Chapter 3: Perforce Basics: Quick Start 36 Perforce 2003.
For example: to make a temporary modification to a file. Each collection is given a name which identifies the client workspace to the Perforce server. Perforce’s management of a client workspace requires a certain amount of cooperation from the user. the client root can be the host’s root.2 User’s Guide 37 . willful users can circumvent the system by turning on write permission. The topics discussed include views. refer to Chapter 3. All files within a Perforce client workspace share a common root directory. or otherwise modifying the file tree supposedly under Perforce’s control. rules for referring to older file revisions. • It turns on write permission when the user requests to edit a file. Perforce counters this with two measures: first. The server knows what files a client workspace has. directly deleting or renaming files. and which files have write permission turned on. Description of the Client Workspace A Perforce client workspace is a collection of source files managed by Perforce on a host. file types. Perforce wildcards. There can be more than one Perforce client workspace on a client host. In the degenerate case. and form syntax. but in practice the client root is the lowest level directory under which the managed source files reside. second. The entire Perforce client workspace state is tracked by the Perforce server.Chapter 4 Perforce Basics: The Details This chapter covers the Perforce rules in detail. By default. or deletes files as required in the workspace when the user requests Perforce to synchronize the client workspace with the depot. For a brief overview of Perforce. called the client root. Because client files are ordinary files with write permission turned off. Perforce manages the files in a client workspace in three direct ways: • It creates. updates. Perforce Basics: Quick Start. but this can be overridden by the environment variable P4CLIENT. where they are. Perforce 2003. the name is simply the host’s name. it is easier to use Perforce than it is to copy and restore the file manually. mapping depots to client workspaces. and • It turns off write permission and submits updated versions back to the depot when the user has finished editing the file and submits his or her changes. Perforce has explicit commands to verify that the client workspace state is in accord with the server’s recording of that state. Perforce tries to make using Perforce at least as easy as circumventing it.
Wildcards Perforce uses three wildcards for pattern matching. a depot name is an alias for a directory on the Perforce server. they’re not in the depot yet).” wildcard is passed by the p4 client program to the Perforce server.. matches only within a single directory. not by the p4d server. %d Meaning Matches anything except slashes.Chapter 4: Perforce Basics: The Details Files not managed by Perforce may also be under a client’s root..” wildcard is expanded by the Perforce server.. Perforce neither creates nor uses any files on the client host. and executables. libraries. Mapping the Depot to the Client Workspace Just as a client name is simply an alias for a particular directory on the client machine. The “. The relationship between files in the depot and files in the client workspace is described in the client view. Otherwise. 38 Perforce 2003. and it is set with the p4 client command.. and since the server doesn’t know what files are being added (after all.” wildcard can’t be used with the p4 add command. Matches anything including slashes. Used for parametric substitution in views. In addition to accessing the client files. See “Changing the order of filename substrings” on page 43 for a full explanation. The * wildcard may be used with p4 add.. where it is expanded to match the corresponding files known to p4d. Perforce may manage the source files in a client workspace. the p4 client program sometimes creates temporary files on the client host. as well as a developer’s temporary files. while the workspace also holds compiled objects. as it is expanded by the local OS shell.. but are ignored by Perforce. Most command shells don’t interfere with the other two wildcards. Wildcards and “p4 add” The “.. Any number and combination of these can be used in a single string: Wildcard * . usually with quotes or a backslash. it must be escaped.. matches across multiple directories. it can’t expand that wildcard. and the files that match the wildcard are passed as multiple arguments to the p4 command. For example. To have Perforce match the * wildcard against the contents of the depot. The “. The * wildcard is expanded locally by the OS shell before the p4 command is sent to the server.2 User’s Guide .
. //eds_elm/projects/. Perforce 2003.. //eds_elm/depot/. The contents of the View: field determine where client files get stored in the depot. The lefthand side specifies one or more files within the depot. //user_depot/. and the right-hand side is the client side. //eds_elm/user_depot/.Chapter 4: Perforce Basics: The Details When you type p4 client. The Perforce System Administrator’s Guide explains how to create multiple depots.. and has the form: //clientname/file_specification The left-hand side of a client view mapping is called the depot side. Root: /usr/edk/elm Options: nomodtime noclobber View: //depot/... and where depot files are copied to in the client. //eds_elm/.... Using views Views consist of multiple lines. If your system administrator has created multiple depots on your server.... or mappings.. Note The p4 client form has more fields than are described here.. and the name of the depot is depot. please see the Perforce Command Reference. //projects/. and each mapping has two parts. there is a single depot in each Perforce server.. Multiple depots By default. the default client view will look something like this: View: //depot/. The Perforce system administrator can create multiple depots on the same Perforce server. and has the form: //depotname/file_specification The right-hand side of each mapping describes one or more files within the client workspace.2 User’s Guide 39 .. For a full discussion.. Perforce displays a variation of the following form: Client: eds_elm Owner: edk Description: Created by ed.
0/. For example..1. or only those files within two directories. if the p4 client form’s Root: field for the client eds_elm is set to /usr/edk/elm. Views can contain multiple mappings. perform the same two functions: • Determine which files in the depot can be seen by a client workspace. Use uppercase drive letters when specifying workspaces across multiple drives.. then the file //eds_elm/doc/elmdoc.. use a Root: of null. for example. 40 Perforce 2003. substitute the value of the p4 client form’s Root: field for the client name on the client side of the mapping... no matter how elaborate.. A view might allow the client workspace to retrieve every file in the depot.. Or it can be oblique..0/. //eds_win/D:/old/rel2. For example: Client: eds_win Owner: edk Description: Ed’s Windows Workspace Root: null Options: nomodtime noclobber View: //depot/main/. or only a single file. //eds_win/D:/old/rel1.. and can be much more complex.2 User’s Guide ." //depot/rel1. for example.. • Construct a one-to-one mapping between files in the depot and files in the client workspace. Each mapping within a view describes a subset of the complete mapping. No matter how the files are named.. the client workspace file tree might be identical to a portion of the depot’s file tree. a file might have one name in the depot and another in the client workspace. To determine the exact location of any client file on the host machine.Chapter 4: Perforce Basics: The Details The default view in the example above is quite simple: it maps the entire depot to the entire client workspace. there is always a one-to-one mapping. Windows workspaces spanning multiple drives To specify a Perforce client workspace that spans multiple Windows drives. or be moved to an entirely different directory in the client workspace.1 will be found on the client host in /usr/edk/elm/doc/elmdoc. and specify the drive letters in the client workspace view. The one-toone mapping might be straightforward.. but all client views.0/.0/. This is determined by the sum of the depot sides of the mappings within a view. //depot/rel2. "//eds_win/C:/Current Release/.
This section discusses Perforce’s mapping methods. //eds_elm/. use the “. //eds_elm/. the file //depot/elm_proj/nls/gencat/README is mapped to the client workspace file //eds_elm/nls/gencat/README.2 User’s Guide 41 . To properly specify file trees.... The result is that any file in the eds_elm client workspace will be mapped to the same location within the depot’s elm_proj file tree. Example: Mapping part of the depot to the client workspace. then the resulting view also includes files and directories such as //depot/elm_project_coredumps. it is possible to map only part of a depot to a client workspace.” wildcard. This view is usually considered to be overkill.. indicates that any file in the directory tree under the client eds_elm will be stored in the identical subdirectory in the depot... Mapping the full client to only part of the depot Usually. as most users only need to see a subset of the files in the depot. the default view //depot/.... and her client root is /usr/bes/docs.) Types of mappings By changing the View: field. which is probably not what you intended. which matches everything including slashes. Bettie is rewriting the documentation for Elm..” wildcard after a trailing slash.. the single mapping contains Perforce’s “... Direct client-to-depot views The default view in the form presented by p4 client maps the entire client workspace tree into an identical directory tree in the depot. Perforce 2003... Any string matched by the wildcard is identical on both sides. For example. you’ll only want to see part of the depot.. For example. or to have files named differently in the depot and the client workspace.. //elm_docs/. In the client view //depot/elm_proj/.Chapter 4: Perforce Basics: The Details Wildcards in views Any wildcard used on the depot side of a mapping must be matched with an identical wildcard in the mapping’s client side. Her client is named elm_docs.. she types p4 client and sets the View: field as follows: //depot/elm_proj/doc/. It is even possible to map files within the same depot directory to different client workspace directories. (If you specify only //depot/elm_proj. Change the left-hand side of the View: field to point to only the relevant portion of the depot.. which is found in the depot within its doc subdirectory.
This is accomplished by prefacing the mapping with a minus sign ( . which is called mike_elm. To do this.. all other files are caught by the first mapping and appear in their normal location. Files not beneath the //depot/elm_proj/doc directory no longer appear in Bettie’s workspace. later mappings have precedence over the earlier ones.Chapter 4: Perforce Basics: The Details The files in //depot/elm_proj/doc are mapped to /usr/bes/docs.).. The elm_proj subdirectory of the depot contains a directory called doc.. any files beginning with elmdoc within Mike’s client workspace help subdirectory are mapped to the doc subdirectory of the depot. which are used to map portions of the depot file tree to different parts of the client file tree. //mike_elm/help/elmdoc.2 User’s Guide .* Any file whose name starts with elmdoc within the depot’s doc subdirectory is caught by the later mapping and appears in Mike’s workspace’s help directory. If there is a conflict in the mappings. which is located at the same level as his doc directory.* //mike_elm/. Mike wants to separate these four files from the other documentation files in his client workspace.. Whitespace is not allowed between the minus sign and the mapping. Included in this directory are four files named elmdoc. See “Two mappings can conflict and fail” on page 44 for details. 42 Perforce 2003.0 through elmdoc. //depot/elm_proj/doc/elmdoc. some depot and client files will remain unmapped. so he fills in the View: field of the p4 client form as follows: View: //depot/. he creates a new directory in his client workspace called help.3. Excluding files and directories from the view Exclusionary mappings allow files and directories to be excluded from a client workspace. Example: Multiple mappings in a single client view. which has all of the Elm documents. Note Whenever you map two sections of the depot to different parts of the client workspace. The four elmdoc files will go here. Conversely. Mapping files in the depot to different parts of the client Views can consist of multiple mappings.
(Mike can be a bit difficult to work with). Mike wants to store the files as above. -//depot/elm_proj/doc/. but %d can be used to rearrange the order of the matched substrings.X in his client workspace.%1 Perforce 2003. Changing the order of filename substrings The %d wildcard matches strings similarly to the * wildcard. //mike_elm/doc/%2... //depot/elm_proj/doc/%1....Elm in his client workspace.. no files from that subdirectory will ever be copied to the depot. Example: Files with different names in the depot and client workspace. he’d like to rename the Elm. wants to view only source code. //billm/. Since later mappings have precedence over earlier ones. Example: Changing string order in client workspace names. The wildcards are replaced in the copied-to direction by the substring that the wildcard represents in the copied-from direction.. if Bill does have a doc subdirectory in his client. His client view would look like this: View: //depot/elm_proj/.. but he wants to take the elmdoc..2 User’s Guide 43 .Chapter 4: Perforce Basics: The Details Example: Using views to exclude files from a client workspace. he’s not interested in the documentation files... //mike_elm/help/helpfile.cover file in the depot cover.. Allowing filenames in the client to differ from depot filenames Mappings can be used to make the filenames in the client workspace differ from those in the depot. Mike wants to change the names of any files with a dot in them within his doc subdirectory in such a way that the file’s suffixes and prefixes are reversed in his client workspace... For example. the nth wildcard in the depot specification corresponds to the nth wildcard in the client description. whose client is named billm. Conversely.%2 //mike_elm/. He uses the following mappings: View: //depot/elm_proj/. no files from the depot’s doc subdirectory will ever be copied to Bill’s client. Bill.* Each wildcard on the depot side of a mapping must have a corresponding wildcard on the client side of the same mapping.* //mike_elm/.. He uses the following mappings: View: //depot/elm_proj..X files in the depot and call them helpfile. There can be multiple wildcards. //billm/doc/. //depot/elm_proj/doc/elmdoc.
2 User’s Guide .c The file //depot/proj1/file. //joe/proj1/newfile.c //joe/proj1/. • If you use p4 client to change the client workspace Root:. When a file doesn’t map to the same place in both directions. In older versions of Perforce. some files may map to two separate places in the depot or on the client. this was often used as a trick to exclude particular files from the client workspace... Because Perforce now has exclusionary mappings. specifically changes to the client view and changes to the client root: • If you change only the value of the client workspace View: field with p4 client. This is particularly important for two types of client spec changes. Because the file would be written back to a different location in the depot than where it was read from.Chapter 4: Perforce Basics: The Details Two mappings can conflict and fail When you use multiple mappings in a single view. perform a p4 sync to copy the files to their new locations within the client view. but that same client file //joe/proj1/newfile. Example: Mappings that conflict and fail. the locations of files in your workspace are affected only when the client specification is used in subsequent commands.. use p4 sync #none to remove the files from their old location in the workspace before using p4 client to change the client root. Note that changing a client specification has no immediate effect on the locations of any files. Perforce ignores that file.. perform a p4 sync immediately afterward. Joe has constructed a view as follows: View: //depot/proj1/. After using p4 client to change the root directory. and the file is ignored.c maps to //joe/proj1/newfile. (If you forget to 44 Perforce 2003.c. The files in the client workspace will be deleted from their old locations and written to their new locations.c maps back to the depot via the higher-precedence second line to //depot/proj1/file. this type of mapping is no longer useful. Editing Existing Client Specifications You can use p4 client at any time to change the client workspace specification.c. //depot/proj1/file. and should be avoided. Perforce doesn’t map this name at all.
separated by spaces. Note: 2000. make sure that the files are in place in the client workspace. it simply removes the Perforce server’s record of the mapping between the depot and the client workspace. use p4 sync #none (described in “Specifying Older File Revisions” on page 51) on the files before deleting the client specification. and then change the other. Deleting a client specification has no effect on any files in the client workspace or depot. or this setting will be ignored.2 or earlier only! Should CR/LF translation be performed automatically when copying files between the depot and the client workspace? (On UNIX. Change either the Root: or the View: according to the instructions above. or use the standard local OS deletion commands after deleting the client specification. this setting is ignored). you can always remove the files from their client workspace locations manually). To delete existing files from a client workspace. Each of the six options have two possible settings.2 User’s Guide 45 . Client specification options The Options: field contains six values.Chapter 4: Perforce Basics: The Details perform the p4 sync #none before changing the client view. The following table provides the option values and their meanings: Option [no]allwrite [no]clobber Choice Default noallwrite noclobber Should unopened files be left writable on the client? Should p4 sync overwrite (clobber) writable but unopened files in the client with the same name as the newly synced files? Should the data sent between the client and the server be compressed? Both client and server must be version 99. [no]compress nocompress [no]crlf crlf Perforce 2003. Warning! It’s not a good idea to change both the client Root: and the client View: at the same time.1 or higher. Deleting an existing client specification An existing client workspace specification can be deleted with p4 client -d clientname.
regardless of the setting of modtime or nomodtime on the client.2 level or earlier. For files with the +m (modtime) file type modifier: • For Perforce clients at the 99. the modification date is the date and time of sync. edit. • For Perforce clients at the 2000. • If nomodtime is set. and the behavior of modtime and nomodtime is as documented above.1 level or higher.2 level or earlier. Note that a Perforce administrator is still able to override the lock with the -f (force) flag. • For Perforce clients at the 2000. the +m modifier is ignored. ted to the depot. regardless of Perforce client version. if modtime is set. the modification date (on the local filesystem) of a newly synced file is the datestamp on the file when the file was submitted to the depot. if modtime is set. date and time of sync) for most files. [no]rmdir (i.1 level or higher. the modification date (on the local filesystem) of a newly synced file is the datestamp on the file when the file was submitted to the depot.Chapter 4: Perforce Basics: The Details Option [un]locked Choice Default unlocked Do other users have permission to edit the client specification? (To make a locked client specification truly effective. be sure to set a password for the client’s owner with p4 passwd. only the owner is able to use. the modification date (on the local filesystem) of a newly synced file is the date Ignored for files with the +m file and time at the server when the file was submittype modifier.) If locked. Should p4 sync delete empty directories in a client if all files in the directory have been removed? normdir 46 Perforce 2003.e. or delete the client spec. [no]modtime For files without the +m (modtime) file type modifier: nomodtime • For Perforce clients at the 99.2 User’s Guide .
and then against the two AltRoots: if they exist. This allows edk to use the same client workspace specification for both UNIX and Windows development. If you are using multiple client workspace roots. Client: eds_elm Owner: edk Description: Created by ed.. the main root is used. Perforce compares the current working directory against the main Root: first. The LineEnd: field accepts one of five values: Option local unix Meaning Use mode native to the client (default) UNIX-style line endings: LF only Perforce 2003. You may specify up to two alternate client workspace roots. may use the AltRoots: field in the p4 client form. If no roots match. rather than e:\porting\edk\elm. and replaces the old convention of specifying crlf or nocrlf in the Options: field. //eds_elm/src/...Chapter 4: Perforce Basics: The Details Multiple workspace roots for cross-platform work Users who work on more than one operating system. but who wish to use the same client workspace.2 User’s Guide 47 . you can always find out which workspace root is in effect by examining the Client root: as reported by p4 info. then Perforce uses the UNIX path as his client workspace root. Note The LineEnd: option is new to Perforce 2001. Note If you are using a Windows directory in any of your client roots.1. The first root to match the current working directory is used. you must specify the Windows directory as your main client Root: and specify your other workspace root directories in the AltRoots: field. Line-ending conventions (CR/LF translation) The LineEnd: field controls the line-ending character(s) used for text files in the client workspace. Root: e:\porting\edk\elm AltRoots: /usr/edk/elm Options: nomodtime noclobber View: //depot/src/.. If edk’s current working directory is under /usr/edk/elm.
line endings will be LF.2 User’s Guide . Local syntax Local syntax is simply a file’s name as specified by the local shell or OS. The components of the path are separated by slashes.. This name may be an absolute path. although it can only contain relative components at the beginning of the file name (that is. if you sync files from UNIX./here/file. When you sync your client workspace.c). or in a number of other ways. or by providing the names of the files in the depot.Chapter 4: Perforce Basics: The Details Option mac win share Meaning Macintosh-style: CR only Windows-style: CR. Filenames specified in this way begin with two slashes and the client or depot name. but edit the files on a Windows machine. it doesn’t allow sub/dir/. If you edit the file on a Windows machine. LF Shared mode: Line endings are LF with any CR/LF pairs translated to LFonly style before storage or syncing with the depot. On UNIX. you may give the name in either local syntax or Perforce syntax. and your editor inserts CRs before each LF. or may be specified relative to the current directory. //elm_client/docs/help.1 48 Perforce 2003. Examples of Perforce syntax //depot/. Referring to Files on the Command Line File names provided as arguments to Perforce commands can be referred to in one of two ways: by using the names of the files in the client workspace. When providing client workspace file names.. the share option eliminates problems caused by Windows-based editors’ insertion of carriage returns in text files. the extra CRs will not appear in the archive file. The most common use of the share option is for users of Windows workstations who mount their UNIX home directories mounted as network drives. Ed could refer to the README file at Elm’s top level as /usr/edk/elm/README. Perforce syntax Perforce provides its own filename syntax which remains the same across operating systems. followed by the path name of the file relative to the client or depot root directory.
depot syntax. while in any directory on the client host.c p4 delete //depot/elm_proj/src/lock. Note The point of this section is worth repeating: any file can be specified within any Perforce command in client syntax. Providing files as arguments to commands Because the client view provides a one-to-one mapping between any file in the client workspace and any file in the depot. depot syntax. and vice versa. or in Perforce syntax by depot or client. A depot’s file specifier can be used to refer to a file in the client. he could type any of the following commands: p4 delete //eds_elm/src/lock. he could type p4 delete src/lock.Chapter 4: Perforce Basics: The Details Perforce syntax is sometimes called depot syntax or client syntax.2 User’s Guide 49 . he could type p4 delete lock.c Client names and depot names in a single Perforce server share the same namespace. Perforce will do the necessary mapping to determine which file is actually used. Any filenames provided to Perforce commands can be specified in any valid local syntax. Perforce uses the client view to locate the corresponding file in the depot. The examples in this manual will use these syntaxes interchangeably. Example: Uses of different syntaxes to refer to a file. If a client filename is provided. while in the src subdirectory. Client workspace names and depot names can never be the same.c file. Ed wants to delete the src/lock.c or. the client view is used to locate the corresponding file in the client workspace. or local syntax. Perforce 2003. If a depot filename is given. He can give the p4 delete command in a number of ways: While in his client root directory.c p4 delete /usr/edk/elm/src/lock. but both forms of file specification work the same way.c or. so Perforce will never confuse a client name with a depot name. or local syntax. depending on whether the file specifier refers to a file in the depot or on the client. any file can be specified within any PERFORCE command in client syntax.
Most UNIX shells interpret # as the beginning of a comment. //... works at the current directory level and includes files in all directory levels below the current level. and the DOS command line uses % to refer to variables. 50 Perforce 2003. //weasel/.. or changelist number. are not allowed in file names. and other identifiers. Perforce revision specifier for revision numbers.. Perforce wildcard: matches anything. nonASCII) characters in filenames. label name... client workspace names. Perforce separator for pathname components. or other identifiers: Character @ # * .. Meaning Files in the current directory starting with J All files called help in current subdirectories All files under the current directory and its subdirectories All such files ending in .e.. Perforce wildcard: %0 through %9 are used for positional substitutions. Perforce wildcards. //depot/.c All files under /usr/edk All files on client (or depot) weasel All files in the depot named depot All files in all depots (when used to specify files on the command line) Name and String Limitations Illegal characters in filenames and Perforce objects In order to support internationalization./*. works within a single directory Perforce wildcard: matches anything. label names. while many DOS commands interpret / as a command line switch. the pathname component separator (/). .Chapter 4: Perforce Basics: The Details Wildcards and Perforce syntax Perforce wildcards may be mixed with both local or Perforce syntax.. label names..2 User’s Guide .. Observe that most of these characters tend to be difficult to use in filenames in crossplatform environments: UNIX separates path components with /. Perforce allows the use of “unprintable” (i. and the revision-specifying characters @ and #... % / Reason Perforce revision specifier for date.c /usr/edk/. Both DOS and UNIX shells automatically expand * to match multiple files. For example: Wildcard J* */help ..
Other Perforce objects. For Release 2001. For instance. Specifying Older File Revisions All of the commands and examples we’ve seen thus far have been used to operate only on the most recent revisions of particular files." maps all files in //depot/main/release 1.2 User’s Guide 51 .. but these spaces are automatically converted to underscores by the Perforce server. All names given to Perforce objects such as branches. such as branch names.Chapter 4: Perforce Basics: The Details Caveats on non-ASCII filenames Although non-ASCII characters are allowed in filenames and Perforce identifiers.2/doc/. Perforce 2003. For example. For details.c is retrieved. entering them from the command line may require platform-specific solutions. and so on.2 documentation subdirectory of client workspace eds_ws. Warning! Some OS shells treat the revision character # as a comment character if it starts a new word. or head revision.2/doc into the 1. the mapping: "//depot/release 1. of lock. but older revisions can be retrieved by tacking a revision specification onto the end of the file name. are limited to 1024 characters. Name and description lengths Descriptions in the forms used by p4 client. there are some limitations on how filenames with nonASCII character sets are displayed. clients." "//eds_ws/1. For internationalization purposes. and so on. all users must have P4CHARSET set properly.2 documentation/.c. the latest revision. may be of any length. escape the # before use. may be specified with spaces. Using spaces in file and path names Use quotation marks to enclose depot-side or client side mappings of files or directories that contain spaces. If your shell is one of these. If you are using Perforce in internationalized mode. set the LOCALE environment variable) in order to ensure that all filenames are displayed consistently across all machines in your organization. if Ed types p4 sync //eds_elm/src/lock. see the Command Reference.. under UNIX. but many Perforce commands can act on older file versions. all users should use a common code page setting (under Windows. use the Regional Settings applet in the Control Panel. and so on.. client names. label names.1.. p4 branch. Users of GUI-based file managers can manipulate such files with drag-and-drop operations.
. even if one exists in the depot. Changelists). p4 sync lock. 52 Perforce 2003. p4 sync lock.c@beta The revision of lock. p4 sync //depot/. identical to referring to the file with no revision specifier.c in the client workspace.c in the label called beta (labels are explained in Chapter 8.Chapter 4: Perforce Basics: The Details Revision Specifier file#n Meaning Examples p4 sync lock. p4 sync lock. file@labelname A label name p4 sync lock.@126 Refers to the state of the entire depot at changelist 126 (numbered changelists are explained in Chapter 7.c when changelist 126 was submitted.c@lisag_ws The revision of lock.c#head or latest version. The revision of file last taken into client workspace clientname.c#have file#have The revision of lock.c last taken into client workspace lisag_ws file#none The nonexistent revision. even if it was not part of the change. This is synonymous to @client where client is the current client name. p4 sync lock.c#3 Revision number A change number Refers to revision 3 of file lock.c#none Says that there should be no version of lock.. file#head The head revision.c@126 Refers to the version of lock.2 User’s Guide . The revision on the current client.c found in the current client. Labels). Except for explicitly noted exceptions. this is of the file. file@clientname A client name.c file@n p4 sync lock.
if a file doesn’t exist at the given revision number. The head revision of the file in the depot on the given date at the given time. the time is specified as HH:MM:SS. 1998. if you move your server across time zones.Chapter 4: Perforce Basics: The Details Revision Specifier file@date Meaning Examples p4 sync lock. Warning! Perforce allows you to search on dates with two-digit years.2 User’s Guide 53 . The date. The date and the time must be separated by a single space or a colon. Perforce 2003. 1970). In all cases. offset from GMT. The head revision of lock. and time zone in effect at your Perforce server are displayed in the “Server date:” line in the output of p4 info.c@1998/05/18 The head revision of the file at 00:00:00 on the morning of that date. Both forms shown above are equivalent.c as of 00:00:00. 1. using a label to refer to a file that isn’t in the label is indistinguishable from referring to a file that doesn’t exist at all. but these years are assumed to fall in the twentieth century. For safety’s sake.c@"1998/05/18 15:21:34" p4 sync lock. it appears as if the file doesn’t exist at all. The time is specified on the 24-hour clock. Thus. Dates are specified as YYYY/MM/DD. May 18.c as of May 18. Date and time specifications are always interpreted with respect to the local time zone of the Perforce server. at 3:21:34 pm. time. file@"date time" p4 sync lock.c@1998/05/18:15:21:34 The head revision of lock. and the entire string should be quoted. the times recorded on the server will automatically be reported in the new timezone. use four-digit years. Note that because the server stores times internally in terms of number of seconds since the Epoch (00:00:00 GMT Jan. 1998. The date is specified as above.
but not from the depot. he creates another client for a different user. the named revision specifies the end of the range. and types p4 sync #none The files are removed from his workspace (“synced to the nonexistent revision”). Thus. #head refers to the head revisions of all files in the depot. but he wants to see only those revisions that existed at change number 30.2 User’s Guide . Ed wants to retrieve all the doc files into his Elm doc subdirectory. Revision Ranges A few Perforce client commands can limit their actions to a range of revision numbers. and the start of the range is assumed to be 1.@eds_elm He could have typed p4 sync @eds_elm and the effect would have been the same. A revision range is two revision specifications. Another client needs all its files removed. He types p4 sync //eds_elm/doc/*@30 Later.. separated by a comma. Example: Retrieving files using revision specifiers. Ed sets up the new client specification and types p4 sync //depot/elm_proj/. rather than just a single revision. Example: Removing files from the client workspace. and @labelname refers to the revisions of all files in the named label. Ed sets P4CLIENT to the correct clientname. This limits the command’s action to the specified revision of all files in the depot or in the client’s workspace.Chapter 4: Perforce Basics: The Details Using revision specifications without filenames Revision specifications can be provided without file names.. The commands that accept revision range specifications are: p4 changes p4 print p4 file p4 sync p4 integrate p4 verify p4 jobs 54 Perforce 2003. The new client should have all of the file revisions that Ed last synced. If no revision number or range is given where a revision range is expected. but these files shouldn’t be deleted from the depot. the default is all revisions. If only a single revision is given where a revision range is expected.
support for RCS keyword expansion. Change 673 on 2000/07/31 by edk@eds_elm ’Final build for QA’ He can then use p4 describe change# against any desired change for a full description. and UNIX symlinks. to change the file type of your Perl script myscript. If any non-text characters are found. but only changes made to text files since the previous revision are normally stored. Perforce attempts to determine the type of the file automatically: when a file is opened with p4 add. When you add a file. and more. see your system administrator. File type modifiers can be applied to the base types to enable preservation of timestamps. • p4 edit -t filetype filespec opens the file for edit. File revisions of binary files are normally stored in full within the depot. file compression on the server. and then examines the first part of the file to determine whether it’s text or binary. (Files of type unicode are detected only when the server is running in unicode mode. file merges and file Perforce 2003. You can determine the type of an existing file by using p4 opened or p4 files.. Perforce first determines if the file is a regular file or a symbolic link. Mac resource forks. native apple files on the Macintosh. A release manager needs to see a list of all changes to the Elm project in July. their type will be changed. otherwise. when the files are submitted.) Once set. and Perforce uses RCS format to store its deltas.. the file is assumed to be text. for instance. unicode files.2000/8/1 The resulting list of changes looks like this: Change 632 on 2000/07/1 by edk@eds_elm ’Started work’ Change 633 on 2000/07/1 by edk@eds_elm ’First build w/bug fix’ . File type modifiers may be combined.. for details. This is called delta storage.@2000/7/1.2 User’s Guide 55 .pl. the file is assumed to be binary. The filetype argument is specified as basetype+modifiers. use p4 edit -t text+kx myscript. He types: p4 changes //depot/elm_proj/. a file’s type is inherited from one revision to the next. but can be overridden or changed by opening the file with the -t filetype flag: • p4 add -t filetype filespec adds the files as the type you’ve specified. The file’s type determines whether full file or delta storage is used. When delta storage is used. binary files.. • p4 reopen -t filetype filespec changes the type of a file that’s already open for add or edit.pl to executable text with RCS keyword expansion. File Types Perforce supports six base file types: text files.Chapter 4: Perforce Basics: The Details Example: Listing changes with revision ranges.
2. The client workspace always contains the file as it was submitted. Non-UNIX binary symlink Non-text file Symbolic link full file. AppleSingle format.Chapter 4: Perforce Basics: The Details compares can be performed. UNIX clients (and the BeOS client) access these as symbolic links. please see the Mac platform notes at. resource Macintosh resource fork The only file type for Mac resource forks in Perforce 99.html full file. please see the Mac platform notes at. The compression occurs during the submission process. For full details. Some file types are compressed to gzip format when stored in the depot. apple Multi-forked AppleSingle storage of Mac data fork. only the part of the file up to the ^Z will be stored in the depot. and decompression happens while syncing. compressed. compressed 56 Perforce 2003. This is still supported.html full file. Accessed as binary files on the client. Macintosh file resource fork. file type and file creator.com/perforce/ technical. Warning! Do not try to fool Perforce into storing binary files in delta storage by changing the file type to text! If you add a file that contains a ^Z as text from a Windows client. Line-ending delta translations are performed automatically on Windows and Macintosh clients.perforce. Base file types The base Perforce file types are: Keyword text Description Comments Server Storage Type Text file Treated as text on the client. compressed delta clients treat them as (small) text files.2 User’s Guide . Stored compressed within the depot. For full details.perforce.1 and before. New to Perforce 99.com/perforce/ technical. but we recommend using the new apple file type instead. Files that are stored in their full form cannot be merged or compared.
2 User’s Guide 57 . +k RCS keyword expansion Expands RCS (Revision Control System) keywords. see the System Administrator’s Guide.Chapter 4: Perforce Basics: The Details Keyword unicode Description Comments Server Storage Type Unicode file Perforce servers operating in internationalized mode support a Unicode file type. and corresponds to the +k (ktext) modifier in earlier versions of Perforce. Stored as UTF-8 File type modifiers The file type modifiers are: Modifier +x +w +ko Description Comments Execute bit set on client File is always writable on client Old-style keyword expansion Used for executable files. When using keywords in files..1. $Id:$) is optional. a colon after the keyword (e.g. Expands only the $Id$ and $Header$ keywords: This pair of modifiers exists primarily for backwards compatibility with versions of Perforce prior to 2000. These files are translated into the local character set. Supported keywords are: • • • • • • • • $Id$ $Header$ $Date$ $DateTime$ $Change$ $File$ $Revision$ $Author$ Perforce 2003. For details. RCS keywords are casesensitive.
2 User’s Guide . +C Server stores the full compressed version of each file revision Server stores deltas in RCS format Server stores full file per revision Only the head revision is stored on the server Preserve original modtime Default server storage mechanism for binary files..g. Useful for binary file types (e. only one user at a time will be able to open a file for editing. The following table lists the older keywords and their current base file types and modifiers: Old Keyword text xtext ktext kxtext binary xbinary ctext cxtext symlink resource Description Base Filetype text text text text binary binary text text symlink resource Modifiers Text file Executable text file Text file with RCS keyword expansion Executable text file with RCS keyword expansion Non-text file Executable binary file Compressed text file Compressed executable text file Symbolic link Macintosh resource fork none +x +k +kx none +x +C +Cx none none 58 Perforce 2003. +D +F +S +m File type keywords Versions of Perforce prior to 99. The file’s timestamp on the local filesystem is preserved upon submission and restored upon sync. such as PostScript files.obj files. Useful for long ASCII files that aren’t read by users as text. Useful for third-party DLLs in Windows environments. Useful for executable or .Chapter 4: Perforce Basics: The Details Modifier +l Description Comments Exclusive open (locking) If set. Older revisions are purged from the depot upon submission of new revisions. graphics) where merging of changes from multiple authors is meaningless. Default server storage mechanism for text files.1 used a set of keywords to specify file types.
Because the timestamps on such files are often used as proxies for versioning information (both within the development environment and also by the operating system). If the file matches an entry in the table. Perforce checks the typemap table. Perforce 2003. When you open a new file for add. rather than the file type it would have otherwise used. Perforce updates the timestamp when a file is synced. You can override the file type specified in the typemap table by specifying it on the command line with the -t filetype modifier. (Normally. and not the time on the client at the time of sync).Chapter 4: Perforce Basics: The Details Old Keyword uresource ltext xltext ubinary uxbinary tempobj ctempobj xtempobj xunicode Description Base Filetype resource text text binary binary ubinary cbinary ubinary unicode Modifiers +F +F +Fx +F +Fx +FSw +Sw +FSwx +x Uncompressed Macintosh resource fork Long text file Executable long text file Uncompressed binary file Uncompressed executable binary file Temporary object Temporary object (compressed) Temporary executable object Executable unicode Overriding file types with the typemap table Some file formats (for example. not the time at the Perforce server at time of submission. Perforce ignores the modtime (“file’s timestamp at time of submission”) or nomodtime (“date and time on the client at time of sync”) options on the p4 client form when syncing the file. but can sometimes be mistakenly detected by Perforce as being of type text. and Rich Text Format files) are actually binary files. The +m modifier is useful when developing using the third-party DLLs often encountered in Windows environments. If you use the +m modifier on a file. Adobe PDF files. Your system administrator can use the p4 typemap command to set up a table matching Perforce file types to file name specifications. and always restore the file’s original timestamp at the time of submit. Perforce uses the file type specified in the table. it is sometimes necessary to preserve the files’ original timestamps regardless of a Perforce user’s client settings. Preserving timestamps with the modtime (+m) modifier The modtime (+m) modifier is a special case: It is intended for use by developers who need to preserve a file’s original timestamp.) It allows a user to ensure that the timestamp of a file in a client workspace after a p4 sync will be the original timestamp existing on the file at the time of submission (that is.2 User’s Guide 59 .
Only the keywords already present on the form are recognized. the form is parsed by Perforce.txt#3 $ $Header: //depot/path/file.txt $ $Revision$ $Author$ $Revision: #3 $ $Author: edk $ Forms and Perforce Commands Certain Perforce commands. present a form to the user to be filled in with values. Some keywords. The rules of form syntax are simple: keywords must be against the left margin and end with a colon. in depot syntax (without revision number) Perforce revision number Perforce user submitting the file $Change: 439 $ $File$ $File: //depot/path/file. and used to complete the command operation. take a 60 Perforce 2003. RCS keywords are expanded as follows: Keyword $Id$ $Header$ $Date$ $DateTime$ Expands To Example $Id: //depot/path/file.2 User’s Guide . When the user changes the form and exits the editor. If there are errors.txt#3 $ $Date: 2000/08/18 $ $DateTime: 2000/08/18 23:17:02 $ File name and revision number in depot syntax Synonymous with $Id$ Date of last submission in format YYYY/MM/DD Date and time of last submission in format YYYY/MM/DD hh:mm:ss Date and time are as of the local time on the Perforce server at time of submission. such as p4 client and p4 submit.Chapter 4: Perforce Basics: The Details Expanding RCS keywords with the +k modifier If you use the +k modifier to activate RCS keyword expansion for a file. such as the Client: field in the p4 client form. This form is displayed in the editor defined in the environment variable P4EDITOR. checked for errors. and values must either be on the same line as the keyword or indented on the lines beneath the keyword. Perforce gives an error message and you must try again. $Change$ Perforce changelist number under which file was submitted File name only.
Chapter 4: Perforce Basics: The Details
single value; other fields, such as Description:, take a block of text; and others, like View:, take a list of lines. Certain fields, like Client: in p4 client, can’t have their values changed; others, like Description: in p4 submit, must have their values changed. If you don’t change a field that needs to be changed, or vice versa, the worst that will happen is that you’ll get an error. When in doubt about what fields can be modified, see the Command Reference or use p4 help command.
Reading forms from standard input; Writing forms to standard output
Any commands that require the user to fill in a form, such as p4 client and p4 submit, can read the form from standard input with the -i flag. Similarly, the -o flag can be used to write a form specification to standard output. These two flags are primarily used in scripts that access Perforce: use the -o flag to read a form, process the strings representing the form within your script, and then use the -i flag to send the processed form back to Perforce. For example, to create a new job within a script you could first use p4 job -o > tempfile to read a blank job specification, then add information to the proper lines in tempfile, and finally use a command like p4 job -i < tempfile to store the new job in Perforce. The commands that display forms and can therefore use these flags are:
p4 branch p4 job p4 submit* p4 change p4 label p4 typemap p4 client p4 protect p4 user
* p4 submit can take the -i flag, but not the -o flag.
General Reporting Commands
Many reporting commands have specialized functions, and these are discussed in later chapters. The following reporting commands give the most generally useful information; all of these commands can take file name arguments, with or without wildcards, to limit reporting to specific files. Without the file arguments, the reports are generated for all files.
Perforce 2003.2 User’s Guide
61
Chapter 4: Perforce Basics: The Details
The following Perforce reporting commands generate information on depot files, not files within the client workspace. When files are specified in local or client syntax on the command line, Perforce uses the client workspace view to map the specified files to their locations in the depot.
Command p4 filelog p4 files p4 sync -n p4 have Meaning
Generates a report on each revision of the file(s), in reverse chronological order. Lists file name, latest revision number, file type, and other information about the named file(s). Tells you what p4 sync would do, without doing it. Lists all the revisions of the named files within the client that were last gotten from the depot. Without any files specifier, it lists all the files in the depot that the client has. Reports on all files in the depot that are currently open for edit, add, delete, branch, or integrate within the client workspace. Lists the contents of the named file(s) to standard output. Given a file argument, displays the mapping of that file within the depot, the client workspace, and the local OS.
p4 opened p4 print p4 where
Revision specifiers can be used with all of these reporting commands, for example p4 files @clientname can be used to report on all the files in the depot that are currently found in client workspace clientname. See Chapter 11, Reporting and Data Mining, for a more detailed discussion of each of these commands.
62
Perforce 2003.2 User’s Guide
Chapter 5
Perforce Basics: Resolving File Conflicts
File conflicts can occur when two users edit and submit two versions of the same file. Conflicts can occur in a number of ways, but the situation is usually a variant of the following: 1. 2. 3. 4. 5. Ed opens file file.c for edit. Lisa opens the same file in her client for edit. Ed and Lisa both edit their client workspace versions of file.c. Ed submits a changelist containing file.c, and the submit succeeds. Lisa submits a changelist with her version of file.c; and her submit fails.
If Perforce were to accept Lisa’s version into the depot, the head revision would contain none of Ed’s changes. Instead, the changelist is rejected and a resolve must be performed. The resolve process allows a choice to be made: Lisa’s version can be submitted in place of Ed’s, Lisa’s version can be dumped in favor of Ed’s, a Perforce-generated merged version of both revisions can be submitted, or the Perforce-generated merged file can be edited and then submitted. Resolving a file conflict is a two-step process: first the resolve is scheduled, then the resolve is performed. A resolve is automatically scheduled when a submit of a changelist fails because of a file conflict; the same resolve can be scheduled manually, without submitting, by syncing the head revision of a file over an opened revision within the client workspace. Resolves are always performed with p4 resolve. Perforce also provides facilities for locking files when they are edited. This can eliminate file conflicts entirely.
RCS Format: How Perforce Stores File Revisions
Perforce uses RCS format to store its text file revisions; binary file revisions are always saved in full. If you already understand what this means, you can skip to the next section of this chapter, as the remainder of this section explains how RCS format works.
Only the differences between revisions are stored
A single file might have hundreds, even thousands, of revisions. Every revision of a particular file must be retrievable, and if each revision was stored in full, disk space problems could occur: one thousand 10KB files, each with a hundred revisions, would use a gigabyte of disk space. The scheme used by most SCM systems, including Perforce, is to
Perforce 2003.2 User’s Guide
63
Chapter 5: Perforce Basics: Resolving File Conflicts save only the latest revision of each file. suppose that a Perforce depot has three revisions of file file.2 User’s Guide . any file revision can be reconstructed. The reconstructed file#1 would read Reconstructed file#1: This is a test of the urgent system The RCS (Revision Control System) algorithm. This is because the head revision is accessed much more frequently than previous file revisions. 64 Perforce 2003. it is said that the full text of the head revisions are stored. uses a notation for implementing this system that requires very little storage space and is quite fast. and then store the differences between each file revision and the one previous. with the deltas leading forward through the revision history of the file. along with the reverse deltas of each previous revision. In RCS terminology. It is interesting to note that the full text of the first revision could be stored. developed by Walter Tichy. if the head revision of a file had to be calculated from the deltas each time it was accessed. but RCS has chosen the other path: the full text of the head revision of each file is stored. with the deltas leading backwards to the first revision. any SCM utilizing RCS format would run much more slowly. As an example. The head revision (file#3) looks like this: file#3: This is a test of the emergency broadcast system Revision two might be stored as a symbolic version of the following: file#2: line 3 was “urgent” And revision one might be a representation of this: file#1: line 4 was “system” From these partial file descriptions.
it is by default only used with text files. it is deleted from the client. a resolve is scheduled between the file revision in the depot. and this conflict must be resolved. it is copied from the depot to the client. or it is found in the client but is unopened. Instead. • If the file has been deleted from the depot. He has retrieved the //depot/elm_proj/doc/*. An alternative is to submit a changelist that contains the newly conflicting files. they must be scheduled.2 User’s Guide 65 . • If the file has been opened in the client with p4 edit. Because Perforce’s diff always determines file deltas by comparing chunks of text between newline characters. Thus.Chapter 5: Perforce Basics: Resolving File Conflicts Use of “diff” to determine file revision differences RCS uses the “GNU diff” algorithm to determine the differences between two versions of the same file. the Perforce server can’t simply copy the file onto the client: any changes that had been made to the current revision of the file in the client would be overwritten. a resolve must be performed before the new file revision can be accepted into the depot.guide files into his client and has opened the files with p4 edit. If a resolve is necessary.guide files in the elm doc subdirectory. but before he has a chance to submit them. Scheduling Resolves of Conflicting Files Whenever a file revision is to be submitted that is not an edit of the file’s current head revision. this can be done with p4 sync. Why “p4 sync” to Schedule a Resolve? Remember that the job of p4 sync is to project the state of the depot onto the client. If a file is binary. Lisa submits new Perforce 2003. Before resolves can be performed with p4 resolve. If the base file revision for a particular file in a client workspace is not the same as the head revision of the same file in the depot. the file on the client. and the base file revision (the revision that was last read into the client). when p4 sync is performed on a particular file: • If the file does not exist in the client. He edits the files. Example: Scheduling resolves with p4 sync Ed is making a series of changes to the *. p4d contains its own diff routine which is used by Perforce servers to determine file differences when storing deltas. there will be a file conflict. each revision is stored in full. and the resolve is scheduled automatically. the submit fails. we’ll call the file revision that was read into a client workspace the base file revision. In slightly more technical terms.
The dialog looks something like this: /usr/edk/elm/doc/answer.guide. If file conflict resolutions are necessary. The advantage of this approach is that the files in the default changelist remain in the default changelist (that is. 66 Perforce 2003.merging //depot/elm_proj/doc/answer. and this number must be used in all future references to the changelist.2 User’s Guide .Chapter 5: Perforce Basics: Resolving File Conflicts versions of some of the same files to the depot. Since these files are already open in the client. the user can accept any of these revisions in place of the current client file. the file conflicts would cause the p4 submit to fail.1#5 Diff chunks: 4 yours + 2 theirs + 1 both + 1 conflicting Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) [e]: The remainder of this section explains what this means. using the files in the changelist as arguments to the command. Ed schedules the resolves with p4 sync //edk/doc/*. a series of options are displayed for the user to respond to. Alternatively. and how to use this dialog. Perforce doesn’t replace the client files. (Numbered changelists are discussed in Chapter 7. p4 resolve starts with three revisions of the same file and generates a fourth version. Perforce schedules resolves between the client files and the head revisions in the depot. and the error message includes the names of the files that need resolution. and the resolves would be scheduled as part of the submission failure. Changelists) Another way of determining whether a resolve is needed is to run p4 sync -n filenames before performing the submit.1 . The new revisions must then be submitted with p4 submit. How Do I Know When a Resolve is Needed? p4 submit fails when it determines that any of the files in the submitted changelist need to be resolved. it is assigned a number. p4 resolve is interactive. The versions Ed has been editing are no longer the head revisions. Performing Resolves of Conflicting Files File conflicts are fixed with p4 resolve [filenames]. Instead. and can edit the generated version before accepting it. the default changelist will not be reassigned to a numbered changelist).guide files in a changelist. Each file provided as an argument to p4 resolve is processed separately. and resolves must be scheduled and performed for each of the conflicting files before Ed’s edits can be accepted. Ed could have submitted the //depot/elm_proj/doc/*. p4 sync -n reports them. If the changelist provided to p4 submit was the default changelist.
File variation generated by Perforce from theirs. yours. The file revisions used by p4 resolve are these: yours The newly-edited revision of the file in the client workspace. yours. but p4 sync can be used to schedule a resolve with any revision between the head revision and base. and result to refer to the corresponding file revisions. The file resulting from the resolve process. The revision in the depot that the client revision conflicts with. for each set of lines in yours. there would be no reason to perform a resolve. p4 resolve asks the following questions: • Is this line set the same in yours. The definitions given above are somewhat different when resolve is used to integrate branched files. Yours and theirs are both generated by a series of edits to base. yours. this is the head revision. Note that base and theirs are different revisions. but different in yours? Perforce 2003. and base. Once these differences are found.Chapter 5: Perforce Basics: Resolving File Conflicts File revisions used and generated by “p4 resolve” p4 resolve [filenames] starts with three revisions of the same file. three new lines that are adjacent to each other are grouped into a single chunk. or can edit merge to have more control over the result. overwriting yours. merge. and must subsequently be submitted by the user. if they were the same.2 User’s Guide 67 . allows the user to edit the new file. and base. The instructions given by the user during the resolve process determine exactly what is contained in this file. result is written to the client workspace. This file is overwritten by result once the resolve process is complete. Usually. The file revision in the depot that yours was edited from. theirs. The user can simply accept theirs. they are grouped into chunks: for example. and base? • Is this line set the same in theirs and base. theirs. or merge as the result. theirs base merge result The remainder of this chapter will use the terms theirs. base. Types of conflicts between file revisions The diff program that underlies the Perforce resolve mechanism determines differences between file revisions on a line-by-line basis. and writes the new file (or any of the original three revisions) to the client. generates a new version that merges elements of all three revisions.
as it is often necessary to examine the changes made to theirs to make sure they’re compatible with other changes that you made. theirs.Chapter 5: Perforce Basics: Resolving File Conflicts • Is this line set the same in yours and base. which can be accepted as is. editing the Perforce-generated merge file is often as simple as opening the merge file. but different in theirs? • Is this line set the same in yours and theirs. edited and then accepted. The “p4 resolve” options The p4 resolve command offers the following options: Option e ey Short Meaning What it Does edit merged edit yours Edit the preliminary merge file generated by Perforce Edit the revision of the file currently in the client 68 Perforce 2003. How the merge file is generated p4 resolve generates a preliminary version of the merge file. A simple algorithm is followed to generate this file: any changes found in yours.2 User’s Guide . two line sets are identical in theirs and base but are different in yours. This isn’t always the case. The number of line sets that answer the other four questions are reported by p4 resolve in this form: 2 yours + 3 theirs + 1 both + 5 conflicting In this case. and any conflicting changes will appear in the merge file in the following format: >>>> ORIGINAL VERSION file#n (text from the original version) ==== THEIR VERSION file#m (text from their file) ==== YOUR VERSION file (text from your file) <<<< Thus. theirs. and five line sets are different in yours. instead of only for changes that are in conflict between the yours and theirs files. searching for the difference marker “>>>>”. p4 resolve -v tells Perforce to generate difference markers for all changes made in either file being resolved. or both yours and theirs are applied to the base file and written to the merge file. This can be facilitated by calling p4 resolve with the -v flag. but different in base? • Is this line set different in all three files? Any line sets that are the same in all three files don’t need to be resolved. one line set was changed identically in yours and theirs. three line sets are identical in yours and base but are different in theirs. and base. and editing that portion of the text. or rejected.
2 User’s Guide 69 . The version originally in the client workspace is overwritten. there are conflicts between yours and theirs. ignoring changes that may have been made in theirs. The version originally in the client workspace is overwritten. Accept merge into the client workspace as the resolved revision. To use this option. accept merge. if yours and theirs are different from base. accept the edited version into the client workspace. Diff line sets from yours that conflict with base Diff line sets from theirs that conflict with base Diff line sets from merge that conflict with base Diff line sets from merge that conflict with yours Invoke the command P4MERGE base theirs yours merge. accept yours. accept theirs. This edit is read-only. Accept yours into the client workspace as the resolved revision. The revision that was in the client workspace is overwritten.Chapter 5: Perforce Basics: Resolving File Conflicts Option et Short Meaning What it Does edit theirs Edit the revision in the depot that the client revision conflicts with (usually the head revision). if yours is identical to base. so skip this file dy dt dm d m diff yours diff theirs diff merge diff merge ? s ay help skip accept yours at accept theirs am accept merge ae accept edit a accept Perforce 2003. otherwise. If theirs is identical to base. Display help for p4 resolve Don’t perform the resolve right now. and there are no conflicts between yours and theirs. you must set the environment variable P4MERGE to the name of a thirdparty program that merges the first three files and writes the fourth as a result. Accept theirs into the client workspace as the resolved revision. If you edited the merge file (by selecting “e” from the p4 resolve dialog).
merging //depot/elm_proj/doc/Alias. and this diff can be overridden by specifying an external diff in the P4DIFF environment variable. dm. The recommended command is chosen by Perforce by the following algorithm: if there were no changes to yours. and sees the following: /usr/edk/elm/doc/Alias. He types dt (for “display theirs”) to view Lisa’s changes. Of most concern to him. The following text is displayed: Acme Technology Mountain View. Lisa had already submitted versions. he types p4 resolve //depot/elm_proj/doc/*.guide. California >>>> ORIGINAL VERSION ==== THEIR VERSION 94041 ==== YOUR VERSION 98041 <<<< 70 Perforce 2003. He also notes that Lisa has made two changes that he’s unaware of.guide#5 Diff chunks: 4 yours + 2 theirs + 1 both + 1 conflicting Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) [e]: This is the resolve dialog for doc/Alias. The command line has the following format: Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) [am]: Perforce’s recommended choice is displayed in brackets at the end of the command line. Ed sees that he’s made four changes to the base file that don’t conflict with any of Lisa’s changes. and d are generated by a diff internal to the Perforce client program. accept yours. He types e to edit the Perforcegenerated merge file and searches for the difference marker “>>>>”. This was necessary because both he and Lisa had been editing the same files. he looks them over and sees that they’re fine. dt.2 User’s Guide .Chapter 5: Perforce Basics: Resolving File Conflicts Only a few of these options are visible on the command line. Ed scheduled the doc/*. the first of the four doc/*. of course. Pressing Return or choosing Accept will perform the recommended choice. Example: Resolving File Conflicts In the last example. Otherwise. The merge file is generated by p4d’s internal diff routine. but all options are always accessible and can be viewed by choosing help. To perform the resolves. and Ed needs to reconcile his changes with Lisa’s. accept merge. accept theirs. If there were no changes to theirs.guide.guide files.guide files for resolve.guide . But the differences displayed by dy. is the one conflicting change.
accept yours. in this case. When a version of the file is accepted onto the client. He edits this portion of the merge file so it reads as follows: Acme Technology Mountain View. Automatically accept the Perforce-recommended file revision: If theirs is identical to base. it would be necessary to perform another resolve. if yours is identical to base. Note that it is possible for another user to have submitted yet another revision of the same file to the depot between the time p4 resolve completes and the time p4 submit is performed. He quits from the editor and types am. “p4 resolve” flag Meaning -ay -at Automatically accept yours. there are conflicts between yours and theirs. the previous client file is overwritten. and the resolve process continues on the next doc/*. accept merge.guide file. seen that they’re compatible with his own. -am Perforce 2003. the edited merge file is written to the client. California 94041 The merge file is now acceptable to him: he’s viewed Lisa’s changes. Use this option with caution. This can be prevented by performing a p4 lock on the file before performing the resolve. and there are no conflicts between yours and theirs.2 User’s Guide 71 . Automatically accept theirs. and the only line conflict has been resolved. if yours and theirs are different from base. but Ed had typed it wrong. particular revisions of the conflicting files are automatically accepted. When these flags are used. so skip this file. Using Flags with Resolve to Automatically Accept Particular Revisions Five optional p4 resolve flags tell the command to work non-interactively. accept theirs. otherwise. as the file revision in the client workspace will be overwritten with no chance of recovery.Chapter 5: Perforce Basics: Resolving File Conflicts He and Lisa have both tried to add a zip code to an address in the file. and the new client file must still be submitted to the depot.
and knows that some of them will require resolving. accept yours.” There is an exception to this rule: Perforce also has a +l file type modifier to support exclusive-open. the user who locked it experiences no further conflicts on that file. accept theirs. you do them. He types p4 sync doc/*. If this option is used. 72 Perforce 2003. However. this comes at a price. a three-way merge is not possible. Under most circumstances. the resulting file in the client should be edited to remove any difference markers. and will not need to resolve the file. The clear benefit of p4 lock is that once a file is locked. if yours is identical to base. Locked files can also be unlocked manually by the locking user with p4 unlock. and all of these files that conflict with files in the depot are scheduled for resolve. Once the file is submitted. If you have a +l file open for edit. it is automatically unlocked. He’ll still need to manually resolve all the other conflicting files. and you can edit and choose between them. and will have to do their own resolves once they submit their revision. -as Example: Automatically accepting particular revisions of conflicting files Ed has been editing the files in doc/*. a file can be locked with p4 lock so that only the user who locked the file can submit the next revision of that file to the depot. Binary files and “p4 resolve” If any of the three file revisions participating in the merge are binary instead of text. a user who locks a file is essentially saying to other users “I don’t want to deal with any resolves. otherwise skip this file.2 User’s Guide . Instead. and those merge files that contain no line set conflicts are written to his client workspace. but the amount of work he needs to do is substantially reduced. p4 resolve performs a two-way merge: the two conflicting file versions are presented.guide.Chapter 5: Perforce Basics: Resolving File Conflicts “p4 resolve” flag Meaning -af Accept the Perforce-recommended file revision.guide. other users who attempt to edit the file will receive an error message. and the merge files for all scheduled resolves are generated. If theirs is identical to base. no matter what. He then types p4 resolve -am. Locking Files to Minimize File Conflicts Once open. as other users will not be able to submit the file until the file is unlocked.
Lisa submits a changelist with her version of the file. 4. but only the person who locked the file may submit it. 8. and his submit succeeds.2 User’s Guide 73 . Lisa opens the same file in her client for edit. By contrast. her submit fails because of file conflicts with the new depot’s file. Ed submits a changelist containing that file. Lisa finishes the resolve and attempts to submit. 5. Locked files appear in the output of p4 opened with an indication of *locked*. Perforce 2003. lock the file. new versions can’t be submitted by other users until the resolved file is either submitted or unlocked. Lisa starts a resolve. 2. the submit fails and must now be merged with Ed’s latest file. you can find all locked files you have open with the following command: p4 opened | grep "*locked*" This lists all open files you have locked with p4 lock. Ed and Lisa both edit their client workspace versions of file. 7.Chapter 5: Perforce Basics: Resolving File Conflicts The difference between p4 lock and +l is that p4 lock allows anyone to open a file for edit... there is no guarantee that the resolve process will ever end. 6. resolve the file. . Ed edits and submits a new version of the same file. Then sync the file. 2. you can use the +l (exclusive-open) filetype modifier to ensure that only one user at a time may work on the file. The following scenario demonstrates the problem: 1. Ed opens file file for edit. Preventing multiple checkouts with +l files If you know in advance that a certain file is only going to be worked on by a single user. and submit the file. a file of type +l allows only one person to open the file for edit in the first place. 3.and so on File locking can be used in conjunction with resolves to avoid this sort of headache. The sequence would be implemented as follows: 1. Preventing multiple resolves with p4 lock Without file locking. As long as the locked file is open. Before scheduling a resolve. On UNIX.
so p4 diff fails. you may want to ask your Perforce administrator to use the p4 typemap command (documented in the Perforce Command Reference) to ensure that all files matching a file specification (for instance. Branching. p4 resolved Reports which files have been resolved but not yet submitted. and p4 resolved. for some file types (usually binary files). Perforce 2003. merging and resolving may not be meaningful. p4 sync -n. p4 sync -n [filenames] Reports what the result of running p4 sync would be.gif for all . If the file is not open for edit in the client. Comparison of the revisions can be forced with p4 diff -f. p4 diff2.gif files) are assigned type +l by default. even revisions of entirely different files. this routine can be overridden by specifying an external diff in the P4DIFF environment variable. The specified files can be any two file revisions.. //depot/.Chapter 5: Perforce Basics: Resolving File Conflicts You can change a file’s type to exclusive-open by reopening it with the +l modifier. For instance: p4 reopen -t binary+l file. without actually performing the sync. and you may decide that you prefer to allow only one user to check these files out at a time. Resolves and Branching Files in separate codelines can be integrated with p4 resolve. for details about resolving branched files. even when the file in the client is not open for edit Although p4 diff runs a diff routine internal to Perforce./*.2 User’s Guide 74 .gif Although this prevents concurrent development. see Chapter 9. This is useful to see which files have conflicts and need to be resolved. If you find this style of work to be useful. The diff routine used by p4d cannot be overridden.. p4 diff2 file1 file2 Runs p4d’s diff subroutine on any two Perforce depot files. Command p4 diff [filenames] Meaning Runs a diff program between the file revision currently in the client and the revision that was last gotten from the depot. Resolve Reporting Four reporting commands are related to file conflict resolution: p4 diff. the two file revisions should be identical.
Reporting and Data Mining) has a longer description of each of these commands. Perforce 2003.2 User’s Guide 75 .Chapter 5: Perforce Basics: Resolving File Conflicts The reporting chapter (Chapter 11. p4 help provides a complete listing of the many flags for these reporting commands.
Chapter 5: Perforce Basics: Resolving File Conflicts 76 Perforce 2003.2 User’s Guide .
• Use the environment variable or registry variable P4CONFIG to point to a file containing a specification for the current Perforce environment.p4env) that is used to store variable settings. smaller facilities. There are three ways of changing your Perforce environment on the fly: • Reset your environment or registry variables each time you want to move to a new workspace. Each variable setting in the file stands alone on a line and must be in the form: P4VAR=value Perforce 2003. and • Recommendations for organization of files within the depot. and subsequent chapters cover the more advanced features. • Renaming files. In between are a host of other. P4CLIENT. the current values of the Perforce environment variables are used. • How to work on files while not connected to a Perforce server. P4CONFIG names a file (for example. each of which may connect to a different port. the values of P4PORT. Reconfiguring the Perforce Environment with $P4CONFIG Some Perforce users have multiple client workspaces. Whenever a Perforce command is executed. and so on. and P4USER. • Use command-line flags (discussed in the next section) to override the value of the environment variables P4PORT. Included here is information on the following: • Changing your Perforce environment with the P4CONFIG environment variable. the current working directory and its parent directories are searched for a file with the name stored in P4CONFIG. • Command-line flags common to all Perforce commands. this chapter covers these topics. P4CLIENT.2 User’s Guide 77 . are read from that file. If a file with that name is found. If no file of the given name is found.Chapter 6 Perforce Basics: Miscellaneous Topics The manual thus far has provided an introduction to the basic functionality provided by Perforce. • Using passwords to prevent impersonation by other users. • Refreshing the client workspace. .
It has a client root of /usr/edk/elm. and when he’s in /usr/edk/elmproj. use the p4 passwd command. Command-line flags (discussed in the next section) override the values found in the P4CONFIG file.2 User’s Guide . The values found in the file specified by P4CONFIG override any environment or registry variables that have been set. or by setting the value of P4USER configuration within the file described by P4CONFIG. and connects to the Perforce server at ida:1818. No one. He creates a file called . it can also lead to security problems. as new settings take effect whenever you switch your current working directory from one client workspace directory to another.p4settings in /usr/edk/elm containing the following text: P4CLIENT=elmproj P4PORT=ida:1818 He creates a second . Its client root is /usr/edk/other/graphics. his Perforce client is graphicwork. It contains: P4PORT=warhol:1666 P4CLIENT=graphicwork He always works within the directories where his files are located.p4settings file in /usr/edk/other/graphics. You can provide this password to Perforce in one of three ways: 78 Perforce 2003. his client is elmproj. If you use multiple client workspaces. this is a very useful feature. will be able to use any p4 command without providing the password to Perforce. To prevent another user from impersonating you within Perforce. by using the -u flag with the p4 command. Although this makes it easy to perform tasks for other users when necessary. The first workspace is elmproj. Whenever Ed is anywhere beneath /usr/edk/other/graphics. Perforce Passwords By default.Chapter 6: Perforce Basics: Miscellaneous Topics Values that can be stored in the P4CONFIG file are: P4CLIENT P4PORT P4DIFF P4MERGE P4EDITOR P4PASSWD P4USER P4HOST P4CHARSET P4LANGUAGE Example: Using P4CONFIG to automatically reconfigure the Perforce environment Ed often switches between two workspaces on the same machine. The second workspace is called graphicwork. Ed sets the P4CONFIG environment variable to .p4settings. and it uses the Perforce server at warhol:1666. P4CONFIG automates the process of changing the Perforce environment variables. any user can assume the identity of any other Perforce user by setting the value of P4USER to a different username. including the user who set the password.
c for editing under client workspace joe. Overrides the P4CLIENT environment variable. Once you have set your Perforce password with p4 user. Note Passwords can also be created. consult the Perforce System Administrator’s Guide for information on resetting passwords and other common user-related tasks. If this happens. p4 -P eds_password submit). Command-Line Flags Common to All Perforce Commands Some flags are available for use with all Perforce commands. these files are found relative to ~elm/src. Specifies the current directory. If you need to have your password reset. Opens file file. Set the value of the environment or registry variable P4PASSWD to the correct password. If you are a Perforce administrator. and deleted within the p4 user form. overriding the environment variable PWD. the password should always be set while logged onto the server. These flags are given between the system command p4 and the command argument taken by p4.c Runs the command on the specified client. p4 -C utf8 print //depot/file -C charset -d directory p4 -d ~elm/src edit one two Opens files one and two for edit. changed. contact your Perforce administrator. Set the value of P4PASSWD within the file described by P4CONFIG. 2. override the P4CHARSET variable. The flags are as follows: Flag -c clientname Meaning Example p4 -c joe edit //depot/file.Chapter 6: Perforce Basics: Miscellaneous Topics 1. Be careful when setting passwords. For security’s sake. For servers in unicode mode. Perforce 2003. Use the -P password flag between p4 and the actual command when giving a Perforce command (for instance. 3. the Perforce superuser will have to reset or remove your password.2 User’s Guide 79 . there is no way for you to use Perforce if you forget their password and the value of P4PASSWD has not been properly set.
Usually used in combination with the -u user flag. Prepend a tag to each line of output so as to make output more amenable to scripting. overriding the environment variable P4HOST. The command works without the -P flag only if bill has not set a Perforce password. p4 -u bill -d /usr/joe help). Specifies a Perforce user. See “Working Detached” on page 81. -p server p4 -p mama:1818 clients Reports a list of clients on the server on host mama.2 User’s Guide . even commands for which these flag usages are useless (for instance. from the named file. -s p4 -s info -u username p4 -u bill user Presents the p4 user form to edit the specification for user bill. one per line. The user may run only those commands to which he or she has access. override the P4LANGUAGE variable. -H host p4 -H host print //depot/file -L language Reserved for system integrators. 80 Perforce 2003.Chapter 6: Perforce Basics: Miscellaneous Topics Flag -G Meaning Example p4 -G info Cause all output (and batch input for form commands using the -i option) to be formatted as marshalled Python dictionary objects Specify the host name. using ida’s Perforce password. these additional flags are command dependent. Other flags are available as well. overriding the P4USER environment variable. See the Perforce Command Reference or use p4 help commandname to see the flags for each command. overriding P4PORT. Gives the Perforce server’s listening address. Supplies a Perforce password. For servers with non-English error messages. Displays the version of the p4 executable. p4 -u ida -P idas_pw job -P password Create a new job as user ida. overriding the value of P4PASSWD. port 1818. -V p4 -V All Perforce commands can take these flags. -x filename Instructs p4 to read arguments.
but whose contents are different than the files last taken by the client with p4 sync. and then edit or delete the files. • Use p4 diff to find all files in your workspace that have changed or been added without Perforce’s knowledge.2 User’s Guide 81 . • If you did not edit the files within the client workspace. These files are candidates for p4 edit. it is not always possible you to have a network connection to be present. copy them to the client workspace when the network connection is reestablished. These files are candidates for p4 delete. p4 diff -sd Note You can use p4 edit on any file. Finding changed files with “p4 diff” Use the p4 diff reporting command to compare a file in the client workspace with the corresponding file in the depot. this command gives the local file write permissions. Reports the names of unopened files missing from the client. As you edit files. even files you don’t want to edit. you use native OS commands to manually change the permissions on files. but does not otherwise alter it. The behavior of p4 diff can be modified with two flags: “p4 diff” Variation p4 diff -se Meaning Tells the names of unopened files that are present on the client. and the server responds by noting the edit in the depot’s metadata. you announce your intentions to the server with p4 edit.Chapter 6: Perforce Basics: Miscellaneous Topics Working Detached Under normal circumstances. Use the output from this command to bring the depot in sync with the client workspace. you work in your client workspace with a functioning network connection to a Perforce server. and you may need a method for working entirely detached from the server. Perforce 2003. The scheme is as follows: • Work on files without giving Perforce commands. Using “p4 diff” to update the depot The p4 diff variations described above can be used in combination with the -x flag to bring the state of the depot in sync with the changes made to the client workspace. However. Instead. and by unlocking the file in your client workspace.
In such a situation. and that the file is one that you wanted to keep.. suppose that you accidentally delete a client workspace file via the UNIX rm command. is to create one subdirectory per project within the depot. use: p4 diff -sd > DEL_FILES p4 -x DEL_FILES delete As always. //eds_elm/. three subtrees might be created within the depot: 82 Perforce 2003. which Perforce does not process until you type p4 submit. For example. If the client workspace is named eds_elm. your edit and delete requests are stored in changelists.2 User’s Guide . For example. Additionally. The safest way to organize the depot. you can use p4 sync -f files to bring the client workspace in sync with the files the depot thinks you have. but another project is added later: everyone who has a client workspace mapped as above will wind up receiving all the files from both projects into their workspaces.Chapter 6: Perforce Basics: Miscellaneous Topics To open changed files for edit after working detached. and can be used for the most simple Perforce depots. but mapping the entire depot to the workspace can lead to problems later on. This is the easiest mapping. This command is mostly a recovery tool for bringing the client workspace back into sync with the depot after accidentally removing or damaging files managed by Perforce. p4 have will still list the file as being present in the workspace. athena. Refreshing files The process of syncing a depot with a formerly detached client workspace has a converse: Perforce can get confused about the contents of a client workspace if you accidentally use the local OS file deletion command. Recommendations for Organizing the Depot The default view brought up by p4 client maps the entire depot to the entire client workspace. Suppose your server currently stores files for only one project... the default workspace view does not facilitate branch creation.. the default view looks like this: //depot/. use: p4 diff -se > CHANGED_FILES p4 -x CHANGED_FILES edit To delete files from the depot that were removed from the client workspace. Even after a submit. if your company is working on three projects named zeus. and apollo. even from the start.
. you can rename files by using p4 integrate to copy the file from one location in the depot to another.. This sort of organization can be easily extended to as many projects and branches as are needed. then one is moved to the d2 directory. if from_file is d1/one and to_file is d2/two..2 User’s Guide 83 . and //depot/apollo.Chapter 6: Perforce Basics: Miscellaneous Topics //depot/zeus. and is renamed two.. The from_file and to_file specifiers may include wildcards. deleting the file from the original location.. //depot/athena. //depot/apollo/.. //joe/. //sarah/athena/. If Joe is working on the zeus project.... and then submitting the changelist that includes the integrate and the delete. you create the new file by creating an integration record that links it to its deleted predecessor. Renaming Files Although Perforce doesn’t have a rename command. //sarah/apollo/. And Sarah. For example.. See the Perforce System Administrator’s Guide for details about setting up multiple depots. Perforce 2003. his mapping might look like this: //depot/zeus/. who’s working on the athena and apollo projects. Revision histories and renamed files When you rename a file (or move it from one directory to another) with p4 integrate.. might set up her client workspace as: //depot/athena/. Another way of solving the same problem is to have the Perforce system administrator create one depot for each project or branch. The process is as follows: p4 integrate from_files to_files p4 delete from_files p4 submit The from_file is moved to the directory and renamed according to the to_file specifier. as long as they are matched on both sides. Perforce write access (explained in the Perforce System Administrator’s Guide) is needed on all the specified files..
you’ll see only changes to newfile. as follows: $ p4 changes -i newfile. you must specify the -i (include changes from integrations) flag to p4 changes.2 User’s Guide . if you run p4 changes newfile.Chapter 6: Perforce Basics: Miscellaneous Topics As a result. regardless of how many times the file (or the directory in which it lives) has been renamed or moved.c Change 4 on 2000/10/24 by Change 3 on 2000/10/23 by Change 2 on 2000/10/21 by change 1 on 2000/10/20 by user@client user@client user@client user@client ’Latest bugfix’ ’Renamed file’ ’second version’ ’initial check-in’ Specifying the -i flag tells p4 changes to trace back through the integration records and retrieve all change information.c Change 4 on 2000/10/24 by user@client ’Latest bugfix’ Change 3 on 2000/10/23 by user@client ’Renamed file’ In order to see the full history of changes to the file (including changes made before the file was renamed or moved). 84 Perforce 2003. Only changes that have taken place after the renaming will be listed: $ p4 changes newfile.
2 User’s Guide 85 . and operations to be performed on these files. Each changelist would be submitted to the depot via separate p4 submit operations. Commands such as p4 add filenames and p4 edit filenames include the affected files in a changelist. suppose a user is fixing two bugs. and p4 submit sends the default changelist to the server for processing. This grouping of files as a single unit guarantees that code alterations spanning multiple files are updated in the depot simultaneously. the user must understand how to work with numbered changelists. is no longer the default changelist. In the above circumstances. Perforce 2003. Perforce commands such as p4 edit add the affected files to the default changelist. their revision numbers. if one user has a file locked and another user submits a changelist that contains that file. and must be referred to by its number. When a changelist is submitted to the depot. and another changelist for the files that fix the second bug. the depot is not actually altered until the changelist is submitted with p4 submit. • Under certain circumstances. For example. To reflect the atomic nature of changelist submissions. the user might elect to create one changelist for the files that fix the first bug. each of which spans a separate set of files. Perforce attempts to make changelist usage as transparent as possible: in the normal case. or none of them are. submission of a changelist is sometimes called an atomic change transaction. Rather than submit the fixes to both bugs in a single changelist. However. the depot is updated atomically: either all of the files in the changelist are updated in the depot. the p4 submit command can fail.Chapter 7 Changelists A Perforce changelist is a list of files. the changelist is assigned a number. the submit fails. there are two sets of circumstances that would require the user to understand and manipulate nondefault changelists: • Sometimes a user wants to split files into separate groups for submission. When a submit of the default changelist fails. For example.
c revision 3 revision 2 edit delete Each of the files in the changelist is said to be open within the client workspace: the first of the files above was opened for edit with p4 edit. p4 submit can take an optional.1 /utils/elmalias. only those files in the default changelist that match the file pattern are included in the submitted changelist. a change form is displayed. it becomes a permanent part of the depot’s metadata. For example. which sends the changelist to the server. In this case. 86 Perforce 2003. Since the p4d server program must receive this file pattern as a single argument. the changelist is assigned a sequential number. When you type p4 submit. The commands that add or remove files from changelists are: p4 add p4 integrate p4 delete p4 reopen p4 edit p4 revert By default. these commands. A changelist must contain a user-entered description. if you type p4 add filename. It is presented again here to provide a complete discussion of changelists. When you type p4 submit. containing the files in the default changelist. make sure to escape the * wildcard if it is used. For example. revision numbers of those files. When the user quits from the p4 submit editor. and its status changes from new or pending to submitted. which describes the nature of the changes being made. the changelist is submitted to the server and the server attempts to update the files in the depot. single file pattern as an argument. and p4 submit. Any file can be deleted from this list. The files in the changelist are updated within the depot with p4 submit. and is unchangeable except by Perforce administrators. a single changelist might contain the following: /doc/elm-help. act on the default changelist. A changelist is a list of files. the default changelist is submitted. Once a changelist has been submitted. the server processes the files contained in the changelist and alters the depot accordingly. and will appear again the next time you type p4 submit. and the second was opened for deletion with p4 delete. when a file is deleted. this file is added to the default changelist. If there are no problems.Chapter 7: Changelists Working with the Default Changelist Note The material in this subsection has already been presented in a slightly different form in earlier chapters. it is moved to the next default changelist. and operations to be performed on those files.2 User’s Guide .
2 User’s Guide 87 . and requires an update of utils/elmalias. to edit a file and submit it in changelist number 4. use p4 reopen -c default filenames. the other problem is in the aliasing system. Working With Numbered Changelists You can use commands such as p4 edit filename. where changenum is the number of the moving-to changelist. which by default adds the files to the default changelist. This command brings up the same form that you see during p4 submit. Ed wants to update each bug separately in the depot. use p4 edit -c 4 filename. He’s already started fixing both bugs. If you are moving files to the default changelist. You can move files from one changelist to another with p4 reopen -c changenum filenames. Example: Working with multiple changelists. Files can be deleted from the changelist by editing the form. All files in the default changelist are moved to this new changelist.c # edit # edit # edit Perforce 2003. files deleted from this changelist are moved to the next default changelist.c //depot/elm_proj/utils/elmalias. For example. The status for a changelist created by this method is pending until you submit the files in the changelist. and this changelist must be subsequently referred to by this change number.c //depot/elm_proj/filter/lock. this will allow him to refer to one bug fix by one change number and the other bug fix by another change number. and has opened some of the affected files for edit. to append a file to a pending numbered changelist with the -c changenum flag. He types p4 change. and sees Change: new Client: eds_elm User: edk Status: new Description: <enter description here> Files: //depot/elm_proj/filter/filter. One of the bugs involves mail filtering and requires updates of files in the filter subdirectory.Chapter 7: Changelists Creating Numbered Changelists Manually A user can create a changelist in advance of submission with p4 change. the changelist is assigned the next changelist number in sequence. Ed is working on two bug fixes simultaneously. Any single client file can be included in only one pending changelist.c. When you quit from the form.
and. 88 Perforce 2003. • User B types p4 edit //depot/file1.c. Ed finishes fixing the aliasing bug. which he created above. is now found in the default changelist. the changelist is assigned a number Submits of changelists occasionally fail. He changes the form. He could include that file in another numbered changelist. He opens this file for edit with p4 edit -c 29 filter/lock. such as not enough disk space.c. since the affected files are in the default changelist.c.c //depot/elm_proj/filter/lock. he submits the changelist with a straightforward p4 submit. Automatic Creation and Renumbering of Changelists When submit of the default changelist fails. He’ll finish fixing the filtering bug later. he could have moved it to changelist 29 with p4 reopen -c 29 filter/lock. the form looks like this: Change: new Client: eds_elm User: edk Status: new Description: Fixes filtering problems Files: //depot/elm_proj/filter/filter.c # edit # edit When he quits from the editor.c. The following sequence shows an example of how this can occur: • User A types p4 edit //depot/file1.c).2 User’s Guide . • There is a server error. He realizes that the filter problem requires updates to another file: filter/lock. • The user was not editing the head revision of a particular file. • The client workspace no longer contains a file included in the changelist.Chapter 7: Changelists Ed wants to use this changelist to submit only the fix to the filter problems. When he’s done. he’s told Change 29 created with 2 open file(s). deleting the last file revision from the file list. The file that he removed from the list. utils/elmalias. He fixes both bugs at his leisure. but decides to leave it where it is. This can happen for a number of reasons: • A file in the changelist has been locked by another user with p4 lock. (If the file had already been open for edit in the default changelist.c. opening the file with the -c 29 flag puts the file in changelist 29.
Perforce also locks the files to prevent others from changing them while the user resolves the reason for the failed submit. User A’s submit is rejected. a merge must be performed before the changelist will be accepted. If the submit failed because the client-owned revision of the file is not the head revision.2 User’s Guide 89 . If any file in a changelist is rejected for any reason. Perforce 2003.c that he edited is no longer the head revision of that file. Example: Automatic renumbering of changelists Ed has finished fixing the filtering bug that he’s been using changelist 29 for. (File merging is described in Chapter 5. the entire changelist is backed out. and this change number must be used from this point on to refer to the changelist. Perforce Basics: Resolving File Conflicts).Chapter 7: Changelists • User B submits her default changelist. and • User A submits his default changelist. Perforce assigns the changelist the next change number in sequence. p4 revert to remove files from the changelist (and revert them back to their old versions). Deleting Changelists To remove a pending changelist that has no files or jobs associated with it. and none of the files in the changelist are updated in the depot. when a changelist is submitted. Ed submits change 29 with p4 submit -c 29. and two other users have submitted changelists. Please see the Perforce System Administrator’s Guide for more information. and is told: Change 29 renamed change 33 and submitted. he’s submitted another changelist (change 30). Changelists that have already been submitted can be deleted by a Perforce administrator only under very specific circumstances. or p4 fix -d to remove jobs from the changelist. If the submitted changelist was the default changelist. use p4 change -d changenum. Since he created that changelist. since the file revision of file1. Thus. Perforce May Renumber a Changelist upon Submission The change numbers of submitted changelists always reflect the order in which the changelists were submitted. it may be renumbered. Pending changelists that contain open files or jobs must have the files and jobs removed from them before they can be deleted: use p4 reopen to move files to another changelist.
Limits the list to those changelists submitted from a particular client workspace. while the latter prints verbose information for a single changelist. Displays full information about a single changelist. one line per changelist.) p4 changes -u user p4 changes -c workspace p4 describe changenum 90 Perforce 2003. the report includes a list of affected files and the diffs of these files. (You can use the -s flag to exclude the file diffs. and an abbreviated description.2 User’s Guide . Command p4 changes p4 changes -m count p4 changes -s status Meaning Displays a list of all pending and submitted changelists. Limits the list to those changelists with a particular status.Chapter 7: Changelists Changelist Reporting The two reporting commands associated with changelists are p4 changes and p4 describe. p4 changes -s submitted will list only already submitted changelists. Limits the list to those changelists submitted by a particular user. The former is used to view lists of changelists with short descriptions. If the changelist has already been submitted. Limits the number of changelists reported on to the last count changelists. for example.
1.Chapter 8 Labels A Perforce label is a set of tagged file revisions. At a later time. or • branch from a known set of file revisions.0. Tag the file revisions with the label. and both can be used to refer to all the revisions in the set.1. you can retrieve all the tagged revisions into a client workspace by syncing the workspace to the label. For example. Perforce 2003. • A changelist number refers to the contents of all the files in the depot at the time the changelist was submitted. • distribute a particular set of file revisions to other users. but labels are named by the user. You can use labels to reproduce the state of these files within a client workspace. Using labels Labeling files is a two-step process. Create the label. Create a label when you want to: • keep track of all the file revisions contained in a particular release of software.2 User’s Guide 91 . • Changelists are always referred to by Perforce-assigned numbers. as both refer to particular sets of file revisions. Labels have some important advantages over change numbers: • The file revisions tagged by a particular label can come from different changelists. • The files and revisions tagged by a label can be changed at any point in the label’s existence. but a label can refer to any arbitrary set of files and revisions. Why not just use changelist numbers? Labels share certain important characteristics with changelist numbers. you might want to tag the file revisions that compose a particular release with the label release2. Labels provide a method of naming important sets of file revisions for future reference. 2.
Note Anyone can use p4 labelsync with your label to tag or untag files. Thus. To prevent others (or yourself) from inadvertently changing which files are tagged by a label. are untagged. use p4 labelsync as follows: p4 labelsync -l my_label All revisions in your client workspace are tagged with my_label. lock the label. branches. you can create a new label my_label by typing: p4 label my_label The following form is displayed: Label: my_label Owner: edk Description: Created by edk. but the same file revision may be tagged with multiple labels. Options: unlocked View: //depot/. (The View: field denotes a label view. After you have created the label.. 92 Perforce 2003. you can use it to tag any revision of any file under Perforce control. For instance. or depot name. Labeling all revisions in your workspace To tag file revisions in your client workspace with a label. this field can be used to limit which files can be tagged with the label.. See “Preventing inadvertent tagging and untagging of files” on page 93 for details. and depots. a new label name must be distinct from any existing client workspace. Only one revision of a given file can be tagged with a given label. This command brings up a form similar to the p4 client form.Chapter 8: Labels Creating a new label Use p4 label labelname to create a label. and any revisions previously tagged by my_label which are not present in your client workspace. branch. You do not normally need to change the View: field.2 User’s Guide . Label names share the same namespace as client workspaces. you can use p4 labelsync to tag files. Files are tagged with labels using the p4 labelsync command. the only thing you need to do is update the label’s description.) After you have created the label.
. if you have previously tagged all revisions under //depot/proj/rel1. Preventing inadvertent tagging and untagging of files Using p4 labelsync with no file arguments tags the eligible files in your client workspace and any applicable label view..) Previewing labelsync’s results You can preview the results of p4 labelsync with p4 labelsync -n. To untag a subset of tagged files. or retagged by the labelsync command without actually performing the operation. untagged. you can untag only the header files with: p4 labelsync -d -l my_label //depot/proj/rel1.0/hdrs/. you can delete the label from files with p4 labelsync -d.. (This operation can also be thought of as “adding” the label to the files. specifying the label and the desired file revisions. and untags all other files.0/hdrs/*. It will be impossible to call p4 labelsync on that label until the label is subsequently unlocked. an implicit //. is assumed.0/hdrs with the label my_label. This command lists the revisions that would be tagged. to tag all files in your client workspace that reside under //depot/proj/rel1.2 User’s Guide 93 . (Just as you can add a label to files with p4 labelsync -a.) Untagging files with p4 labelsync You can untag revisions with: p4 labelsync -d -l labelname filepattern If you omit the filepattern... use p4 labelsync -a. with my_label.. all files formerly tagged by the label are untagged.. For example.0/hdrs/.h header files are no longer tagged with my_label. This means that it is possible to accidentally lose the information that a label is meant to contain. The revisions of files under //depot/proj/rel1.Chapter 8: Labels Tagging specific files and revisions with p4 labelsync To tag a set of files (in addition to any revisions that may already have been tagged). use the following: p4 labelsync -a -l my_label //depot/proj/rel1. that also reside in your client workspace are tagged with the name my_label. Perforce 2003. To prevent this.0/. For example. call p4 label labelname and set the value of the Options: field to locked. hence the use of the -a flag with p4 labelsync.h Revisions of the *. supply a file specification.
He types p4 label build1. To include files and directories in a label view.2 User’s Guide ...0/bin/. and wishes to tag a recently built set of binaries in this workspace with the label build1. use p4 files. he must type: p4 labelsync -a //depot/proj/rel1.0. (This command is equivalent to p4 files //.).0 Owner: edk Description: Created by edk. a new empty label build1. Ed can use p4 labelsync -l build1.. He wants to ensure that he doesn’t inadvertently tag the rest of his workspace by calling p4 labelsync without specifying a file argument.0 is created. change action. With the default View: of //depot/.0 and uses the label’s View: field to restrict the scope of the label as follows: Label: build1. and changelist number. This label can tag only files in the /rel1.@labelname) Using label views The View: field in the p4 label form limits the files that can be tagged with a label. 94 Perforce 2003. -l labelname With the new View:.. After he saves from the editor. The locked / unlocked option in the Options: field can be used to prevent others from inadvertently retagging files with p4 labelsync. which allows you to tag any (and every) file in the depot with p4 labelsync.. set the label’s View: field to a subset of the depot.Chapter 8: Labels Listing files tagged by a label To list the revisions tagged with labelname.0 to tag the desired files. specify the files and directories to be included using depot syntax. specifying the label name as follows: p4 files @labelname All revisions tagged with labelname are listed with their file type. See “Preventing inadvertent tagging and untagging of files” on page 93)..0/bin directory.. Example: Using a label view to control what files can be tagged Ed is working in a large client workspace. The default label view includes the entire depot (//depot/.. To prevent yourself from inadvertently tagging your entire workspace with a label...0/bin/.. Options: unlocked View: //depot/proj/rel1.
Example: Retrieving files tagged by a label into a client workspace.. Lisa wants to retrieve some of the binaries tagged by Ed’s build1. so she types: p4 sync //depot/proj/rel1.0 label into her client workspace.0/bin/osx/server#6 .0 label and are also in Lisa’s client workspace view are retrieved into her workspace.0 Instead. changelist number (@7381).@build1. To get all files tagged by build1. she could type: p4 sync //depot/. If p4 sync @labelname is called with no file parameters.2 User’s Guide 95 .0/bin/osx/install#2 ..added as /usr/lisa/osx/install#2 <etc> All files under //depot/proj/rel1.0/bin/osx/logger#12 . Open files or files not under Perforce control are unaffected.@labelname. All files in the workspace that do not have revisions tagged by the label are deleted from the workspace. use the following command: p4 label -d labelname Perforce 2003.0 and sees: //depot/proj/rel1. Deleting labels To delete a label. This command is equivalent to p4 sync //.added as /usr/lisa/osx/server#6 //depot/proj/rel1.Chapter 8: Labels Referring to files using a label You can use a label name anywhere you can refer to files by revision (#1. files in the user’s workspace that are specified on the command line and also tagged by the label are updated to the tagged revisions. she’s interested in seeing only one platform’s build from that label. all files in the workspace that are tagged by the label are synced to the revision specified in the label. as in p4 sync files@labelname. or date (@2003/07/01). #head)..0 or even: p4 sync @build1.0/bin/osx that are tagged with Ed’s build1.0. If p4 sync @labelname is called with file arguments..added as /usr/lisa/osx/logger#12 //depot/proj/rel1.0/bin/osx/*@build1.
the revision is tagged with the label if it is not already tagged with the label. but the arguments contain no revision specifications. whether the client workspace contains a different revision than the one specified. 3.] The rules followed by labelsync to tag files with a label are as follows: 1. 6. the revision specified on the command line is tagged with the label. When p4 labelsync is used to tag a file revision with a label. and the label must be unlocked. When you call p4 labelsync with file pattern arguments. Any files or directories not included in a label view are ignored by p4 labelsync. it is untagged and the newly specified revision is tagged. these revisions (“the #have revisions”) can be seen in the p4 have list. (or doesn’t contain the file at all). If a different revision of the file is already tagged with the label.. Calling p4 labelsync this way removes the label from revisions it previously tagged unless those revisions are in your workspace. You must be the owner of the label to use p4 labelsync on it. All files tagged with a label must be in the label view specified in the p4 label form. then all the files in both the label view and the client workspace view are tagged with the label.2 User’s Guide . you may (assuming you have sufficient permissions) make yourself the owner by running: p4 label labelname and changing the Owner: field to your Perforce user name in the p4 label form. but only one revision of any file can be tagged with a given label at any one time. If you call p4 labelsync with file pattern arguments and those arguments contain revision specifications.Chapter 8: Labels Details: How p4 labelsync works The full syntax of the p4 labelsync command is: p4 labelsync [-a -d -n] -l labelname [filename. If you are not the owner of a label. If you are the owner of a label. you may unlock the label by setting the Options: field (also in the p4 label form) to unlocked. 2. Specifying a revision in this manner overrides all other ways of specifying a revision with a label. the specified file revisions are tagged with the label. The revisions tagged by the label are those last synced into the client workspace.. the #have revision is tagged with the label. If labelsync is called with no filename arguments. 96 Perforce 2003. as in: p4 labelsync -l labelname 4. 5. Any given file revision may be tagged by one or more labels.
Chapter 8: Labels
The following table lists variations of p4 labelsync as typed on the command line, their implicit arguments as parsed by the Perforce Server, and the sets of files from which p4 labelsync selects the intersection for tagging.
Call p4 labelsync with -l label Implicit Arguments -l label //myworkspace/...#have
(no files specified)
-l label files
Tags every file in your client workspace at the revision currently in your client workspace.
-l label [cwd]/files#have
(files specified in local syntax, no revision specified)
-l label files#rev
Tags only the files in your client workspace that you specify, at the revision currently in your client workspace.
-l label [cwd]/files#rev
(files specified in local syntax, specific revision requested)
Tags only the files in your client workspace that you specify, at the revision you specify. Files must be in your client workspace view. You can use numeric revision specifiers here, or #none to untag files, or #head to tag the latest revision of a file, even if you haven’t synced that revision to your workspace.
-l label //files#have
-l label //files
(files specified in depot syntax, no revision specified)
Tags only the files in the depot that you specify, at the revision currently in your client workspace, whether the files are in your client workspace view or not.
-l label //files#rev
-l label //files#rev
(files specified in depot syntax, specific revision requested)
Tags only the files in the depot that you specify, at the revision at the revision you specify, whether the files are in your client workspace view or not.
Label Reporting
The commands that list information about labels are:
Command p4 labels p4 labels file#revrange Description
List the names, dates, and descriptions of all labels known to the server List the names, dates, and descriptions of all labels that tag the specified revision(s) of file.
Perforce 2003.2 User’s Guide
97
Chapter 8: Labels
Command p4 files @labelname p4 sync -n @labelname
Description
Lists all files and revisions tagged by labelname. Lists the revisions tagged by the label that would be brought into your client workspace, (as well as files under Perforce control that would be deleted from your client workspace because they are not tagged by the label), without updating your client workspace.
98
Perforce 2003.2 User’s Guide
Chapter 9
Branching
Perforce’s Inter-File Branching™ mechanism allows any set of files to be copied within the depot, and allows changes made to one set of files to be copied, or integrated, into another. By default, the new file set (or codeline) evolves separately from the original files, but changes in either codeline can be propagated to the other with the p4 integrate command.
What is Branching?
Branching is a method of keeping two or more sets of similar (but not identical) files synchronized. Most software configuration management systems have some form of branching; we believe that,: • The members of the development group want to submit code to the depot whenever their code changes, whether or not it compiles, but the release engineers don’t want code to be submitted until it’s been debugged, verified, and signed off on.
Perforce 2003.2 User’s Guide
99
The second method remembers the mappings between the two file sets. if required. and is now going to begin work on a Macintosh driver using the UNIX code as their starting point. but requires the user to manually track the mappings between the two sets of files. it is integrated into the release codeline. The command looks like this: p4 integrate fromfiles tofiles In the second method. integrated back into the development code. integrate them back into the //depot/main/ codeline. but requires some additional work to set up. is given a name. 100 Perforce 2003. Make release-specific bug fixes in the release branch and. When the development codeline is ready. • A company is writing a driver for a new multi-platform printer.2 User’s Guide . One basic strategy is to develop code in //depot/main/ and create branches for releases (for example. the user specifies both the files that changes are being copied from and the files that the changes are being copied into. and this mapping. or branch specification. patches and bug fixes are made in the release code.1/). and now have two copies of the same code. In the first method. //depot/rel1. and at some point in the future. bug fixes can be propagated from one codeline to the other with the Perforce p4 integrate command. One method requires no special setup. If bugs are found in either codeline. Perforce’s Branching Mechanisms: Introduction Perforce provides two mechanisms for branching. It has written a UNIX device driver. These two codelines can then evolve separately. The command the user runs to copy changes from one set of files to the other looks like this: p4 integrate -b branchname [tofiles] These methods are described in the following two sections. The developers create a branch from the existing UNIX code. Make bug fixes that affect both codelines in //depot/main/ and integrate them into the release codelines. Afterwards.Chapter 9: Branching They would branch the release codeline from the development codeline. Perforce stores a mapping that describes which set of files get branched to other files.
which copies all the files under //depot/elm_proj/. Version 2. The new files are created within the depot. and work on version 3... need to be branched into //depot/elm_r2.0/. 3..0 is about to commence. Example: Creating a branched file. Perforce 2003.0. 2. and are now available for general use.. The target files need to be contained within the current client workspace view... Finally. Run p4 integrate fromfiles tofiles. In both cases. he runs p4 submit. Examples and further details are provided below.0/..0 will take place in //depot/elm_r2.2 User’s Guide 101 . so long as the source files are specified in depot syntax.0 in his client workspace. Add the corresponding mapping specification to your client view..Chapter 9: Branching Branching and Merging.. Determine where you want the copied (or branched) file(s) to reside within the depot and within the client workspace..0/. to //eds_elm/v2. changes can be propagated from one set of files to the other with p4 resolve. Creating branched files To create a copy of a file that will be tracked for branching. the entire contents of the source files are copied to the target files. so Ed does the following: He decides that he’ll want to work on the new //depot/elm_r2. use the following procedure: 1.... He runs p4 integrate //depot/elm_proj/. Run p4 submit.0/. The source files do not need to be.. //eds_elm/r2. and it is determined that maintenance of version 2.. //depot/elm_r2......0/.. If the target files have already been created. The files in //depot/elm_proj/.0/.. He uses p4 client to add the following mapping to his client view: //depot/elm_r2. files within his client workspace at /usr/edk/elm_proj/r2. p4 submit must be used to store the new file changes in the depot. which adds the new branched files to the depot. Work on the current development release always proceeds in //depot/elm_proj/.0 of Elm has just been released. The source files are copied from the server to target files in the client workspace. If the target files do not yet exist. Method 1: Branching with File Specifications Use p4 integrate fromfiles tofiles to propagate changes from one set of files (the source files) to another set of files (the target files).
Branching not only enables you to more easily track changes.c //depot/elm_r2.0 codeline. so that the depot holds only one copy of the original file and a record that a branch was created. He wants to merge the same bug fix to the release 2. (You’ll find a general discussion of the resolve process in Chapter 5. The procedure is as follows: 1.0/src/elm.c file.c#9 The file has been scheduled for resolve. and has fixed a bug in the original codeline’s src/elm. From his home directory. you create two copies of the same file on the server. The changes are made to the target files in the client workspace.c#2 Diff chunks: 0 yours + 1 theirs + 0 both + 0 conflicting Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) [at]: 102 Perforce 2003.integrate from //depot/elm_proj/src/elm. allowing easy propagation of changes between one set of files and another. when you use p4 integrate.c and sees //depot/elm_r2. Run p4 integrate fromfiles tofiles to tell Perforce that changes in the source files need to be propagated to the target files. /usr/edk/elm_r2.c#1 .merging //depot/elm_proj/src/elm.c . 2. Propagating changes between branched files After a file has been branched from another with p4 integrate. Example: Propagating changes between branched files. Use p4 resolve to copy changes from the source files to the target files. He types p4 resolve. and the standard merge dialog appears on his screen. Perforce can track changes that have been made in either set of files and merge them using p4 resolve into the corresponding branch files.0/src/elm. Run p4 submit to store the changed target files in the depot.0 branch of the Elm source files as above. Perforce Basics: Resolving File Conflicts. it creates less overhead on the server. When you copy files with p4 add. 3. File resolution with branching is discussed in “How Integrate Works” on page 108).0/src/elm. Ed types p4 integrate elm_proj/src/elm. Perforce performs a “lazy copy” of the file. Perforce is able to track the connections between related files in an integration record. When you use branching.Chapter 9: Branching Why not just copy the files? Although it is possible to accomplish everything that has been done thus far by copying the files within the client workspace and using p4 add to add the files to the depot. Ed has created a release 2.2 User’s Guide .
103 Perforce 2003. a p4 resolve -as or p4 resolve -am to accept the Perforcerecommended revision is usually sufficient. and changes never need to be propagated. but there are always differences between two versions of the same file in two different codelines. you can create a branch specification and use it as an argument to p4 integrate. The changes in the branched file can now be merged into his source file.c file to the original version of the same file. When changes to one codeline need to be propagated to another. there is no difference between branched files and non-branched files. Make sure that the new files and directories are included in the p4 client view of the client workspace that will hold the new files. edit.c and then runs p4 resolve. delete. you’ll never need to integrate or resolve the files in the two codelines. do the following: 1. When he’s done.0/src/screen. 2. and it still must be submitted to the depot. There is one fundamental difference between resolving conflicts in two revisions of the same file. and resolving conflicts between the same file in two different codelines. and the original files as the target files. you must tell Perforce to do this with p4 integrate. He types p4 integrate //depot/elm_r2. but if the codelines evolve separately.0/src/screen.) In their day-to-day use. Ed wants to integrate some changes in //depot/elm_r2. are used with all files. Use p4 branch branchname to create a view that indicates which target files map to which source files. by supplying the branched files as the source files.Chapter 9: Branching He resolves the conflict with the standard use of p4 resolve. submit. Propagating changes from branched files to the original files A change can be propagated in the reverse direction. Method 2: Branching with Branch Specifications To map a set of source files to target files. Example: Propagating changes from branched files to the original files. Branching and Merging. The standard Perforce commands like sync. To create and use a branch specification. and these differences usually don’t need to be resolved manually. See “Using Flags with Resolve to Automatically Accept Particular Revisions” on page 71 for details.2 User’s Guide . from branched files to the original files. The difference is that Perforce will detect conflicts between two revisions of the same file and then schedule a resolve. (In these cases.c //depot/elm_proj/src/screen. and so on. the result file overwrites the file in his branched client. and evolution of both codelines proceeds separately.
The following form is displayed: Branch: elm2. use p4 integrate -b branchname [tofiles].... The files in //depot/elm_proj/. //depot/elm_r2.0 maintenance codeline View: //depot/elm_proj/.0. to //eds_elm/r2.. 104 Perforce 2003.0 of Elm has just been released... 4.. need to be branched into //depot/elm_r2. Use p4 integrate -b branchname to create the new files..0 is about to commence.0 will take place in //depot/elm_r2.0/.. //depot/.0 Date: 1997/05/25 17:43:28 Owner: edk Description: Elm release 2. The view maps the original codeline’s files (on the left) to branched files (on the right). Ed changes the View: and Description: fields as follows: Branch: elm2. He runs p4 integrate -b elm2. Perforce uses the branch specification to determine which files the merged changes come from Use p4 submit to submit the changes to the target files to the depot.. then he runs p4 submit. so Ed does the following: Ed creates a branch specification called elm2.. Version 2. He uses p4 client to add the following mapping to his client view: //depot/elm_r2... 5. View: //depot/.0/.0/. Ed wants to work on the new //depot/elm_r2.0 by typing p4 branch elm2...Chapter 9: Branching 3. which adds the newly branched files to the depot. Work on the current development release always proceeds in //depot/elm_proj/. which copies all the files under //depot/elm_proj/.0.. and it is determined that maintenance of version 2...0/..0. this time using a branch specification....2 User’s Guide .0/.... To propagate changes from source files to target files. in his client workspace. The following example demonstrates the same branching that was performed in the example above. Example: Creating a branch..0 Date: 1997/05/25 17:43:28 Owner: edk Description: Created by edk.. and work on version 3. files within his client workspace at /usr/edk/elm_proj/r2. //eds_elm/r2..0/.0/.
He types p4 resolve. For example..0 source code and documents to two separate locations within the depot: Branch: elm2. the following branch specification branches the Elm 2. He types p4 integrate -b elm2. just as client views can. the result file overwrites the file in his branched client. Ed wants to propagate the same bug fix to the branched codeline he’s been working on.integrate from //depot/elm_proj/src/elm.merging //depot/elm_proj/src/elm.c file. The branch specification merely specifies which files are affected by subsequent p4 integrate commands.c#1 .c . use the -r flag. • Exclusionary mappings can be used within branch specifications.. and it still must be submitted to the depot.2 User’s Guide 105 .0/src/elm.. Branch Specification Usage Notes • Creating or altering a branch specification has absolutely no immediate effect on any files within the depot or client workspace. A bug has been fixed in the original codeline’s src/elm. changes can be propagated from the source files to the target files with p4 integrate -b branchname. • Branch specifications may contain multiple mappings..c#9 Diff chunks: 0 yours + 1 theirs + 0 both + 0 conflicting Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) [at]: He resolves the conflict with the standard use of p4 resolve. Perforce 2003..0 Date: 1997/05/25 17:43:28 Owner: edk Description: Elm release 2..0/src/. //depot/elm_r2.0/.0 ~edk/elm_r2. //depot/docs/2..0/src/elm.0 maintenance codeline View: //depot/elm_proj/src/. When he’s done. • To reverse the direction of an integration that uses a branch specification.c#9 The file has been scheduled for resolve.Chapter 9: Branching Once the branch has been created and the files have been copied into the branched codeline. /usr/edk/elm_r2. and the standard merge dialog appears on his screen.c and sees: //depot/elm_r2.0/src/elm. Example: Propagating changes to files with p4 integrate.. //depot/elm_proj/docs/.
Chapter 9: Branching
Integration Usage Notes
• p4 integrate only acts on files that are the intersection of target files in the branch view and the client view. If file patterns are given on the command line, integrate further limits its actions to files matching the patterns. The source files supplied as arguments to integrate need not be in the client view. • The basic syntax of the integrate command when using a branch specification is:
p4 integrate -b branchname [tofiles]
If you omit the tofiles argument, all the files in the branch are affected. • The direction of integration through a branch specification may be reversed with the -r flag. For example, to integrate changes from a branched file to the original source file, use p4 integrate -b branchname -r [tofiles] • The p4 integrate command, like p4 add, p4 edit, and p4 delete, does not actually affect the depot immediately; instead, it adds the affected files to a changelist, which must be submitted with p4 submit. This keeps the integrate operation atomic: either all the named files are affected at once, or none of them are. • The actual action performed by p4 integrate is determined by particular properties of the source files and the target files: If the target file doesn’t exist, the source file is copied to target, target is opened for branch, and Perforce begins tracking the integration history between the two files. The next integration of the two files will treat this revision of source as base. If the target file exists, and was originally branched from the source file with p4 integrate, then a three-way merge is scheduled between target and source. The base revision is the previously integrated revision of source. If the target file exists, but was not branched from the source, then these two file revisions did not begin their lives at a common, older file revision, so there can be no base file, and p4 integrate rejects the integration. This is referred to as a baseless merge. To force the integration, use the -i flag; p4 integrate will use the first revision of source as base. (Actually, p4 integrate uses the most recent revision of source that was added to the depot as base. Since most files are only opened for add once, this will almost always be the first revision of source.)
Note In previous versions of Perforce (99.1 and earlier), integration of a target
that was not originally branched from the source would schedule a twoway merge, in which the only resolve choices were accept yours and accept theirs. As of Perforce 99.2, it is no longer possible to perform a two-way merge of a text file (even when possible, it was never desirable).
106
Perforce 2003.2 User’s Guide
Chapter 9: Branching
• By default, a file that has been newly created in a client workspace by p4 integrate cannot be edited before its first submission. To make a newly-branched file available for editing before submission, perform a p4 edit of the file after the resolve process is complete. • To run the p4 integrate command, you need Perforce write access on the target files, and read access on the source files. (See the Perforce System Administrator’s Guide for information on Perforce protections).
Deleting Branches
To delete a branch, use
p4 branch -d branchname
Deleting a branch deletes only the branch specification, making the branch specification inaccessible from any subsequent p4 integrate commands. The files themselves can still be integrated with p4 integrate fromfiles tofiles, and the branch specification can always be redefined. If the files in the branched codeline are to be removed, they must be deleted with p4 delete.
Advanced Integration Functions
Perforce’s branching mechanism also allows integration of specific file revisions, the reintegration and re-resolving of already integrated code, and merging of two files that were previously not related.
Integrating specific file revisions
By default, the integrate command integrates into the target all the revisions of the source since the last source revision that integrate was performed on. A revision range can be specified when integrating; this prevents unwanted revisions from having to be manually deleted from the merge while editing. In this case, the revision used as base is the first revision below the specified revision range. The argument to p4 integrate is the target, the file revision specifier is applied to the source.
Example: Integrating Specific File Revisions.
Ed has made two bug fixes to his file src/init.c, and Kurt wants to integrate the change into his branched version, which is called newinit.c. Unfortunately, init.c has gone through 20 revisions, and Kurt doesn’t want to have to delete all the extra code from all 20 revisions while resolving.
Perforce 2003.2 User’s Guide
107
Chapter 9: Branching
Kurt knows that the bug fixes he wants were made to file revisions submitted in changelist 30. From the directory containing his newinit.c file in his branched workspace, he types
p4 integrate -b elm_r1 newinit.c@30,@30
The target file is given as an argument, but the file revisions are applied to the source. When Kurt runs p4 resolve, only the revision of Ed’s file that was submitted in changelist 30 is scheduled for resolve. That is, Kurt only sees the changes that Ed made to init.c in changelist 30. The file revision that was present in the depot at changelist 29 is used as base.
Re-integrating and re-resolving files
After a revision of a source file has been integrated into a target, that revision is usually skipped in subsequent integrations with the same target. If all the revisions of a source have been integrated into a particular target, p4 integrate returns the error message All revisions already integrated. To force the integration of already-integrated files, specify the -f flag to p4 integrate. Similarly, a target that has been resolved but not (yet) submitted can be re-resolved by specifying the -f flag to p4 resolve, which forces re-resolution of already resolved files. When this flag is used, the original client target file has been replaced with the result file by the original resolve process; when you re-resolve, yours is the new client file, the result of the original resolve.
How Integrate Works
The following sections describe the mechanism behind the integration process.
The yours, theirs, and base files
The following table explains the terminology yours, theirs, and base files.
Term yours Meaning
The file to which changes are being propagated (also called the target file). This file in the client workspace is overwritten by the result when you resolve. The file from which changes are read (also known as the source file). This file resides in the depot, and is not changed by the resolve process. The last integrated revision of the source file. When you use integrate to create the branched copy of the file in the depot, the newly-branched copy is base.
theirs
base
The integration algorithm
108 Perforce 2003.2 User’s Guide
2. the target is marked for deletion. depending on particular characteristics of the source and target files: Action branch Meaning If the target file does not exist. This is consistent with integrate’s semantics: it attempts to make the target tree reflect the source tree. If both the source and target files exist. which is a variant of edit. it is opened for branch. a list of all source/target file pairs is generated. the target is opened for integration. the original codeline contains the source files. Before a user can submit a file that has been opened for integration. 3. if you reverse the direction of integration by specifying the -r flag. the source and target must be merged with p4 resolve.Chapter 9: Branching p4 integrate performs the following steps: 1. but Perforce keeps a record of which source file the target file was branched from. Integrate all remaining source/target pairs. and the branched codeline is the target. However. to avoid making you merge changes more than once. the branched codeline contains the source. If no files are provided on the command line. integrate delete By default. The branch action is a variant of add. Integrate’s actions The integrate command will take one of three actions. when you integrate using a branch specification. and the original files are the targets. Discard any source/target pairs for which the source file revisions have already been integrated. This allows three-way merges to be performed between subsequent source and target revisions with the original source file revision as base. When the target file exists but no corresponding source file is mapped through the branch view. including each revision of each source file that is to be integrated. Each revision of each file that has been integrated is recorded. 4. Perforce 2003. The target file is opened on the client for the appropriate action and merging is scheduled.2 User’s Guide 109 . Apply the branch view to any target files provided on the command line to produce a list of source/target file pairs. Discard any source/target pairs whose source file revisions have integrations pending in files that are already opened in the client.
When should a branch be created? At what point should code changes be propagated from one codeline to another? Who is responsible for performing merges? These questions will arise no matter what SCM system you’re using. including an overview of basic branching techniques.html Christopher Seiwald and Laura Wingerd’s Best SCM Practices paper provides a discussion of many source configuration management issues. (To perform the integration. Three on-line documents can provide some guidance in these matters.com/~bradapp/acme/plop98/streamed-lines.) Displays files that have been resolved but not yet submitted. the theory of branching can be very complex.) p4 resolve -n [filepatterns] Displays files that are scheduled for resolve by p4 integrate. is available from: 9: Branching Integration Reporting The branching-related reporting commands are: Command Function p4 integrate -n [filepatterns] Previews the results of the specified integration.com/perforce/bestpractices. including the integration histories of files from which the specified files were branched.perforce. and the answers are not simple.2 User’s Guide . A white paper on InterFile Branching. Displays all branches. p4 resolved p4 branches p4 integrated filepatterns p4 filelog -i [filepatterns] For More Information Although Perforce’s branching mechanism is relatively simple. This paper is available at:. You’ll find it at:. Displays the revision histories of the specified files. omit the -n flag.html 110 Perforce 2003. omit the -n flag. Displays the integration history of the specified files. (To perform the resolve.com/perforce/branch. which describes Perforce’s branching mechanism in technical detail. but does not perform the integration. but does not perform the resolve.html Streamed Lines: Branching Patterns for Parallel Software Development is an extremely detailed paper on branching techniques.perforce.
Chapter 10 Job Tracking A job is a written description of some modification to be made to a source code set. • Jobs can be created and edited by any user with p4 job. and deleted by Perforce administrators. or it might be a system improvement request. the job is marked as closed when the changelist is submitted. and their default values. • Jobs can be linked to changelists automatically or manually. Perforce 2003. • The jobs that have been fixed can be displayed with Perforce reporting commands. The remainder of this chapter discusses how these tasks are accomplished. The type of information tracked by the jobs system can be customized. Jobs perform no functions internally to Perforce. A job can later be looked up to determine if and when it was fixed. and who fixed it. These commands can list all jobs that fixed particular files or file revisions. like “the system crashes when I press return”. like “please make the program run faster. the possible values of a job’s fields. This job template is edited with the p4 jobspec command. which file revisions implemented the fix. changed. a changelist represents work actually done. all the jobs that were fixed in a particular changelist. A job might be a bug description. Perforce’s job tracking mechanism allows jobs to be linked to the changelists that implement the work requested by the job. A job linked to a numbered changelist is marked as completed when the changelist is submitted. Job Usage Overview There are five related but distinct aspects of using jobs.2 User’s Guide 111 . when a job is linked to a changelist. (See the Perforce System Administrator’s Guide for details on how to edit the job specification. • The Perforce superuser or administrator decides what fields are to be tracked in your system’s jobs. The job specification need not be changed before users can create jobs). which user is responsible for implementing the job. or all the changelists that were linked to a particular job fix. • The p4 jobs command can be used to look up all the jobs that meet specified criteria. they are provided as a method of keeping track of information such as what changes to the source are needed.” Whereas a job represents work that is intended. and which file revisions contain the implementation of the job. fields in the job form can be added. rather.
or new. The date and time at the moment this job was last modified.2 User’s Guide . the fields in jobs at your site may be very different than what you see above. Sarah knows about a job in Elm’s filtering subsystem. usually the username of the person assigned to fix this particular problem. Sarah creates a new job with p4 job and fills in the resulting form as follows: Job: new Status: open User: edk Date: 1998/05/18 17:15:40 Description: Filters on the “Reply-To:” field don’t work. The user whom the job is assigned to.Chapter 10: Job Tracking Creating and editing jobs using the default job specification Jobs are created with the p4 job command. and she knows that Ed is responsible for Elm filters. they change to status open as soon as the form has been completed and the job added to the database. The date the job was last modified. User creation form is closed. changes to open after job The name of the job. Date 112 Perforce 2003. suspended. The default p4 job form’s fields are: Field Name Job Status Description Default new new. Whitespace is not allowed in the name. An open job is one that has been created but has not yet been fixed. Jobs with status new exist only while a new job is being created. A suspended job is an open job that is not currently being worked on. Since job fields differ from site to site. Example: Creating a job Sarah’s Perforce server uses Perforce’s default jobs specification. closed. open. A closed job is one that has been completed. Sarah has filled in a description and has changed User: to edk. displayed as YYYY/MM/DD HH/MM/SS Perforce username of the person creating the job.
Job: new Status: open User: setme Type: setme Priority: unknown Subsystem: setme Owned_by: edk Description: <enter description here> Perforce 2003. or ’suspended’. Can be changed. but this can be changed by the user to any desired string. there may be additional fields in your p4 jobs form. Type: The type of the job. (A job. Status: Either ’open’. or suspended. Required. has this status automatically changed to open upon completion of the job form.Chapter 10: Job Tracking Field Name Description Description Default Arbitrary text assigned by the user. Text that must be changed If p4 job is called with no parameters.2 User’s Guide 113 . where N is a sequentially-assigned six-digit number. the status can be changed to any of the three valid status values open. Usually a written description of the problem that is meant to be fixed. closed. ’sir’. A sample customized job specification might look like this: # # # # # # # # # # # # Custom Job fields: Job: The job name. The name that appears on the form is new. Can be changed User: The user who created the job. When you call p4 job jobname with a nonexistent jobname. if submitted with a Status: of new. Acceptable values are ’bug’.) Creating and editing jobs with custom job specifications A Perforce administrator can add and change fields within your server’s jobs template with the p4 jobspec command. or ’unknown’ Subsystem: One of server/gui/doc/mac/misc/unknown Owned_by: Who’s fixing the bug Description: Comments about the job. ’c’. Existing jobs can be edited with p4 job jobname. Date: The date this specification was last modified. The user and description can be changed arbitrarily. ’new’ generates a sequenced job number. ’problem’ or ’unknown’ Priority: How soon should this job be fixed? Values are ’a’. ’b’. Perforce will assign the job the name jobN. ’closed’. If this has been done. and the names of the fields described above may have changed. Perforce creates a new job. If the Job: field is left as new. a new job is created.
for example. the following rules apply: • Textual comparisons within jobviews are case-insensitive. Throughout the following discussion. Example: Finding jobs that contain any of a set of words in any field. In its simplest form. separate the terms with the '|' character. file. file or mailbox. However. your Perforce administrator can tell you this in comments at the top of the job form.. wordN' can be used to find jobs that contain all of word1 through wordN in any field (excluding date fields). so the jobviews 'joe sue' and 'joe&sue' are identical. You can use ampersands instead of spaces in jobviews. The p4 job fields don’t tell you what the valid values of the fields are. Priority: must be one of a. He types: p4 jobs -e 'filter|file|mailbox' 114 Perforce 2003.2 User’s Guide . • there is currently no way to search for particular phrases. To find jobs that contain any of the terms. please tell your Perforce administrator. b. as are the field names that appear in jobviews. c. Example: Finding jobs that contain all of a set of words in any field. • only alphanumeric text and punctuation can appear in a jobview. p4 jobs will list every job stored in your Perforce server.. If you find the information in the comments for your jobs to be insufficient to enter jobs properly. He types: p4 jobs -e 'filter file mailbox' Spaces between search terms in jobviews act as boolean and’s. Viewing jobs by content with jobviews Jobs can be reported with p4 jobs. Finding jobs containing particular words The jobview 'word1 word2 .Chapter 10: Job Tracking Some of the fields have been set by the administrator to allow one of a set of values. Ed wants to find jobs that contains any of the words filter. p4 job -e jobview will list all jobs that match the criteria contained in jobview. with no arguments. and mailbox. Ed wants to find all jobs that contain the words filter. or unknown. Jobviews can search jobs only by individual words.
To search for words that happen to contain wildcards. and so on. p4 jobs -e '^user=edk' is not allowed. escape them at the command line. The jobview “fieldname=string*” matches “string”. a User: of edk.c in any non-date field.2 User’s Guide 115 . Perforce 2003. Ed wants to find all open jobs related to filtering of which he is not the owner. Example: Finding jobs that don’t contain particular words. He types: p4 jobs -e 'status=open user=edk filter. “stringlike”. the not operator. For instance. The not operator ^ can be used only directly after an and (space or &). “stringy”.c' This will find all jobs with a Status: of open. Example: Finding jobs that contain words in specific fields Ed wants to find all open jobs related to filtering of which he is the owner. You can use the * wildcard to get around this: p4 jobs -e 'job=* ^user=edk' returns all jobs with a user field not matching edk. and the word filter in any non-date field. to search for “*string” (perhaps in reference to char *string). Using and escaping wildcards in jobviews The wildcard “*” allows for partial word matches. and the word filter. Value must be a single alphanumeric word. you’d use the following: p4 jobs -e '\*string' Negating the sense of a query The sense of a search term can be reversed by prefacing it with ^.Chapter 10: Job Tracking Finding jobs by field values Search results can be narrowed by matching values within specific fields with the jobview syntax 'fieldname=value'. a User: of anyone but edk. He types: p4 jobs -e 'status=open ^user=edk filter' This displays all jobs with a Status: of open. Thus.
One of a set of values A date value A user name: edk A job’s description An email address A user’s real name. the equality operator = matches the entire day. Ed wants to view all jobs modified on July 13. They are: = > < >= <= The behavior of these operators depends upon the type of the field in the jobview. The field called Fields: lists the job fields’ names and datatypes.The field types are: Field Type word text line Explanation Examples A single word A block of text A single line of text. Differs from text fields only in that line values are entered on the same line as the field name. and text values are entered on the lines beneath the field name. which outputs the job specification your local jobspec. 1998. If you’re not sure of a field’s type. for example Linda Hopper select A job’s status: open/suspended/closed date The date and time of job creation: 1998/07/15:13:21:4 Field types are often obvious from context. Example: Using dates within jobviews.2 User’s Guide . is most likely a date field. for example. run p4 jobspec -o.Chapter 10: Job Tracking Using dates in jobviews Jobs can be matched by date by expressing the date as yyyy/mm/dd or yyyy/mm/dd:hh:mm:ss. If you don’t provide a specific time. He enters p4 jobs -e 'mod_date=1998/07/13' Comparison operators and field types The usual comparison operators are available. 116 Perforce 2003. a field called mod_date.
The equality operator = matches the job if the word given as the value is found anywhere in the specified field. Jobs can be linked to changelists in one of two ways: • Automatically.Chapter 10: Job Tracking The jobview comparison operators behave differently depending upon the type of field they’re used with. Dates are matched chronologically. The inequality operators are of limited use here. Linking jobs to changelists with the JobView: field The p4 user form can be used to automatically include particular jobs on any new changelists created by that user. Inequality operators perform comparisons in ASCII order. Linking Jobs to Changelists Perforce automatically changes the value of a job’s status field to closed when the job is linked to a particular changelist. call p4 user and change the JobView: field value to any valid jobview. the operators =.2 User’s Guide 117 . and the jobview is 'ShortDesc<filter'. since they’ll match the job if any word in the specified field matches the provided value. <=. above. The comparison operators match the different field types as follows: Field Type word Use of Comparison Operators in Jobviews The equality operator = must match the value in the word field exactly. by setting the JobView: field in the p4 user form to a jobview that matches the job. • manually. Perforce 2003. text line select date See text. To do this. and >= will match the whole day. if a job has a text field ShortDescription: that contains only the phrase gui bug. with the p4 fix command. If a specific time is not provided. and the changelist is submitted. by editing them within the p4 submit form. The inequality operators perform comparisons in ASCII order. The equality operator = matches a job if the value of the named field is the specified word. the job will match the jobview. For example. and • manually. because bug<filter.
the value of the job’s Status: field is changed to closed. delete jobs that aren’t fixed by the changelist from the changelist form before submission.2 User’s Guide . or unlinked from a changelist by deleting the job from the changelist’s change form. the bug reported by the job was fixed in Ed’s previously submitted changelist 18. 118 Perforce 2003. and should. Linking jobs to changelists with p4 fix p4 fix -c changenum jobname can be used to link any job to any changelist. You can use p4 fix to link a changelist to a job owned by another user. He types p4 user and adds a JobView: field: User: Update: Access: JobView: edk 1998/06/02 13:11:57 1998/06/03 20:11:07 user=edk&status=open All of Ed’s jobs that meet these JobView: criteria automatically appear on all changelists he creates. He can. the job keeps its current status. Linking jobs to changelists from within the submit form You can also add jobs to changelists by editing the Jobs: field (or creating a Jobs: field if none exists) in the p4 submit form.Chapter 10: Job Tracking Example: Automatically linking jobs to changelists with the p4 user form’s JobView field. Example: Manually attaching jobs to changelists. Ed wants to see all open jobs that he owns in all changelists he creates. When a changelist is submitted. If the changelist has already been submitted. Unbeknownst to Sarah. Otherwise. Ed links the job to the previously submitted changelist by typing: p4 fix -c 18 options-bug Since changelist 18 has already been submitted. Any job can be linked to a changelist by adding it to a changelist’s change form. the jobs linked to it will have their status: field’s value changed to closed. Sarah has submitted a job called options-bug to Ed. the job’s status is changed to closed.
she set the User: field to edk). he deletes job000125 from the form and then quits from the editor. He is unaware of a job that Sarah has made Ed the owner of (when she entered the job. the job’s status is changed to closed.c # edit Since the job is fixed in this changelist. Example: Submitting a changelist with an attached job. Perforce 2003.c //depot/src/file_util. Ed has set his p4 user ’s JobView: field as in the example above.c # edit //depot/filter/audit. When he quits from the editor.c //depot/src/fileio. Ed leaves the job on the form. He fixes this problem. and a number of other bugs. Automatic update of job status The value of a job’s Status field is automatically changed to closed when one of its associated changelists is successfully submitted. Ed uses the reporting commands to read the details about job job000125.c # edit # edit # edit Since this job is unrelated to the work he’s been doing.c # edit //depot/filter/filter. he types p4 submit and sees the following: Change: new Client: eds_ws User: edk Status: new Description: Updating "File" I/O files Jobs: job000125 # Filters on "Reply-To" field don’t work Files: //depot/src/file.Chapter 10: Job Tracking Example: Including and excluding jobs from changelists. The changelist is submitted without job000125 being associated with the changelist. he sees: Change: new Client: eds_ws User: edk Status: new Description: Fixes a number of filter problems Jobs: job000125 # Filters on "Reply-To" field don’t work Files: //depot/filter/actions. He is currently working on an unrelated problem. when he next types p4 submit. and since it hasn’t been fixed.2 User’s Guide 119 .
Job Reporting Commands The job reporting commands can be used to show the correspondence between files and the jobs they fix..perforce. Use This Command: p4 jobs -e jobview p4 jobs filespec . Integrating with External Defect Tracking Systems If you want to integrate Perforce with your in-house defect tracking system. or develop an integration with a third-party defect tracking system. Jobs can be deleted entirely with p4 job -d jobname.2 User’s Guide . To See a Listing of.com/perforce/products/p4dti. See the Perforce System Administrator’s Guide for more information. but nothing in the job changes when the changelist is submitted. Deleting Jobs A job can be unlinked from any changelist with p4 fix -d -c changenum jobname.all changelists and file revisions that fixed a particular job p4 fixes -j jobname 120 Perforce 2003.all jobs that match particular criteria ... see the P4DTI product information page at:. (In most cases. If the job specification has been altered so that this is no longer true. this is not a desired form of operation. and a kit (including source code and developer documentation) for building integrations with other products or in-house systems. P4DTI is probably the best place to start.) Please see the chapter on editing job specifications in the Perforce System Administrator’s Guide for more details.. jobs can still be linked to changelists.. Even if you don’t use the P4DTI kit as a starting point. To get started with P4DTI. you can still use Perforce’s job system as the interface between Perforce and your defect tracker.html Available from this page are the TeamShare and Bugzilla implementations. an overview of the P4DTI’s capabilities.Chapter 10: Job Tracking What if there’s no status field? The discussion in this section has assumed that the server’s job specification still contains the default Status: field..all the jobs that were fixed by changelists that affected particular file(s) ...
. Perforce 2003....all jobs linked to a particular changelist . or consult the Perforce Command Reference.all jobs fixed by changelists that contain particular files or file revisions Other job reporting variations are available. Use This Command: p4 fixes -c changenum p4 fixes filespec . please see “Job Reporting” on page 133.2 User’s Guide 121 .Chapter 10: Job Tracking To See a Listing of. For more examples...
2 User’s Guide .Chapter 10: Job Tracking 122 Perforce 2003.
One previously mentioned note on syntax is worth repeating here: any filespec argument in Perforce commands. Brackets around [filespec] mean that the file specification is optional. there are almost as many reporting commands as there are action commands. Files The commands that report on files fall into two categories: those that give information about file contents. many of the reporting commands can take revision specifiers as part of the filespec. Additionally. and those that supply information on file metadata. File metadata Basic file information To view information about single revisions of one or more files. p4 diff). or type p4 help command at the command line. in fact. and the files’ types. or client syntax. use p4 files. please consult the Perforce Command Reference.g. and so on) on those files at the specified revisions. The first set of reporting commands discussed in this section describe file metadata.. Tables in each section contain answers to questions of the form “How do I find information about. the data that describe a file with no reference to content (e. This command provides the locations of the files within the depot. There are many reporting commands. as in: p4 files filespec will match any file pattern that is supplied in local syntax.edit change 6 (text) Perforce 2003. delete. The output has this appearance: //depot/README#5 .Chapter 11 Reporting and Data Mining Perforce’s reporting commands supply information on all data stored within the depot. with any Perforce wildcards. the actions (add. but discussion of all options for each command is beyond the scope of this manual. the changelists the specified file revisions were submitted in.?” Many of the reporting commands have numerous options. p4 filelog). while the second set describe file contents. edit. (for instance.. p4 print. depot syntax.2 User’s Guide 123 . this chapter presents the same commands and provides additional information for each command. These commands have been discussed throughout this manual. For a full description of any particular command. p4 files. Revision specifiers are discussed on “Specifying Older File Revisions” on page 51.
. and the first few characters of the changelist description. Perforce uses the head revision..... be provided in Perforce or local syntax. #3 change 23 edit on 1997/09/26 by edk@doc <ktext> ’Fix help system’ ...<etc. If you don’t provide a revision number..all files in the depot.all the files currently in any client workspace . but the output always reports on the corresponding files within the depot...... the user who submitted the revision...a particular set of files in the current working directory . p4 files also describes deleted revisions. To View File Metadata for. With the -l flag. #2 change 9 edit on 1997/09/24 by lisag@src <text> ’Change file’ .a particular file within a particular label File revision history The revision history of a file is provided by p4 filelog.2 User’s Guide .. and since the point of p4 filelog is to list information about each revision of particular files. as always.. the date of submission.. the entire description of each changelist is printed: #3 change 23 edit on 1997/09/26 by edk@doc Updated help files to reflect changes in filtering system & other subsystems .all the files in the depot that are mapped through your current client workspace view . #1 change 3 add on 1997/09/24 by edk@doc <text> ’Added filtering bug’ For each file that matches the filespec argument.all files at change n. along with the number of the changelist that the revision was submitted in. whether or not visible through your client view . The output of p4 filelog has this form: .. the complete list of file revisions is presented. file arguments to this command may not contain a revision specification. Unlike most other commands.Chapter 11: Reporting and Data Mining The p4 files command requires one or more filespec arguments.. p4 files @clientname p4 files //clientname/. Use This Command: p4 files //depot/..> 124 Perforce 2003. One or more file arguments must be provided. p4 files filespec p4 files filespec#revisonNum p4 files @n p4 files filespec@labelname . the file’s type at that revision. rather than suppressing information about deleted files. Filespec arguments can....a particular file at a particular revision number .. whether or not the file was actually included in change n ....
a list of all opened files in all client workspaces .txt Perforce 2003.guide /usr/edk/doc/Ref...a list of all files in the default changelist . p4 sync -n is the only command in this set that allows revision specifications on the filespec arguments. The commands that express the relationship between client and depot files are p4 where.. To See. the second part is the location of the same file in client syntax. p4 have’s output has this form: //depot/doc/Ref.Chapter 11: Reporting and Data Mining Opened files To see which files are currently opened within a client workspace... p4 have.2 User’s Guide 125 ..whether or not a specific file is opened by you . delete./usr/edk/elm/doc/Ref. and the file’s type.. p4 opened prints a line like the following: //depot/elm_proj/README .a list of all files in a numbered pending changelist .. The output of p4 where filename looks like this: //depot/elm_proj/doc/Ref.guide The first part of the output is the location of the file in depot syntax... which changelist the file is included in.edit default change (text) Each opened file is described by its depot name and location... All these commands can be used with or without filespec arguments. p4 where.whether or not a specific file is opened by anyone Relationships between client and depot files It is often useful to know how the client and depot are related at a particular moment in time. and local OS syntax. and the third is the location of the file in local OS syntax. Perhaps you simply want to know where a particular client file is mapped to within the depot. or you may want to know whether or not the head revision of a particular depot file has been copied to the client. The first of these commands.a listing of all opened files in the current workspace .. edit. or integrate).txt#3 .. branch. use p4 opened. shows the mappings between client workspace files.guide //edk/doc/Ref. depot files. For each opened file within the client workspace that matches a file pattern argument. p4 have tells you which revisions of files you’ve last synced to your client workspace. the operation that the file is opened for (add. Use This Command: p4 opened p4 opened -a p4 opened -c changelist# p4 opened -c default p4 opened filespec p4 opened -a filespec . and p4 sync -n describes which files would be read into your client workspace the next time you perform a p4 sync. and p4 sync -n.
./filespec p4 sync -n . To See the Contents of Files.. if no revision is specified. This command simply prints the contents of the file to standard output.which revision of a particular file is in your client workspace .... the head revision is printed.. The banner can be removed by passing the -q flag to p4 print.which files would be synced into your client workspace from the depot when you do the next sync File contents Contents of a single revision You can view the contents of any file revision within the depot with p4 print..txt The following table lists other useful commands: To See.updating /usr/edk/elm/doc/Ref.. If a revision is specified. Use This Command: p4 print filespec p4 print -q filespec p4 print filespec@changenum .. the client workspace. When printed...... Use This Command: p4 have p4 have filespec p4 where filespec p4 where //depot/. or to the specified output file.. the file is printed at the specified revision..edit change 50 (text) p4 print takes a mandatory file argument.where a particular file maps to within the depot..at the current head revision ...Chapter 11: Reporting and Data Mining and p4 sync -n provides output like: //depot/doc/Ref.. along with a one-line banner that describes the file. and the local OS .txt#3 ...where a particular file in the depot maps to in the workspace . the banner has this format: //depot/elm_proj/README#23 .without the one-line file header .which revisions of which files you have in the client workspace .at a particular change number 126 Perforce 2003.2 User’s Guide . which can include a revision specification.
a third changelist is submitted. The -a option displays all lines. The third line has not been changed. p4 annotate displays the file.edit change 153 (text) 151: This is a text file.edit change 153 (text) 1: This is a text file.txt#2. Perforce 2003.edit change 12345 (text) 1-3: This is a text file. The -c option displays changelist numbers. The first line of output shows that the first line of the file has been present for revisions 1 through 3.txt#3 . that includes no changes to file. To show all lines (including deleted lines) in the file. including lines no longer present at the head revision. as submitted in changelist 151. as submitted in changelist 152.txt#3 . 152: The second line is new. 1-1: The second line has not been changed. 1-1: The third line has not been changed. use p4 annotate -a as follows: $ p4 annotate -a file. and associated revision ranges. $ p4 annotate -c file. 2: The second line is new.txt //depot/files/file. The first line of file. The third line is deleted and the second line edited so that file.txt has been present since file. Finally. The second line is new.txt#1. the output of p4 annotate and p4 annotate -c look like this: $ p4 annotate file.2 User’s Guide 127 .txt#3 .Chapter 11: Reporting and Data Mining Annotated file contents Use p4 annotate to find out which file revisions or changelists affected lines in a text file. The last line of output shows that the line added in revision 2 is still present in revision 3.txt //depot/files/file. containing the following lines: This is a text file.txt present only in revision 1.txt#1) to the depot. Example: Using p4 annotate to track changes to a file A file is added (file.txt.txt#2 reads: This is a text file.txt //depot/files/file. By default. After the third changelist. The second line has been present since file. rather than revision numbers. 2-3: The second line is new. each line of which is prepended by a revision number indicating the revision that made the change. The second line has not been changed. The next two lines of output show lines of file.
but any wildcards in the first file argument must be matched with a corresponding wildcard in the second. For more details.all files at changelist n and the same files at changelist m p4 diff -f file p4 diff file#head p4 diff file#revnumber p4 diff2 filespec filespec#n p4 diff2 filespec@n filespec@m 128 Perforce 2003....a file within the client workspace and the same file’s current head revision .Chapter 11: Reporting and Data Mining You can combine the -a and -c options to display all lines in the file and the changelist numbers (rather than the revision numbers) at which the lines existed. p4 diff2 takes two file arguments -..the n-th and head revisions of a particular file . To See the Differences between.. please consult the Perforce Command Reference.. There are many more flags to p4 diff than described below.an open file within the client workspace and the revision last taken into the workspace .. if no revision specification is supplied.any file within the client workspace and the revision last taken into the workspace . For a full listing.a file within the client workspace and a specific revision of the same file within the depot .. the workspace file is compared against the revision last read into the workspace. only a few are described in the table below. This command takes a filespec argument.2 User’s Guide ..wildcards are allowed.. File content comparisons A client workspace file can be compared to any revision of the same file within in the depot with p4 diff.. p4 diff2 can be used to compare any two revisions of a file.. Use This Command: p4 diff file . This makes it possible to compare entire trees of files. Whereas p4 diff compares a client workspace file against depot file revisions... or consult the Perforce Command Reference. It can even be used to compare revisions of different files. The p4 diff command has many options available. please type p4 help diff at the command line.
... and p4 submit... Flags are passed to the underlying diff according to the following rules: • If the character immediately following the -d is not a single quote. Use This Command: p4 diff2 //depot/path1/. -dc. Although the server must always use Perforce’s internal diff routine. and -dn. and the server diff is used by p4 describe. These flags behave identically to the corresponding flags in the standard UNIX diff. If you want to pass the following flag to an external client diff program: -u --brief -C 25 Then call p4 diff this way: p4 diff -du p4 diff -d-brief p4 diff -d’C 25’ Perforce 2003. Any flags used by the external diff can be passed to it with p4 diff’s -d flag.. Both p4 diff and p4 diff2 allow any of these flags to be specified. passing the context diff flag to the underlying diff The last example above bears further explanation. p4 diff -dc file . • If the character immediately following the -d is a single quote. The client diff is used by p4 diff and p4 resolve.. then all the characters between the -d and whitespace are prepended with a dash and sent to the underlying diff.all files within two branched codelines .a file within the client workspace and the revision last taken into the workspace.2 User’s Guide 129 . proprietary code. to understand how this works. p4 diff2.. The following examples demonstrate the use of these rules in practice.Chapter 11: Reporting and Data Mining To See the Differences between. //depot/path2/. Both diffs contain identical. the client diff can be set to any external diff program by pointing the P4DIFF environment variable to the full path name of the desired executable... then all the characters between the opening quote and the closing quote are prepended with a dash and sent to the underlying diff. Perforce uses two separate diffs: one is built into the p4d server. and the other is used by the p4 client. Perforce’s built-in diff routine allows three -d<flag> flags: -du. but are used by separate sets of commands. it is necessary to discuss how Perforce implements and calls underlying diff routines.
Use This Command: p4 changes p4 changes -l p4 changes -m n p4 changes -s status p4 changes -u user p4 changes -c workspace p4 changes filespec p4 changes -i filespec .. lists the files and jobs affected by a single changelist....from a particular user .Chapter 11: Reporting and Data Mining Changelists Two separate commands are used to describe changelists.. Currently. without describing the files or jobs that make up the changelist...with the first 31 characters of the changelist descriptions .from a particular client workspace .. p4 changes displays an aggregate report containing one line for every changelist known to the system.with a particular status (pending or submitted) ..... The second command.including only the last n changelists . or changelists that affect a particular file.. The first. but including changelists that affect files which were later integrated with the named files 130 Perforce 2003. but command line flags and arguments can be used to limit the changelists displayed to those of a particular status. those affecting a particular file. although you can write simple shell or Perl scripts to implement this (you’ll find an example of such a script in the Perforce System Administrator’s Guide). These commands are described below. such as changelists with a certain status..with the complete description of each changelist . the output can’t be restricted to changelists submitted by particular users.limited to those that affect particular files .. The output looks like this: Change 36 on 1997/09/29 by edk@eds_elm ’Changed filtering me’ Change 35 on 1997/09/29 by edk@eds_elm ’Misc bug fixes: fixe’ Change 34 on 1997/09/29 by lisag@lisa ’Added new header inf’ By default. Viewing changelists that meet particular criteria To view a list of changelists that meet certain criteria..2 User’s Guide . or the last n changelists. To See a List of Changelists. p4 describe... use p4 changes.limited to those that affect particular files. p4 changes. lists changelists that meet particular criteria.
@date2 p4 changes @date1. The output of p4 describe looks like this: Change 43 by lisag@warhols on 1997/08/29 13:41:07 Made grammatical changes to basic Elm documentation Jobs fixed.1#2 (text) ==== 53c53 > Way number 2. ==== //depot/doc/elm..limited to those that affect particular files at each files revisions between labels lab1 and lab2 .#n .> Perforce 2003....2 User’s Guide 131 .. along with the diffs of the new file revisions and the previous revisions.. .. job000001 fixed on 1997/09/29 by edk@edk Fix grammar in main Elm help file Affected files..@now Note For details about Perforce commands that allow you to use revision ranges with file specifications.@lab2 ....<etc. see “Revision Ranges” on page 54.between an arbitrary date and the present day p4 changes @date1.limited to those between two dates ... use p4 describe..1#2 edit Differences.limited to changelists that affect particular files..Chapter 11: Reporting and Data Mining To See a List of Changelists. like --> The second method is commonly used when transmitting .. what is used common-like when. you know... Files and jobs affected by changelists To view a list of files and jobs affected by a particular changelist. Use This Command: p4 changes filespec#m.. //depot/doc/elm. including only those changelists between revisions m and n of these files p4 changes filespec@lab1..
a list of all files submitted and jobs fixed by a particular changelist... To See: Use This Command: p4 labels p4 labels file#revrange p4 files @labelname p4 sync -n @labelname . without the file diffs . p4 labels... To See: Use This Command: p4 opened -c changelist# p4 describe changenum .. prints its output in the following format: Label release1.Chapter 11: Reporting and Data Mining This output is quite lengthy..a list of all labels containing a specific revision (or range) .. displaying the diffs between the file revisions submitted in that changelist and the previous revisions . while passing the context diff flag to the underlying diff program .....3 1997/5/18 ’Created by edk’ Label lisas_temp 1997/10/03 ’Created by lisag’ ...a list of files contained in a pending changelist .a list of all files and jobs affected by a particular changelist.. the dates they were created.a list of all files submitted and jobs fixed by a particular changelist.a list of all labels.<etc..what p4 sync would do when retrieving files from a particular label into your client workspace 132 Perforce 2003.2 User’s Guide .. whether or not these files were affected by the changelist p4 describe -s changenum p4 describe -dc changenum p4 files filespec@changenum For more commands that report on jobs. The only command that reports only on labels. and the name of the user who created them . see “Job Reporting” on page 133.a list of files that have been included in a particular label with p4 labelsync ..the state of particular files at a particular changelist.> The other label reporting commands are variations of commands we’ve seen earlier. but a shortened form that eliminates the diffs can be generated with p4 describe -s changenum... Labels Reporting on labels is accomplished with a very small set of commands..
without actually doing the integrate .a list of all the revisions of a particular file. The first.Chapter 11: Reporting and Data Mining Branch and Integration Reporting The plural form command of branch. lists the different branches in the system.what a particular p4 resolve variation would do. This command produces output similar to the following: job000302 on 1997/08/13 by saram *open* ’FROM: headers no’ filter_bug on 1997/08/23 by edk *closed* ’Can’t read filters w’ Perforce 2003.. along with their owners. reports on all jobs known to the system.. p4 jobs.. Separate commands are used to list files within a branched codeline.and integration-related reporting.what a particular p4 integrate variation would do. p4 fixes.. including revision of the file(s) it was branched from p4 resolved [filespec] p4 integrated filespec p4 filelog -i filespec Job Reporting Two commands report on jobs.. reports only on those jobs that have been attached to changelists.a list of files that have been resolved but have not yet been submitted .. without actually doing the resolve . and to perform other branch-related reporting....2 User’s Guide 133 . To See: Use This Command: p4 branches p4 files filespec p4 integrate [args] -n [filespec] . use p4 jobs.. to describe which files have been integrated...a list of all the revisions of a particular file p4 filelog -i filespec p4 resolve [args] -n [filespec] . submitted files that match the filespec arguments .a list of integrated.. The table below describes the most commonly used commands for branch. p4 branches. while the second command. dates created. Basic job information To see a list of all jobs known to the system. and descriptions.a list of all branches known to the system ... Both of these commands have numerous options..a list of all files in a particular branched codeline .
. and the first 31 characters of the job description. job owner.including the full texts of the job descriptions .. and can be reported with p4 fixes.that have been fixed by changelists that contain specific files p4 jobs filespec p4 jobs -i filespec Jobs. see “Viewing jobs by content with jobviews” on page 114) .. These options are described in the table below. The output of p4 fixes looks like this: job000302 fixed by change 634 on 1997/09/01 by edk@eds_elm filter_bug fixed by change 540 on 1997/10/22 by edk@eds_elm A number of options allow the reporting of only those changes that fix a particular job.. All jobs known to the system are displayed unless command-line options are supplied. p4 submit.including all jobs known to the server .Chapter 11: Reporting and Data Mining Its output includes the job’s name. since open jobs can be linked to pending changelists... use p4 jobs. A fixed job will not necessarily have a status of closed job. or jobs fixed by changelists that are linked to particular files..for which certain fields contain particular values (For more about jobviews.. date entered..2 User’s Guide . Use This Command: p4 fixes p4 fixes -j jobname p4 fixes -c changenum . To See a Listing of...all changelists linked to a particular job .... or p4 fix is said to be fixed..all jobs linked to a particular changelist 134 Perforce 2003...all fixes for all jobs . status. and pending jobs can be reopened even after the associated changelist has been submitted. including changelists that contain files that were later integrated into the specified files . To list jobs with a particular status. To See a List of Jobs: Use This Command: p4 jobs p4 jobs -l p4 jobs -e jobview .that have been fixed by changelists that contain specific files. and changelists Any jobs that have been linked to a changelist with p4 change.. jobs fixed by a particular changelist. fixes.
the numbers of all changelists that have not yet been reported by a particular counter variable .....all users who have subscribed to read any files in a particular changelist . To report on client workspaces. Use this Command: p4 counters p4 review -t countername p4 reviews filespec p4 reviews -c changenum p4 users username .. and the date that Perforce was last accessed by that user.’ Perforce 2003.all jobs fixed by changelists that contain particular files .) accessed 1997/07/14 Each line includes a username.. use p4 clients: Client eds_elm 1997/09/12 root /usr/edk ’Ed’s Elm workspace’ Client lisa_doc 1997/09/13 root /usr/lisag ’Created by lisag.all jobs fixed by changelists that contain particular files.a particular user’s email address System Configuration Three commands report on the Perforce system configuration.... including changelists that contain files that were later integrated with the specified files Reporting for Daemons The Perforce change review mechanism uses the following reporting commands... One command reports on all Perforce users. For further information on daemons.. and a third reports on Perforce depots.) accessed 1997/07/13 lisag <lisa@lisas_ws> (Lisa G. another prints data describing all client workspaces.2 User’s Guide 135 . an email address.. Any of these commands might also be used with user-created daemons.Chapter 11: Reporting and Data Mining To See a Listing of.. To list.the names of all counter variables currently used by your Perforce system . p4 users generates its data as follows: edk <edk@eds_ws> (Ed K. the user’s “real” name.. please see the Perforce System Administrator’s Guide...all users who have subscribed to review particular files . Use This Command: p4 fixes filespec p4 fixes -i filespec ..
brief descriptions of all client workspaces .. its creation date. The -o flag is available with most of the Perforce commands that normally bring up forms for editing. Instead.. can be used with certain action commands to change their behavior from action to reporting.. instead of bringing the definition into the user’s editor. its IP address (if remote). the commands simply tell you what they would ordinarily do.Chapter 11: Reporting and Data Mining Each line includes the client name. its type (local or remote). the mapping to the local depot. You can use the -n flag with the following commands p4 integrate p4 resolve p4 labelsync p4 sync Reporting with Scripting Although Perforce’s reporting commands are sufficient for most needs. 136 Perforce 2003... the reporting commands can be used in combination with scripts to print only the data that you want to see. -o and -n.. the client root. The use of multiple depots on a single Perforce server is discussed in the Perforce System Administrator’s Guide. and the system administrator’s description of the depot. the described fields include the depot’s name. there may be times when you want to view data in a format that Perforce doesn’t directly support. In these situations. Depots can be reported with p4 depots.user information for all Perforce users . This flag tells these commands to write the form information to standard output.a list of all defined depots Special Reporting Flags Two special flags..user information for only certain users .. All depots known to the system are reported on. To view: Use This Command: p4 users p4 users username p4 clients p4 depots .2 User’s Guide . the date the client was last updated. This flag is supported by the following commands: p4 branch p4 change p4 client p4 job p4 label p4 user The -n flag prevents commands from doing their job. and the description of the client.
Chapter 11: Reporting and Data Mining Comparing the change content of two file sets To compare the “change content” of two sets of files. you have to diff them externally. > changes-in-main p4 changes //depot/r98. To do this..4 that haven’t been integrated back into main.. once on each set of files.4 You can use this to uncover which changes have been made to r98. > changes-in-r98.4 is a codeline that was originally branched from main: p4 changes //depot/main/. Perforce 2003..4/.. main represents the main codeline. In the following example. and r98.2 User’s Guide 137 . and then use any external diff routine to compare them. run p4 changes twice.
2 User’s Guide .Chapter 11: Reporting and Data Mining 138 Perforce 2003.
or p4. and the Perforce server is usually located either in /usr/local/bin or in its own server root directory. The server and client executables are available from the Downloads page on the Perforce web site:. Provide the name of the Perforce server and the p4d port number to the Perforce client program(s). we strongly encourage you to read the detailed information in the Perforce System Administrator’s Guide. ensure that the p4d executable is owned and run by a Perforce user account that has been created for that purpose. Perforce 2003. After downloading p4 and p4d. This appendix is mainly intended for people installing an evaluation copy of Perforce for trial use. To limit access to the Perforce server files. Perforce client programs can be installed on any machine that has TCP/IP access to the p4d host. you need to do a few more things before you can start using Perforce: 1.2 User’s Guide 139 . and save the files to disk.perforce. select the files for your platform. Installing Perforce on UNIX Although p4 and p4d can be installed in any directory. 5. Provide a TCP/IP port to p4d to tell the Perforce server what port to listen to. Create a server root directory to hold the Perforce database and versioned files. if you’re installing Perforce for production use. or are planning on extensive testing of your evaluation server. 2. Getting Perforce Perforce requires at least two executables: the server (p4d). Make the downloaded p4 and p4d files executable.Appendix A Installing Perforce This appendix outlines how to install a Perforce server for the first time.exe on Windows). and at least one Perforce client program (such as p4 on UNIX.com/perforce/loadprog. 4. 3.html Go to the web page. on UNIX the Perforce client programs typically reside in /usr/local/bin.exe or p4win. Start the Perforce server (p4d).
Starting the Perforce server After setting p4d’s P4PORT and P4ROOT environment variables. you must also make the Perforce executables (p4 and p4d) executable. p4d -p 1818). or set the port with the P4PORT environment or registry variable. there is no need to run p4d as root or any other privileged user. use the chmod command to make them executable. and execute permissions on the server root and all directories beneath it. but the account that runs p4d must have read. as follows: chmod +x p4 chmod +x p4d Creating a Perforce server root directory Perforce stores all of its data in files and subdirectories of its own root directory. or use the -r root_dir flag when invoking p4d.2 User’s Guide . If p4d is to listen on a different port. For security purposes. start the server by running p4d in the background with the command: p4d & 140 Perforce 2003. Unlike P4ROOT. Telling the Perforce server which port to listen to The p4d server and Perforce client programs communicate with each other using TCP/IP.Appendix A: Installing Perforce Download the files and make them executable On UNIX (or MacOS X). This directory is called the server root. set the environment variable P4ROOT to point to the server root. The server root can be located anywhere. To specify a server root. When p4d starts. Perforce client programs never use the P4ROOT directory or environment variable. specify that port with the -p port_num flag when starting p4d (as in. After downloading the programs. the environment variable P4PORT is used by both the Perforce server and Perforce client programs. listening on port 1666. set the umask(1) file creation-mode mask of the account that runs p4d to a value that denies other users access to the server root directory. See the System Administrator’s Guide for details. and must be set on both Perforce server machines and Perforce client workstations. The Perforce client assumes (also by default) that its p4d server is located on a host named perforce. the p4d server is the only process that uses the P4ROOT variable. it listens (by default) on port 1666. A Perforce server requires no privileged access. which can reside anywhere on the server system. write.
exe) from the Downloads page of the Perforce web site. Telling Perforce clients which port to talk to By this time. you must find the process ID of the p4d server and kill the process manually from the UNIX shell. see “Connecting to the Perforce Server” on page 21 for information on how to set up your environment to allow Perforce’s client programs to talk to the server.exe) executables. can be provided.Appendix A: Installing Perforce Although the example shown is sufficient to run p4d.exe (the Perforce Command-Line Client). Installing Perforce on Windows To install Perforce on Windows. Perforce 2003. your Perforce server should be up and running. and journaling. These flags (and others) are discussed in the Perforce System Administrator’s Guide. or to automatically upgrade an existing Perforce server or service running under Windows. use the command: p4 admin stop to gracefully shut down the Perforce server. use the Perforce installer (perforce.exe) and service (p4s. This option allows you to install p4. These options allow you to install Perforce client programs and the Perforce Windows server (p4d. and Power User privileges to install Perforce as a server.2 User’s Guide 141 . Only a Perforce superuser can use p4 admin stop. checkpointing. • Install Perforce as either a Windows server or service as appropriate. as p4d might leave the database in an inconsistent state if p4d is in the middle of updating a file when a SIGKILL signal is received. the Perforce Windows Client). The Perforce installer allows you to: • Install Perforce client software (“User install”). p4win. (“Administrator typical” and “Administrator custom” install).2. Stopping the Perforce server To shut down a Perforce server.dll (Perforce’s implementation of the Microsoft common SCM interface). you must have Administrator privileges to install Perforce as a service. Use kill -15 (SIGTERM) instead of kill -9 (SIGKILL). If you are running a release of Perforce from prior to 99. and p4scc.exe (P4Win. other flags that control such things as error logging. Under Windows 2000 or higher.
the back-end program can be started either as a Windows service (p4s. invoke p4d. respectively. they are identical apart from their filenames. When run.2 User’s Guide .2 and earlier versions of Perforce.) In most cases.exe) process that must be invoked from a command prompt. 142 Perforce 2003. the manual shutdown options are obsolete. however. For a more detailed discussion of the distinction between services and servers. service. Shut down servers running in command prompt windows by typing CTRL-C in the window or by clicking on the icon to Close the command prompt window.exe or p4dmyserver. see the Perforce System Administrator’s Guide.2 or above. or as a server (p4d. in the sense that the server or service is shut down abruptly. Terminology note: Windows services and servers The terms “Perforce server” and “p4d” are used interchangeably to refer to “the process which handles requests from Perforce client programs”. there is only one Perforce “server” program (p4d) responsible for this back-end task. (For example. and client executables. On Windows. the service starts whenever the machine boots. Use the Services applet in the Control Panel to control the Perforce service’s behavior. use the command: p4 admin stop Only a Perforce superuser can use p4 admin stop.exe) and the Perforce server (p4d.exe) executables are copies of each other. Starting and stopping Perforce on Windows If you install Perforce as a service under Windows. the distinction is made. In cases where the distinction between an NT server and an NT service is important. and service entries. If you install Perforce as a server under Windows. Although these manual shutdown options work with Release 99.exe) process that runs at boot time. registry keys. the executables use the first three characters of the name with which they were invoked (either p4s or p4d) to determine their behavior. shut down services manually by using the Services applet in the Control Panel. not a server. For older revisions of Perforce.exe from a command prompt. it is preferable to install Perforce as a service.Appendix A: Installing Perforce • Uninstall Perforce: remove the Perforce server. On UNIX systems. The Perforce service (p4s. With the availability of the p4 admin stop command in 99. To stop a Perforce service (or server) at Release 99.exe named p4smyservice. The Perforce database and the depot files stored under your server root are preserved. The flags for p4d under Windows are the same as those used under UNIX.exe invoke a service and a server.2. they are not necessarily “clean”. invoking copies of p4d.
You’ll find a full description of each variable in the Perforce Command Reference.2 User’s Guide 143 . Only used if the Host: field of the current client workspace has been set in the p4 client form. Name and path of the file to which Perforce server error and diagnostic messages are to be logged. A file that holds the database journal data.Appendix B Environment Variables This table lists all the Perforce environment variables and their definitions. for the p4 client. the character set to use for Unicode translations Name of current client workspace File name from which values for current environment variables are to be read The name and location of the diff program used by p4 resolve and p4 diff The editor invoked by those Perforce commands that use forms Name of host computer to impersonate. or off to disable journaling. Variable P4CHARSET P4CLIENT P4CONFIG P4DIFF P4EDITOR P4HOST P4JOURNAL P4LANGUAGE P4LOG P4MERGE P4PAGER P4PASSWD P4PORT Definition For internationalized installations only. the name and port number of the Perforce server with which to communicate The directory used to resolve relative filename arguments to p4 commands Directory in which p4d stores its files and subdirectories The user’s Perforce username The directory to which Perforce writes its temporary files PWD P4ROOT P4USER TMP Perforce 2003. the port number to listen on. This variable is reserved for system integrators. A third-party merge program to be used by p4 resolve’s merge option The program used to page output from p4 resolve’s diff option Stores the user’s password as set in the p4 user form For the Perforce server.
use p4 set without any arguments. On UNIX. export P4CLIENT setenv P4CLIENT value def/j P4CLIENT “value” set -e P4CLIENT value p4 set P4CLIENT=value Mac MPW Windows (See the p4 set section of the Perforce Command Reference or run the command p4 help set to obtain more information about setting Perforce’s registry variables in Windows). or the value in the registry and whether it was defined with p4 set (for the current user) or p4 set -s (for the local machine). The following table shows how to set the P4CLIENT environment variable in each OS and shell: OS or Shell UNIX: ksh. bash UNIX: csh VMS Environment Variable Example P4CLIENT=value . this displays the values of the associated environment variables. To view a list of the values of all Perforce variables. On NT. 144 Perforce 2003. Windows administrators running Perforce as a service can set variables for use by a specific service with p4 set -S svcname var=value.Appendix B: Environment Variables Setting and viewing environment variables Each operating system and shell has its own syntax for setting environment variables. this displays either the MS-DOS environment variable (if set).2 User’s Guide . sh.
A specification of the branching relationship between two codelines in the depot. An access level that gives the user permission to run Perforce commands that override metadata. apple file type atomic change transaction base binary file type branch branch form branch specification branch view Perforce 2003. Client workspaces. labels. If all operations in the transaction succeed. but do not affect the state of the server. Perforce file type assigned to a non-text file. permitting the data fork and resource fork to be stored as a single file. Grouping operations affecting a number of files in a single transaction. By default. (noun) A codeline created by copying another codeline. The Perforce form you use to modify a branch. Specifies how a branch is to be created by defining the location of the original codeline and the branch. See protections. See branch. all the files are updated. The file revision on which two newer. (verb) To create a codeline branch with p4 integrate. conflicting file revisions are based. and defines how files are mapped from the originating codeline to the target codeline. If any operation in the transaction fails.2 User’s Guide 145 . Perforce file type assigned to Macintosh files that are stored using AppleSingle format. branch is often used as a synonym for branch view. none of the files are updated. as opposed to a codeline that was created by adding original files. and branch specifications cannot share the same name. Each branch view has a unique name.Appendix C Glossary Term Definition access level admin access A permission assigned to a user to control which Perforce commands the user can execute. The branch specification is used by the integration process to create and update branches. the contents of each revision are stored in full and the file is stored in compressed format.
A set of mappings that specifies the correspondence between file locations in the depot and the client workspace. Client workspaces. The unique numeric identifier of a changelist. The Perforce form you use to modify a changelist. The Perforce form you use to define a client workspace. and branch specifications cannot share the same name.Appendix C: Glossary Term Definition changelist An atomic change transaction in Perforce.2 User’s Guide . By default this name is set to the name of the host machine on which the client workspace is located. specifying where the corresponding depot files are located in the client workspace. allowing each set of files to evolve separately. The right-hand side of a mapping within a client view. labels. A copy of the underlying server metadata at a particular moment in time. One codeline can be branched from another. The process of sending email to users who have registered their interest in changes made to specified files in the depot. See metadata. set the P4CLIENT environment variable. If two or more client workspaces are located on one machine. A name that uniquely identifies the current client workspace. they cannot share a root directory. A set of files that evolve collectively. Directories on the client computer where you work on file revisions that are managed by Perforce. The root directory of a client workspace. The changes specified in the changelist are not stored in the depot until the changelist is submitted to the depot. changelist form changelist number change review checkpoint client form client name client root client side client view client workspace codeline 146 Perforce 2003. to override the default name.
A set of lines that don’t match when two files are compared. The default depot name is depot. unless a numbered changelist is specified. Older revisions of the file are still available. In this case. There can be multiple depots on a single server. specifying the location of files in a depot. after which the other user can’t submit because of a conflict. The left side of any client view mapping. indicating that the files have been changed in different ways. In Perforce. default depot deleted file delta depot depot root depot side depot syntax detached diff donor file exclusionary mapping A view mapping that excludes specific files. A default pending changelist is created automatically when a file is opened for edit. a file with its head revision marked as deleted. Perforce 2003. The type of conflict is caused by non-matching diffs. The depot name that is assumed when no name is specified. The other type of conflict is when users try to merge one file into another. It contains all versions of all files ever submitted to the server. the merge can’t be done automatically and must be done by hand. The differences between two files. Perforce syntax for specifying the location of files in the depot. The changelist used by Perforce commands. The cause of this type of conflict is two users opening the same file.2 User’s Guide 147 . This type of conflict occurs when the comparison of two files to a common base yields different results. A client computer that cannot connect to a Perforce server. The file from which changes are taken when propagating changes from one file to another. See file conflict. One user submits the file. The root directory for a depot. A conflict is a pair of unequal diffs between each of two files and a common third file. counter default changelist A numeric variable used by Perforce to track changelist numbers in conjunction with the review feature.Appendix C: Glossary Term Definition conflict One type of conflict occurs when two users open a file for edit. A file repository on the Perforce server.
A list of Perforce users. A job that has been linked to a changelist. A specific version of a file within the depot.2 User’s Guide . Also: an attempt to submit a file that is not an edit of the head revision of the file in the depot. In a three-way file merge. typically occurs when another user opens the file for edit after you have opened the file for edit. you use the Perforce change form to enter comments about a particular changelist and to verify the affected files. Examples of file types are text and binary. which Perforce uses for text files. • determine if the changes have already been propagated. Because file revisions are numbered sequentially. Each revision is assigned a number. in sequence. For example. this revision is the highest-numbered revision of that file. Screens displayed by certain Perforce commands. for example: testfile#3. In Perforce. The list of file revisions currently in the client workspace. file tree file type fix form full-file storage get group have list head revision integrate 148 Perforce 2003. • propagate any outstanding changes. a situation in which two revisions of a file differ from each other and from their base file. shared by all users. An attribute that determines how Perforce stores and diffs a particular file. The most recent revision of a file within the depot. this is called the depot. To compare two sets of files (for example. An obsolete Perforce term: replaced by sync. two codeline branches) and • determine which changes in one set apply to the other. file pattern file repository file revision Perforce command line syntax that enables you to specify files using wildcards. The master copy of all files. All the subdirectories and files under a given root directory.Appendix C: Glossary Term Definition exclusionary access file conflict A permission that denies access to the specified files. Any revision can be accessed in the depot by its revision number. Contrast this with reverse delta storage. The method by which Perforce stores revisions of binary files in the depot: every file revision is stored in full.
2 User’s Guide 149 .Appendix C: Glossary Term Definition Inter-File Branching job Perforce’s proprietary branching mechanism. Lazy copies minimize the consumption of disk space by storing references to the original file instead of copies of the file. A named list of user-specified file revisions. The job template determines what information is tracked. The view that specifies which file names in the depot can be stored in a particular label. Files are unlocked with the p4 unlock command or submitting the changelist that contains the locked file. Error output from the Perforce server. Any depot located on the current Perforce server. Ensures that the number of Perforce users on your site does not exceed the number for which you have paid. The process of recording changes made to the Perforce server’s metadata. error output is written to standard error. A user-defined unit of work tracked by Perforce. The template can be modified by the Perforce system administrator A specification containing the fields and valid values stored for a Perforce job. By default. set the P4LOG environment variable. A method used by Perforce to make internal copies of files without duplicating file content in the depot. A file containing a record of every change made to the Perforce server’s metadata since the time of the last checkpoint. A Perforce file lock prevents other clients from submitting the locked file. The operating-system-specific syntax for specifying a file name. job specification job view journal journaling label label view lazy copy license file list access local depot local syntax lock log Perforce 2003. A protection level that enables you to run reporting commands but prevents access to the contents of files. or use the p4d -L flag. To specify a log file. A syntax used for searching Perforce jobs.
protections. P4Diff is the default application used to compare files during the file resolution process. The Perforce user who created a particular client. The data stored by the Perforce server that describes the files in the depot. The method used by Perforce to verify the integrity of archived files. and the command you issue to execute Perforce commands from the operating system command line. The time a file was last changed. The left side specifies the depot file and the right side specifies the client files. A file that you are changing in your client workspace. The process of combining the contents of two conflicting file revisions into a single file. consisting of a left side and a right side that specify the correspondences between files in the depot and files in a client.Appendix C: Glossary Term Definition mapping A single line in a view. label. Syncing to a nonexistent revision of a file removes it from your workspace. A changelist that has not been submitted. A pending changelist to which Perforce has assigned a number. branch view. An empty file revision created by deleting a file and the #none revision specifier are examples of nonexistent file revisions. The program on the Perforce server that manages the depot and the metadata. A Perforce application that displays the differences between two files. or label. Metadata includes all the data stored in the server except for the actual contents of the files. users. and branches. The Perforce Windows Client. A completely empty revision of any file. label view). The Perforce Command-Line Client program. a Windows Explorer-style application that enables you to perform Perforce operations and view results graphically. clients. the current state of client workspaces. labels. A file generated by Perforce from two conflicting file revisions. Perforce 2003. branch. or branch.2 User’s Guide MD5 checksum merge merge file metadata modification time nonexistent revision numbered changelist open file owner P4 P4D P4Diff P4Win pending changelist 150 . (See also client view.
The process of resolving a file after the file is resolved and before it is submitted The process you use to reconcile the differences between two revisions of a file. plus the full text of the head revision. The permissions stored in the Perforce server’s protections table. To discard the changes you have made to a file in the client workspace. A depot located on a server other than the current Perforce server. The method that Perforce uses to store revisions of text files. Revision Control System format. A special protections level that includes read and list accesses. For example. One fork of a Macintosh file. See also change review. A number indicating which revision of the file is being referred to. (Macintosh files are composed of a resource fork and a data fork. specified as the low and high end of the range.Appendix C: Glossary Term Definition Perforce server protections RCS format The Perforce depot and metadata on a central host. RCS format uses reverse delta encoding for file storage. Perforce uses RCS format to store text files. See also reverse delta storage.) You can store resource forks in Perforce depots as part of an AppleSingle file by using Perforce’s apple file type. Used for storing revisions of text files. Any daemon process that uses the p4 review command. file#5. read access remote depot reresolve resolve resource fork reverse delta storage revert review access review daemon revision number revision range Perforce 2003. and grants permission to run the review command. Perforce stores the changes between each revision and its previous revision. Also the program that manages the depot and metadata.2 User’s Guide 151 . A range of revision numbers for a specified file.7 specifies revisions 5 through 7 of file file. A protection level that enables you to read the contents of files managed by Perforce.
Perforce file type assigned to a file that contains only ASCII text. set the P4ROOT environment variable. the program that executes the commands sent by client programs. To register to receive email whenever changelists that affect particular files are submitted. The revision in the depot with which the client file is merged when you resolve a file conflict.Appendix C: Glossary Term Definition revision specification A suffix to a filename that specifies a particular revision of that file. install triggers. and tracks the state of client workspaces. label names. To copy a file revision (or set of file revisions) from the depot to a client workspace. See also binary file type. When you are working with branched files. Revision specifiers can be revision numbers. change numbers. or shut down the server for maintenance. In Perforce. During a threeway merge. closed. or client names. For a changelist.2 User’s Guide server server root status submit subscribe super access symlink file type sync target file text file type theirs three-way merge 152 . For a job. theirs is the donor file. or submitted. You can customize job statuses. Perforce 2003. or suspended. To specify the server root. you can identify where conflicting changes have occurred and specify how you want to resolve the conflicts. pending. To send a pending changelist and changed files to the Perforce server for processing. symlink files are stored as text files. a value that indicates whether the changelist is new. The Perforce server (p4d) maintains depot files and metadata describing the files. The file that receives the changes from the donor file when you are integrating changes between a branched codeline and the original codeline. a value that indicates whether the job is open. On nonUNIX clients. The process of combining three file revisions. The directory in which the server program stores its metadata and all the shared files. A Perforce file type assigned to UNIX symbolic links. including commands that set protections. An access level that gives the user permission to run every Perforce command. date/time specifications.
Perforce wildcards are: • * matches anything except a slash • . matches anything including slashes • %d used for parameter substitution in views typemap user view wildcard write access A protection level that enables you to run commands that alter the contents of files in the depot. The process of combining two file revisions. yours Perforce 2003. branch view.2 User’s Guide 153 . label view. See client view. A script automatically invoked by the Perforce server when changelists are submitted.Appendix C: Glossary Term Definition tip revision trigger two-way merge In Perforce. the target file when you integrate a branched file. Also. The identifier that Perforce uses to determine who is performing an operation. you can see differences between the files but cannot see conflicts. when you resolve a file. The edited version of a file in the client workspace. In a two-way merge. A description of the relationship between two sets of files... the head revision. A special character used to match other characters in strings. Tip revision is a term used by some other SCM systems. A Perforce table in which you assign Perforce file types to files. Write access includes read and list accesses.
Appendix C: Glossary 154 Perforce 2003.2 User’s Guide .
(wildcard) 38 = operator in job queries 116 > operator in job queries 116 >>>> as diff marker 68 @ forbidden in filenames 50 syncing to a label’s contents 95 ^ operator in job queries 115 A accepting files when resolving 70 access level defined 145 adding files to depot 29 administration depot configuration 82 allwrite client option 45 annotate 127 architecture of Perforce 14 atomic change transactions 85 branching and integration 106 Perforce 2003.. 115 +k flag keyword expansion 55 .Index Symbols # forbidden in filenames 50 #have defined 14...2 User’s Guide base defined 145 resolving 67 base file types 55 baseless merge 106 basics of Perforce 25 BeOS symbolic links 56 binary files how files are stored 56 how revisions are stored 55 resolving 72 branch specs branching with 103 creating 103 deleting 107 example 104 exclusionary mappings allowed 105 usage notes 105 using with p4 integrate -b 104 branch views creating 103 defined 145 branches comparing files between 129 defined 145 deleting 107 listing files in 133 propagating changes between files 102. 105 when to create 99 branching automatic 103 best practices 110 branch command 103 155 . 145 example 33 automating Perforce 61 B specifying the revision synced-to 52 #head specifying the latest revision 52 #none 52 % forbidden in filenames 50 %0 . 43 * (wildcard) 38. %n 38.
16. 146 displaying files 62 listing 135 moving files between client and server 14 options 45 p4 have command 35 populating 29. 134 atomic change transactions and 85 automatic renumbering of 88 default 30. 111 moving files between 87 numbered 85. 91 p4 reopen command 89 pending (defined) 150 processed atomically 14 reporting 90. 87. 95 refreshing 82 spanning multiple drives 40 specifying 26 state of 37 switching between 26 Perforce 2003. 85 default (defined) 147 defined 145 deleting 89 files open in 86 introduced 14 jobs 117 jobs vs. diff 67 client files mapping to depot files 125 client programs 14. 102 defined 99 files without common ancestors 106 introduced 15 manually. 130 reporting by user 90 scheduling resolves 65 status of 86 156 specifying 27 client side (of mapping) 39 client specification defining 26 deleting 45 editing 44 client syntax 49 client view changing 44 defined 146 exclusionary mappings 42 introduced 15 specifying 27. 21 client root changing 44 defined 37. 131. 129 defined 25. 38 client workspace changing client root 44 changing view 44 comparing files against depot 74. 146 null 40 carriage return 45 change management 13 change review 13 defined 146 changelist number defined 146 changelists adding and removing files 86 associated jobs 89. 68 how to propagate between codelines 103 propagating between codelines 102. 103 undoing with p4 revert 34 chunks.Index branch spec example 104 codelines and 99 copying files vs.2 User’s Guide . with p4 integrate 101 reporting 133 reverse integration and 106 two techniques 100 when to branch 99 white paper 110 bug tracking 13 build management 13 C submitting 29 changes conflicting 63. 37.
2 User’s Guide default changelist defined 147 introduced 29 using 85 default depot defined 147 default job specification 112 defect tracking interfacing with third-party products 120 jobs and 16 using jobs 111 deleting branch specs 107 client specifications 45 files 29. 120. 123 comparing files 128 compress client option 45 concurrent development 13 configuration changing 77 configuration files 77 conflicting changes 63 conflicts file 15. 72 file (defined) 148 counter defined 147 CR/LF translation 45. 61. 25. common to all commands 79 specifying files on 48 commands applying to multiple revisions at once 54 forms and 60 reporting 34. 47 creating jobs 112 crlf client option 45 cross-platform development line endings 47 customizing job specification 113 D daemons reporting 135 Perforce 2003. 74. 32 jobs 120 labels 95 delta defined 147 depot adding files from workspace 29 changelists and 14 comparing against files in workspace 129 compressing files 56 copying files to workspace 28 default (defined) 147 defined 14. 147 listing 135 local (defined) 149 mapping to client files 125 multiple 39 organizing 82 remote (defined) 151 side of mapping 39 syntax 49 syntax (defined) 147 updating after working offline 81 detached defined 147 development concurrent 13 distributed 13 diff 157 .Index user directories 14 client/server architecture 14 clobber client option 45 codelines branching and 99 comparing files between 129 defined 146 listing files in 133 propagating changes between 103 resolving differences between 103 when to branch 99 command-line common flags and p4 help usage 35 flags.
143 P4DIFF 143 P4EDITOR 26.Index chunks 67 differences between revisions 65 excluding 90 markers 68 suppressing display 132 two algorithms used by Perforce 129 diffs annotated 127 directories and spaces 51 client workspace 14 removing empty 46 distributed development 13 donor file defined 147 E advanced integration 107 branch spec 104 combining file type modifiers 55 creating a label 92 filling forms with -i and -o 61 linking jobs and changelists 117. 72 F fields jobviews and 116 file conflict defined 148 introduced 15 resolving 70 file format RCS (defined) 151 file repository defined 148 file revision defined 148 file specifications branching with 101 file type modifiers combining 55 listed 57 file types +l 72 apple 56 binary 56 example set for this manual 25 examples adding files to depot 30 158 compressed in depot 56 determined by Perforce 55 Perforce 2003. 143 P4PORT 22. 143 P4ROOT 143 P4USER 143 PWD 143 setting 144 TMP 143 error messages 23 propagating changes to branches 105 RCS keyword expansion 60 reporting and scripting 137 reporting on jobs 120 resolving file conflicts 70 use of %0 . 31 email notification 146 environment variables P4CHARSET 143 P4CLIENT 26.. %n wildcard 43 exclusionary mappings branch specs and 105 client views and 42 defined 147 exclusive-open locking vs. 118 p4 job 112 editing client specifications 44 files 29.2 User’s Guide . 143 P4HOST 143 P4JOURNAL 143 P4LOG 143 P4MERGE 143 P4PAGER 143 P4PASSWD 78. 143 P4CONFIG 77.
132 displaying mappings 62 displaying opened 62. 28 multi-forked 56 nonexistent revision 52 opening 29. 32 deleting from labels 95 displaying branch contents 133 displaying contents 126 displaying integrated and submitted 133 displaying label contents 98. 72 changelist revision specifier 52 changelists and 14 changing type 55 client workspace 38 client workspace revision specifier 52 command line syntax 48. 79 -i flag 61 159 displaying revision history 62 displaying workspace contents 62 donor (defined) 147 editing 29. 31 have revision 52 head revision 52 Perforce 2003. 58 overview 55 resource 56 specifying 55. 74 copying vs. 133 integrating 107 label revision specifier 52 listing with p4 files 62 locked 73 locking 72 managed by Perforce 37 merging 67.2 User’s Guide . 53. 49 commands for reporting 123 comparing 74. 57 propagating changes between branches 102 removing from workspace 52 renaming 83 reopening in other changelist 89 re-resolving 108 resolving 66. 70 result 67 specifying revision 51. 86 permissions 45. 57 stored in RCS format 63 submitting changes to depot 29 target (defined) 152 text 55 text (defined) 152 theirs (defined) 152 types of 55 undoing changes 34 wildcards 38 working offline 81 yours (defined) 153 fix defined 148 jobs and changelists 134 flags common to all commands 35. 68 merging (defined) 150 modifying a changelist 86 moving between changelists 87 moving between workspace and server 14. 57 symlink 56 text 56 filenames and spaces 51 forbidden characters 50 spaces in 50 files adding to depot 29. branching 102 deleting from depot 29. 128 conflicting 63. 52.Index determining 55 explained 55 keywords 58 listed 56. 30 annotated 127 binary 55. 54 specifying type 55. 125 displaying resolved but not submitted 74.
131. 116 third-party defect trackers and 120 K filling forms with standard input 61 installation UNIX 139 Windows 141 installing on Windows 141 integration advanced functions 107 defined 148 displaying integrated files 133 displaying submitted integrated files 133 files without common ancestors 106 forcing 108 lazy copy (defined) 149 160 keywords expansion 55. 16. 149 use of 99 J have list defined 148 have revision defined 52 head revision defined 52.2 User’s Guide . 133 searching 114. 148 resolving conflicts 65 help displaying command help 34 displaying view syntax 35 p4 help command 34 history displaying revision history 124 host Perforce server 21 I -i flag job specification customizing 113 default 112 defined 149 job tracking 13. 16. 111 creating 112 defined 111 deleting 120 editing 112 jobviews 114. 91 changing owner of 96 client workspaces and 95 defined 149 Perforce 2003. 57 RCS examples 60 specifying Perforce file types 58 L label specifier without filenames 54 label view 94 defined 149 labels changelist numbers vs. 134 changelists vs. 117 reporting 120. 111 jobs 111 * wildcard 115 changelists 117 changelists associated 120. 116.Index -n flag 136 -o flag 136 forms automating processing of 61 P4EDITOR 26 standard input/output and 61 using 60 G getting started with Perforce 25 group defined 148 H previewing 133 reporting commands 110 reverse 106 specific file revisions 107 specifying direction of 106 technical explanation 108 Inter-File Branching defined 16.
132 introduced 15 locking 93 reporting 97. clients. 149 wildcards and 50 locked client option 46 locked files finding 73 locking files 72 defined 149 p4 lock vs. 132 unlocking 96 labelsync ownership required 96 syntax 96 lazy copy 102 defined 149 lifecycle management 13 limitations description lengths 50 valid filenames 50 line endings 47 LineEnd 47 linefeed convention 45 listing file contents 126 files in a branch 133 files in a label 132 files resolved but not submitted 133 integrated and submitted files 133 jobs in system 133 opened files 125 local syntax defined 48. 68 three-way (defined) 152 two-way (defined) 153 merging conflicting changes 68 files (defined) 150 metadata 124 defined 150 mode files in workspace 45.2 User’s Guide previewing commands 34. 125 examples 41 exclusionary 105 exclusionary (defined) 147 multiple 105 renaming client files 43 views and 39 markers. +l 72 M mappings client-side (defined) 146 conflicting 44 defined 150 depot and client sides 39 depot-side (defined) 147 directories with spaces 51 displaying 62.Index deleting 95 deleting files from 95 displaying contents 97. 35. 136 namespace shared for labels. difference 68 merge baseless 106 defined 67. branches. 57 modtime client option 46 moving files between changelists 87 multi-forked file 56 multiple depots 39 multiple mappings 105 N -n flag Macintosh file types 56 line-ending convention 48 linefeed convention 45 resource fork 56 resource fork (defined) 151 Perforce 2003. 98. and depots 92 network data compression 45 new changelist 86 161 . 150 three-way 15.
105. 38. 143 p4d host 21 port 21 purpose of 14. 117.exe 142 P4DIFF 143 P4DTI 120 P4EDITOR 26. 133 job command 112 jobs command 133 label command 95 labels command 97. 124. 133 revert command 34 review command 135 reviews command 135 submit command 29. 30 branch command 103. 65. 133 files command 55. 85. 66. 101. 103. 82. 124 fix command 89. 62. 126 help command 34 info command 23. 81. 128 diff2 command 74. 86. 95. 88 sync command 29. 21 p4d. 131 diff command 74. 125 passwd command 78 print command 62. 128 162 Perforce 2003. 108. 117 users command 135 where command 62. 31 filelog command 62. 136 offline working with Perforce 81 older revisions 51 opened files listing 62 operators job queries 116 options client workspace 45 p4 resolve command 68 overriding 59 owner changing label 96 P p4 admin and Windows 142 stopping server with 141 p4 annotate 127 p4 commands add command 29. 107 branches command 133 change command 89 changes command 90. 98. 62. 133 resolved command 74. 72. 89 resolve command 66. 44 common flags 79 counters command 135 delete command 29. 132 labelsync command 95 lock command 72 opened command 55. 68. 106. 74. 126 typemap command 59 user command 79.Index noallwrite client option 45 noclobber client option 45 nocompress client option 45 nocrlf client option 45 nomodtime client option 46 normdir client option 46 edit command 29. 130 client command 26. 62. 118 fixes command 134 have command 35. 32 depots command 136 describe command 90. 143 numbered changelists creating 87 O -o flag scripting 61. 34 integrate command 83. 126 rename command 83 reopen command 55. 143 P4CONFIG 77. 103. 62. 126 P4CHARSET 143 P4CLIENT 26.2 User’s Guide .
server 142 Perforce syntax defined 48 wildcards 50 perforce. automatic 88 reporting basic commands 34. 143 p4s. 132 overview 123 resolves 74 scripting 136 163 .exe 142 P4USER 143 defined 153 previewing integration results 133 label contents 93 -n flag 136 resolve results 133 revert results 34 sync results 35. 131 daemons and 135 file metadata 124 files 123 integration 110. 74 propagating changes branches 105 proxy 13 PWD 143 R RCS format parametric substitution 38. 21 Perforce server and P4PORT 140 connecting to 21 defined 151 host 21 port 21 purpose of 14.2 User’s Guide defined 151 files 63 RCS keyword expansion 57 +k modifier 55 examples 60 recent changelists p4 changes command 90 release management 13 remote depot defined 151 removing files from depot 32 from workspace 52 renaming files 83 renumbering changelists. 143 and server 140 P4ROOT 140. 62. 130.Index P4HOST 143 P4JOURNAL 143 P4LOG 143 P4MERGE 143 P4PAGER 143 P4PASSWD 78. 143 P4PORT 22. 57 user (defined) 145 port for server 140 Perforce server 21 pre-submit trigger Perforce 2003. 133 labels 97. 43 passwords 78. 21 tracks state of client workspace 37 vs. 79 pending changelist defined 150 deleting 89 submitting 86 Perforce client programs connecting to server 21 purpose 14. service 142 working when disconnected from 81 Perforce service vs.exe 141 permissions files in workspace 45. 133 jobs 120. 61 branches 133 changelists 90.
Index repository file (defined) 148 resolve between codelines 103 branching and 74 conflicting changes 63 default 70 defined 15. 21 Perforce (defined) 151 port 140 stopping with p4 admin 141 verifying connection 23 vs. 151 detecting 66 diff chunks 67 displaying files before submission 133 multiple 108 performing 66 preventing multiple 73 previewing 133 reporting 74 scheduling 65 resource fork 56 defined 151 result resolving 67 reverse delta storage defined 151 reverse integration 106 revert defined 151 example 34 revision base (defined) 145 diffs and 65 file (defined) 148 have 52 head 52 head (defined) 148 history 62. 54 specification (defined) 152 tip (defined) 153 rmdir client option 46 root 164 client 37 S SCM 13 scripting examples 61 -o flag 136 reporting 136 searching jobs 114 server connecting to 21 Perforce 14. 124 number (defined) 151 range 54 range (defined) 151 specification 51. service 142 Windows 142 server root and P4ROOT 140 creating 140 defined 140 setting environment variables 144 setting up client workspaces 26 environment 21 p4 info 23 shell parsing wildcards 38 software configuration management 13 spaces filenames 50 within filenames 51 special characters filenames 50 specification revision (defined) 152 standard input filling forms with 61 standard output generating forms with 61 p4 print command 62 stopping server Perforce 2003.2 User’s Guide .
74 syntax client 49 depot 49 depot (defined) 147 local 48 local (defined) 149 Perforce syntax 48 specifying files 49 system administration checkpoint (defined) 146 groups (defined) 148 journal (defined) 149 reporting 135 T when scheduled 106 time zones 53 timestamps preserving DLLs 59 tip revision defined 153 TMP 143 tracking defects 13 jobs 16 translation CR/LF 45 trigger defined 153 two-way merge defined 153 typemap file types 59 U umask(1) 140 unicode 57 UNIX target files defined 152 TCP/IP 14 line-ending convention 47 linefeed convention 45 unlocked client option 46 usage notes integration 106 users email addresses 135 listing submitted changelists 90 passwords 78 reporting on 135 V -v flag and port number 140 text files 55. 56 defined 152 theirs 67 defined 152 three-way merge binary files and 72 defined 152 merge file generation 68 Perforce 2003. delta (defined) 148 reverse delta (defined) 151 submit defined 152 submitted changelist 86 submitting multiple changes at once 33 subscribe defined 152 symbolic links 56 file types and 55 non-UNIX systems 56 sync forcing 82 preview 62. creating 103 client 15. 38 client (defined) 146 165 . 27.2 User’s Guide diff markers 68 variables environment.Index with p4 admin 141 storage full-file vs. how to set 144 version control 13 views branch (defined) 145 branch.
37. 38 defined 38 escaping on command line 86 jobviews 115 local shell considerations 38 local syntax 50 Perforce syntax 50 views 41 Windows and p4 admin 142 installer 141 installing on 141 line-ending convention 48 linefeed convention 45 multiple drives 40 server 142 setting variables on a Windows service 144 third-party DLLs 59 166 Perforce 2003..Index conflicting mappings 44 defined 153 examples of mappings 41 exclusionary mappings 42 help on 35 jobviews 114 label 94 label (defined) 149 mappings and 39 multiple mapping lines 42 renaming client files using mappings 43 wildcards 41 W working detached 81 working detached (defined) 147 workspace client 14... 43 * 38 . 95 client (defined) 146 comparing files against depot 129 copying files from depot 29 displaying files 62 refreshing 82 spanning multiple drives 40 Y yours 67 defined 153 warnings # and local shells 51 binary files and delta storage 56 changing client root 44 white paper best practices 110 branching 110 Streamed Lines 110 wildcards %0 . %n 38.2 User’s Guide .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview. | https://www.scribd.com/document/69158083/Perforce-Users-Guide | CC-MAIN-2017-04 | refinedweb | 48,906 | 68.77 |
For about two weeks now, the published version of the VSCode OCaml Platform extension has had something special about it.
It is using Js_of_ocaml! This is the result of a month-long effort to switch the extension’s OCaml-to-JS compiler from BuckleScript to Js_of_ocaml.
In this post, I will describe the extension, explain the reasoning for switching to Js_of_ocaml, and go over some of the things I learned through the porting experience.
The OCaml Platform
The VSCode OCaml Platform extension is part of the larger OCaml Platform; it interacts directly with OCaml-LSP, an implementation of the Language Server Protocol for OCaml editor support. The OCaml-LSP language server provides editor features like code completion, go to definition, formatting with ocamlformat, and error highlighting.
OCaml-LSP can be used from any editor that supports the protocol, but the VSCode extension provides additional features: managing different package manager sandboxes; syntax highlighting of many OCaml-related filetypes; and integration with VSCode tasks, snippets, and indentation rules.
Both the language server and VSCode extension are continuously tested to ensure compatibility for opam and esy on macOS, Linux, and even Windows.
Making OCaml more accessible is a goal for these projects. Providing support for a popular cross-platform code editor and the widely supported language server protocol helps achieve that goal.
BuckleScript vs. Js_of_ocaml
BuckleScript and Js_of_ocaml are technologies that accomplish a similar goal: compiling OCaml to Javascript code. However, there are a few differences that made it worthwhile to switch to Js_of_ocaml.
The ways in which BuckleScript and Js_of_ocaml approach compiling to JS are notably different. BuckleScript compiles from an early intermediate representation of the OCaml compiler to generate small JS files for each OCaml module; this is effective but fixes the OCaml language to a certain version (4.06.1 at the time of writing). Js_of_ocaml takes a different approach and generates JS from OCaml bytecode, which is more stable across different versions of OCaml but might provide less information. Using Js_of_ocaml allows the VSCode extension to be built with a recent version of OCaml (4.11.1 right now).
BuckleScript has undergone a rebranding and it is now called ReScript with the addition of a new syntax. At one point, OCaml documentation was removed from the website. As I revisit the site today, OCaml documentation has returned in the old v8.0.0 documentation as “Older Syntax”. It does seem that OCaml and ReasonML will be technically supported for now (forever?), but the project feels more distant from OCaml than it did as BuckleScript.
Js_of_ocaml, on the other hand, is deeply integrated with the OCaml language and ecosystem. This integration is great for existing OCaml developers because it means complex JS projects can be built with the excellent dune build system with access to most of the same opam packages as native projects.
For a more in-depth comparison of the two technologies, I recommend reading @jchavarri’s post about the topic.
gen_js_api
For a VSCode extension, there are many bindings that have to be created for interaction with the VSCode extension API. For the BuckleScript version of the extension, we used the built-in syntax for bindings.
For example, to bind to
vscode.window.createOutputChannel in BuckleScript:
external createOutputChannel : name:string -> OutputChannel.t = "createOutputChannel" [@@bs.module "vscode"] [@@bs.scope "window"]
This expresses that
createOutputChannel is a function from the
window namespace of the
vscode node module. The
bs.module annotation automatically inserts the
require for the
vscode module in the generated JavaScript.
There are a few ways to express the same things in Js_of_ocaml. The first is to use the provided functions in the
Js_of_ocaml.Js module to manually convert between OCaml and JS types:
let createOutputChannel ~name = Js.Unsafe.global##.vscode##.window##createOutputChannel [| Js.string name |]
Notice that certain OCaml types (like strings) have to be converted into their JS representation. Doing these conversions manually may work for small libraries, but it would be impractical to do that for every binding and type in the expansive VSCode API.
For that reason, gen_js_api is a great alternative. The same binding with gen_js_api looks like this:
val createOutputChannel : name:string -> OutputChannel.t [@@js.global "vscode.window.createOutputChannel"]
What gen_js_api will do is generate code that automatically calls
Ojs.string_to_js for the parameter and
OutputChannel.t_of_js for the return value. An OCaml value can be converted a JS value if it is a “JS-able” type, or if the appropriate
of_js/
to_js functions exist.
It is important to note that unlike BuckleScript, gen_js_api is actually doing a conversion between values. If a function binding is written that returns an OCaml record, modifying a field of that record only modifies the record itself; the original JS value is untouched. This is different from BuckleScript, where an OCaml type directly corresponds to its JS data representation.
To avoid this, it is possible to keep values as an abstract
Ojs.t type, which are the unconverted JS values. Accessing and setting fields can be done with a function annotated with
[@@js.set] or
[@@js.get]. This method was used for the entirety of the extension’s VSCode bindings, which can be found here.
Node Modules
As mentioned previously, BuckleScript provides a way to reference Node modules with
[@@bs.module]. As far as I know, there is no simple equivalent provided by Js_of_ocaml or gen_js_api at the moment. Fortunately, there is a simple workaround with a single JS stub file:
joo_global_object.vscode = require("vscode");
In this JavaScript file,
joo_global_object refers to the same value as
Js.Unsafe.global. Setting the
vscode field this way allows it to be referenced by the gen_js_api functions globally.
For this JavaScript file to be used, the library’s dune configuration must be updated with:
(js_of_ocaml (javascript_files vscode_stub.js))
Afterward, bindings can be created that reference
vscode and its namespaces or values.
There is some ongoing work in gen_js_api that may improve the interaction between node modules and scopes.
JSON
JSON is a staple of many browser and node.js projects; the VSCode extension is no different. In the extension, JSON is used to (de)serialize user settings and interact with the language server using JSON-RPC.
When the extension was built with BuckleScript, it used @glennsl’s bs-json library for composable encoding and decoding functions. bs-json wasn’t available for Js_of_ocaml, so I decided to reimplement it for Js_of_ocaml as jsonoo (opam). The documentation for jsonoo is available here.
The main idea is that there are
decoder and
encoder types which are
Jsonoo.t -> 'a and
'a -> Jsonoo.t function types, respectively. The functions provided by jsonoo can easily compose
decoder or
encoder functions to handle complex JSON values. The
Jsonoo.t type is represented as a JS value and uses the Js_of_ocaml library to convert between OCaml values and JavaScript JSON values.
For example, to try to decode a list of integers, returning a default value otherwise:
let decode json = let open Jsonoo.Decode in try_default [] (list int) json
Since jsonoo provides
t_of_js and
t_to_js functions, it is also possible to use the JSON type with gen_js_api bindings:
val send_json : t -> Jsonoo.t -> unit [@@js.call]
jsonoo seems to work well for its purpose of a Js_of_ocaml JSON library, but @rgrinberg brought up the point that this fragments the JSON libraries based on their underlying JSON implementation. For that reason, it may be worthwhile to look into json-data-encoding, an alternative that allows using the same API across different JSON representations.
Promises
As an extension that primarily operates on the user-interface level, asynchronous operations through the JS Promise API are very important for a smooth user experience. Creating bindings to the promise functions seems straightforward at first, but you will eventually find that JS promises have a soundness problem.
For example, with a direct binding to the
resolve function, one would expect that for every value passed to the function it would return that value wrapped in a promise.
val resolve : 'a -> 'a promise
let x : int promise = resolve 1 let y : int promise promise = resolve (resolve 2) (* flattened! *)
Everything seems fine from the OCaml side, but it turns out that JavaScript automatically flattens nested promises by following the
then function of any value that is passed to it. Even though
y appears to have the
int promise promise type, the JS representation will be flattened to
int promise. This is obviously a bad sign because the type system is misrepresenting the data, which will surely result in nasty runtime errors.
So how do we prevent the promise functions from following a value’s
then functions? The solution is simple: ensure that the JS functions never receive values that have a
then function in the first place.
Using a technique I first saw in @aantron’s promise library for BuckleScript, it is possible to check for values that have a
then function and wrap them in an object to prevent the JS functions from calling it:
function IndirectPromise(promise) { this.underlying = promise; } function wrap(value) { if ( value !== undefined && value !== null && typeof value.then === "function" ) { return new IndirectPromise(value); } else { return value; } } function unwrap(value) { if (value instanceof IndirectPromise) { return value.underlying; } else { return value; } }
Calling
wrap on every value that is passed to
Promise.resolve and calling
unwrap on every resolved (completed) value will make the behavior consistent. Doing the wrapping and unwrapping for each unsound promise function binding will result in an API that is suitable for type-safe usage.
The final product of these bindings is the promise_jsoo (opam) library for Js_of_ocaml. It includes bindings for the majority of the JS API, as well as supplemental functions that make it easier to interoperate with OCaml. promise_jsoo provides the necessary functions to use it with gen_js_api. The documentation for promise_jsoo is available here.
As an added bonus, running an OCaml version of at least 4.08 (which wasn’t possible with BuckleScript) allows using binding operators:
val let* : 'a promise -> ('a -> 'b promise) -> 'b promise
let async_function () : int promise = let* first_num = get_num () in let* second_num = get_num () in async_calculation first_num second_num
This syntax is reminiscent of
await syntax in other languages and it is a good alternative to the previous style of monadic operators:
let async_function () : int promise = get_num () >>= fun first_num -> get_num () >>= fun second_num -> async_calculation first_num second_num
promise_jsoo has a comprehensive test suite that should give weight to its claims of type safety. It was difficult to find a testing library that would work for an asynchronous library in Js_of_ocaml, but I eventually found webtest by @johnelse.
In the future, I’d like to investigate giving types to promise rejections and providing a simple way to convert to Async or Lwt types.
Sys.unix
Apparently, the value of
Sys.unix in Js_of_ocaml is always true. The system seems to be hardcoded in Js_of_ocaml’s JS runtime, which caused problems for path handling with the
Filename OCaml module on a certain operating system (sorry Windows users!).
I assume the reason for the hardcoded system is because of a lack of a good way to get the operating system across different runtimes (browser, node.js). The browser has user agents and node.js has
process.platform, but not vice versa.
As a workaround, the VSCode extension just uses bindings to the node
path module for proper cross-platform path handling since the extension already depends on node.js.
Closing
Overall, I am very happy with the transition to Js_of_ocaml. The ability to use the same build system and packages for native and JS projects leads to a smooth and enjoyable development experience. I am still learning the quirks of the JS target, but for the most part, Js_of_ocaml just works.
The VSCode OCaml Platform is an actively developed project with numerous contributors, so please feel free to submit an issue or contribute a pull-request.
If you have any questions or comments about this post, I can answer them on the OCaml Forum topic. | https://mnxn.github.io/blog/ocaml/vscode-jsoo/ | CC-MAIN-2021-04 | refinedweb | 1,989 | 54.73 |
*
Parameter passing problem
Rus Corina
Ranch Hand
Joined: Jul 08, 2011
Posts: 90
posted
Oct 20, 2012 10:25:13
0
Hello. I am currently learning how to use jsf and i have a big problem that I don't know how to solve. I might not even be able to explain very accurate what the problem is but I will try.
Here it goes:
I have a page, admin.jsp, where you can perform CRUD operations on a table. The problem i have is with the Read action. In order to read users from the db, you insert the username and then press Read button. The users whose username is similar to the one inserted by the user are displayed in a datatable, on another page (data.jsp). The problem is, how do I transfer the username from one page to another? I have a bean, called "login_bean" where the username is kept, as long as I perform some operation from the bean on the admin.jsp page. But once I go to another page, username dissappears. I will post some code, hopefully it will become clearer.
PS: I simplifid the code and left only info concerning username, hoping that it will become easier to understand
admin.jsp:
<%-- Document : success Created on : Jan 18, 2010, 9:35:40 PM Author : Prashant --%> <%"> <title>Welcome!</title> </head> <body> <f:view> <h:form <h2>User CRUD operations:</h2> <table width="250" border="0" cellspacing="0" cellpadding="2"> <tr> <td><h:outputText</td> <td><h:inputText</td> </tr> </table> <table width="250" border="0" cellspacing="0" cellpadding="2"> <tr> <td> <input type="button" onclick="window.location.href=''" value="Back" /> </td> </tr> <tr> <input type="button" onclick="window.location.href=''" value="Log Out" /> </tr> </table> </h:form> </f:view> </body> </html>
data.jsp
<%@ taglib <f:facet <h:outputText </f:facet> <h:column> <f:facet <h:outputText </f:facet> <h:outputText</h:outputText> </h:column> </h:dataTable><br> <input type="button" onclick="window.location.href=''" value="Back" /> </center> </body></html></f:view>
login_bean.java
import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author Prashant */ import java.sql.*; import java.util.*; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletRequest; @ManagedBean(name = "login_bean") @RequestScoped public class login_bean { private String username = ""; Connection con; Statement ps; ResultSet rs; String SQL_Str; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private List perInfoAll = new ArrayList(); private int nrRows=0; public List getperInfoAll() { nrRows = 0; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;" + "databaseName=LOGINH1;user=sa;password=parola;"); ps = con.createStatement(); rs = ps.executeQuery("select * from SysUser where username like '%"+username+"%'"); while (rs.next()) { System.out.println(rs.getString(1)); perInfoAll.add(nrRows, new perInfo(rs.getString(1)); nrRows++; } } catch (Exception e) { System.out.println("Error Data : " + e.getMessage()); } return perInfoAll; } public int getNrRows() { return nrRows; } public void setNrRows(int nrRows) { this.nrRows = nrRows; } public class perInfo { String username; public perInfo(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } }
[/code]
I must mention that everything I did here was taken from internet examples. I don't know jsf/jsp, I needed to make a project for the university in 2 weeks, and I did not have much time to repare.
Thank you
Rus Corina
Ranch Hand
Joined: Jul 08, 2011
Posts: 90
posted
Oct 20, 2012 10:27:44
0
I need to know how I can make the username in java_bean remain the same as it is in admin.jsp when the user presses "read" button and transfers him to data.jsp page
Volodymyr Levytskyi
Ranch Hand
Joined: Mar 29, 2012
Posts: 481
1
I like...
posted
Oct 20, 2012 11:47:33
0
Hello!
It is better to use on jsf page mainly jsf components. Instead of <table> use <h:dataTable>
If you want to pass some parameter from one page to another look at this simple sample:
This is command button that can execute some method of bean and navigate to next page by 'action' attribute:
<h:commandButton <f:param </h:commandButton> Page where I was forwarded by clicking at above button is: <f:metadata> <f:viewParam <f:validateLongRange </f:viewParam> </f:metadata> <f:event
Of course it is only part of that page. <f:viewparam> element takes id passed from previous page and stores id in bean.selectedEventId.
It is important to have attribute 'name' of f:param and <f:paramview> with identical value on both pages. Also action attribute must include- includeViewParams=true
True person is moral, false is right!
Tim Holloway
Saloon Keeper
Joined: Jun 25, 2001
Posts: 15629
15
I like...
posted
Oct 22, 2012 05:42:58
0
It's even better not to put parameters on pages at all. They add to network traffic, they offend the MVC architecture by blurring the separation between Model and View, and they can be exploited by hackers.
JSF
is designed to keep most of its data on the server side, therefore you usually shouldn't send data out to the View and back in again as parameters, you should simply transfer the data from backing bean to backing bean.
I could do an entirely different rant on user-coded logins and why they are even more insecure than parameters on the View, but I'll probably do that somewhere else today anyway.
Customer surveys are for companies who didn't pay proper attention to begin with.
I agree. Here's the link:
subject: Parameter passing problem
Similar Threads
Navigation problem
Datatable with scrollbar in JSF
Setting up a JSF project with data tables
JSF ArralyList rendering to Target page is throwing Class Cast Exception
Jsf Data table values are coming as null
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/595691/JSF/java/Parameter-passing | CC-MAIN-2014-15 | refinedweb | 980 | 55.64 |
Phil Steitz wrote:
> Alex Karasulu wrote:
>
>> Henri Yandell wrote:
>
<snip/>
>> That would be really nice. If there were only a way to get
>> notification back from the file system of changes. You can do that
>> on windows but not on other OSs it seems hence the lack of support in
>> JDK. But notification of change over polling is an awesome thing to
>> have.
>
>
> What are the use cases? Isn't it better to use the JNDI / LDAP APIs
> to listen for / trigger changes?
Yeah that true! This is cake for the Eve LDAP JNDI provider since we can
detect all alterations coming in through our interfaces (LDAP or JNDI).
This is not the case for other namespaces/providers which store files
that are more likely to be altered by a human editor. Things like
properties files that are accessed via JNDI for example can change
because they get edited. Then you want to detect this back door edit.
Such a mechanism would help achieve this is I guess what we were thinking.
Alex | http://mail-archives.apache.org/mod_mbox/directory-dev/200412.mbox/%3C41B561E0.5000709@bellsouth.net%3E | CC-MAIN-2017-17 | refinedweb | 173 | 82.34 |
September 13, 2020
Bartek Iwańczuk, Ryan Dahl, and Luca Casonato
Today we are releasing Deno 1.4.0, our largest feature release yet. Here are some highlights:
deno run --watchto automatically reload it on file changes
deno test --coverageto get a summary of your test coverage
If you already have Deno installed you can upgrade to 1
This release adds support for the web standard
WebSocket API,
available in all modern browsers. It can be used to communicate with remote
servers over the WebSocket protocol.
Here is a short example of how it works:
// Start the connection to the WebSocket server at echo.websocket.orgconst ws = new WebSocket("ws://echo.websocket.org/");// Register event listeners for the open, close, and message eventsws.onopen = () => {console.log("WebSocket ready!");// Send a message over the WebSocket to the serverws.send("Hello World!");};ws.onmessage = (message) => {// Log the message we recieve:console.log("Received data:", message.data);// Close the websocket after receiving the messagews.close();};ws.onclose = () => console.log("WebSocket closed!");ws.onerror = (err) => console.log("WebSocket error:", err.error);// When running this the following is logged to the console://// WebSocket ready!// Received data: Hello World!// WebSocket closed!
You can try it out locally:
deno run --allow-net=echo.websocket.org
This release also removes the websocket connect methods from
std/ws. Use the
WebSocket API instead.
deno run --watch
Deno now has an integrated file watcher that can be used to restart a script when any of its dependencies change.
To use it, run your script like you usually would, but add the
--watch flag.
You additionally have to add the
--unstable flag because this feature is not
stable yet.
$ echo "console.log('Hello World!')" > mod.ts$ deno run --watch --unstable mod.tsCheck WorldWatcher Process terminated! Restarting on file change...# now run `echo "console.log('File watching works!')" > ./mod.ts` in a different terminalWatcher File change detected! Restarting!Check watching works!Watcher Process terminated! Restarting on file change...
The watch flag takes no arguments for directories or files to watch. Instead it automatically determines all of the local imports of your script, and watches those.
Currently file watching is only supported for
deno run, but in the future it
will also be added to
deno test and possibly other subcommands.
deno test --coverage
You can now find code that is not covered by your tests using the
--coverage
flag for
deno test. When enabled this will print a summary of your code
coverage per file after all tests are run. You additionally have to add the
--unstable flag because this feature is not stable yet.
$ git clone git@github.com:denosaurs/deno_brotli.git && cd deno_brotli$ deno test --coverage --unstableDebugger listening on ws://127.0.0.1:9229/ws/5a593019-d185-478b-a928-ebc33e5834beCheck 2 teststest compress ... ok (26ms)test decompress ... ok (13ms)test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out (40ms)test coverage: 100.000% 100.000%
Currently the only available output format is the text summary. Other output
formats like
lcov and
json will be added in the future.
--unstable
For all users using
--unstable the
isolatedModules and
importsNotUsedAsValues TypeScript compiler options will be switched on by
default now. We will enable these flags by default for everyone in the future.
These flags enable some stricter checks in the TypeScript compiler that will
likely lead to some new errors you have not seen before:
ERROR TS1205: Re-exporting a type when the '--isolatedModules' flag is provided requires using 'export type'.ERROR TS1371: This import is never used as a value and must use 'import type' because the 'importsNotUsedAsValues' is set to 'error'.
These errors occur when interfaces or type aliases are imported or re-exported.
To fix the error, change your imports and re-exports to use
import type and
export type. Example:
// Badimport { MyType } from "./mod.ts";export { MyType } from "./mod.ts";// Goodimport type { MyType } from "./mod.ts";export type { MyType } from "./mod.ts";
deno infoimprovements
The
deno info tool for doing dependency analysis has gotten a major overhaul
this update. It is now faster and less buggy. Additionally the file size of
dependencies is now displayed making it very easy to figure out what
dependencies are adding a lot of code to your project.
Most modern browsers support styling
console.log messages with CSS. In our
ongoing effort to be as web compatible as possible, Deno now also supports CSS
styling for
console.log.
To style a message, add a
%c format parameter to your message, and specify the
styles to apply as an argument to
console.log:
console.log("%cStop!", "color:red;font-weight:bold");// This will print a bold red `Stop!` to the console.
Deno supports the CSS properties
color,
background-color,
font-weight,
font-style,
text-decoration-color, and
text-decoration-line. Support for
these properties, and custom rgb, hex, and hsl colors depend on your terminal's
support for ANSI.
View the source code at
In this release we've added support for the final rules required to get
deno lint rules on par with recommended
eslint and
typescript-eslint
ruleset. This means that
deno lint should be able to catch all errors that
@eslint/recommended and
@typescript-eslint/recommended can. (At an order of
magnitude better performance.) This is a major step towards stabilizing
deno lint.
deno doc
deno doc and has also gotten a round of new features and
fixes this release. Support for the
export { foo }; syntax has been added
(exporting a statement after declaration), and re-exports of multiple symbols
with the same name are now supported.
To try out these new features, just browse any module on. It has been updated with the new release already.
In this release the
writeJson,
writeJsonSync,
readJson, and
readJsonSync
functions have been removed from the. You can easily
switch them out with these functions:
- const accounting = await readJson("accounting.json");+ const accounting = JSON.parse(await Deno.readTextFile("accounting.json"));- const accounting = readJsonSync("accounting.json");+ const accounting = JSON.parse(Deno.readTextFileSync("accounting.json"));- await writeJson("hello_world.json", { "hello": "world" });+ await Deno.writeTextFile("hello_world.json", JSON.stringify({ "hello": "world" }));- writeJsonSync("hello_world.json", { "hello": "world" });+ Deno.writeTextFileSync("hello_world.json", JSON.stringify({ "hello": "world" }));
deno_coreRust API
The base subsystem for Deno,
deno_core, continues to evolve as we improve the
CLI. In 0.57.0, we've merged
CoreIsoate and
EsIsolate into a single struct
called
JsRuntime. Also an easier facility for creating ops has been exposed.
Have a look at the
example.
to see how these APIs fit together.
The VS Code extension for Deno has had some major feature releases recently. Here is a quick summary:
A great new feature of the extension is IntelliSense for deno.land imports. It gives you autocomplete suggestions for module names on deno.land/x, all of their versions, and their full directory listing. All of this is done without actually downloading the module source code, instead it is all powered by the recent updates to deno.land/x.
deno lintdiagnostics
deno lint is now fully integrated with the extension. To enable it, just set
the
deno.unstable and
deno.lint settings in the extension to
true. After
doing this you will get inline real-time diagnostics for your code:
The full release notes, including bug fixes, can be found at. | https://deno.land/posts/v1.4 | CC-MAIN-2020-45 | refinedweb | 1,215 | 51.75 |
Access specifiers and visibility
Contents
- 1 Description
- 2 Current state of affairs in D
- 3 Current state of affairs in C++
- 4 Requirements for DIP
Description
Current state of affairs in D
Access specifier (protection attribute) meaning
Mostly copied from
private
Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. Private members cannot be overridden.
dlang.org states that "Private module members are equivalent to static declarations in C programs." but this is wrong, they have external linkage:
module sample; private void func1(int) { } void func2(int) { }
$ dmd -c sample.d $ nm -a sample.o | grep func 00000000 t .text._D6sample5func1FiZv 00000000 t .text._D6sample5func2FiZv 00000000 T _D6sample5func1FiZv 00000000 T _D6sample5func2FiZv
package
Package extends private so that package members can be accessed from code in other modules that are in the same package. This applies to the innermost package only, if a module is in nested packages.
protected
Public means that any code within the executable can access the member.
export
Export means that any code outside the executable can access the member. Export is analogous to exporting definitions from a DLL.
Global static
Global static storage class currently is a no-op storage class in D, global symbols with one are compiled but ignored.
Name lookup :
One other obvious consequence of this - in case private symbol is only possible lookup, error message will show to it, instead of issuing unknown symbol.
What is missing
- There is currently no way in D to mark symbols for internal linkage, saying "this an implementation detail, you should not even know this one exists". This is an important module-level encapsulation tool which also somewhat guarantees that those symbols can't be linked to by accident by some other module and you are free to change them keeping binary interface same.
- Name clash between public and private symbols has also been stated as unneeded and useless feature that makes possible to break a compilation of a project by changing private name. It is also impossible to use an UFCS function now if class already has private one with same signature.
Complications
- Compile-time reflection, i.e. serialization libraries or @attribute scanners. Limiting access for __traits may forbid certain currently working idioms.
- Symbol leakage via aliases or function arguments.
private struct _Hidden { } alias const(_Hidden) UseMe; void func(_Hidden input) { }
Currently it is all valid as _Hidden symbol is perfectly accessible, just prohibited from direct usage. If some true internal linkage storage class / specifier is introduced (private or not) this case needs to be defined in smallest details. See Access_specifiers_and_visibility#Module-scope_analogies for how it is handled in C++.
- Templates do symbol look up in their original scope, not in the scope that they're instantiated. They only do symbol lookup in the scope that they're instantiated in if they're mixed in. Consequences - unknown, but it is related to name lookup.
Related bugzilla issues
Current state of affairs in C++
Access specifier (protection attribute) meaning
private
private as an access specifier is defined only for classes/structs. It does not hide symbol, but prevents usage:
class Test { private: int a; }; int main() { Test t; t.a = 42; return 0; }
test.cpp:9:15: error: 'a' is a private member of 'Test' Test t; t.a = 42; ^ test.cpp:4:13: note: declared private here int a; ^
protected
Similar to private, but allows access for descendants.
public
Default one for globals (you can't have any other access specifier for globals), "if you can see symbol - you can access it". Also default for struct members.
Module-scope analogies
C++ does not have a modules in D sense. It is based on translation units (*.cpp) and headers are just copy-pasted upon include, so module-level access specifiers make no sense to C++. However, there is an "unnamed namespace" feature, that forces internal linkage for a symbol:
// sample.cpp void func1(int) { } namespace { void func2(int) { } }
$ clang++ -c sample.cpp $ nm -a ./sample.o | grep func 00000000 T _Z5func1i
One of interesting cases - what happens when hidden symbol becomes the part of public interface? Consider this sample:
// sample.cpp namespace { class Hidden { }; } class Test { public: void func(Hidden) { } }; // if func() referencing Test will be skipped, then // no traces of Test::func will be found in object file. // Can't find part of standard that explains it. void func(Test t) { t.func(Hidden()); }
$ clang++ -c sample.cpp $ nm -a sample.o | grep Hidden 00000020 t _ZN4Test4funcEN12_GLOBAL__N_16HiddenE
While symbol somewhat leaked into external linking, it has special mangling and, I suppose, impossible to use without some assembler-like forging. Note that it is impossible to share Test class definition via header as Hidden symbol won't resolve within any other translation unit.
Why D should not mimic private semantics
Jonathan M Davis, on name clash issue:
C++ doesn't have module-level access modifiers or UFCS, so it's completely unaffected by this. In C++, you can't add functions to classes from the outside, so there's no concern about adding private functions to a class breaking code using that class. And you can't add a private function to a module, because there are neither modules nor private, free functions, so you aren't going to get breakage from adding a private function, because you can't add a private function.
Regardless can't override private functions even within a module, because in D, private and package functions are never virtual and therefore cannot be overridden. If you want to be able to override them, you have to make them public or protected.
In C++, you can make private functions virtual and override them, but that's not possible in D, primarily because we took the simpler route of tying the virtuality of a function to its access level rather than having to explicitly mark functions as virtual.
Requirements for DIP
Everyone here has raised some good points. But this isn't a simple issue, so I suggest getting together and preparing a DIP. A DIP should address:
1. what access means at module scope 2. at class scope 3. at template mixin scope 4. backwards compatibility 5. overloading at each scope level and the interactions with access 6. I'd also throw in getting rid of the "protected" access attribute completely, as I've seen debate over that being a useless idea 7. there's also some debate about what "package" should mean
I.e. it should be a fairly comprehensive design addressing access, not just one aspect of it.
(c) Walter | https://wiki.dlang.org/Access_specifiers_and_visibility | CC-MAIN-2019-09 | refinedweb | 1,106 | 55.95 |
If you want to use `is` in your DSL you could try:
def check(condition) {
// Define and initialize a new map
def map = [:]
// Remove the `is` method from the map's metaclass
map.metaClass.is = null
// Add the key-value pair we care for the DSL
map[is] = { bool ->
println "checking if $condition yields $bool, with 'is'"
}
// Return the map
map
}
I don't know if the above follows good practices or at very least is a good
idea (remember that I'm very new) but it works.
On Wed, Oct 28, 2015 at 12:19 AM, Edinson E. Padrón Urdaneta <
edinson.padron.urdaneta@gmail.com> wrote:
> Well, I'm very new to groovy so I could be very wrong but `is` is a method
> of `GroovyObjectSupport`, so maybe you are invoking that method in your DSL
> without knowing that.
>
> On Tue, Oct 27, 2015 at 10:47 PM, Marc Paquette <marcpa@mac.com> wrote:
>
>> Playing with DSL here (going through chapter 19 of « Groovy In Action,
>> second edition », well worth the read). It seems that one cannot use the
>> word ‘is’ to build a command chain dsl, but ‘IS’ or ‘Is’ or ‘iS’
are ok… Or
>> is it something I’m doing wrong ?
>>
>> ```
>> [marcpa@MarcPaquette dsl]$ groovy --version
>> Groovy Version: 2.4.3 JVM: 1.8.0_60 Vendor: Oracle Corporation OS: Mac OS
>> X
>> [marcpa@MarcPaquette dsl]$ cat chainWithLowerCaseIsFails.groovy
>> def check(condition) {
>> [is: { bool ->
>> println "checking if $condition yields $bool, with 'is'"
>> },
>> IS: { bool ->
>> println "checking if $condition yields $bool, with 'IS'"
>> }]
>> }
>>
>> cond = (1<2)
>> check cond is true
>> check cond IS true
>> [marcpa@MarcPaquette dsl]$ groovy chainWithLowerCaseIsFails.groovy
>> checking if true yields true, with 'IS'
>> [marcpa@MarcPaquette dsl]$
>> ```
>>
>> Marc Paquette
>>
>>
> | http://mail-archives.eu.apache.org/mod_mbox/groovy-users/201510.mbox/%3CCACtcGtwq794bcy_LxhJuzgXt-YdqW-AtA6B9dekj=0B-sKabTw@mail.gmail.com%3E | CC-MAIN-2019-51 | refinedweb | 283 | 60.14 |
My. In this post, we’ll look at how Go code is organized into packages, the various commands to build and install them, and how to integrate third-party libraries.
Packages
All Go programs and libraries are defined in packages. Packages are named after the final part in their directory path. An
import declaration is used to load a package.
package main import ( "net/http" "fmt" "io/ioutil" ) func main() { resp, err := http.Get("") if err != nil { panic(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(body)) }
The entry point for every Go program is the
main function in the
main package. This program imports three packages from the Go standard library. A package’s name is used to access its exported interface. In this example,
http is used to access the package’s
Get function.
Creating a Custom Package
The first step in creating a custom package is to create a workspace. A workspace is a directory hierarchy containing three subdirectories:
src– Go source code organized into packages
pkg– OS and architecture specific compilation artifacts
bin– executable Go programs
When you import a custom package, Go looks for its definition in each workspace listed in the
GOPATH environment variable.
Let’s create a workspace and set the
GOPATH.
% mkdir -p ~/Projects/golang/src % export GOPATH=~/Projects/golang/
Our custom package will be defined in a
src subdirectory.
~/Projects/golang/src/foo/foo.go
package foo import ( "fmt" ) func Bar() { fmt.Println("bar") }
% tree golang golang └── src └── foo └── foo.go
A Go package is named after its directory. Within its directory, it can be implemented in any number of arbitrarily named files. In this example, I chose to name our custom package’s only file after the package.
Importing a Custom Package
With this directory structure in place and the
GOPATH set, we can now create a Go program that can import and use our custom package. This program will also be defined in a
src subdirectory.
~/Projects/golang/src/fooer/fooer.go
package main import ( "foo" ) func main() { foo.Bar() }
% tree golang golang └── src ├── foo │ └── foo.go └── fooer └── fooer.go
Our next step is to build and install this program.
Building Go Code
Build Go code using the
go command-line tool’s
build command.
Building a program creates an executable file in the program’s directory. The executable file is named after its directory.
% pwd /Users/jared/Projects/golang/src/fooer % go build % ls fooer fooer.go % ./fooer bar
Building a custom package results in no build artifacts.
Installing Go Code
Install Go code using the
go command-line tool’s
install command.
Programs are installed in the workspace’s
bin directory.
% pwd /Users/jared/Projects/golang/src/fooer % go install % ls ../../bin fooer
Custom packages are installed in an OS and architecture specific subdirectory in the workspace’s
pkg directory.
% pwd /Users/jared/Projects/golang/src/foo % go install % ls ../../pkg/darwin_amd64 foo.a
Add
$GOPATH/bin to your
PATH to make executing Go programs easier.
Integrating Third-Party Go Code
Integrate third-party Go code using the
go command-line tool’s
get command. Third-party code is downloaded and installed in the first workspace listed in the
GOPATH.
% pwd /Users/jared/Projects/golang/src % go get -v code.google.com/p/freetype-go/freetype code.google.com/p/freetype-go (download) code.google.com/p/freetype-go/freetype/raster code.google.com/p/freetype-go/freetype/truetype code.google.com/p/freetype-go/freetype % ls code.google.com foo fooer % ls ../pkg/darwin_amd64/ code.google.com foo.a
Moving Beyond Scripts
Every programming language has its own way of organizing code. Knowing where a language is expecting code is a must when moving beyond simple scripts.
Great post Jared, I’ve really been enjoying your series on Go! Quick question on code organization of multiple projects on the same machine:
Do you create multiple workspaces (ie, one per project) -OR- a single workspace with a single src, pkg, bin directory tree for all projects?
To put it another way, should my src directories look like this:
~/Projects/project_1/src
~/Projects/project_2/src
- OR -
~/Projects/go/src/project_1
~/Projects/go/src/project_2
The IntelliJ IDEA plugin seems to expect the former whereas golang.org seems to expect the latter.
And, imho, the former seems a much nicer way to keep things organized.
October 28, 2013 at 5:20 pm
@Ross,
There doesn’t seem to be a consensus in the Go community on single vs. multiple workspaces. The IntelliJ Go plugin creates a separate directory for each project; so it must append each directory to the GOPATH. The Go docs () mention multiple workspaces, but then
provide an example using multiple libraries, each organized in their own Git repository, in a single workspace.
The single workspace feels like how Unix stores binaries in a few places /bin or /usr/bin for example. The multiple workspace equivalent would require adding more and more custom ‘bin’ directories to your PATH; which feels a little less elegant.
I guess it comes down to personal/team preference. For a language that eliminated code formatting bikeshedding via `gofmt`, it’s disappointing there’s not a definite advantage to either way.
October 28, 2013 at 9:52 pm
Sounds like I’ll be sticking with multiple workspaces for now — despite the pain of GOPATH and package management. Thanks!
October 29, 2013 at 12:05 pm
The preferred way (according to Andrew Gerrand) seems to be using one GOPATH with all the projects in the same workspace.
Although, I prefer separate workspaces :(
October 29, 2013 at 12:27 pm
Thanks for this! It really demostrated Golang’s custom package build process in a consise and simple example.
April 16, 2014 at 12:57 pm
I’ve been putting all my GOPATH stuff in a “gorc” file. When I work on a project, I just run its gorc file. I suppose it might be a bit wonky, but I typically do all of my build/run commands from one small terminal in the corner, so I only have to run that once per project/session. I open other terminals to do all of my editing in vi.
Thanks for the article. I do wish you touched a bit on what level of related functionality *should* go in one package, but I suppose that’s a matter of taste and style, and probably leads to religious arguments. ;)
May 14, 2014 at 1:47 pm | http://pivotallabs.com/next-steps-in-go-code-organization/?tag=xp | CC-MAIN-2014-41 | refinedweb | 1,085 | 57.77 |
06 July 2011 03:54 [Source: ICIS news]
By Peh Soo Hwee
?xml:namespace>
The region’s olefins markets have been at a contango since late June, with deals for August-arrival cargoes concluded at higher prices than for July trades, they said.
Ethylene was hovering at a seven-month low of $1,100-1,130/tonne (€759-780/tonne) CFR (cost and freight) northeast (NE) Asia last week, while propylene prices were assessed at $1,400-1,420/tonne CFR NE (northeast) Asia – a level not seen in five months – over the same period, according to ICIS data.
“There are a lot of cracker shutdowns in August (please see table below), so we think that demand will be higher next month,” said a Japanese olefins trader.
Petrochemical giant Shell is expected to shut its 800,000 tonne/year mixed-feed cracker in
The company has declined to comment on its maintenance schedule.
“We are expecting Shell to purchase some propylene next month but firm discussions have yet to start,” said another Japanese olefins trader.
Meanwhile, Shell has already bought spot ethylene parcels as it plans to keep a derivative 750,000 tonne/year monoethylene glycol (MEG) plant at the same site running during the cracker shutdown, market sources said.
“The producer is likely to be in a buying mode from July to September for ethylene,” said an industry source.
Estimates from market sources place Shell’s monthly ethylene requirements at around 40,000 tonnes in the third quarter.
Consequently, ethylene deals into southeast Asia for first-half August arrival hit a high of $1,200/tonne CFR SE (southeast) Asia last week, compared with fixtures for July arrival that were heard at lower prices - under $1,150/tonne CFR SE Asia.
For propylene, some traders said they were aiming for higher price targets for August-arrival cargoes compared with July deals that were mainly done in the low-$1,400/tonne CFR NE Asia levels. Firm offers are only expected to emerge later this week.
Limited tank space in the key markets of
Meanwhile, some potential olefins buyers doubt that prices will strengthen soon, saying they would need to see stronger signs of a pick-up in polymer demand that will support higher olefins prices.
Polyethylene (PE) and polypropylene production usually peaks in the third quarter to meet Christmas orders for finished goods. But there is concern that business will be slower this year given continued weakness in the major exports markets of Europe and the
“We need to see a pick-up in derivative demand before we can start buying propylene at higher prices,” said a buyer in southeast Asia.
Asia cracker turnarounds in Aug | http://www.icis.com/Articles/2011/07/06/9474876/asia-olefins-market-may-see-price-recovery-on-tight-supply.html | CC-MAIN-2013-48 | refinedweb | 447 | 53.65 |
Python imports validation
Recently a colleague from work presented to me a nice pattern. I immediately decided to write about it. This blog post is all about this pattern! Let's get started!
This pattern is useful when working with python modules. When you import module code inside this file gets executed. All of it. This can lead to a nice way of validation. But what can you validate? For example, if given module is configured properly before starting working with it or maybe you need to tell the user that this module can be used only on Linux.
How does this pattern works? It's very simple yet effective. Imagine
that you have a module called
windows_utils:
import platform
if platform.system() != 'Windows':
raise ImportError('This module works only on Windows')
def some_function():
print("I'm doing something")
If I'm about to import function from this module I can expect this to happen:
>>> from windows_utils import some_function
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-1-1ed2a6723517> in <module>()
----> 1 from windows_utils import some_function
~/Development/personal-blog-projects/blog_python_import/windows_utils.py in <module>()
2
3 if platform.system() != 'Windows':
----> 4 raise ImportError('This module works only on Windows')
5
6
ImportError: This module works only on Windows
As you can see the side effects of such import can be useful! That's all for today! And special thanks for Maniek! | https://krzysztofzuraw.com/blog/2017/python-imports-validation/ | CC-MAIN-2022-21 | refinedweb | 232 | 59.5 |
Don't we all remember the days when we programmed C or C++? You had to use new and delete to explicitly create and remove objects. Sometimes you even had to malloc() an amount of memory. With all these constructs you had to take special care that you cleaned up afterwards, else you were leaking memory.
Now however, in the days of Java, most people aren't that concerned with memory leaks anymore. The.
I stumbled across this small program while reading JavaPedia, which clearly shows that Java is also capable of inadvertent memory leaks..
at TestGC..
public class String { // Package private constructor which shares value array for speed. String(int offset, int count, char value[]) { this.value = value; this.offset = offset; this.count = count; }); }
We see that the substring call creates a new String using the given package protected constructor. And the one liner comment immediately shows what the problem is. The character array is shared with the large string. So instead of storing very small substrings, we were storing the large string every time, but with a different offset and length.
This problem extends to other operations, like String.split() and . The problem can be easily avoided by adapting the program as follows:
public class TestGC { private String large = new String(new char[100000]); public String getSubString() { return new String(this.large.substring(0,2)); // <-- fixes leak! } public static void main(String[] args) { ArrayList
subStrings = new ArrayList (); for (int i = 0; i < 1000000; i++) { TestGC testGC = new TestGC(); subStrings.add(testGC.getSubString()); } } }
I have many times heard, and also shared this opinion that the String copy constructor is useless and causes problems with not interning Strings. But in this case, it seems to have a right of existence, as it effectively trims the character array, and keeps us from keeping a reference to the very large String.
GadgetGadget.info - Gadgets on the web » Leaking Memory in Java -
October 4, 2007 at 12:44 pm
[...] Devlib wrote an interesting post today!.Here’s a quick excerptNow however, in the days of Java, most people aren’t that concerned with memory leaks anymore. The common line of thought is that the Java Garbage Collector will take care of cleaning up behind you. This is of course totally true in all … [...]
Sherif Mansour -
October 4, 2007 at 2:04 pm
Hi There,
Thanks for the insightful article! I found this quite useful - especially in understanding why Java OutOfMemory's work...
Sherif
Jos Hirth -
October 5, 2007 at 1:30 am
Well, that's not a memory leak. See:
The behavior is intentional - it trades memory for performance. As most things in the standard library (eg collections) it's optimized for general usage and, well, generally it's alright. But you certainly shouldn't tokenize a really big string this way.
The classic type of memory leaks doesn't exist in managed languages. The only thing we can produce are so called reference leaks. That is... referencing stuff (and thus preventing em from being GCed) for longer as necessary (or for all eternity).
Fortunately it's easy to avoid - for the most part.
The important things to know:
Locally defined objects can be GCed as soon as there are no more no more references to it. Typically it's the end of the block they are defined in (if you don't store the reference anywhere). If you do store references, be sure to remove em if you don't need em anymore..
Randomly Intermittent Thoughts » A Good Reasoning to Nullify an Object! -
October 5, 2007 at 10:33 pm
[...] Jos Hirth wrote this in response to this post by Jeroen van Erp. [...]
links for 2007-10-06 - smalls blogger -
October 6, 2007 at 2:45 am
[...] Xebia Blog Leaking Memory in Java (tags: java memoryleak programming jvm) [...]
James McInosh -
October 9, 2007 at 11:07 pm
I don't know which version of the JVM you are sunning but when it constructs a new string using this constructor:
String(char value[], int offset, int count)
It sets the value using this:
this.value = Arrays.copyOfRange(value, offset, offset+count);
creyle -
October 10, 2007 at 1:48 am
To be more obvious, with the underlying big char array being referenced, all the TestGC objects created in the big for-loop could not be GCed. that's the problem.
Thanks
Jeroen van Erp -
October 10, 2007 at 8:36 am
James,
True for String(char[] value, int offset, int count), but not for String(int offset, int count, char[] value). The constructor you mention is a public constructor. The constructor that is called from the substring method is a package private constructor.
Ryan -
January 31, 2008 at 8:37 am
This is not a memory leak. As Jos Hirth said, this is trading memory for speed.
As soon as you remove the substrings from the ArrayList all the memory that has been allocated for it will be freed. No memory leak there.
Chris -
July 8, 2008 at 9:27 pm
I'm leaving this for those who google to find...
To those saying its not a memory leak, you are being very strict with the term. I, and others I know, have spent many man months of effort tracking down leaks due to this "general" use case.
Well, unfortunately, its not very general. The problem is that any substring used (or split string used) will keep the whole block. When splitting up large JMS text messages (for example) this will leave the entire message in memory, for an unspecified time.
It is a real problem that for a general algorithm you will get a leak like effect but not be warned of it in the javadocs.
User Beware.
Make Java Memory Efficient | Morteza Shahriari Nia's personal website. -
April 22, 2014 at 7:36 pm
[…] from here and […]
Pedro -
June 26, 2015 at 11:22 pm
You should try this: | http://blog.xebia.com/2007/10/04/leaking-memory-in-java/ | CC-MAIN-2015-32 | refinedweb | 987 | 64.71 |
{"name":"609511","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/8\/0\/80e245fe9794e4f0fc7edda64c2084c3.png","w":799,"h":623,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/8\/0\/80e245fe9794e4f0fc7edda64c2084c3"}
SourceResources
Windows BinaryVersion 1.1 - speedhack entry (see thread for windows compatibility code modifications)
I'll try to put the binary (Mac app) up later. For now, time to put up the white flag and get a nap in before work.
EDIT:===
Well done Onewing !Can't wait to have all SH binaries ^^
Edit:Mac Only ?
"Code is like shit - it only smells if it is not yours"Allegro Wiki, full of examples and articles !!
Mac only
For now...yes. I have a PC at home too that I'll try to get a functioning windows build, but gonna have to spend family time tonight and got a big site launch tomorrow evening, so that will have to wait a bit.
I'll wait for your build then ^^
From the screenshot, looks like you put a lot of effort into the dialog.. Look forward to a windows version when you get around to it..
it wasn't me, it was other kids
I too am waiting for a windows binary. I tried building it with CB and MinGW but it fails to compile with several warnings and an error about not being able to find the arc4random function. Also, how do you compile .m files? Are those Obj.
Yes, it's completely nonsensical but .m is an Objective-C file. No idea how that will ever be able to be ported, I thought Obj-C was an Apple-only thing.
Yeah, I haven't been coding very much past few years and when I do, I'm coding Objective-C for non-allegro projects in xcode. I've completely forgotten the make processes and how to do so.
Our site just launched, so I'm going to eat some dinner and play around with getting a windows build for you guys. Apologies for the delays!
Here's the full compile log for the *.cpp files at least :
Little progress, but I'm (obviously) going to have to get allegro 5 installed on a windows machine. My PC is not connected to the internet and is running Windows XP. I'll have better luck on my work machine which can dual boot to windows. Got to refresh up on makefiles, so that's good.
Fortunately, the only error I'm seeing from Edgar's post is regarding arc4random, which will just need the right include file most likely. The warnings don't look too concerning.
I tried compiling on clang but realized I needed to for solve Cocoa and ended up getting distracted on Facebook. #windowsbuild
--AllegroFlare • CLUBCATT • allegro.cc markdown • Allegro logo • Twitch (Offline)
FYI, the two .m files (ViewController.m and main.m) can be deleted and are not required for building. I deleted them (apparently, just the reference) from the project and never touched/saw them again, but accidentally blindly copied them into the source I uploaded.
So I've created a build. I had to make a few modifications.
I created a replacement for the arc4random() function, just using rand()
#include <time.h>
#include <stdlib.h>
int arc4random()
{
static bool initialized = false;
if (!initialized) { srand(time(0)); initialized = true; }
return rand();
}
Added the *.wav files into the resources file (the game would crash without them).
Took out the unnecessary .m files.
Compiled with -std=gnu++11
Added #include "allegro5/allegro_primitives.h" and al_init_primitives_addon() in main.cpp. The game was crashing without the addon being initialized.
Had to go hunt down chintzy.ttf on the internet, and put it in the root folder. The font rendering appears different than in your screenshot, I'm not sure what the cause of this is. A result is that the fonts are quite a bit more difficult to read. It's possible that I grabbed an older version of chintzy.ttf that doesn't render as well.{"name":"609560","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/3\/e\/3e9951383b82d2eed478b3d5b645e0f1.png","w":838,"h":662,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/3\/e\/3e9951383b82d2eed478b3d5b645e0f1"}
I did my make like this
CPP_FILES := $(wildcard *.cpp)
OBJ_FILES := $(addprefix obj/,$(notdir $(CPP_FILES:.cpp=.o)))
main.exe: $(OBJ_FILES)
g++ -o $@ $^ -LE:/allegro-5.1.11-mingw-edgar/lib -lallegro_monolith-debug.dll
obj/%.o: %.cpp
g++ -std=gnu++11 -c -o $@ $< -IE:/allegro-5.1.11-mingw-edgar/include
I haven't played the game through, yet, but I'm assuming it will work to the end. Here's the binary (including the DLLs).
Elders of Ethos - Win32
And here's the revised source and makefile I used:
EoE - revised source
Got it compiled, and after 1 false start, I managed to win it. That was pretty fun! By the way, you're missing the font (I had to substitute it with a different font without issue).
This is another game that could have used the backspace key .
"For in much wisdom is much grief: and he that increases knowledge increases sorrow."-Ecclesiastes 1:18[SiegeLord's Abode][Codes]:[DAllegro5]:[RustAllegro]
It's possible that I grabbed an older version of chintzy.ttf that doesn't render as well.
Sure enough
I downloaded the chintzy.ttf font from another website and it was a newer verion. It renders much more nicely now.{"name":"609561","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/2\/4\/24642286653b61209b05da0a93ac2482.png","w":842,"h":662,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/2\/4\/24642286653b61209b05da0a93ac2482"}I've updated the downloads to include the new font.
Oates, your first download link gives a 404 not found error. The second source link works though.
I'll have to try this now. The screenshots look very 90s-retro (that's a good thing). Like a Wolfenstein 3D-era DOS game.
Oates, your first download link gives a 404 not found error. The second source link works though.
Yikes! Sorry about that. Fixed now. Here's that link again:
Elders of Ethos - Win32
This is another game that could have used the backspace key .
Yes!
That aside it was a nice polished entry. A bit monotone but it's not crashing and the ambiance is cool :-)
Thanks Mark for the Windows build ;-)
Mark: On the subject of arc4random, I don't think your implementation is strictly correct
int arc4random()
{
srand(time(0));
return rand();
}
Reason (from cppreference)
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
I think it actually doesn't matter here because the time between each of the user's entries is going to be random anyway.Since we're in C++11, might as well use <random>:
#include <random>
#include <stdint.h>
static std::uniform_int_distribution<uint32_t> uni;
static std::default_random_engine engine;
uint32_t arc4random() {
return uni(engine);
}
Onewing: I've got a Linux makefile if you want.
Cheers,Pete
Mark: On the subject of arc4random, I don't think your implementation is strictly correct
You are correct, it isn't. I wasn't in the business of creating the ideal PRNG, just make a random number generator and make it work. My implementation of arc4random() doesn't meet the specification of the original arc4random() (return uint32_t for example), but it does adequately meet the requirements of its use case in the game.
but it does adequately meet the requirements of its use case in the game.
Well, yes and no. On my Linux it makes the particles go all in a line - and maybe affects the gameplay too, I couldn't tell.{"name":"609564","src":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/2\/5\/258550c9e7f0d5b59382a8404ea08a63.jpg","w":1600,"h":1200,"tn":"\/\/djungxnpq2nug.cloudfront.net\/image\/cache\/2\/5\/258550c9e7f0d5b59382a8404ea08a63"}
Interesting.
Spent 20 minutes getting 10 from purity to the top. Had some weird shit going on with meditation requiring every follower to rest at one point before stabilising and moving them back to other disciplines. Good speedhack entry, well done.
Aha! I see the definition of arc4random you gave in your spoiler isn't the same as I found in your source zip file; with the addition of the if (!initialized) bit, yes, I agree, it should work perfectly fine!Cheers,pete | https://www.allegro.cc/forums/thread/615499/1014393 | CC-MAIN-2022-33 | refinedweb | 1,392 | 67.35 |
java.iopackage. While this package is designed with ease of use in mind, developers new to the platform often make mistakes that can lead to poor I/O performance. Fortunately, a better understanding of this package can lead to major improvements in I/O performance.
Section 4.1 provides a brief overview of the
java.io package, identifies the most common cause of poor I/O performance, and describes several different approaches to solving this problem. Section 4.2 focuses on object serialization, a key part of many of the newest features in the Java platform.
java.iopackage:
InputStreamand
OutputStream. These interfaces define the key abstractions for I/O operations. Concrete implementations of
InputStreamand
OutputStreamprovide access to different types of data sources such as disks and network connections.
The
java.io package also provides several filter streams that don't point to a specific data source and are meant to be stacked on top of other streams. These filter streams are at the heart of the
java.io architecture. From a performance perspective, the most interesting filter streams are buffered streams. Figure 4-1 shows a simplified class hierarchy that includes the buffered streams.
Simplified
java.ioclass hierarchy
By default, most of the streams provided in the Java libraries write one byte of data at a time. Instead of putting buffering behavior into each individual stream type, the buffering behavior is implemented in dedicated
BufferedInputStream and
BufferedOutputStream classes. This is very different from C, where the basic
stdio operations are buffered by default. To better understand the effects of buffering streams, look at Listing 4-1. This example copies a file from one location to another.
public static void copy(String from, String to) throws IOException{ InputStream in = null; OutputStream out = null; try { in = new FileInputStream(from); out = new FileOutputStream(to); while (true) { int data = in.read(); if (data == -1) { break; } out.write(data); } in.close(); out.close(); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Simple file copy
Copying with basic streams
The
copy method opens a
FileInputStream and a
FileOutputStream and copies the contents of one directly into the other. Since the
read and
write methods work on individual bytes, this means an actual disk read and write occurs for each byte copied. Figure 4-2 illustrates how the data moves from one file to the other.
When the code in Listing 4-1 is run on our test configuration to copy a 370K JPEG test image, it takes almost 11 seconds to execute. Listing 4-2 shows a slightly modified version of the same code that uses buffered streams to improve performance. This code stacks buffered streams on top of the bare file streams. The buffered streams save up read and write requests and then execute them all at once-usually batching several thousand tiny requests into one larger request. When the code in Listing 4-2 is used to copy the same JPEG test file, it executes in a mere 130 milliseconds-almost 100 times faster!
public static void copy(String from, String to) throws IOException{ InputStream in = null; OutputStream out = null; try { InputStream inFile = new FileInputStream(from); in = new BufferedInputStream(inFile); OutputStream outFile = new FileOutputStream(to); out = new BufferedOutputStream(outFile); while (true) { int data = in.read(); if (data == -1) { break; } out.write(data); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Faster file copy
Figure 4-3 shows how the data flows from one file to another when you're using buffers. Although using buffered streams is much faster than using bare file streams, you can see from Figure 4-3 that the buffers add a level of indirection. This does add some overhead and in some cases it's possible to improve performance by implementing a custom buffering scheme.
Copying with buffered streams
whileloop isn't as fast as you'd like it to be. Because the JVM enforces bounds checking, there is a good deal of overhead associated with such operations. When you're using buffered streams as shown in Listing 4-2, you essentially end up copying a lot of data from one array to another-several times, in fact. A large number of method calls are also made, many of them
synchronized, with arguments that are passed and copied on the stack. Much of this overhead can be avoided, while still taking advantage of the fact that hard disks are good at reading and writing large chunks of data.
Listing 4-3 shows the
copy method rewritten to use a custom buffering scheme. This block of code takes advantage of the fact that the
read and
write methods in
InputStream and
OutputStream are overloaded to work with
byte arrays as well as individual bytes.
These methods allow you to work with large chunks of data, instead of just single bytes. In Listing 4-3 the code creates its own buffer, in the form of aThese methods allow you to work with large chunks of data, instead of just single bytes. In Listing 4-3 the code creates its own buffer, in the form of apublic int read(); public int read(byte[] bytes); public void write(); public void write(byte[] bytes);
byte[],which it then uses to map the entire file into memory with a single
readcall. It then uses just one call to the
writemethod to create the newly copied file.
public static void copy(String from, String to) throws IOException{ InputStream in = null; OutputStream out = null; try { in = new FileInputStream(from); out = new FileOutputStream(to); int length = in.available(); // danger! byte[] bytes = new byte[length]; in.read(bytes); out.write(bytes); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Custom buffered copy
This code is very fast. Where the previous buffered stream version took about 130 milliseconds to copy the JPEG test file, using the single
read and
write operations reduces the time to about 33 milliseconds.
Note that there are two trade-offs to consider when using this strategy. First, this code creates a buffer the size of the original source file. If this code is used to copy large files, the buffer can get very large (perhaps larger than your available RAM). Second, this code creates a new buffer for each copy operation. If this code is used to copy a large number of files, the JVM has to allocate and collect many of these potentially large buffers. This is going to hurt performance.
It is possible to create a version of the custom buffered
copy that avoids these two pitfalls and is even faster. To do this, you create a single,
static buffer and then read or write blocks the size of that buffer. This results in more than one read or write operation for files larger than the buffer, but the cost is offset by the fact that a fresh buffer doesn't have to be allocated for each file that is copied. (The costs of such allocations are discussed further in Chapter 7, Object Mutability: Strings and Other Things.) The size of the buffer is known and can be optimized to achieve the best trade-off between speed and memory-use for each particular situation.
Listing 4-4 shows the code for the improved custom buffered
copy function. In this version, a static 100K buffer is used for the copy operation. For copying the same JPEG test file, this implementation is even faster than the one in Listing 4-3. This is because a new buffer doesn't have to be allocated for every copy.
static final int BUFF_SIZE = 100000; static final byte[] buffer = new byte[BUFF_SIZE]; public static void copy(String from, String to) throws IOException{ InputStream in = null; OutputStream out = null; try { in = new FileInputStream(from); out = new FileOutputStream(to); while (true) { synchronized (buffer) { int amountRead = in.read(buffer); if (amountRead == -1) { break; } out.write(buffer, 0, amountRead); } } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
Improved custom buffered copy
One key item to note in Listing 4-4 is the
synchronized block. In a single threaded environment, this code will work fine without the
synchronized block. However, if you want to use this code in a multithreaded environment, you need to synchronize the buffer to prevent multiple threads from trying to write to it simultaneously. Although there are costs associated with synchronization, there is almost no performance impact because the number of iterations through the
while loop is small. In our tests, both synchronized and unsynchronized versions of this code took the same amount of time to copy the test file.
Table 4-1 shows the approximate copy times for the different copy tactics. While the results from such micro-benchmarks don't show the whole performance picture, they provide a rough idea of how the different options compare.
For example, consider an FTP or HTTP server. The primary job of such a server is to copy files from a disk to a network socket. Although a server might have access to thousands of files, a small fraction of these files typically represent the majority of the files served. A web site's main homepage is probably served much more often than other pages in the site. To improve performance, you could implement your server so that the most commonly accessed files are mapped into cached
byte[] structures. That way, those files don't need to be read from disk each time; they can be copied directly from memory to the network socket.
java.iopackage provides classes that support object serialization.
One of the best features of serialization is that it is almost completely automatic. It takes very little work to use serialization to make your objects persistent-in general, all you need to do is implement the
Serializable interface.
The outward simplicity of the serialization API hides its internal complexity. The internal machinery that enables transparent object serialization is very complex and can be quite costly at runtime. Fortunately, there are tactics you can use to mitigate these costs.
Serializableinterface is actually purely a tagging interface-it doesn't define any methods.
Serializableis simply used to indicate that the class is designed to be serialized. Listing 4-5 shows a simple class that implements the
Serializableinterface.
public class TestObject implements Serializable { private int value; private String name; private Date timeStamp; private JPanel panel; public TestObject(int value) { this.value = value; name = new String("Object:" + value); timeStamp = new Date(); panel = new JPanel(); panel.add(new JTextField()); panel.add(new JButton("Help")); panel.add(new JLabel("This is a text label")); } }
Simple serializable class
Because this class implements the
Serializable interface and the instance variables are serializable, any instance of this class can be written to an
ObjectOutputStream. Listing 4-6 shows a code fragment that creates 50 instances of the
TestObject class and writes them to an
ObjectOutputStream.
for (int i =0;i <50; i++) { vector.addElement(new TestObject(i)); } Stopwatch timer = new Stopwatch().start(); try { OutputStream file = new FileOutputStream("Out.test"); OutputStream buffer = new BufferedOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(vector); out.close(); } catch (Exception e) { e.printStackTrace(); } timer.stop(); System.out.println("elapsed = " + timer.getElapsedTime());
Writing objects to a stream
Once you've streamed these objects to disk, you can re-create them using an
ObjectInputStream. Listing 4-7 shows a code fragment that loads objects from a file.
Stopwatch timer = new Stopwatch().start(); try { InputStream file = new FileInputStream("Out.test"); InputStream buffer = new BufferedInputStream(file); ObjectInputStream in = new ObjectInputStream(buffer); vector = (Vector)in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } timer.stop(); System.out.println("elapsed = " + timer.getElapsedTime());
Reading objects from a stream
When the file created by writing a
Vector that contains 50 of these test objects is written to disk, the resulting file occupies about 91K. That's almost 2K per instance of the class. That seems like a lot, considering the entire source file that defines the class takes up only about 500 bytes. Clearly, there is a lot of stuff being written into these files. This stems from the fact that serialization is a recursive process. When a single object is serialized, the
ObjectOutputStream examines all the object's fields (even the private ones) and writes them out. If the fields contain other objects, those are also written out, and so on.
In the
TestObject example, all of the Swing UI widgets and any objects they reference are written out along with the
TestObject. Even fields set to the same value that is set by the class's default constructor are written out, because serialization has no knowledge of the default values for fields.
transientkeyword. This keyword allows you to specify values that are noncritical, or that can be reconstructed manually after the object is read into memory.
Listing 4-8 shows a new version of the
TestObject class that uses the
transient keyword to specify that two of the four fields defined by the class should not to be written out by the
ObjectOutputStream. It also defines a
private method called
readObject. The
ObjectInputStream class looks for a method with this signature (using machinery from within the JVM) and automatically calls this method while reading the object in, even though it is
private. This hook can be used to reinitialize transient state in your object after it has been reconstructed from a stream. In this example, the user interface panel and the name are reinitialized after the class is read in. This dramatically improves performance for both reading and writing.
public class TestObjectTrans implements Serializable { private int value; private transient String name; private Date timeStamp; private transient JPanel panel; public TestObjectTrans(int value) { this.value = value; timeStamp = new Date(); initTransients(); } public void initTransients() { name = new String("Object:" + value); panel = new JPanel(); panel.add(new JTextField()); panel.add(new JButton("Help")); panel.add(new JLabel("This is a text label")); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); initTransients(); } }
Improved serializable object
Table 4-2 shows a comparison between the
TestObject implementation and the modified version that uses the
transient keyword to prevent selected fields from being written out.
As you can see, using the
transient keyword drastically improves the performance of serializing these objects:
In the example in Listing 4-8, streaming out a simple object causes several Swing user interface components to be streamed out as well. While this example might seem artificial, it's actually a simplified version of a problem encountered by a group of developers who were working on a server program.
When the server process needed to be terminated, the program serialized a set of important objects and streamed them to a file. When the server was restarted, this enabled it to re-create these objects and begin running in the same state where it left off. The problem was that it took more than 30 minutes to stream these objects to disk, which was clearly unacceptable. When the developers analyzed the required persistent state of their objects, they found many things were being streamed that didn't need to be. In fact, because of the recursive nature of serialization, almost the entire object heap was being streamed to disk. Careful use of the
transient keyword drastically reduced the time it took to write out their data. | http://java.sun.com/docs/books/performance/1st_edition/html/JPIOPerformance.fm.html | crawl-002 | refinedweb | 2,546 | 54.32 |
C# Custom LinkedList Derived Classes, Constructor Initializations - Learning C# - Part 2
To allow our derived class to inherit from our Inventory class, after defining the LinkedList class, we add a colon and the name of the base class "Inventory." Upon typing the word "Inventory" from the keyboard, type "Ctrl" + "." -- this key combination opens up a drop down asking you to "Implement abstract class Inventory." Select that option and your class is created with the base class overrideable methods, in this case "Category."
public class LinkedList : Inventory { public override string Category() { throw new NotImplementedException(); } }
We define a private string inventoryCategory, to hold our assigned values. When we need to retrieve these values, we use the Category method. On your own, do some research on using Get/Set Properties instead of methods.
public class LinkedList : Inventory { // custom linked list private string inventoryCategory; public override string Category() { return inventoryCategory; } // self-referencing members (same name as its class) private LinkedList Head; // pointer to the top of the stack // the last node added to the list private LinkedList Next; // index to locate an item in the list private int size; // how many records in the list public LinkedList() // constructor / default values { Head = null; // no items have been added Next = null; inventoryCategory = string.Empty; size = 0; // 1 based - list starts out as empty }
We create two self-referencing members, meaning the type is the same name as their class: "private LinkedList Head" and "private LinkedList Next". The first points to the most recent node added to the list or the top of the stack. The second points to the next node on the list that was just previously added so that we can traverse through the list. Once we traverse to the next node, it again has its own Next node, to point to the previous node, and so forth.
The "private int size" statement defines an integer used to keep track of how many records are in the list.
Next we define our constructor: "public LinkedList()." "Constructors: are class methods that are executed when an object of a class or struct is created. They have the same name as the class or struct, and usually initialize the data members of the new object."
True to our definition, we initialize the Head and Next to null. We set our inventoryCategory to empty using "string.Empty." We could have just as easily set our inventoryCategory to empty by assigning it a value of "" (2 quote marks).
We set our size to 0. Our list will be 1 based and increment to 1 when the first node is added.
In Part 3 of our series, we will define our Push and Pop methods.
-] | https://weblogs.asp.net/nannettethacker/c-custom-linkedlist-derived-classes-constructor-initializations-learning-c-part-2 | CC-MAIN-2018-43 | refinedweb | 445 | 59.64 |
the problem is explained in the comments part in the top of the code between /* and */ , I will really apreciate any kind of help about this please.
Code:/************************************************************* Write a program that uses for structures to print the following patters separately, one bellow the other. Use for loops to generate the patters separately. All asterisks (*) should be printed by a single statement of the form cout << '*'; ( this causes the asterisks to print side by side). [Hint: The last two patterns require that each line begin with an apropiate number of blanks. * ** *** **** ***** ****** ******* ******** ********* ********** ************************************************************/ #include <iostream> #include <cstdlib> #include <cstdio> using namespace std; int main() { // wait until user is ready before terminating program // to allow the user to see the program results system("PAUSE"); return 0; } | http://cboard.cprogramming.com/cplusplus-programming/57266-need-help-please-homework-problem.html | CC-MAIN-2015-22 | refinedweb | 123 | 59.33 |
Jesus M. Gonzalez-Barahona wrote: > However, I'm a bit concerned with users of cil being surprised to find > that "cil" is a different thing... Anybody sees this as a problem? Is > there anything about this in Policy? (I looked for it, but didn't found > anything relevant). Well, assuming users upgrade woody->sarge->etch without skipping sarge, they'll not have a cil package once the sarge upgrade is done (assuming they don't just keep the old one from woody, but that's what the replaces/conflicts is for). However, I'd think it's better to not reuse the name. For example, users running a mixed sarge/etch system with cl-cil from sarge will not be able to install cil. This, and other concerns about namespace pollution (which really is the issue here), could make it preferable to use the cinterlang name. Cheers T. -- Thomas Viehmann, <>
Attachment:
pgpc_jKQmiDgM.pgp
Description: PGP signature | https://lists.debian.org/debian-devel/2004/08/msg01049.html | CC-MAIN-2020-10 | refinedweb | 156 | 73.98 |
Hi, i'm trying to understand the Inheritance machine in 100%. Can u help mi with that ?
I have an error in my code."No enclosing instance of type Inheritance is accessible. Must qualify the allocation with an enclosing instance of type
Inheritance (e.g. x.new A() where x is an instance of Inheritance)."
I done the same with more complex classes and everything was ok, but here is something wrong.
Code:class Inheritance { public static void main(String[] args){ new B().sum(); // here it is (error) } public class A{ int i=1, j=0; void showij(){ System.out.println("i= " + i); System.out.println("j= " + j); } } public class B extends A{ int k; void showk(){ System.out.println("k= " + k); } public void sum(){ System.out.println("i+j+k= " + (i+j+k)); } } } | http://forums.devshed.com/java-help-9/inheritance-953332.html | CC-MAIN-2017-17 | refinedweb | 134 | 53.78 |
Have an account?
Need an account?Create an account
This document describes the features, caveats, and limitations of Cisco NX-OS Release 9.2(1) software for use on the following switches:
■ Cisco Nexus 9000 Series
■ Cisco Nexus 3264C-E).-R,.2(1)
■ New Software Features in Cisco NX-OS Release 9.2(1)
Cisco NX-OS Release 9.2(1) supports the following new hardware:
■ The Cisco Nexus 3264C-E (N3K-C3264C-E) is a 2 rack unit (RU) switch with 64 100-Gigabit QSFP28 and 2 10-Gigabit SFP+ ports. This switch supports both port-side exhaust and port-side intake airflow schemes. The switch requires one power supply for operation, but it can have a second power supply for redundancy.
■ The Cisco Nexus 9504-FM-R (N9K-C9504-FM-R) is a 100-Gigabit -R fabric module (for the Cisco Nexus 9504 chassis) that supports the 100-Gigabit (-R) line cards. When used, there must be 4 of these fabric modules installed in fabric slots 22, 23, 24, and 26.
■ The Cisco Nexus 9508-FM-E2 (N9K-C9508-FM-E2) is a 100-Gigabit –E2 fabric module (for the Cisco Nexus 9508 chassis) that supports the 100-Gigabit (-EX, -FX) line cards. When used, there must be 4 of these fabric modules installed in fabric slots 22, 23, 24, and 26.
■ The Cisco Nexus 9516-FM-E2 (N9K-C9516-FX-E2) is a 100-Gb –E2 fabric module (for the Cisco Nexus 9516 chassis that supports the 100-Gb (-EX, -FX) line cards. When used, there must be four of these fabric modules installed in fabric slots 22, 23, 24, and 26.
■ The Cisco Nexus 96136YC-R line card (N9K-X96136YC-R) with 52-port 16x1/10-Gigabit, 32x10/25 Gigabit Ethernet SPF, and 4x40/100-Gigabit Ethernet QSFP.
■ The Cisco Nexus 9732C-FX line card (N9K-X9732C-FX) with 32 100-Gigabit QSFP28 ports.
Cisco NX-OS Release 9.2(1) supports the following new software features:
■ Bypass and Drop Mode—Provides the ability to skip a Cisco Nexus device in your configured chain without changing the topology or existing configuration.
■ Failsafe—Allows users the option to add a default VLAN group, port group and chain for an instance, and generate the backend configuration accordingly.
■ Reverse Configuration—Introduces a CLI solution to define the egress interface in the reverse direction for each segment of the chain based on port number or IP address.
For more information, see the Cisco Nexus 9000 Series NX-OS Catena Configuration Guide, Release 9.2(x).
FCoE Features
■ FC Uplinks—Support added for Cisco Nexus 9348GC-FXP, 93108TC-FX and 93180YC-FX switches.
■ Host Pinning—All hosts on a FEX are pinned to the same NP link for the Cisco Nexus 93180YC-FX switch.
For more information, see the Cisco Nexus 2000 Series NX-OS Fabric Extender Configuration Guide for Cisco Nexus 9000 Series Switches, Release 9.2(x).
FEX Features
■ FCoE over FEX—Support added on N9K-C93180YC-FX switches in both straight-through and dual-homed mode with N2K-C2348UPQ, N2K-C2232PP, N2K-B22IBM-P and N2K-B22HP-P FEX models. Support added on Cisco Nexus 9300-FX platform switches.
■ NetFlow for FEX Layer-3 Ports—Support added on Cisco Nexus 9300-EX and 9300-FX platform switches.
■ ST-FEX and AA-FEX Modes—Support added on Cisco Nexus 93108TC-FX and Cisco Nexus 93180YC-FX switches.
■ ST-FEX Mode—Support added on Cisco Nexus 9336C-FX2 and Cisco Nexus 93240YC-FX2 switches.
For more information, see the Cisco Nexus 2000 Series NX-OS Fabric Extender Configuration Guide for Cisco Nexus 9000 Series Switches, Release 9.2(x).
■ Scale Monitoring—Provides the ability to verify, detect, and predict your environment against Cisco verified scale numbers.
■ Platform Support—Added support for Cisco Nexus 3164Q, 9300, and 9500 platform switches.
For more information, see the Cisco Nexus 9000 Series NX-OS iCAM Configuration Guide, Release 9.2(x).
Intelligent Traffic Director (ITD) Features
■ ITD—Support added for the Cisco Nexus C9364C, C9336C-FX2, C93240YC-FX2 switches (for IPv4 & IPv6).
For more information, see the Cisco Nexus 9000 Series NX-OS Intelligent Traffic Director Guide, Release 9.2(x).
Interface Features
■ Auto Negotiation for 25G—Support added for auto negotiation on native 25G ports on Cisco Nexus N9K-X97160YC-EX, N9K-C93180YC-FX, N9K-C93240YC-FX2 and N9K-C93240YC-FX2-Z switches.
■ BFD Multihop—Support added for Cisco Nexus 9300-EX, 9300-FX, 9300-FX2, 9300-FXP, 9500-EX, and 9500-FX platform switches in compliance with RFC5883 for IPv4. IPv6 is not supported.
■ GTP load-sharing—Added support for Cisco Nexus 9364C, 93180YC-FX, 93108TC-FX, and 9348GC-FXP switches.
■ IP Dampening—Support added for IP event dampening on Cisco Nexus 9300-EX, 9300-FX, 9300-FX2, 9300-FXP, 9500-EX, and 9500-FX platform switches.
■ IP TCP MSS—Support added for IP TCP MSS. The IP TCP Maximum Segment Size (MSS) feature enables a switch to set a maximum segment size for all TCP connections that originate from or terminate at a Cisco Nexus 9000 Series Switches.
■ Optics Scale—Support added for the Cisco Nexus 9508 switch with N9K-X96136YC-R line cards support 1 Gb speed on all 48 ports.
■ QSFP-40/100-SRBD (also known as QSFP-100G40G-BIDI) comes up in the speed of 100-G and interoperates with other QSFP-40/100-SRBD at either 100-G or 40-G speed and with QSFP-40G-SR-BD at 40-G speed on Cisco Nexus 9500 platform switches with N9K-X9636C-RX line card. See transceiver compatibility documents for both 40-G and 100-G for future module support additions.
■ TCP Aware NAT—Beginning with Cisco NX-OS Release 9.2(1) support is now added for TCP-aware NAT. It enables NAT flow entries to follow the state of TCP sessions and get created and deleted accordingly.
For more information, see the Cisco Nexus 9000 Series NX-OS Interfaces Configuration Guide, Release 9.2(x).
IP SLAs Features
■ TWAMP Responder—Support added for IP SLA TWAMP responder on a Cisco device measuring IP performance between the Cisco device and a non-Cisco TWAMP control device.
For more information, see the Cisco Nexus 9000 Series NX-OS IP SLAs Configuration Guide, Release 9.2(x).
Label Switching Features
■ The following features have been added:
o Segment routing with traffic engineering (on-demand next hop) with XTC integration
o Segment routing with OSPFv2 SID (Prefix/Node SID only for /32 FEC)
o IS-IS distribute link-state
o Layer 3 EVPN and Layer 3 VPN Stitching/interworking. Supported on Cisco Nexus 9300, 9300-FX and 9500 platform switches with 9700-FX line cards.
o Improved MPLS label scale and MPLS ECMP adjacency
■ The following features are supported on the Cisco Nexus 9364C switch:
o Segment routing with BGP LU and IS-IS (Node SID/Prefix SID)
o Layer 3 EVPN over segment routing
o Egress peer engineering
o MPLS label stack imposition
o MPLS OAM
For more information, see the Cisco Nexus 9000 Series NX-OS Label Switching Configuration Guide, Release 9.2(x).
Layer 2 Features
■ VEPA/Reflective Relay—Support added for switching option reflective relay on the Cisco Nexus 93180TC-FX and 93180YC-FX switches.
For more information, see the Cisco Nexus 9000 Series NX-OS Layer 2 Switching Configuration Guide, Release 9.2(x).
Multicast Routing Features
■ Multicast Network Load Balancing (NLB)—Support added for the ability to distribute client requests across a set of servers. This feature is supported on the Cisco Nexus 9300-EX, 9300-FX, 9300-FX2 platform switches. This feature is not supported on Cisco Nexus 9500 platform switches with 9508-FM-2 or 9516-FM-E2 line cards.
■ MVR knob—Support added to disable forwarding IGMP queries.
For more information, see the Cisco Nexus 9000 Series NX-OS Multicast Routing Configuration Guide, Release 9.2(x).
N9000V Features
■ Software Upgrade as Disruptive ISSU—Added support configuring disruptive ISSU process.
■ VXLAN EVPN Multi-Site—Added support for configuring VXLAN EVPN Multi-Site on Cisco Nexus 9000v switches.
For more information, see the Cisco Nexus 9000v Guide.
NX-API Features
■ NX-API REST Data Paths—See the New and Changed Information section of the Cisco Nexus 3000 and 9000 Series NX-API REST User Guide and API Reference for a detailed list of the updates.
■ Expanded Support for NX-API CLI— See the Cisco Nexus 3500 Series NX-API CLI Reference for examples of show commands supported for NX-API CLI.
■ Expanded Support for NX-API CLI—See the Cisco Nexus 9000 Series NX-API CLI Reference, Release 9.x for examples of show commands supported for NX-API CLI.
■ Cisco NX-OS Release 9.2(1) supports the following commands for NX-API:
o show bfd addrmap [application <appid> discriminator <discr> address-type <addrtype> address <addr>]\
■ The NX-API feature is enabled by default on HTTPS port 443 and HTTP port 80 is disabled.
For more information, see the Cisco Nexus 9000 Series NX-API CLI Reference.
OpenConfig YANG Feature
■ OpenConfig YANG—Support added for the OpenConfig YANG data modeling language. See the Cisco Nexus OpenConfig YANG Reference for examples of configuring and retrieving state data.
Programmability Features
■ Ansible 2.5—Support is added for Ansible 2.5.
■ Docker Containers—Support added for using Docker within the Cisco NX-OS on a switch.
■ gRPC—Support added for gRPC chunking as a part of telemetry.
■ Guest Shell—Guest Shell is running in a separate namespace, which allows the host system to be even better protected from activities within the Guest Shell. The user and the group ID mapping done for the user namespace may require more attention to the file permission settings while sharing files (on bootflash) between the host system and the guest shell.
■ Hardware Telemetry—Support added for hardware telemetry where the Streaming Statistics Export (SSX) module reads statistics from the ASIC.
■ Puppet—Support added for EVPN Multi-Site types and Tenant Routed Multicast types.
■ Streaming Telemetry—Support added for streaming telemetry to IPv6 destinations.
■ Streaming of YANG—Support added for the streaming of YANG models as part of telemetry. Both device YANG and the open-config YANG model are supported.
For more information, see the Cisco Nexus 9000 Series NX-OS Programmability Guide, Release 9.2(x).
■ 802.1x—Support added to multiple authentication, dynamic VLAN, and MAB authentication.
■ MACsec—Support added for the Cisco Nexus 93180YC-FX and 93108TC-FX switches.
■ SSH—Added support for ECDSA, added the show rekey command and the ability to change the default SSHv2 port.
■ Unicast RPF— Support added for Cisco Nexus 9300-EX platform switches (for IPv4 only) and on Cisco Nexus 9300-FX/FX2 platform switches (for IPv4 and IPv6).
For more information, see the Cisco Nexus 9000 Series Security Configuration Guide, Release 9.2(x).
Smart Channel Features
■ Smart Channel—Support added for the Cisco Nexus 93018TC-EX switch.
For more information, see the Cisco Nexus 9000 Series NX-OS Smart Channel Configuration Guide, Release 9.2(x).
Software Upgrade/Downgrade Features
■ Optionality: Added support for modular package management. Cisco NX-OS software now provides the flexibility to add, remove, and upgrade features selectively without changing the base Cisco NX-OS software.
■ vPC topology: Added the upgrade and downgrade procedure for switches in a vPC topology.
For more information, see the Cisco Nexus 9000 Series NX-OS Upgrade and Downgrade Guide, Release 9.2(x)
System Management Features
■ IEEE DCBXP TLV—Support added for IEEE 802.1Qaz mode type-length-values (TLVs) on Cisco Nexus 9000 Series switches.
■ LLDP—Introduced the show qos dcbxp interface command.
■ MIBs—SNMP MIB support has been added for the following:
o cseTcamUsageTable in CISCO-SWITCH-ENGINE-MIB
o cefcFanTable in CISCO-ENTITY-FRU-CONTROL-MIB
o cmnMacMoveNotification in CISCO-MAC-NOTIFICATION-MIB
■ SNMP—Enhanced CISCO-ENTITY-EXT-MIB to support ceExtNVRAMSizeOverflow, ceExtHCNVRAMSize, ceExtNVRAMUsedOverflow, and ceExtHCNVRAMUsed.
■ System Message Logging—Added support to send syslog messages to remote logging servers over a secure TLS transport connection.
For more information, see the Cisco Nexus 9000 Series NX-OS System Management Configuration Guide, Release 9.2(x).
■ Weighted ECMP—Added support for Cisco Nexus 9332PQ, 9396PX, and 9396TX switches.
For more information, see the Cisco Nexus 9000 Series NX-OS Unicast Routing Configuration Guide, Release 9.2(x).
VXLAN Features
■ PIM BiDir—Support added for VXLAN underlay with and without vPC support.
■ Private VLANs with VXLAN— Support added for configuring a vn-segment to a PVLAN.
■ Proportional Multipath for VNF—Enables advertising of all the available next hops to a given network destination.
■ Sampled Flow Export—Support added for Sampled Flow (sFlow) export over VXLAN.
■ TRM with vPC—Supports multicast forwarding between sender/receiver in L3-cloud and send/receive in a VXLAN fabric.
■ VXLAN CLI Simplification—Support added for the reduction of CLI commands.
■ VXLAN Cross Connect—Support for point-to-point tunneling of data and control packets from one VTEP to another.
■ VXLAN Multi-Site with vPC—Support added for border gateways to allow local connectivity of endpoints and the enablement of bridging and routing functions for those endpoints on the border gateways.
■ VXLAN EVPN with vPC—Support added for the Cisco Nexus 9508 with 9636C-RX and 96136YC-R line cards.
For more information, see the Cisco Nexus 9000 Series NX-OS VXLAN Configuration Guide, Release 9.2(x)
This section includes the following topics:
■ Resolved Caveats—Cisco NX-OS Release 9.2(1)
■ Open Caveats—Cisco NX-OS Release 9.2(1)
■ Known Behaviors—Cisco NX-OS Release 9.2(1)
The following table lists the Resolved Caveats in Cisco NX-OS Release 9.2(1). Click the bug ID to access the Bug Search tool and see additional information about the bug.
Table 13 Resolved Caveats in Cisco NX-OS Release 9.2(1)
The following table lists the open caveats in the Cisco NX-OS Release 9.2(1). Click the bug ID to access the Bug Search tool and see additional information about the bug.
Table 14 Open Caveats in Cisco NX-OS Release 9.2(1)
The following known behaviors are in this release.
■ The output format for the exec command CLI show vpc orphan-ports has changed from the 7.0(3)F3(4) release to the 9.2(1) release.
■ Release 9.2.2(1):
Note: Enhanced ISSU to Cisco NX-OS Release 9.2(1) results in a disruptive upgrade. If syncing images to standby SUP failed during the disruptive upgrade from Cisco NX-OS Releases 7.0(3)I4(8), 7.0(3)I5(3,) or 7.0(3)I6(1) to 9.2(1), you should manually copy the image to the standby SUP and perform the disruptive upgrade.
■ When upgrading to Cisco NX-OS Release to 9.2.2.2(1) using the install all command, BIOS will not be upgraded due to CSCve24965. When the upgrade to Cisco NX-OS Release 9.2(1) is complete, use the install all command again to complete the BIOS upgrade, if applicable.
■ An upgrade performed via the install all command for Cisco NX-OS Release 7.0(3)I2(2b) to Release 9.2.2.2.2.2.2.2.)
For additional information, see the Cisco NX-OS ISSU Support application.
The following are the upgrade paths from previous 7.0(3)F3(x) releases:
■ Release 7.0(3)F3(3) -> Release 7.0(3)F3(4) -> Release 9.2(1)
■ Release 7.0(3)F3(3c) -> Release 9.2(1)
■ Release 7.0(3)F3(4) -> Release 9.2(1).2.2(1) to an earlier release.
■ Performing an ISSU downgrade from Cisco NX-OS Release 9.2, Release 9.2(x)..2(1).64C, N9K-C9336C-FX2. This change is made as of cisco NX-OS Release 7.0(3)I7(3). If your PID is not listed, please contact Cisco TAC for additional verification.
■ Support for NetFlow is not available on FM-E based chassis. Autonegotiation (40 G/100 G) and 1 Gb with QSA is not supported on the following ports:
o Cisco Nexus 9336C-FX2 switch: ports 1-6 and 33-36
o Cisco Nexus 9364C switch: ports 49-66
o Cisco Nexus 93240YC-FX2 switch: ports 51-54
o Cisco Nexus 9788TC line card: ports 49-52
NOTE: Peer speed must be set when using coper cables on these ports.
■ We recommend using multicast heavy template for optimal bandwidth utilization when using multicast traffic flows.
■ IPv6 multicast is not supported on Cisco Nexus 9500 platform switches.
■ Multicast heavy template is recommended for optimal bandwidth utilization when using multicast traffic flows. 9.2(1). The ports on uplink modules should be used only for uplinks.
■ PortLoopback and BootupPortLoopback tests are not supported.
■ PFC (Priority Flow Control) and LLFC (Link-Level Flow Control) are supported for all Cisco Nexus 9300 and 9500 platform switches except for the 100 speed 1000–Auto negotiates and advertises pause (advertises only for 1000 Mbps full duplex).
■ Eight QoS groups are supported only on modular platforms with the Cisco Nexus 9300 N9K-M4PC-CFP2 uplink module, and the following Cisco Nexus 9500 Routed ACL (Access Control List) is applied to multiple SVIs in the egress direction
■ Cisco Nexus 9000 Series switch hardware does not support range checks (layer 4 operators) in egress TCAM. Because of this, ACL/QoS policies with layer 4 operations-based classification need to be expanded to multiple entries in the egress TCAM. Egress TCAM space planning should take this limitation into account.
■ Applying the same QoS policy and ACL on multiple interfaces requires applying the qos-policy with the no-stats option to share the label.
■ Multiple port VLAN mappings configured on an interface during a rollback operation causes the rollback feature to fail.
■ The following switches support QSFP+ with the QSFP to SFP/SFP+ adapter (40 Gb to 10 G.2(1) is available at the following URL.
The Cisco Nexus 9000 Series NX-OS Verified Scalability Guide, Release 9.2.2(1) | https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus9000/sw/92x/release/notes/921_9000_nxos_rn.html | CC-MAIN-2019-43 | refinedweb | 3,001 | 56.25 |
Red Hat Bugzilla – Bug 437706
F-9 pv_ops xen: graphical nstall doesn't work - rhplx videocard probing doesn't find pvfb
Last modified: 2013-01-21 15:20:27 EST
Description of problem:
When trying to install rawhide as a PVM the VNC window comes up but remains
empty (black). This is probably due to xenfb not being in rawhides initrd.
Version-Release number of selected component (if applicable):
How reproducible:
Consistent
Steps to Reproduce:
1. Try in install rawhide as a Xen PVM. Example cmd line provided in bug 437217.
Actual results:
Black VNC screen.
Expected results:
Text install options followed by the anaconda graphical installer within the VNC
window.
Additional info:
The host is an up-to-date F8 with minor modifications to OSDistro.py to avoid
bug 437217.
GUI install of guest F8 works fine, as does text install of rawhide.
So the last screen of tty 4 gives me:
*******************
<6>Floppy drive(s): fd0 is unknown type 15 (usb?) ....
<3>IRQ handler type mismatch for IRQ 6
<3> current handler: vkbd
<4>Pid: 468, comm: modprobe Not tainted 2.5.25-0.2.rc4.fc9xen #1
... a stack trace - I can reproduce for you if you want ...
<4>floppy: Unable to grab IRQ6 for the floppy driver
<6>BIOS EDD facility ....
<6>EDD information ont available.
<6>input: PC Speaker ....
<6>squashfs: version ....
<5>iscsi: registered transport (tcp)
<6>NET: Registered protocol family 10
<6>lo: Disabled Privacy Extensions
<6>Initialising Xen virtual etherenet driver.
<6> xvda: xvda1 xvda2
<4>modprobe used greatest stack depth: 2312 bytes left
********************
And tty3 gives me:
********************
[time omitted] INFO : kernel command line:
method=
[time omitted] INFO : anaconda version 11.4.0.52 on i386 starting
[time omitted] INFO : text mode forced due to serial/virtpconsole
[time omitted] INFO : 508004 kB are available
FATAL: Error inserting floppy
(/lib/modules/2.6.25-0.2.rc4.fc9xen/kernel/drivers/block/floppy.ko): Device or
resource busy
**********************
Shame of shames, it is going to text mode then failing - but I don't want text
mode. Hopefully this is a good bit more helpful than "black screen" :-).
The fb driver should probably continue to be built-in rather than built as a module
The fb driver is built in currently
Markus: could you take a look?
i'm seeing the same problem running RHEL5.2 beta (w/ latest packages) trying to
install rawhide
As far as I can see, both vfb and vkbd initialize just fine, and displays a
blank screen (as the reporter wrote). Looks like pvfb works, but guest user
space doesn't use it.
If I complete the text install and reboot into the newly installed system, pvfb
works. Same kernel, isn't it?
Also note this line from comment#1:
[time omitted] INFO : text mode forced due to serial/virtpconsole
This seems to suggest that anaconda forces a text install. Why does it do that?
Aha, that line is the key. This is just the second part of bug 434763 (but
going to leave it separate for now)
It looks like what's going on is that the kernel is setting up hvc0 as the
console rather than the framebuffer. And so when we do auto-console detection
in anaconda, we find that there's hvc0 and that the kernel has set it up as the
console. If you have the framebuffer set up, then it needs to be the console as
far as the kernel is concerned. This is what some of the original pain involved
in the xenfb code was all about.
Back to kernel-xen for now
*** This bug has been marked as a duplicate of 434763 ***
Whoops, did not mean to close
So, the logic we're talking about here is:
--
static struct termios orig_cmode;
struct termios cmode, mode;
int cfd;
cfd = open("/dev/console", O_RDONLY);
tcgetattr(cfd,&orig_cmode);
close(cfd);
cmode = orig_cmode;
cmode.c_lflag &= (~ECHO);
cfd = open("/dev/console", O_WRONLY);
tcsetattr(cfd,TCSANOW,&cmode);
close(cfd);
...
char * consoles[] = { "/dev/xvc0", "/dev/hvc0", NULL };
...
for (i = 0; consoles[i] != NULL; i++) {
if ((fd = open(consoles[i], O_RDWR)) >= 0 && !tcgetattr(fd, &mode) &&
!termcmp(&cmode, &mode)) {
printf("anaconda installer init version %s using %s as console\n",
VERSION, consoles[i]);
isSerial = 3;
console = strdup(consoles[i]);
break;
}
close(fd);
}
cfd = open("/dev/console", O_WRONLY);
tcsetattr(cfd,TCSANOW,&orig_cmode);
close(cfd);
...
if (isSerial == 3) {
*argvp++ = "--virtpconsole";
*argvp++ = console;
}
--
i.e. we only force --virtpconsole if /dev/hvc0 is what underlies /dev/console
and pvfb is what *should* underly /dev/console
Right. This was the root of a log of the register_console/unregister_console
stuff in the early pvfb patches.
I believe the culprit is
linux-2.6-xen-0004-xen-Make-hvc0-the-preferred-console-in-domU.patch
We put that in to make the Xen console just work. It sets the default
preferred console to hvc0. But with PVFB compiled in, we want the
preferred console to be PVFB, i.e. tty0. It is when I take out that
patch in an upstream kernel. I haven't tried with an f9 kernel, or an
actual install.
Yes, we only want hvc0 to be the primary console, when the guest is not
configured to use PVFB in xenstore. eg, so 'virt-install --nographics' gets
anaconda text mode sent to hvc0, while 'virt-install --vnc' gets anaconda
graphical mode to pvfb.
Consoles tty, hvc and ttyS register in this order.
The framebuffer isn't up yet then, and tty is still the dummy console.
Unless the kernel command line dictates otherwise, the first one to
register becomes *the* console (the one behind /dev/console). This is
tty. Except we patched things so that hvc wins over tty in dom0.
We want to use tty if we have PVFB, else hvc.
If we have PVFB, xenfb_probe() gets to run. But by the time that
happens, the console game's over.
I'll dig some more.
Err, wins over tty in *domU*.
Right. Some of the various ppc and ia64 platforms where this matters can check
the firmware info early in the boot sequence to see if they should change their
preferred to the serial-ish console. The problem with having xen domU do so is
that it required xenstore which can't be accessed early.
I've dropped "prefer hvc0" patch again in kernel-xen-2.6-2.6.25-0.12.rc7.git6.fc9
bug #437761 should track getting hvc0 to be preferred if there's no pvfb
Okay, now with kernel-xen-2.6-2.6.25-0.12.rc7.git6.fc9 I'm seeing:
INFO: No video hardware found, assuming headless
ajax -- how did you want to handle fbdev devices in rhpxl now?
rhplx seems to be filtering on pci.device_class, which pvfb doesn't have:
class VideoCardInfo:
def __init__ (self, forceDriver = None):
...
pdevs = [x for x in pdevs if x.GetPropertyInteger('pci.device_class') == 3]
lshal shows the following for pvfb:
udi = '/org/freedesktop/Hal/devices/xen_vfb_0'
info.linux.driver = 'vfb' (string)
info.parent = '/org/freedesktop/Hal/devices/computer' (string)
info.product = 'Xen Device (vfb)' (string)
info.subsystem = 'xen' (string)
info.udi = '/org/freedesktop/Hal/devices/xen_vfb_0' (string)
linux.hotplug_type = 2 (0x2) (int)
linux.subsystem = 'xen' (string)
linux.sysfs_path = '/sys/devices/vfb-0' (string)
xen.bus_id = 'vfb-0' (string)
xen.path = 'device/vfb/0' (string)
xen.type = 'vfb' (string)
Just seems like the xen support got lost when moving from probing with kudzu,
which used to do:
snprintf(path,64,"/sys/class/graphics/fb%d/name",i);
name = __readString(path);
if (!name)
break;
if (!strcmp(name, "xen")) {
xendev = xenNewDevice(NULL);
xendev->desc = strdup("Xen Virtual Framebuffer");
xendev->type = CLASS_VIDEO;
xendev->driver = strdup("xenfb");
xendev->classprivate = (void *)strdup("fbdev");
if (devlist)
xendev->next = devlist;
devlist = (struct device *) xendev;
}
Moving to rhpxl
Fix for this (I hope) built as rhpxl 1.4. Please test, and reopen if this isn't
resolved.
Thanks, seems to be working fine now with the 2008-04-10 install tree
(i.e. rhpxl-1.7-1.fc9) | https://bugzilla.redhat.com/show_bug.cgi?id=437706 | CC-MAIN-2018-05 | refinedweb | 1,331 | 66.54 |
Interview: JFugue Goes Hip Hop
Pretend they own your code java.dzone.com
For those who don't know, JFugue is a Java API that makes programming music as easy as writing one or two lines of code, such as the following:
Player player = new Player();
player.play("C D E F G A B");
After a successful session last year, Dave will again present some cool and fun JFugue API stuff tomorrow, in a technical session at 16.10 in room 303, as well as in a BOF later in the day. Below, he talks about some of the lesser known but very cool features of the API, that you'll see in action if you go to his session.
Dave, you're back at JavaOne with JFugue. Let's not beat around the bush and get down to some brass tacks right away. Show us something really cool!
OK. We'll look at some real code, three examples, which result in the Midi files that you can download via a ZIP file by clicking here. So, let's first look at a lesser used feature of the JFugue API, not quite as popular as most of the others, but still very cool. It allows you to create a rhythm by just banging keys on your keyboard, which is what the block of code below illustrates:
rhythm.setLayer(1, "O..oO...O..oOO..");
rhythm.setLayer(2, "..*...*...*...*.");
rhythm.setLayer(3, "^^^^^^^^^^^^^^^^");
rhythm.setLayer(4, "...............!");
With JFugue API, you can map keys to instruments. For example, the letter "o" could be a bass drum, the asterisk could be a snare drum, the exclamation mark something else, and so on. Look at the 16-beat rhythm code below and see how easily this mapping can be done:
public static void beat16()
{
Rhythm rhythm = new Rhythm();
// Each MusicString should have a total duration of an eighth note
rhythm.addSubstitution('O', "[BASS_DRUM]i");
rhythm.addSubstitution('o', "Rs [BASS_DRUM]s");
rhythm.addSubstitution('*', "[ACOUSTIC_SNARE]i");
rhythm.addSubstitution('^', "[PEDAL_HI_HAT]s Rs");
rhythm.addSubstitution('!', "[CRASH_CYMBAL_1]s Rs");
rhythm.addSubstitution('.', "Ri");
rhythm.setLayer(1, "O..oO...O..oOO..");
rhythm.setLayer(2, "..*...*...*...*.");
rhythm.setLayer(3, "^^^^^^^^^^^^^^^^");
rhythm.setLayer(4, "...............!");
Pattern pattern = rhythm.getPattern();
pattern.repeat(4);
Player player = new Player();
player.play(pattern);
try {
player.saveMidi(pattern, new File("beat16.mid"));
} catch (IOException e)
{
e.printStackTrace();
}
}
This is really cool. Why is it a lesser known feature that is not really used?
It is probably less known because, from my understanding of how the API is used, banging a keyboard is not a typical way of making music. To use this approach, people need to break with their mental model of sheet music and, instead, expand their thinking into new ways of how music is made. However, the result looks a lot like a beatbox. People are used to that concept, but here it's a little bit cooler than a beatbox because once you get a "JFugue pattern" (more on this below) you can manipulate it in unique and interesting ways.
So how does this really work under the hood, i.e., how do you map keystrokes to instruments?
A hashmap is created that maps the letters to the instruments. Then long strings are created that simply use those substitutions. The strings are JFugue music strings that the JFugue parser can interpret to make Midi events. In fact, this is one of the first features requested by a member of the JFugue community.
Since when has this "keyboard banging" feature been part of the API?
It's been in there since JFugue 3.0.
And now version 4.0 has come out, just in time for JavaOne. What does this release give me?
Several new features, in fact. For example, JFugue API now supports chord inversions and tuplets, both of which were requested by members of the user community. This latest release integrates a Michael Good's Music XML format, which was a contribution from a member of the user community, called E. Phil Sobolik. And there have been improvements in the way patterns in the API can be manipulated.
For those of us who don't know, what is a JFugue pattern?
A pattern is a snippet of music that can be reused and recombined. For example, a lot of the music we listen to today has repeating segments of music. JFugue alllows you to specify a repeating segment of music once and then reuse that pattern.
So, what's new with patterns in this latest release?
One cool feature of JFugue is that you can read existing Midi files into a pattern and then you can transform that pattern to make new music (provided you have legal rights to that music in the first place, of course!). The new version of JFugue improves the way in which patterns can be transformed. Specifically, I improved the interface.
As an example, what we are going to do below is take some music from an existing music file (again, assuming we have permission to change it), then we do some simple cleaning up of the Midi, after which we invert the pattern around a note. Next, we reverse the pattern and change the interval of the notes in the pattern. Then, we reverse the pattern again and add it to itself. Finally, we have a new piece of music, a fugue, which uses this pattern and plays it on top of itself with different instruments.
All the code below is compilable, i.e., you can simply copy and paste it into your own application, put the latest JFugue API JAR on the classpath, and then simply run it. Make sure to replace "mymusic.mid" in line 112 in the code below with the name and location of a file that you have access to:
import java.io.File;
import java.io.IOException;
import javax.sound.midi.InvalidMidiDataException;
import org.jfugue.Instrument;
import org.jfugue.MusicStringParser;
import org.jfugue.Note;
import org.jfugue.Pattern;
import org.jfugue.PatternTransformer;
import org.jfugue.Player;
import org.jfugue.extras.DurationPatternTransformer;
import org.jfugue.extras.GetPatternForVoiceTool;
import org.jfugue.extras.IntervalPatternTransformer;
import org.jfugue.extras.ReversePatternTransformer;
public class RemixMidi {
private Player player;
private File file;
public RemixMidi(File file) {
this.player = new Player();
this.file = file;
}
/** Loads a MIDI file, and converts the MIDI into a JFugue Pattern. */
public Pattern getPattern() {
Pattern pattern = null;
try {
pattern = player.loadMidi(file);
} catch (InvalidMidiDataException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return pattern;
}
/**
* Using the GetPatternForVoiceTool, isolate a single voice (or channel) of the
* Pattern and return it.
*/
public Pattern getPatternForVoice(Pattern pattern, int voice) {
GetPatternForVoiceTool tool = new GetPatternForVoiceTool(voice);
MusicStringParser parser = new MusicStringParser();
parser.addParserListener(tool);
parser.parse(pattern);
Pattern voicePattern = tool.getPattern();
return voicePattern;
}
/** Plays a Pattern - this is a pass-through method to JFugue's Player */
public void play(Pattern pattern) {
player.play(pattern);
}
/**
* Using the InvertPatternTransformer, invert the given pattern.
*/
public Pattern invertPattern(Pattern pattern) {
InvertPatternTransformer ipt = new InvertPatternTransformer(MusicStringParser.getNote("C5"));
Pattern invertPattern = ipt.transform(pattern);
return invertPattern;
}
/**
* Using the ReversePatternTransformer, reverse the given pattern.
* "C D E" becomes "E D C"
*/
public Pattern reversePattern(Pattern pattern) {
ReversePatternTransformer rpt = new ReversePatternTransformer();
Pattern reversePattern = rpt.transform(pattern);
return reversePattern;
}
/**
* Causes the duration of each note in the Pattern to be lengthened
* by the provided factor.
*/
public Pattern stretchPattern(Pattern pattern, double stretch) {
DurationPatternTransformer dpt = new DurationPatternTransformer(stretch);
Pattern stretchedPattern = dpt.transform(pattern);
return stretchedPattern;
}
/**
* Changes the note values of each note in the Pattern - this causes
* the entire Pattern to be played with higher or lower pitches.
*/
public Pattern changeInterval(Pattern pattern, int delta) {
IntervalPatternTransformer it = new IntervalPatternTransformer(delta);
Pattern intervalPattern = it.transform(pattern);
return intervalPattern;
}
public Pattern cleanInstrument(Pattern pattern) {
PatternTransformer t = new PatternTransformer() {
@Override
public void instrumentEvent(Instrument instrument) {
// Do nothing
}
};
Pattern cleanedPattern = t.transform(pattern);
return cleanedPattern;
}
private static void remixBach() {
RemixMidi mix = new RemixMidi(new File("mymusic.mid"));
Pattern pattern = mix.getPattern();
System.out.println("From midi: " + pattern);
Pattern voicePattern = mix.getPatternForVoice(pattern, 0);
Pattern cleanInstrumentPattern = mix.cleanInstrument(voicePattern);
Pattern invertedPattern = mix.invertPattern(cleanInstrumentPattern);
System.out.println("After inversion: " + invertedPattern);
Pattern reversedPattern = mix.reversePattern(invertedPattern);
System.out.println("After reversal: " + reversedPattern);
// mix.play(reversedPattern);
// reversedPattern = mix.stretchPattern(reversedPattern, 0.3);
reversedPattern = mix.changeInterval(reversedPattern, +16);
// mix.play(reversedPattern);
System.out.println(reversedPattern);
// Add pattern to itself, reversed again
Pattern reversedAgain = mix.reversePattern(reversedPattern);
reversedPattern.add(reversedAgain);
// Repeat it
reversedPattern.repeat(4);
Pattern fugue = new Pattern();
fugue.add("V0 I[Piano]");
fugue.add(reversedPattern);
fugue.add("V1 I[Synth_strings_1] R/0.637353");
fugue.add(mix.changeInterval(reversedPattern, -12));
fugue.add("V2 I[Blown_Bottle] R/0.637353 R/0.566652");
fugue.add(mix.changeInterval(reversedPattern, -17));
System.out.println(fugue);
mix.play(fugue);
try {
fugue.savePattern(new File("fugue.jfugue"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
remixBach();
}
}
//***Sample PatternTransformer***
class InvertPatternTransformer extends PatternTransformer {
private byte fulcrumNoteValue;
public InvertPatternTransformer(Note note) {
this.fulcrumNoteValue = note.getValue();
}
/** Transforms the given note */
@Override
public void noteEvent(Note note) {
doNoteEvent(note);
}
/** Transforms the given note */
@Override
public void sequentialNoteEvent(Note note) {
doNoteEvent(note);
}
/** Transforms the given note */
@Override
public void parallelNoteEvent(Note note) {
doNoteEvent(note);
}
private void doNoteEvent(Note note) {
byte noteValue = note.getValue();
if (noteValue > fulcrumNoteValue) {
note.setValue((byte) (fulcrumNoteValue - (noteValue - fulcrumNoteValue)));
getReturnPattern().addElement(note);
} else if (noteValue < fulcrumNoteValue) {
note.setValue((byte) (fulcrumNoteValue - (fulcrumNoteValue - noteValue)));
getReturnPattern().addElement(note);
} else {
// No change in note value
getReturnPattern().addElement(note);
}
}
}
So, what in this code is new?
In the code above, nothing. But it's just a cool feature that could be used more often in the context of people experimenting with this API to craft new music. However, in the next snippet, we do introduce something new. Recall the rhythm API that we opened the interview with. Well, in the new version of JFugue, you can mix music notes with your rhythms to create riffs, as you might hear, for example, in hip hop. In this code sample, we are banging on our computer keyboard, as before, but we're also using JFugue's new interval notation to specify notes that can be played along with the rhythm. We can then get a specific instance of this rhythm for a particular bass note, which causes actual notes to be created based on those intervals.
public static void hiphopBeat()
{
Rhythm rhythm = new Rhythm();
// Each MusicString should have a total duration of an eighth note
rhythm.addSubstitution('j', "<1>s Rs");
rhythm.addSubstitution('k', "<6>s Rs");
rhythm.addSubstitution('l', "<8>s Rs");
rhythm.addSubstitution('m', "<9>s Rs");
rhythm.addSubstitution('n', "<4>s Rs");
rhythm.addSubstitution('o', "[BASS_DRUM]i");
rhythm.addSubstitution('*', "[HAND_CLAP]s Rs");
rhythm.addSubstitution('%', "[TAMBOURINE]s Rs");
rhythm.addSubstitution('.', "Ri");
rhythm.setLayer(3, "o...o...o...o...o...o...o...o...");
rhythm.setLayer(4, "..*...*...*...*...*...*...*...*.");
rhythm.setLayer(5, "...%...%...%...%...%...%...%...%");
rhythm.setVoice(1, "jjnnjjmlnnllnnlkjjnnjjmlkkklnnnk");
rhythm.setVoiceDetails(1, "I[CHOIR_AAHS]");
Pattern pattern = rhythm.getPatternWithInterval("Bb4");
pattern.insert("T95");
Player player = new Player();
player.play(pattern);
try {
player.saveMidi(pattern, new File("hiphopBb4.mid"));
} catch (IOException e)
{
e.printStackTrace();
}
}
Here we're banging the keyboard, but in the new part we can set up some non-percusive instruments to play along with that beat. Then we can get a pattern with a bass note, in this case, B flat with a 4th octave. And then, finally, we can save the freshly minted Midi file.
Thanks Dave and good luck with your session and BOF!
- Login or register to post comments
- 1046 reads
- Flag as offensive
- Printer-friendly version
cfagan replied on Thu, 2008/05/08 - 5:41pm
@Dave WOW this is really cool. The keyboard mapping, can that be done at runtime? So that I hit space and get a [BASS_DRUM]i sound. If so how hard do you think it would be to map to game controller buttons instead of keyboard buttons? I ask because I have Rock Band and it has a USB drum set. I think it would be fun to map the drum pads to sounds.
dmkoelle replied on Fri, 2008/05/09 - 4:09am
@cfagan - Yes, you can indeed to this at runtime. You can create a StreamingPlayer, then implement a KeyListener that calls streamingPlayer.stream("[BASS_DRUM]i") whenever the space bar is pressed.
Game controllers probably wouldn't be much more difficult. Look at the JInput project () for details on how to read game controllers. Incidentally, I'd love to see something where one could create music with a Wii. "Symphony Hero", perhaps?
cfagan replied on Fri, 2008/05/09 - 7:02am
in response to: dmkoelle | http://java.dzone.com/news/interview-jfugue-goes-hip-hop | crawl-001 | refinedweb | 2,074 | 51.85 |
The.
I have researched the list of packages that needed a recompilation, and in some cases I performed an upgrade at the same time (qt5 went up to 5.9.3, poppler synced to the 0.62.0 in Slackware-current, qtav went up to 1.12.0). The 64bit packages have already been uploaded but if you are running 32bit Slackware-current (why are you doing that?) you’ll have to wait another day because I just started the compilation there.
What has been updated in the ‘ktown’ repository? Here is a list, mostly in order of compilation:
deps:qt5,qt5-webkit,phonon,qtav,poppler kde4:kdelibs,akonadi4,kdepimlibs4 frameworks:kfilemetadata5 kdepim:EVERYTHING plasma:plasma5-nm applications:okular applications-extra:calligra,digikam,kile
Every package in kdepim? Well yeah, there were many broken packages and it was simply faster to recompile all of kdepim and be done with it.
Users of slackpkg+ will be up & running fast with these updates; the others probably just need to download the individual packages I listed above from a mirror like.
When the 32bit package set has been finished The 32bit packages have now been recompiled and uploaded to the repository.
I will also recompile whatever is needed in the ‘testing’ repository (that’s where the Wayland related packages are stored).
Other – not related to Plasma5 – updates/rebuilds
are coming soon have finally been uploaded too. Those are LibreOffice, Pale Moon, Calibre; these programs are also affected by the updates in slackware-current but the urgency was lower than with the Plasma5 desktop.
Thank you Eric! Will download right away!
Thank you, Eric. You’re a god (- send). 🙂
Thanks for the quick work, Eric! I’ve upgraded the packages and rebooted, but KDE still won’t start. I even reinstalled the entire ktown repo just in case, but no dice. Is it just that not everything has been uploaded yet, or is there something else I need to do?
Thank you Eric!
There is one issue I have come across so far. I use the run command and krunner segfaults:
Application: krunner (krunner), signal: Segmentation fault
Using host libthread_db library “/lib64/libthread_db.so.1”.
[Current thread is 1 (Thread 0x7f7df24e67c0 (LWP 11622))]
Hi Eric! Now everything runs fine… except Krunner. I have the same issue than Radical Dreamer.
The trace from Dr.Konqui is here:
Thanks!!
Eduardo
Sorry, one more thing I’ve run into so I am reporting it. All are just minor issues for me.
kmix: kmix
Unable to load library icui18n “Cannot load library icui18n: (icui18n: cannot open shared object file: No such file or directory)”
kmix –failsafe works though 😉
Actually – disregard my earlier message, I figured out what I did wrong. I had the alienbob repository set to have higher priority than ktown, which meant qt5 and qt5-webkit were kept at older versions. I just changed the priority in slackpkgplus.conf and now I’m up and running 🙂
I am having the same issue with krunner as Eduardo and Radical Dreamer.
sddm.bin wont fire for me, complaining about “libicui18n.so.56” being missing. The default slackware-current repo seem to have upgraded “icu4c-60.1-x86_64-1” to that version. I ran a upgrade using slackpkgplus. These are all my packages that are installed right now.
Hakan:
> qt5-5.9.2-x86_64-1alien
> qt5-webkit-5.9.1-x86_64-1alien
Check the priorities in your slackpkgplus.conf file. You seem to have set the ktown priority lower than the slackbuilds repository (just like chris mentioned above) and as a result, your qt5 and qt5-webkit packages were not upgraded.
Hi Eric, after the latest upgrade all seems to work well, but libreoffice don’t work. He spit out the same message regarding ‘missing libraries libicui18n.so.56’. And the tray icon of dropbox is disappeared
Alienbob:
Yea you are right. I had two things wrong. I had set the tag priority to \”on\” and I also had the wrong PKGS_PRIORITY. This fixed it for me.
PKGS_PRIORITY=( ktown alienbob slackpkgplus )
# TAG_PRIORITY=off
Thanks for your quick update on the packages. 🙂
I might have spoken too soon on krunner – it seems to be working fine now. It segfaulted the first time I logged in to Plasma, but after rebooting the problem went away.
After I reported the issue to Eric on Krunner, it worked without isues at the second boot so I was going to say something similar to what Chris posted. But then, on the third boot and the fourth, and the fifth, it displayed the same bug again. Odd.
Thank you very much.
I have found some not found libraries in deps/telepathy and kde/telepathy packages.
There is libicui18n.so.56 not found in /usr/bin/jsc-1 (this is in openjdk ?)
Indeed there’s some issues with the Telepathy packages but I am not sure if I will have time to deal with those, they are low on my priority list now.
The “jsc-1” binary is not on my system so perhaps it is part of Oracle’s binary JDK package.
@alienbob
Finally I found that jsc-1 is in webkitgtk (another package to recompile)
Helios – OK, not a package I need to fix then if t came from SBo 😉
I have uploaded new packages for Pale Moon and Calibre, and rebuilt my Libre Office packages for -current. There’s still at least mkvtoolix that does not work but that will come later.
Does the Calibre need PyQt5? When I try and run ebook-viewer from calibre-3.13.0-x86_64-1alien I get:
Traceback (most recent call last):
File “/usr/bin/ebook-viewer”, line 20, in
sys.exit(ebook_viewer())
File “/usr/lib64/calibre/calibre/gui_launch.py”, line 81, in ebook_viewer
from calibre.gui2.viewer.main import main
File “/usr/lib64/calibre/calibre/gui2/viewer/main.py”, line 28, in
from calibre.gui2.viewer.ui import Main as MainWindow
File “/usr/lib64/calibre/calibre/gui2/viewer/ui.py”, line 11, in
from PyQt5.Qt import (
ImportError: cannot import name QWebView
both qt5-5.9.3-x86_64-1alien and qt5-webkit-5.9.1-x86_64-2alien are installed.
hi Eric,
I believe kdepimlibs4 needs recompiled too, because of libical
Interesting LoneStar, I did recompile kdepimlibs4 already, I wonder why it still shows a dependency against libical? I even had to apply a patch to get it to compile against libical3.
Note that “ldd” will also show *indirect* dependencies, i.e. a library which kdepimlibs4 links against, still has a libical2 dependency, The trick is finding out which library.
Brad Reed did you use my package or did you compile the package from source, yourself?
My package works fine here, and yes, PyQt5 is required. A private copy of it is included in my package because I compile mine with “BUILD_PYTHON=YES”.
@Eric
I found that kdepimlibs4 had not been updated by slackpkg. I did a reinstall and now it’s ok. Maybe package kept build number 4 like the previous version while it should be bumped to build 5?
I’m also finding that I still have a kde-workspace-4.11.22 which is no longer present in current ktown binaries, but there still is source for it in the source part. Going back to previous posts and READMEs I didn’t find an instruction about removing it like it’s done for other packages that got dropped or replaced.
my bad, I found you posted something about removing it, in a previous ktown announcement. I suggest to add a line about it in READMEs too.
Confirmed. For me the Krunner bug persists.
LoneStar, that was exactly the issue with kdepimlibs4. The new package had the same BUILD number so the pkgtools/slackpkg would not upgrade it.
I will fix that in the repository.
LoneStar I have updated the README at the appropriate place:
Thanks for mentioning it again, because in that old blog article’s comments section I had promised to update the README and I forgot.
Eduardo, initially i wanted to answer that I was unable to get krunner to crash here, but then suddenly it did crash.
I have not touched the plasma-workspace (which contains krunner) nor kwindowsystem (which contains the plugin that is mentioned on standard output when krunner starts crashing).
Thank you Eric for this. I will await any news on the matter.
Thank you. With this update now works everything
Pingback: Links 9/12/2017: Mesa 17.3, Wine 3.0 RC1, New Debian Builds | Techrights
Strange, I can’t build it from your slackbuild either. The build ends with:
*
* Running build
*
Traceback (most recent call last):
File “setup.py”, line 119, in
sys.exit(main())
File “setup.py”, line 104, in main
command.run_all(opts)
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/__init__.py”, line 236, in run_all
self.run_cmd(self, opts)
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/__init__.py”, line 228, in run_cmd
self.run_cmd(scmd, opts)
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/__init__.py”, line 232, in run_cmd
cmd.run(opts)
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/build.py”, line 245, in run
self.env = init_env()
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/build.py”, line 140, in init_env
from setup.build_environment import msvc, is64bit, win_inc, win_lib, NMAKE
File “/tmp/build/tmp-calibre/calibre-3.13.0/setup/build_environment.py”, line 84, in
from PyQt5.QtCore import PYQT_CONFIGURATION
ImportError: No module named PyQt5.QtCore
Brad I assume you don’t have PyQt5 installed.
The SlackBuild script will not compile its own python or any python modules if you have python 2.7 installed… but you can get around that by running the following command which will force the inclusion of an internal python interpreter plus the required python modules. Your only external dependencies left will be podofo, unrar, libxkbcommon, qt5 and qt5-webkit:
# BUILD_QT=NO BUILD_PYTHON=YES BUILD_MTP=YES ./calibre.SlackBuild
Alternatlvely you can of course install all the required python modules as external dependencies separately.
Well, I purged everything, resynced to current, reinstalled qt5-5.9.3-x86_64-1alien and qt5-webkit-5.9.1-x86_64-2alien
and now your build of calibre is working for me. I still can’t build it though. Wonder what is up with my system.
Regarding krunner crash: it seems to happen in
/usr/lib64/qt5/plugins/plasma_runner_marble.so according to the backtrace.
As a workaround I removed the marble package (which was not recompiled during the mass recompilation) and krunner works again.
Hope this helps.
Excellent! I uninstalled marble and krunner seems to work again! Thanks!
I have rebuilt the marble package and uploaded it. My krunner is not crashing here now. YMMV.
Why does httpd link to both libicu 56 and libicu 60?
Geremia if you used “ldd” to determine that, be aware that ldd will also show you the “indirect” dependencies, i.e. dependencies of any library that httpd links against directly.
So, it will probably not be httpd that is at fault but some custom extension you compiled in the past.
I didn’t know that about ldd.
thanks
Geremia, if you only want to list the *direct* dependencies of a binary, try the ‘readelf’ command instead. For instance, use:
readelf -d $(which httpd) |grep ‘(NEEDED)’
and play around with the output.
Hi, Eric
I have a very strange problem after all these updates. I keep an instance of pidgin running in the system tray and if I plug in a usb stick with LUKS encrypted partition on it, and try to unlock it by clicking on the systray icon (solid) – no password dialogue comes up, and what is more strange – the pidgin icon dissapears from the systray. The LUKS partition cannot be unlocked and mounted and if I run pidgin again , it shows up but cannot dock into the system tray.
When in xfce4, the unlocking and mounting of the LUKS partition works all right.
Could this mean that solid should be recompiled or it is something else? Does anybody else has a problem like this?
Pidgin can attach to systray again if I log out/log in plasma.
I’m with Slackware current 64bit + Multilib + Ktown. Everithing elase is working as it should (As far as I can tell).
toodr, try looking at the X session log files to see if any of these applications is writing errors.
toodr, I have a problem that is similar to yours. After plugging in a USB stick with a LUKS encrypted partition, if I try to mount it using the device notifier in the system tray, only the spinner starts showing, but no password prompt appears. Also, my custom shortcuts stop working but things like Alt+Tab still work. The custom shortcuts start working again if I just open the Custom Shortcuts configuration page in the System Settings, without making any changes. This seems to restart some services, as it is accompanied by a pop-up notification about the WiFi connection being active, and occasionally also by a notification that kded5 or kdeinit5 closed unexpectedly. After all that, the spinner in the device notifier is still going, but the password prompt still doesn’t appear.
This issue started for me only with the rebuilt KDE 5_17.11 for the latest Slackware-current; I had no problems with the earlier 5_17.11 packages (19 Nov).
Eric, what are the X session log files to check for errors? When attempting to mount the drive, I don’t see anything that is written to /var/log/Xorg.0.log or to ~/.xsession-errors.
This is the only obvious error.
Initializing “kcm_access” : “kcminit_access”
kdeinit5: Got EXEC_NEW ‘/usr/bin/kaccess’ from launcher.
………………………………………………………..
kf5.kded: Could not load kded module “kded_accounts”:”Could not load library /usr/lib64/qt5/plugins/kded_accounts.so: (libicui18n.so.56: could not open file: No such file or directory)” (library path was:”kded_accounts”)
By the way, this behaviour also happens if one tries to unlock any of the KDE Vaults. Without any LUKS partition.
And now I noticed that other icons disapear from the system tray as well. KOrganizer icon, for instance. Just as a result of trying to mount a Vault.
I think, it’s ‘libaccounts-qt5’ who need rebuild 😉
libaccounts-qt5-1.15 stable is available:
This is not an immediate emergency for me.
LUKS and Vaults can be mounted from command line. And there is a new release of KDE soon so maybe these issues will be solved anyway by a new compile of Eric’s.
To Jeff: Thanks for the suggestion for restarting the services without logging out. This really works. And sddm keeps a log file in user’s directory at ~/.local/share/sddm/xorg-session.log
I’ve posted similar posts in the past, but Chromium 63 have been out for a while, and theres been important fixes.
Mikei, yes I know. But the year-end is kind of a busy time, wrapping up all the work for the holidays and handing over tasks to the people that stay in the office.
The family comes first, paid work comes next, the hobbies come last.
There are still parts of KDE that would need a rebuild, for example the Telepathy parts.
Anyway new releases of Framework and Applications are out already and in the meanwhile a temporary fix can be grabbing the icu4c 56.1 package from Slackware 14.2 and copying the library files somewhere in ldconfig path.
Generally I prefer /usr/local/lib64 for such things.
Hi Eric,
It looks like the latest plasma5-nm package (plasma5-nm-5.11.3-x86_64-2alien.txt) was compiled without openconnect as it is missing the .so file and the 2 .desktop files.
I have recompiled the package myself and it created the files fine, however, even with the files installed, it still doesn’t work.
the applet prepares to connect but the dialogue box asking for credentials never shows up and it eventually gives up.
I am not sure where to look to see what the applet does and where it fails. I can connect to the VPN fine using the openconnect command directly.
I haven’t tried recompiling your networkmanager-openconnect package in case the new networkmanager package changed something so that will be my next step.
ArTourter let me know about the progress.
There will not be further recompilations – when I have the time I will compile the newest Frameworks/Plasma/Applications and at that time, also refresh the Telepathy deps.
Since the new Applications 17.12.0 is free of KDE4 stuff now, I will have to see what needs to be preserved in my kde4 & kde4-extragear directories to keep 3rd party kdelibs4-based packages going.
HI Eric,
Well recompiling NetworkManager-openconnect didn’t fix the problem but looking at the output of the compilation it looks like there is a flag being set in the configure file that seem to indicate the limitation:
-DNM_VERSION_MAX_ALLOWED=NM_VERSION_1_4
modifying the slackbuild to change that value to NM_VERSION_1_10 (was worth a try) has no effect (well we get a slightly different message in the applet before it gives up but other than that nope)
will keep looking
No problem here, Eric, for build latest applications and frameworks 😉
And, latest plasma
Hi Eric, just wanted to report that your latest libreoffice packages for current do not run anymore after today’s boost upgrade in -current. However, symlinking the relevant 1.66.0 libraries with links using the old version 1.65.1 solves (at least temporarily) the problem.
Thanks for all your help and effort.
Eduardo, someone else already mentioned this on the ‘Feedback’ page… it’s what you get for running slackware-current. I don’t know when I will have time to compile a new package, LibreOffice is a big one.
Hi Eric, I understand what you said. I just wanted to note here the workaround in case someone finds it useful. As for the rebuild, don’t worry. I can manage so far. Thanks again!!
Just info, Eric,i have the new ConsoleKit2-1.2.1, installed here, since 8 days, it work without problem 😉
Gérard I think I can still slip that update into the next ktown release.
Thanks, I think you are preparing a nice Christmas present for plasma5 users 😉
You saw that Pat added Mako at current now, mesa no need the patch now 😉
Don’t worry the patch is commented out. It stays there in case someone wants to try these sources on Slackware 14.2.
Ok, Eric, thanks 😉 | https://alien.slackbook.org/blog/rebuilt-packages-for-plasma5-ktown/ | CC-MAIN-2020-16 | refinedweb | 3,103 | 66.84 |
Structures of Alloys Generation And Recognition
Project description
This is a (P)ure python implementation of algorithm to determin Niggli cell. The library supports both 2D and 3D niggli transformations.
Rows of list or rows of numpy.ndarray correspond basis vectors, a, b, c or a, b They are input to niggli_reduce as a row with three colum matrices, same as most DFT softwares’ lattice inputs.
In the implementation details, since the lattice is represented by a row vector, the transformation operation on the lattice is left-multiplied, such as:
import numpy as np # TMatrix is the transform matrix new_Lattice = np.matmul(TMatrix, old_Lattice)
For details of the algorithm, see [[Niggli for 2d and 3d]](http://)
Install
$ pip install pniggli
Usage
from pniggli import niggli_reduce, niggli_check lattice_3D = [4.912, 0.000, 0.000, -2.456, 4.254, 0.000, 0.000, 0.000, 0.000] niggli_lattice = niggli_reduce(lattice_3D) print(niggli_lattice) # Out: # array([[ 4.912, 0. , 0. ], # [-2.456, 4.254, 0. ], # [ 0. , 0. , 16. ]]) print(niggli_check(niggli_lattice)) # True lattice_2D = [2.4560000896, 0.0000000000, 11.0520002567, 2.1269502021] niggli_lattice = niggli_reduce(lattice_2D) print(niggli_lattice) # Out[6]: # array([[-1.2279999 , -2.1269502 ], # [-1.22800019, 2.1269502 ]])
The 2D example is a triangle motif.
Version
v0.1.2
- 2D and 3D niggli reduce support
- niggli_check for 3D lattice
v0.1.0
- 3D niggli reduce support
- niggli_check for 3D lattice
Project details
Release history Release notifications
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/pniggli/ | CC-MAIN-2019-35 | refinedweb | 252 | 54.83 |
Metadata
This chapter describes how to store metadata in QuickTime Movie files. It also defines keys for some common metadata types as examples of how to employ the metadata capabilities in the QuickTime file format.
Overview
Metadata can be defined as useful information related to media. This section describes a method of associating metadata with media in a QuickTime file that is extensible and allows for language and country tagging. In addition, it provides a means to store the type of the metadata and associate a name with metadata. This method of storing metadata is supported in both QuickTime 7 and QuickTime X.
This metadata format uses a key–value pair for each type of metadata being stored. Standard keys, with specific formats for the values they indicate, have been defined. See QuickTime Metadata Keys for details.
Data Type
The storage type of metadata items is defined via an enumerated list of data types, defined statically; an example might be “plain Unicode text”. See the Well-Known Types table for details of the standard, defined data types.
Meaning or Purpose
The meaning of a metadata item identifies what it represents: a copyright notice, the performer’s name, and so on. It uses an extensible namespace allowing for meanings or keys to be added, and then referenced, from metadata items. These keys may be four-character codes, names in reverse-address format (such as “com.apple.quicktime.windowlocation”) or any other key format including native formats from external metadata standards. A key is tagged with its namespace allowing for extension in the future. It is recommended that reverse-address format be used in the general case: this provides an extensible syntax for vendor data or for other organizations or standards bodies.
Data Location
Metadata is stored immediately in the corresponding atom structures, by value.
Localization
A metadata item can be identified as specific to a country or set of countries, to a language or set of languages, or to some combination of languages and countries. This identification allows for a default value (suitable for any language or country not explicitly called out), a single value, or a list of values.
Storage Location in a QuickTime File
Within a QuickTime file, metadata can be stored within a movie atom (
‘moov’), a track atom (
‘trak’) or a media atom (
‘mdia’). Only one metadata atom is allowed for each location. If there is user data and metadata stored in the same location, and both declare the same information, for example, declare a copyright notice, the metadata takes precedence.
Metadata Structure
The container for metadata is an atom of type
‘meta’. The metadata atom must contain the following subatoms: metadata handler atom (
‘hdlr’), metadata item keys atom (
‘keys’), and metadata item list atom (
‘ilst’). Other optional atoms that may be contained in a metadata atom include the country list atom (
‘ctry’), language list atom (
‘lang’) and free space atom (
‘free’). The country list and language list atoms can be used to store localized data in an efficient manner. The free space atom may be used to reserve space in a metadata atom for later additions to it, or to zero out bytes within a metadata atom after editing and removing elements from it. The free space atom may not occur within any other subatom contained in the metadata atom.
Metadata Atom
The metadata atom is the container for carrying metadata.
Figure 3-1 shows a sample layout for this atom.
Metadata Handler Atom
The metadata handler atom is a full atom with an atom type of
‘hdlr’. It defines the structure used for all types of metadata stored within the metadata atom.
The layout of the metadata handler atom is defined:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'hdlr'
- Version
One byte that is set to 0
- Flags
Three bytes that are set to 0
- Predefined
A 32-bit integer that is set to 0
- Handler type
A 32-bit integer that indicates the structure used in the metadata atom, set to
‘mdta’
- Reserved
An array of 3 const unsigned 32-bit integers set to 0
- Name
The name is a NULL-terminated string in UTF-8 characters which gives a human-readable name for a metadata type, for debugging and inspection purposes. The string may be empty or a single byte containing 0.
Metadata Header Atom
The metadata format optionally assigns unique identifiers to metadata items for such purposes as defining stable identifiers for external references into the set of metadata items. This is accomplished by including an item information atom in added metadata item atoms contained by the metadata item list atom. Such unique identifiers must be guaranteed to be unique.
To make the assignment of unique item identifiers more efficient, the metadata atom may contain a metadata header atom holding the integer value for the next unique item identifier to assign stored in the nextItemID field. In general it holds a value one greater than the largest identifier used so far.
Upon assigning the identifier to a metadata item, if the value of the nextItemID field is less than 0xFFFFFFFF, it should be incremented to the next unused value. If the value of nextItemID is equal to 0xFFFFFFFF, it should not be changed: in that case, a search for an unused item identifier value in the range from 0 to 0xFFFFFFFF is needed for all additions.
The metadata header atom is a full atom with an atom type of
‘mhdr’. It contains the following fields:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'mdhr'
- Version
One byte that is set to 0.
- Flags
Three bytes that are set to 0.
- nextItemID
A 32-bit unsigned integer indicating the value to use for the item ID of the next item created or assigned an item ID. If the value is all ones, it indicates that future additions will require a search for an unused item ID.
Extensibility
In order to allow metadata to be rewritten easily and without the need to rewrite the entire QuickTime movie file, free space atoms may occur anywhere in the definition of the metadata atom between the positions of other atoms contained by the metadata atom. Free space atoms may not be inserted between items in the metadata item list atom or within atoms in the metadata item list atom. This restriction on free space atom definition avoids the risk of confusing a free space atom with a meaning of a
‘free’ identifier or a value atom of type
‘free’ defined in the context of the metadata atom structure.
Similarly, UUID atoms for specific extensions may be placed in any position where a succession of atoms is permitted. Note that UUID atoms should not be created for atoms already defined using four-character codes.
Unrecognized atoms (that is, those atoms whose types not defined in the context of the metadata atom structure and are contained within the metadata item list atom) are ignored.
Localization List Sets
When metadata items have individual values associated with more than one country or more than one language, a country list atom and/or language list atom are required. Alternatively, if all values are associated with zero or one country, no country list atom is required, and if all values are associated with zero or one language, no language list atom is required.
Country List Atom
When one or more items must be identified as being suitable for more than one country, each list of countries is stored in this otherwise optional atom. The country list atom is a full atom with an atom type of
‘ctry’.
Each list starts with a two-byte count of the number of items in the list, and then each ISO 3166 code representing countries in the list.
The atom consists of a count of the number of lists, expressed as a 32-bit integer, and then these lists, appended end-to-end. The country list atom contains the following fields:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'ctry'
- Version
One byte that is set to 0.
- Flags
Three bytes that are set to 0.
- Entry_count
A 32-bit integer indicating the number of Country arrays to follow in this atom.
- Country_count
A 16-bit integer indicating the number of Countries in the array.
- Country[Country_count]
An array of 16-bit integers, defined according to the ISO 3166 definition of country codes.
Note that:
Indexes into the country list atom are 1-based.
Zero (0) is reserved and never used as an index.
Currently, there is a limit of 255 countries that may be recorded in a country list atom.
An example country list atom consisting of two country lists with two and three countries, respectively, is shown in Table 3-1.
Language List Atom
When one or more items must be identified as being suitable for more than one language, each list of languages is stored in this otherwise optional atom. The language list atom is a full atom with an atom type of
‘lang’.
Each list starts with a 2-byte count of the number of items in the list, and then each ISO 639-2/T code, packed into two bytes, according to the ISO Language Code definition in the MP4 specification.
The atom consists of a count of the number of lists, expressed as a 32-bit integer, and then these lists, appended end-to-end. The language list atom contains the following fields:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'lang'
- Version
One byte that is set to 0.
- Flags
Three bytes that are set to 0.
- Entry_count
A 32-bit integer indicating the number of language arrays to follow in this atom.
- Language_count
A 16-bit integer indicating the number of languages in the array.
- Language[Language_count]
An array of 16-bit integers, defined according to the ISO 639-2/T definition of language codes.
Note that:
Indexes into the Language List atom are 1-based.
Zero (0) is reserved and never used as an index.
Currently, there is a limit of 255 languages that may be recorded in a Language List atom.
Table 3-2 shows an example Language List atom consisting of two language lists with three and two languages, respectively.
Metadata Item Keys Atom
The metadata item keys atom holds a list of the metadata keys that may be present in the metadata atom. This list is indexed starting with 1; 0 is a reserved index value. The metadata item keys atom is a full atom with an atom type of
‘keys’.
This atom has the following structure:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'keys'
- Version
One byte that is set to 0
- Flags
Three bytes that are set to 0
- Entry_count
A 32-bit integer indicating the number of key arrays to follow in this atom
- Key_size
A 32-bit integer indicating the size of the entire structure containing a key definition. Therefore the key_size = sizeof(key_size) + sizeof(key_namespace) + sizeof(key_value). Since key_size and key_namespace are both 32 bit integers, together they have a size of 8 bytes. Hence, the key_value structure will be equal to key_size - 8.
- Key_namespace
A 32-bit integer defining a naming scheme used for metadata keys. Location metadata keys, for example, use the
‘mdta’key namespace.
- Key_value[Key_size-8]
An array of 8-bit integers, each containing the actual name of the metadata key. Keys with the ‘mdta’ namespace use a reverse DNS naming convention. For example, the location metadata coordinates use a metadata key_value of ‘com.apple.quicktime.location.ISO6709’.
Note that:
Indexes into the metadata item keys atom are 1-based (1…entry_count).
Zero (0) is reserved and never used as an index.
The structure of key_value depends upon the key namespace.
Figure 3-2 shows a sample layout for this atom.
Figure 3-3 shows an example of a metadata item keys atom consisting of three keys: two from one key namespace and a third from another key namespace.
Metadata Item List Atom.
Metadata Item Atom
Each item in the metadata item list atom is identified by its key. The atom type for each metadata item atom should be set equal to the index of the key for the metadata within the item atom, taking this index from the metadata item keys atom. In addition, each metadata item atom contains a Value Atom, to hold the value of the metadata item.
The metadata item atom has the following structure:
- Item_info
An optional item information atom, see Item Information Atom (ID and flags)
- Name
An optional name atom, defined below.
- Data value atom[]
An array of value atoms, defined below.
Value Atom
The value of the metadata item is expressed as immediate data in a value atom. The value atom starts with two fields: a type indicator, and a locale indicator. Both the type and locale indicators are four bytes long. There may be multiple ‘value’ entries, using different type, country or language codes (see the Data Ordering section below for the required ordering).
The Value atom structure contains the following fields:
- Type
A type indicator, defined in Type Indicator.
- Locale
A locale indicator, defined in Locale Indicator.
Type Indicator
The type indicator is formed of four bytes split between two fields. The first byte indicates the set of types from which the type is drawn. The second through fourth byte forms the second field and its interpretation depends upon the value in the first field.
The indicator byte must have a value of 0, meaning the type is drawn from the well-known set of types. All other values are reserved.
If the type indicator byte is 0, the following 24 bits hold the well-known type. Please refer to the list of Well-Known Types, in the Well-Known Types section below.
Locale Indicator
The locale indicator is formatted as a four-byte value. It is formed from two two-byte values: a country indicator, and a language indicator. In each case, the two-byte field has the possible values shown in Table 3-3.
Note that both ISO 3166 and ISO 639-2/T codes have a nonzero value in their top byte, and so will have a value > 255.
Software applications that read metadata may be customized for a specific set of countries or languages. If a metadata writer does not want to limit a metadata item to a specific set of countries, it should use the reserved value ZZ from ISO 3166 as its country code. Similarly if the metadata writer does not want to limit the user’s language (this is not recommended) it uses the value ‘und’ (undetermined) from the ISO 639-2/T specification.
A software application matches a country code if either (a) the value to be matched to is 0 (default) or (b) the codes are equal. A software application matches to a list of codes if its value is a member of that list. A software application matches to a locale if both country and language match.
Table 3-4 shows some example metadata tags.
To reiterate, if the country_indicator value is in the range 1 to 255, it is interpreted as the 1-based index for a country list in the Country Language atom in the Metadata atom. If the language_indicator value is in the range 1 to 255, it is interpreted as the 1-based index for a language list in the Language List atom in the Metadata atom. Otherwise, the country_indicator or language_indicator is unspecified (0) or holds the immediate value for a single country or language.
Item Information Atom (ID and flags)
The optional item information atom contains information about the item: item-specific flags and item optional identifier. This ID must be unique within the metadata atom. To simplify assignment of item identifiers, the metadata header atom’s nextItemInfo field can be used as described in Metadata Header Atom.
The item information atom must be present if the item has an assigned ID or has nonzero flags.
No flags are currently defined; they should be set to 0 in this version of the specification.
The item information atom is a full atom with an atom type of
‘itif’. This atom has the following structure:
- Size
A 32-bit unsigned integer that indicates the size in bytes of the atom structure
- Type
A 32-bit unsigned integer value set to
'itif'
- Version
One byte that is set to 0.
- Flags
Three bytes that are set to 0.
- Item_ID
An unsigned 32-bit integer, unique within the container.
Name
The Name atom is a full atom with an atom type of ‘name’. This atom contains a metadata name formatted as a string of UTF-8 characters, to fill the atom. It is optional. If it is not present, the item is unnamed, and cannot be referred to by name. Names are not user visible; they provide a way to refer to metadata items. The maximum length of a name may be limited in specific environments.
No two metadata items may have the same name.
This atom has the following structure:
- Version
One byte that is set to 0.
- Flags
Three bytes that are set to 0.
- Name
An array of bytes, constituting a UTF-8 string, containing the name.
Data Atom Structure
The Data atom has an atom type of ‘data’, and contains four bytes each of type and locale indicators, as specified in Type Indicator and Locale Indicator, and then the actual value of the metadata, formatted as required by the type.
This atom has the following structure:
- Type Indicator
The type indicator, as defined in Type Indicator.
- Locale Indicator
The locale indicator, as defined in Locale Indicator.
- Value
An array of bytes containing the value of the metadata.
Data Ordering
Multiple values for the same tag represent multiple representations of the same information, differing either by language or storage type or by the size or nature of the data. For example, an artist name may be supplied in three ways:
as a large JPEG of their signature
as a smaller ‘thumbnail’ JPEG of their signature
as text
An application may then choose the variation of the the artist name to display based on the size it needs.
Data must be ordered in each item from the most-specific data to the most general. An application may, if it wishes, stop ‘searching’ for a value once it finds a value that it can display (it has an acceptable locale and type).
Well-Known Types
The basic data-type list is in Table 3-5.
The sorting variant of text is used for languages in which sorting is not evident from the written form (for example, some forms of Asian languages). In these cases, the sorting can only be performed by a human who can identify the actual words by understanding the context. For these languages, an alternative form of the same information can be stored using a different representation of the same text which can be machine sorted. This alternative representation is still sorted according to the sort rules of the language in question, as defined for the text system in use (for example, Unicode). In general, a simple lexical sorting which compares the values of the characters alone is not sufficient.
Location Metadata
Many systems have the ability to detect or establish their position in a coordinate reference system. The specification “ISO 6709:2008 Standard representation of geographic point location by coordinates” describes one way of storing such information. One of the common systems is the Global Positioning System (GPS) developed by the US Department of Defense. Other systems include the ability of some cellular telephone systems to triangulate the position of cell-phones, and the possibility that IEEE 802.11 Wireless Base Stations are tagged with their position (whereupon mobile units that can ‘see’ their signal can establish that they are probably ‘near’ that location).
This support is increasingly common in still and movie cameras, or composite devices (such as camera-phones) that can function as cameras.
Apple has defined a key for storing the location coordinates as metadata, as well as several auxiliary pieces of information about a location. For all the location metadata keys defined in this specification, the Metadata atom handler-type should be ‘mdta’. See the com.apple.quicktime.location.ISO6709 entry in the following table for a description of the main location metadata key, and the additional table describing auxiliary location metadata keys.
QuickTime Metadata Keys
QuickTime has defined the keys shown in Table 3-6 for holding data in a Metadata atom:
In addition, QuickTime recommends the auxiliary keys shown in Table 3-7 for holding additional metadata to be associated with a location.
Direction Definition
For the metadata keys which define a direction, com.apple.quicktime.direction.facing and com.apple.quicktime.direction.motion, directions are specified as a string consisting of one or two angles, separated by a slash if two occur. The first is a compass direction, expressed in degrees and decimal degrees, optionally preceded by the characters “+” or “-”, and optionally followed by the character “M”. The direction is determined as accurately as possible; the nominal due north (zero degrees) is defined as facing along a line of longitude of the location system, unless the angle is followed by the “M” character indicating a magnetic heading. The second is an elevation direction, expressed in degrees and decimal degrees between +90.0 and -90.0, with 0 being horizontal (level), +90.0 being straight up, and -90.0 being straight down (and for these two cases, the compass direction is irrelevant).
Copyright © 2004, 2016 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2016-09-13 | https://developer.apple.com/library/content/documentation/QuickTime/QTFF/Metadata/Metadata.html | CC-MAIN-2017-51 | refinedweb | 3,703 | 60.65 |
The QIntCache class is a template class that provides a cache based on long keys. More...
#include <qintcache.h>
Inherits QPtrCollection.
List of all member functions.
QIntCache is implemented as a template class. Define a template instance Q.
Constructs a cache whose contents will never have a total cost greater than maxCost and which is expected to contain less than size items.
size is actually the size of an internal hash array; it's usually best to make it prime and at least 50% bigger than the largest expected number of items in the cache.
Each inserted item. k, or 0 if k does not exist in the cache, and moves the item to the front of the least recently used list.
If there are two or more items with equal keys, the one that was inserted most recently most recently is removed.
All iterators that refer to the removed item are set to point to the next item in the cache's traversal order.
See also take() and clear().
Sets the maximum allowed total cost of the cache to m. If the current total cost is greater than m, some items are removed immediately.
See also maxCost() and totalCost().
Returns the size of the hash array used to implement the cache. This should be a bit larger most recently-2007 Trolltech. All Rights Reserved. | http://idlebox.net/2007/apidocs/qt-x11-free-3.3.8.zip/qintcache.html | CC-MAIN-2014-15 | refinedweb | 225 | 75.91 |
With the release of version 1.5, Java introduced a new type of for loop known as enhanced or numerical for loop. It is designed to simplify loops that process elements of array or collection. It is useful when you want to access all the elements of an array but if you want to process only part of the array or modify the values in the array then use the simple for loop.
When used with an array, the enhanced for loop has the following syntax,
for (type itr_var : arrayName)
{ statement(s) }
where type identifies the type of elements in the array and itr_var provides a name for the iteration variable that is used to access each element of the array, one at a time from beginning to end. This variable will be available within the for block and its value will be the same as the current array element. The arrayName is the array through which to iterate. For example:
for (int i : num)
System.out.println(i);
This enhanced for loop header specifies that for each iteration, assign the next element of
the array to int type variable i and then execute the statement. During the first loop iteration, the value contained in num[0] is assigned to i which is then displayed using the println () method. After completion of the first iteration, in the next iteration, the value contained in num[1] is assigned to i which is then displayed using println ()method. This process continues until the last element of the array is processed.
public class EnhancedForLoop
{
public static void main(String[] args)
{
int[] num = {5,15,25,30,50};
System.out.println("Display Elements Using Numeric for Loop : ");
for(int i=0;i<num.length;i++)
System.out.print(num[i]+" ");
System.out.println("\nDispay Elemnts Using Enhanced for Loop : ");
for(int i : num)
System.out.print | http://ecomputernotes.com/java/array/enhanced-for-loop | CC-MAIN-2019-39 | refinedweb | 312 | 52.49 |
Return variables with Flask
bluepaperbirds
・2 min read
Python can be used for web development, Flask is a Python web framework based on WSGI. Flask lets you build web apps with Python (what is Flask).
You can use Flask to build single page apps, a blog, web apps and many more things. Some people use it to build a user interface on their Raspberry Pi.
Before playing with Flask, you should learn Python
Return variables in Flask
There are different ways to return variables with Flask. Did you know you can use f-Strings inside Flask? This is one of the most simple ways.
If you want to return some variables for your request, you can do:
return f'a is {a} and b is {b}'
So a full example of returning these two variables would be
from flask import Flask app = Flask(__name__) @app.route('/') def index(): a = 62 b = 41 return f'a is {a} and b is {b}' app.run(host='0.0.0.0', port=5000)
In the browser:
Run the server and open the localhost url on your pc:
➜ ~ python3 example.py * Serving Flask app "example" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on (Press CTRL+C to quit)
Related links:
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
| https://practicaldev-herokuapp-com.global.ssl.fastly.net/bluepaperbirds/return-variables-with-flask-m34 | CC-MAIN-2020-24 | refinedweb | 251 | 72.36 |
Ticket #3950 (closed Bugs: fixed)
boost::interprocess::mapped_region destructor deletes shm where it shouldn't.
Description
Hello,
I have troubles with the following piece of code:
#include <cstdlib> #include <boost/interprocess/anonymous_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> int main() { boost::interprocess::mapped_region aRegion( boost::interprocess::anonymous_shared_memory( sizeof( int ) ) ); *(int *)aRegion.get_address() = 0x33; return EXIT_SUCCESS; }
It should create an anonymous memory region and writes an int in it.
Whereas this piece of code works when compiled with gcc without optimizations, when it is compiled with -O2 or -O3 with gcc 4.4.3, it produces a segmentation fault.
strace and gdb show that the shared memory is mmapped and unmapped before the assignment is done. (Whereas when the code is compiled without optimization, the shared memory is clearly mapped, then the assignement is done, then it is unmapped.)
My understanding of what happens is that:
- the anonymous_shared_memory() function calls raw_mapped_region_creator::create_posix_mapped_region which creates a local mapped_region object.
- This mapped_region object is non-copyable, but movable.
When the return statement for that local object is called, it invokes mapped_region::mapped_region(BOOST_INTERPROCESS_RV_REF(mapped_region) other) which:
- create the returned object as invalid,
- swap the content of the local object with the one of the "invalid initialized" returned object.
Thanks to this, the returned object has the proper values and the local object is set as "invalid" just before its destructor is called so that the shm won't be unmapped at raw_mapped_region_creator::create_posix_mapped_region and anonymous_shared_memory exit.
For a reason I don't understand, I have the feeling that, when the code is compiled with gcc 4.4.3 -O2 or -O3, this "swap with invalid mapped_region" mechanism is zapped out so that the shm mmapped at the beginning of anonymous_shared_memory is unmapped by ~mapped_region when this function returns.
Attachments
Change History
Changed 6 years ago by Lénaïc Huard <lhuard@…>
- attachment boost_interprocess.patch
added
comment:2 Changed 6 years ago by Lénaïc Huard <lhuard@…>
I found the problem.
The problem was indeed caused by the strict aliasing rule violation by the class rv (in detail/move.hpp)
The case described here above and in #3951 can be solved by flagging the class rv with the gcc specific __attribute__((__may_alias__)).
The full patch that fixes the issue is attached in boost_interprocess.patch.
Could you please have a look at it?
comment:3 Changed 6 years ago by igaztanaga
Thanks! What if you modify move.hpp to modify all reinterpret_cast with static_cast? Does this also solve the problem?
comment:4 Changed 6 years ago by Lénaïc Huard <lhuard@…>
I tried to replace all the reinterpret_cast by static_cast but it doesn't help to solve the issue.
According to what I've read here:
GCC is fairly aggressive about it: enabling strict aliasing will cause it to think that pointers that are "obviously" equivalent to a human (as in, foo* a; bar * b; b = (foo*)a;) cannot alias, which allows for some very aggressive transformations, but can obviously break non-carefully written code.
If rv references alias to references to other "supposed incompatible" types, GCC will assume that operations on the first reference cannot affect the object pointed to by the second reference. In nearly all cases. Hence the issue.
The code example of this issue doesn't raise any warning. But the one of #3951 raises:
/home/lenaic/doc/prog/boost-trunk/boost/interprocess/sync/scoped_lock.hpp:348: warning: dereferencing pointer ‘<anonymous>’ does break strict-aliasing rules /home/lenaic/doc/prog/boost-trunk/boost/interprocess/sync/scoped_lock.hpp:347: warning: dereferencing pointer ‘<anonymous>’ does break strict-aliasing rules /home/lenaic/doc/prog/boost-trunk/boost/interprocess/segment_manager.hpp:1334: note: initialized from here
And those warnings are well removed by the addition of __attribute__((__may_alias__)) on rv.
By the way, in the patch I provided, I'm still wondering why I had to touch mapped_region.hpp. But without moving those two methods definition to their declaration, I get this unbelievable error:
/home/lenaic/doc/prog/boost-trunk/boost/interprocess/mapped_region.hpp:381: error: prototype for ‘boost::interprocess::mapped_region::mapped_region(boost::interprocess::rv<boost::interprocess::mapped_region>&)’ does not match any in class ‘boost::interprocess::mapped_region’ /home/lenaic/doc/prog/boost-trunk/boost/interprocess/mapped_region.hpp:84: error: candidates are: boost::interprocess::mapped_region::mapped_region(boost::interprocess::rv<boost::interprocess::mapped_region>&) [...]
comment:5 follow-up: ↓ 7 Changed 6 years ago by igaztanaga
Many thanks, I wouldn't be able to fix it by myself, I thought downcasted classes would not break strict aliasing but I was wrong.
comment:6 Changed 6 years ago by Lénaïc Huard <lhuard@…>
You're welcome!
I'm not a strict aliasing rules expert. Maybe is it gcc which is wrong and which performs optimizations that are even more aggressive than what the standard allows. I'm not able to say.
comment:7 in reply to: ↑ 5 ; follow-up: ↓ 8 Changed 6 years ago by kab@…
Replying to igaztanaga:
Many thanks, I wouldn't be able to fix it by myself, I thought downcasted classes would not break strict aliasing but I was wrong.
A downward static_cast should be fine, so long as the object is in fact of the type being downcasted to. See C++03 5.2.9/5. If gcc strict aliasing optimizations are breaking that, that would be very bad.
comment:8 in reply to: ↑ 7 Changed 6 years ago by kab@…
comment:9 follow-up: ↓ 10 Changed 6 years ago by igaztanaga
I think GCC is right, because the dynamic type of the object is not rv<T> but T. We don't create any rv<T> object so downcasting T to a non-existent rv<T> object is at least doubtful. The standard says:
INCITS+ISO+IEC+14882-2003 C++03 standard.
3.10 Lvalues and rvalues / 15
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined48):
-.
rv<T> is a class, but not an aggregate class, since (8.5.1 Aggregates [dcl.init.aggr] p.2):
An aggregate class is a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.
comment:10 in reply to: ↑ 9 Changed 6 years ago by kab@…
Replying to igaztanaga:
I think GCC is right, because the dynamic type of the object is not rv<T> but T. We don't create any rv<T> object so downcasting T to a non-existent rv<T> object is at least doubtful.
Ah, I didn't realize that. So there are no objects whose dynamic type is rv<T>. That would mean the static downcast is hitting the "undefined behavior" case at the end of 5.2.9/8. And if the compiler can figure that out (that the T* really can't be an rv<T>*) then it can generate pretty much any old garbage code.
comment:11 Changed 6 years ago by igaztanaga
- Status changed from new to closed
- Resolution set to fixed
- Milestone changed from Boost 1.43.0 to Boost-1.45.0
Fixed for Boost 1.45 in release branch
The issue #3951 is very very similar to this one.
Like in this ticket, I strongly suspect a bug in latest gcc which optimizations break something in the tricks emulating Rvalue references. Both issues disappear when the code samples are compiled with latest gcc and -std=c++0x or -std=gnu++0x in which case, the Rvalue references are managed by the compiler and the boost tricks become useless. | https://svn.boost.org/trac/boost/ticket/3950 | CC-MAIN-2016-44 | refinedweb | 1,259 | 55.13 |
get-es-imports-exportsget-es-imports-exports
Recursively or non-recursively gets all ES6 imports and exports used within a project.
E.g.
// a.js;;...
// b.js;...
// c.js;;...
Returns an object in the form:
imports:'full path of ./b': 'default''full path of ./c': '*''full path of lodash': 'find'exports:'full path of ./a': 'default''full path of ./b': '*''full path of ./c': 'find'
APIAPI
;const imports exports loadedFiles stats = await;
files is an array of paths for JS files you want to check.
The
recurse option will recursively look at the files imported to find more imports. Will not recurse and look for dependencies within node_modules, but imports to these files are still recorded.
The
exclude option is an array of file globs for files you don't want to check when recursing. As with node_modules, imports to these files are still reported.
The
parser and
parserOptions options are identical to ESLint. By default, it will supports ES6 modules and JSX.
The
resolveOptions is passed to resolve to resolve imports.
Return valuesReturn values
imports is a map of absolute file path to an array of imports. Named imports are left as-is, default imports are reported as
'default', and namespace imports are reported as
'*'.
I.e.
; // 'a'; // 'a'; // 'default'; // '*'
Note that exports can also report as an import.
; // equates to import * from 'lodash'
exports is also a map of absolute filepath to an array, but this time, exports. As before, the same naming convention is used.
const five = 5; // 'five'5; // 'default'; // '*'
loadedFiles is the files that were loaded and checked.
stats is an array of warnings. Currently the only warning is if a file failed to parse, and had an extension that wasn't .js (which would otherwise throw).
The default parser and default parser options are exported for your convenience.
TipsTips
To use
babel-eslint, use, | https://preview.npmjs.com/package/get-es-imports-exports | CC-MAIN-2021-39 | refinedweb | 310 | 68.26 |
For and DataFrame function.
- Objectives:
- Retrieving stocks information (Key statistics) from Yahoo Finance.
- Required Tools:
- Python Pandas— Using Pandas read_html function for reading web table form.
Usage — Pulling a particular stock data data
import pandas as pd tgt_website = r'' def get_key_stats(tgt_website): # The web page is make up of several html table. By calling read_html function. # all the tables are retrieved in dataframe format. # Next is to append all the table and transpose it to give a nice one row data. df_list = pd.read_html(tgt_website) result_df = df_list[0] for df in df_list[1:]: result_df = result_df.append(df) # The data is in column format. # Transpose the result to make all data in single row return result_df.set_index(0).T # Save the result to csv result_df = get_key_stats(tgt_website)
Pulling all the stocks symbols
Here, we are pulling one known stock symbol. To get all the stocks in particular indices, the stock symbols need to be known first. The below code will extract all the stock symbols, along with other data, from the NASDAQ website.
import pandas as pd weblink = '' sym_df = pd.read_csv(weblink) stock_symbol_list = sym_df.Symbol.tolist()
Pulling key statistics for all stock symbols (for given index)
The last step will be to iterate all the symbols and get the corresponding key statistcis
all_result_df = pd.DataFrame() url_prefix = '{0}/key-statistics?p={0}' for sym in stock_symbol_list: stock_url = url_prefix.format(sym) result_df = get_key_stats(stock_url) if len(all_result_df) ==0: all_result_df = result_df else: all_result_df = all_result_df.append(result_df) # Save all results all_result_df.to_csv('results.csv', index =False) | https://simply-python.com/2019/01/ | CC-MAIN-2019-30 | refinedweb | 251 | 60.72 |
- Advertisement
Content Count15
Joined
Last visited
Community Reputation517 Good
About ApEk
- RankMember
How do you manage object pools in your engine/game?
ApEk replied to HexDump's topic in General and Gameplay ProgrammingNote that the memory overhead caused by link pointers can be safely eliminated through the proper use of unions and type punning.
std::vector of pointers
ApEk replied to Crusable77's topic in For Beginners's Forum@Crusable what SyncViews says is correct and you're trying to store temporaries in a vector, but I also see something else. Although it is harmless, you seem to be using the auto keyword in your for loop here: for(auto iter = m_Map.begin(); iter != m_Map.end(); ++iter){ (*iter)->render(scrRegion, scrSize, window); //<- does not go to the function } But why not go the distance, since you are already using c++11, and use a range based for loop instead of explicitly using iterators? for (auto tile : m_Map) { tile->render(scrRegion, scrSize, window); } Isn't this the nice?
Sparse Voxel Octree vs. Gigavoxel vs. Octree
ApEk replied to ChristOwnsMe's topic in General and Gameplay ProgrammingI have no experience with implementing these structures myself, but I do read alot. - for many excellent pdfs about everything you want to know - excellent information about sparse voxel octrees using morton encoding There are many more sources of good information I have not mentioned, partly because of my memory, but you could ask on. These topics are probably more popular there and the people more knowledgeable about the latest white papers. Note that ompf forums are kind of slow as of lately D:
New c++11 video tutorials, tell me what you think.
ApEk replied to EddieV223's topic in Your AnnouncementsI hope you are prepared for some constructive criticism. From what I have seen so far, 8, 10 through 13, I haven't found anything from the new c++11 standard. Don't encourage the use of using namespace directives without explaining what namespaces are, what they do, and how to use them first. Consider condensing some of the material, there are videos less than three minutes and two whole videos just for loops. Note somewhere in the playlist description, in the videos, or in the first video that c++11 won't be "covered" until "lesson 23" or some point in time.
Rand is the same every time.
ApEk replied to Kripis's topic in For Beginners's ForumFleBlanc is correct. The variable arrayChooser never changes because you only call rand() once before the loop.
std::chrono::hige_resolution_clock for timer?
ApEk replied to Nanook's topic in General and Gameplay ProgrammingIn the event VS2012 actually supports std::chrono, here is a timer class that uses it.
Udp server on homePC
ApEk replied to Anand Baumunk's topic in General and Gameplay ProgrammingConsidering no packets reach the server, the problem could possibly be with network address translation. Look up information on "udp punch through", or "udp hole punching".
game loop
ApEk replied to Aerodactyl55's topic in For Beginners's ForumFirst off I would suggest you refine your whitespace and indentation syntax as well as your naming convention. [s]You are passing a constant delta time to update. Why? I don't know. Instead you should probably be calculating the delta time between previous and current frame and passing that to update. Update then uses the delta time by multiplying it by a constant.[/s] Edit: should work harder on my critical reading.
"Frames" per second in Win32 console application
ApEk replied to dAND3h's topic in General and Gameplay ProgrammingIf you are able to use the new c++11 standard try to use the new chrono date and time utilities found here: Note that using chrono is a little less than straightforward but here is a complete chrono timer class:
Event System in C++
ApEk replied to kuda's topic in For Beginners's ForumIf you are looking for libraries that implement signals and slots you have many options. You have a whole range of options from heavy, feature rich boost::signals its thread safe sibling boost::signals2, libsigc++, sigslot, cpp-events, and ting. I've actually released an extremely lightweight implementation that uses c++11 called nano-signal-slot. It all boils down to what you estimate you will need. I would not recommend an old or dead implementation as maintainability could become an issue. I would suggest boost::signals2 as that is the thread safe version of boost::signals, and performance between the two is similar.
- I have done research on current libraries. All of them make me say why? I'm about to just store a mutex in tracked and lock for any operation. Then instead of weak_ptr::expired do weak_ptr::lock and test the shared_ptr then lock the mutex inside of the erase callback? Edit: saving thread safety for another time. could probably end up wrapping up the underlying data structure and add locking.
- Well got around to doing some performance testing against two other implementations, sigc++ and boost::signals. However, still wondering how the heck to make it thread safe. Higher is better. x axis is input size where there are N connections made and N signals fired.
signal slot and thread safety
ApEk posted a topic in General and Gameplay ProgrammingHello, I'm currently working on a very small signal slot implementation and have an initial version released, however, the code will probably fail in any concurrent scenarios. Basically I'm asking for any helpful information as to what must happen to make the following code thread safe. I'm not sure if the problem can be easily solved with the current implementation as a signal would probably have to be locked during any operation not to mention the destructor of tracked. Lastly, any constructive criticism is welcome. For those who don't even link: struct tracked { std::shared_ptr<std::function<void(std::uintptr_t)>> erase_callback; std::unordered_map<std::uintptr_t, std::weak_ptr<std::function<void(std::uintptr_t)>>> connections; tracked ( ) : erase_callback(new std::function<void(std::uintptr_t)>) { (*erase_callback) = [this] (std::uintptr_t connection) { this->connections.erase(connection); }; } virtual ~tracked ( ) { for (auto const& connection : connections) { if (connection.second.expired() == false) { (*connection.second.lock())(connection.first); } } } }; template <typename... Args> struct signal { signal ( ) = delete; }; template <typename... Args> struct signal<void(Args...)> : private tracked { signal ( ) : tracked ( ) { (*erase_callback) = [this] (std::uintptr_t connection) { this->connections.erase(connection); this->m_slot.erase(connection); }; } //------------------------------------------------------------------------------ template<typename T> void connect(void(T::*callback)(Args...), T* instance) { std::uintptr_t hash = member_hash<T, Args...>()(callback, instance); m_slot.emplace(hash, make_function<T, Args...>(callback, instance)); derived_tracked<T>(hash, instance); } void connect(void(*callback)(Args...)) { m_free.emplace(reinterpret_cast<std::uintptr_t>(callback), callback); } //------------------------------------------------------------------------------ template<typename T> void disconnect(void(T::*callback)(Args...), T* instance) { (*erase_callback)(member_hash<T, Args...>()(callback, instance)); } void disconnect(void(*callback)(Args...)) { m_free.erase(reinterpret_cast<std::uintptr_t>(callback)); } //------------------------------------------------------------------------------ void operator() (Args... args) const { for (auto const& connection : m_slot) { connection.second(args...); } for (auto const& connection : m_free) { connection.second(args...); } } private: //----------------------------------------------------------------- template<typename T> void derived_tracked(std::uintptr_t hash, typename T::tracked* instance) { connections.emplace(hash, instance->erase_callback); instance->connections.emplace(hash, erase_callback); } template<typename T> void derived_tracked(...) { } // sfinae std::unordered_map<std::uintptr_t, std::function<void(Args...)>> m_slot; std::unordered_map<std::uintptr_t, std::function<void(Args...)>> m_free; }; Edit: above code is for context. current code is at the link above.
Implicit conversion false to null pointer
ApEk replied to jeroenb's topic in General and Gameplay Programming Default arguments in constructors should almost always be implemented as different constructors along with associating initialization lists.
Help with C++
ApEk replied to felicia's topic in General and Gameplay Programming You should be using code tags so your code is properly displayed on the page. You prime your while loop but never cin to choice inside of it therefore it will never be able to quit or do anything other than create. You should never use "using namespace std" in global scope as this will import all the symbols used in the std namespace and name conflicts can occur. Your item string should be declared locally inside of the loop this way it is always constructed and destructed at the end of the scope. It seems as though you tried to reduce your code for a smaller paste size but idk.
- Advertisement | https://www.gamedev.net/profile/199184-apek/ | CC-MAIN-2019-22 | refinedweb | 1,377 | 56.05 |
--- "Karr, David" <david.karr@wamu.net> wrote:
> > So is the "package" attribute supposed to match the Java
> > package of the Action classes? Martin Gainty had earlier
> > said I should use actionPackages. Before I added that, it
> > wasn't even getting into my Action classes at all. If I now
> > remove actionPackages, change the package attribute to match
> > my Java class, and then remove the namespace attribute, do
> > you expect that will work?
>
> I can self-answer this, I guess. After removing actionPackages, and
> setting the "package" attribute to match the Java class (something I can
> easily see someone assuming) makes it say this (it's even bad grammar,
> besides being a broken message):
What "package" attribute? In the struts config file? I'll look in to that. I
don't think the documentation states anything in particular about naming
requirements for packages; if there is one we'll document it.
> Are there still any issues hiding here that I should know about?
I'm not sure how we'd know if there were or not. This is the first time,
AFAIK, that these issues have come up at all. You tried to mix two forms of
configuration; AFAIK the actionPackages element is only for zero-config,
annotation-based configuration. Most people don't try to mix the two, I
guess.
Dave
---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org | http://mail-archives.apache.org/mod_mbox/struts-user/200803.mbox/%3C390434.68432.qm@web56715.mail.re3.yahoo.com%3E | CC-MAIN-2021-39 | refinedweb | 240 | 67.04 |
Images, Fonts, and Files
With Webpack: svg, jpg, jpeg, png, gif, mp4, webm, wav, mp3, m4a, aac, and oga. public.
An alternative way of handling static assets is described in the next section.
Using the
static Folder
Adding Assets Outside of the Module SystemAdding Assets Outside of the Module System
You can also add other assets to a
static folder at the root of your project.
Note that we normally encourage you to
import assets in JavaScript files
instead.
static folder, it will not be processed by
Webpack. Instead it will be copied into the public folder untouched. E.g. if you
add a file named
sun.jpg to the static folder, it’ll be copied to
public/sun.jpg. To reference assets in the
static folder, you’ll need to
import a helper function from
gatsby-link named
withPrefix.
You will need to make sure
you set
pathPrefix in your gatsby-config.js for this to work.
import { withPrefix } from 'gatsby-link' render() { // Note: this is an escape hatch and should be used sparingly! // Normally we recommend using `import` for getting asset URLs // as described in “Adding Images and Fonts” above this section. return <img src={withPrefix('/img/logo.png')}; }
Keep in mind the downsides of this approach:
- None of the files in
staticfolder get fonts library may be incompatible with Webpack and you have no other option but to include it as a
<script>tag. | https://www.gatsbyjs.org/docs/adding-images-fonts-files/ | CC-MAIN-2018-05 | refinedweb | 237 | 64.91 |
I will be describing in this blog one of the tricks to optimize memory in Dynamic Programming solutions.
Problem in short:
A.
N <= 5000 , Memory Limit : 16MB
Dynamic Programming solution:
First of all let's discuss solving this problem by Dynamic Programming.
Most of the times, whenever we face a problem about palindromes. The most important thing is to think about the structure of palindrome. It's a string that starts empty or consisting of only 1 letter, then it's extended by adding 2 identical letters one at the beginning and one at the end of the string. Till we just get our palindrome. Our problem here is asking as to insert minimum characters in our string so it just becomes palindrome afterwards.
Of course, the first step of a Dynamic Programming solution is figuring out the recursive function. Imagine that the first letter in our string and the last letter are the same, we can just drop them and say they never existed (That's true! prove it yourself).
If they are different, it's clear that we must insert one letter as we are building the palindrome in the way I mentioned. This letter must be identical to one of them (but which one?). Unfortunately we must try both cases. By saying a letter equal to the first one, it means we should insert the same letter at the end of the string (so now we have a string with identical endings so we can drop both of them), but the difference here from the step above that insertion cost us here 1 operation and in fact we dropped only the first letter. (Think how does that apply to the last letter).
ًThe best way to handle this is recursion (Why?). Because at each step we have a string that we should drop the first letter or the second letter and pick the choice that will lead us to a smaller string with smallest possible remaining steps to achieve our goal. In case the 2 letters are equal, the ultimate choice is just to drop them.
So let us build our recursive function :
How will the function look like (data type, parameters). In terms of computer science (Method signature) ?
int F(int l , int r);
Our function will return the minimum number of characters needed to make the substring starting at the lth character and ending at the rth character a palindrome.
What will be the base case of our function?
if(l >= r)return 0;
That's true, because an empty string or a string made of only 1 character is a palindrome.
What will be the transitions of our function?
// dropping both ends :if(str[l] == str[r])F(l,r) -> F(l+1 , r-1)// inserting a letter equal to the first letterF(l,r) -> F(l+1,r)// inserting a letter equal to the last letterF(l,r) -> F(l , r-1)
Our function will be like:
int F(int l , int r){if(l >= r)return 0;if(str[l] == str[r])return F(l + 1 , r - 1);return min(F(l + 1 , r) , F(l , r - 1)) + 1;}
It's obvious that we can use Dynamic Programming technique and memorize our answers. We can do that because for a fixed state (l, r) of our functions, our answer will not change. Because all calls with same parameters are solved under the same conditions. (Make the table of memorization yourself).
The problem here is that the table of memorization is int [5000][5000] which costs up to 100MB which is too much for the problem memory limit.
Optimizing Memory:
The first thing to observe when we need to optimize memory in a dynamic programming solution is the nature of transitions.
Take a look again please at the transitions of our function, the answer of a substring (L,R). On what does it depend?
It depends on the answer of substring (L+1 , R-1) in case of dropping both ends or the answer of substring(L+1 , R) or the answer of substring (L,R-1).
You can observe that the answer of a string of length K depends on the answers of strings of length K-2 (first case) , and length K-1 (remaining two cases).
Let's change the parameters of our function a little, instead of F(l, r) let's make it F(len , l).
l denoting the start of our substring.
len denoting the length of our substring.
It won't affect our state, because r = l + len - 1. So we haven't changed our state much. Just stored another information which can identify our states. It doesn't matter if you know the nominator and the value of fraction from knowing the denominator and the value (in both cases you know what's the fraction).
Let's rewrite our function but this time, the bottom up (iterative) implementation :
#include<bits/stdc++.h>using namespace std;int dp[5009][5009];string str;int main(){int n;cin>>n>>str;for(int j = 0 ; j < n ; j++)dp[0][j] = dp[1][j] = 0;for(int len = 2 ; len <= n ; len++){for(int l = 0 ; l < n ; l++)dp[len][l] = (1<<30);for(int l = 0 ; l + len - 1 < n ; l++){if(str[l] == str[l + len - 1])dp[len][l] = dp[len-2][l+1];else dp[len][l] = min(dp[len-1][l] , dp[len-1][l+1]) + 1;}}cout<<dp[n][0]<<endl;}
You can notice that for any state dp[len][?]
? refers to any arbitrary position.
for any state dp[len][?] we are only considering states dp[len-1][?] and states dp[len-2][?] (How is that useful?)
We have at the beginning dp[0][?] , dp[1][?] as they represent answers for empty and single character strings. Let's just calculate dp[2][?] (the whole table) and continue on. When we are calculating dp[3][?] do we still need the table dp[0][?] (The answer is No, we mentioned why above) the same goes to dp[4][?] (We don't need dp[0][?] neither dp[1][?]). In fact when calculating the value of dp[x][?] we don't need any of values dp[y][?] (where y < x-2).
As a conclusion, we can calculate the values of our function in increasing order by length. and keeping only the last 2 tables while calculating the current one. After finishing the current one dp[len][?] we can just drop the table dp[len-2][?] and continue on. So we need just 3 tables.
There is something deserves mention, is that we are not able to apply this trick if we are implementing our function the recursive way. Because the recursive way while calculating the answer for a fixed state it may calculates the answer for arbitrary subproblems (sub-states) and like filling a random part of the table. So this is not applicable. While here before proceeding into a deeper level we are sure that we have all the information we need to calculate the answer for the next level fully.
Implementation with clarifications:
#include<bits/stdc++.h>using namespace std;int dp[3][5009];string str;int main(){int n;cin>>n>>str;// handling the empty / single characters strings casefor(int j = 0 ; j < n ; j++)dp[0][j] = dp[1][j] = 0;// iterating through lengthsfor(int len = 2 ; len <= n ; len++){// initiating the table we are going to fillfor(int l = 0 ; l < n ; l++)dp[2][l] = (1<<30);// filling table as describedfor(int l = 0 ; l + len - 1 < n ; l++){if(str[l] == str[l + len - 1])dp[2][l] = dp[0][l + 1];else dp[2][l] = min(dp[1][l+1] , dp[1][l]) + 1;}// dropping the pre-previous table and shifting our tablesswap(dp[1] , dp[0]);swap(dp[1] , dp[2]);// make sure to always initialize your next table before filling// because as you can see we are bringing a table with old values that may affect our answer}cout<<dp[1][0]<<endl;} | https://www.commonlounge.com/discussion/e09892b9b8e14ac1be20aeeabc726d46/all/fd9fe15aa3f54a68ac94d6c9fc40fdff | CC-MAIN-2021-49 | refinedweb | 1,347 | 72.26 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
Getting started with odoo unit testing
According to the documentation, I created tests package and added some demo tests. But I cant see their execution. Simply this is what I have done.
my_module
|------
tests
__init__.py
test_my_test.py
Code in test_my_test.py
from openerp.tests import common
class TestStringMethods(common.TransactionCase):
def setup(self):
print ("executing setup . . .")
super(TestStringMethods, self).setUp()
def test_upper(self):
print ("executing test upper. . . ")
self.assertEqual('foo'.upper(), 'FOO')
In the __init__.py I imported test_my_test and imported tests in main __init__.py
Also added --test-enable parameter in run script.
When updating module, I can't see the execution of these test methods on console
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/getting-started-with-odoo-unit-testing-86794 | CC-MAIN-2017-13 | refinedweb | 165 | 53.98 |
I am now able to create multiple figures, each with one
> or more subplots with my software. What a great
> collection of software. Thanks for all the work.
Great, glad it helped. I was pretty sure that was the answer.
> I tried using mx.datetime to create an mx.datetime
> instance which worked fine. However, mx2num() fails with
> python claiming an undefined mxdates. I checked the
> source and found only one mxdates. No idea how it should
> be defined. In the mean time I am using a datetime
> instance but I lose a small bit of precision with only
> integer seconds.
Oops, replace mx2num in matplotlib/dates.py with
def mx2num(mxdates):
"""
Convert mx datetime instance (or sequence of mx instances) to the
new date format,
"""
scalar = False
if not iterable(mxdates):
scalar = True
mxdates = [mxdates]
ret = epoch2num([m.ticks() for m in mxdates])
if scalar: return ret[0]
else: return ret
Thanks for the report!
JDH | https://discourse.matplotlib.org/t/more-than-one-subplot-fails-when-embedding-in-tk/1959 | CC-MAIN-2019-51 | refinedweb | 157 | 78.35 |
Optimization¶
Performance can be significantly improved in different contexts by making small optimizations on the Dask graph before calling the scheduler.
The
dask.optimization module contains several functions to transform graphs
in a variety of useful ways. In most cases, users won’t need to interact with
these functions directly, as specialized subsets of these transforms are done
automatically in the Dask collections (
dask.array,
dask.bag, and
dask.dataframe). However, users working with custom graphs or computations
may find that applying these methods results in substantial speedups.
In general, there are two goals when doing graph optimizations:
- Simplify computation
- Improve parallelism
Simplifying computation can be done on a graph level by removing unnecessary
tasks (
cull), or on a task level by replacing expensive operations with
cheaper ones (
RewriteRule).
Parallelism can be improved by reducing
inter-task communication, whether by fusing many tasks into one (
fuse), or
by inlining cheap operations (
inline,
inline_functions).
Below, we show an example walking through the use of some of these to optimize a task graph.
Example¶
Suppose you had a custom Dask graph for doing a word counting task:
>>> from __future__ import print_function >>> def print_and_return(string): ... print(string) ... return string >>> def format_str(count, val, nwords): ... return ('word list has {0} occurrences of {1}, ' ... 'out of {2} words').format(count, val, nwords) >>> dsk = {'words': 'apple orange apple pear orange pear pear', ... 'nwords': (len, (str.split, 'words')), ... 'val1': 'orange', ... 'val2': 'apple', ... 'val3': 'pear', ... 'count1': (str.count, 'words', 'val1'), ... 'count2': (str.count, 'words', 'val2'), ... 'count3': (str.count, 'words', 'val3'), ... 'out1': (format_str, 'count1', 'val1', 'nwords'), ... 'out2': (format_str, 'count2', 'val2', 'nwords'), ... 'out3': (format_str, 'count3', 'val3', 'nwords'), ... 'print1': (print_and_return, 'out1'), ... 'print2': (print_and_return, 'out2'), ... 'print3': (print_and_return, 'out3')}
Here we are counting the occurrence of the words
'orange,
'apple', and
'pear' in the list of words, formatting an output string reporting the
results, printing the output, and then returning the output string.
To perform the computation, we pass the Dask graph and the desired output keys
to a scheduler
get function:
>>> from dask.threaded import get >>> outputs = ['print1', 'print2'] >>> results = get(dsk, outputs) word list has 2 occurrences of apple, out of 7 words word list has 2 occurrences of orange, out of 7 words >>> results ('word list has 2 occurrences of orange, out of 7 words', 'word list has 2 occurrences of apple, out of 7 words')
As can be seen above, the scheduler computed only the requested outputs
(
'print3' was never computed). This is because the scheduler internally
calls
cull, which removes the unnecessary tasks from the graph. Even though
this is done internally in the scheduler, it can be beneficial to call it at
the start of a series of optimizations to reduce the amount of work done in
later steps:
>>> from dask.optimization import cull >>> dsk1, dependencies = cull(dsk, outputs)
Looking at the task graph above, there are multiple accesses to constants such
as
'val1' or
'val2' in the Dask graph. These can be inlined into the
tasks to improve efficiency using the
inline function. For example:
>>> from dask.optimization import inline >>> dsk2 = inline(dsk1, dependencies=dependencies) >>> results = get(dsk2, outputs) word list has 2 occurrences of apple, out of 7 words word list has 2 occurrences of orange, out of 7 words
Now we have two sets of almost linear task chains. The only link between them
is the word counting function. For cheap operations like this, the
serialization cost may be larger than the actual computation, so it may be
faster to do the computation more than once, rather than passing the results to
all nodes. To perform this function inlining, the
inline_functions function
can be used:
>>> from dask.optimization import inline_functions >>> dsk3 = inline_functions(dsk2, outputs, [len, str.split], ... dependencies=dependencies) >>> results = get(dsk3, outputs) word list has 2 occurrences of apple, out of 7 words word list has 2 occurrences of orange, out of 7 words
Now we have a set of purely linear tasks. We’d like to have the scheduler run
all of these on the same worker to reduce data serialization between workers.
One option is just to merge these linear chains into one big task using the
fuse function:
>>> from dask.optimization import fuse >>> dsk4, dependencies = fuse(dsk3) >>> results = get(dsk4, outputs) word list has 2 occurrences of apple, out of 7 words word list has 2 occurrences of orange, out of 7 words
Putting it all together:
>>> def optimize_and_get(dsk, keys): ... dsk1, deps = cull(dsk, keys) ... dsk2 = inline(dsk1, dependencies=deps) ... dsk3 = inline_functions(dsk2, keys, [len, str.split], ... dependencies=deps) ... dsk4, deps = fuse(dsk3) ... return get(dsk4, keys) >>> optimize_and_get(dsk, outputs) word list has 2 occurrences of apple, out of 7 words word list has 2 occurrences of orange, out of 7 words
In summary, the above operations accomplish the following:
- Removed tasks unnecessary for the desired output using
cull
- Inlined constants using
inline
- Inlined cheap computations using
inline_functions, improving parallelism
- Fused linear tasks together to ensure they run on the same worker using
fuse
As stated previously, these optimizations are already performed automatically in the Dask collections. Users not working with custom graphs or computations should rarely need to directly interact with them.
These are just a few of the optimizations provided in
dask.optimization. For
more information, see the API below.
Rewrite Rules¶
For context based optimizations,
dask.rewrite provides functionality for
pattern matching and term rewriting. This is useful for replacing expensive
computations with equivalent, cheaper computations. For example, Dask Array
uses the rewrite functionality to replace series of array slicing operations
with a more efficient single slice.
The interface to the rewrite system consists of two classes:
RewriteRule(lhs, rhs, vars)
Given a left-hand-side (
lhs), a right-hand-side (
rhs), and a set of variables (
vars), a rewrite rule declaratively encodes the following operation:
lhs -> rhs if task matches lhs over variables
RuleSet(*rules)
A collection of rewrite rules. The design of
RuleSetclass allows for efficient “many-to-one” pattern matching, meaning that there is minimal overhead for rewriting with multiple rules in a rule set.
Example¶
Here we create two rewrite rules expressing the following mathematical transformations:
a + a -> 2*a
a * a -> a**2
where
'a' is a variable:
>>> from dask.rewrite import RewriteRule, RuleSet >>> from operator import add, mul, pow >>> variables = ('a',) >>> rule1 = RewriteRule((add, 'a', 'a'), (mul, 'a', 2), variables) >>> rule2 = RewriteRule((mul, 'a', 'a'), (pow, 'a', 2), variables) >>> rs = RuleSet(rule1, rule2)
The
RewriteRule objects describe the desired transformations in a
declarative way, and the
RuleSet builds an efficient automata for applying
that transformation. Rewriting can then be done using the
rewrite method:
>>> rs.rewrite((add, 5, 5)) (mul, 5, 2) >>> rs.rewrite((mul, 5, 5)) (pow, 5, 2) >>> rs.rewrite((mul, (add, 3, 3), (add, 3, 3))) (pow, (mul, 3, 2), 2)
The whole task is traversed by default. If you only want to apply a transform
to the top-level of the task, you can pass in
strategy='top_level' as shown:
# Transforms whole task >>> rs.rewrite((sum, [(add, 3, 3), (mul, 3, 3)])) (sum, [(mul, 3, 2), (pow, 3, 2)]) # Only applies to top level, no transform occurs >>> rs.rewrite((sum, [(add, 3, 3), (mul, 3, 3)]), strategy='top_level') (sum, [(add, 3, 3), (mul, 3, 3)])
The rewriting system provides a powerful abstraction for transforming computations at a task level. Again, for many users, directly interacting with these transformations will be unnecessary.
Keyword Arguments¶
Some optimizations take optional keyword arguments. To pass keywords from the
compute call down to the right optimization, prepend the keyword with the name
of the optimization. For example, to send a
keys= keyword argument to the
fuse optimization from a compute call, use the
fuse_keys= keyword:
def fuse(dsk, keys=None): ... x.compute(fuse_keys=['x', 'y', 'z'])
Customizing Optimization¶
Dask defines a default optimization strategy for each collection type (Array, Bag, DataFrame, Delayed). However, different applications may have different needs. To address this variability of needs, you can construct your own custom optimization function and use it instead of the default. An optimization function takes in a task graph and list of desired keys and returns a new task graph:
def my_optimize_function(dsk, keys): new_dsk = {...} return new_dsk
You can then register this optimization class against whichever collection type you prefer and it will be used instead of the default scheme:
with dask.config.set(array_optimize=my_optimize_function): x, y = dask.compute(x, y)
You can register separate optimization functions for different collections, or
you can register
None if you do not want particular types of collections to
be optimized:
with dask.config.set(array_optimize=my_optimize_function, dataframe_optimize=None, delayed_optimize=my_other_optimize_function): ...
You do not need to specify all collections. Collections will default to their standard optimization scheme (which is usually a good choice).
API¶
Top level optimizations
Utility functions
Rewrite Rules
Definitions¶
dask.optimization.
cull(dsk, keys)¶
Return new dask with only the tasks required to calculate keys.
In other words, remove unnecessary tasks from dask.
keysmay be a single key or list of keys.
Examples
>>> d = {'x': 1, 'y': (inc, 'x'), 'out': (add, 'x', 10)} >>> dsk, dependencies = cull(d, 'out') >>> dsk {'x': 1, 'out': (add, 'x', 10)} >>> dependencies {'x': set(), 'out': set(['x'])}
dask.optimization.
fuse(dsk, keys=None, dependencies=None, ave_width=None, max_width=None, max_height=None, max_depth_new_edges=None, rename_keys=None, fuse_subgraphs=None)¶
Fuse tasks that form reductions; more advanced than
fuse_linear
This trades parallelism opportunities for faster scheduling by making tasks less granular. It can replace
fuse_linearin optimization passes.
This optimization applies to all reductions–tasks that have at most one dependent–so it may be viewed as fusing “multiple input, single output” groups of tasks into a single task. There are many parameters to fine tune the behavior, which are described below.
ave_widthis the natural parameter with which to compare parallelism to granularity, so it should always be specified. Reasonable values for other parameters with be determined using
ave_widthif necessary.
dask.optimization.
inline(dsk, keys=None, inline_constants=True, dependencies=None)¶
Return new dask with the given keys inlined with their values.
Inlines all constants if
inline_constantskeyword is True. Note that the constant keys will remain in the graph, to remove them follow
inlinewith
cull.
Examples
>>> d = {'x': 1, 'y': (inc, 'x'), 'z': (add, 'x', 'y')} >>> inline(d) {'x': 1, 'y': (inc, 1), 'z': (add, 1, 'y')}
>>> inline(d, keys='y') {'x': 1, 'y': (inc, 1), 'z': (add, 1, (inc, 1))}
>>> inline(d, keys='y', inline_constants=False) {'x': 1, 'y': (inc, 1), 'z': (add, 'x', (inc, 'x'))}
dask.optimization.
inline_functions(dsk, output, fast_functions=None, inline_constants=False, dependencies=None)¶
Inline cheap functions into larger operations
Examples
>>> dsk = {'out': (add, 'i', 'd'), ... 'i': (inc, 'x'), ... 'd': (double, 'y'), ... 'x': 1, 'y': 1} >>> inline_functions(dsk, [], [inc]) {'out': (add, (inc, 'x'), 'd'), 'd': (double, 'y'), 'x': 1, 'y': 1}
Protect output keys. In the example below
iis not inlined because it is marked as an output key.
>>> inline_functions(dsk, ['i', 'out'], [inc, double]) {'out': (add, 'i', (double, 'y')), 'i': (inc, 'x'), 'x': 1, 'y': 1}
dask.optimization.
functions_of(task)¶
Set of functions contained within nested task
Examples
>>> task = (add, (mul, 1, 2), (inc, 3)) >>> functions_of(task) set([add, mul, inc])
dask.rewrite.
RewriteRule(lhs, rhs, vars=())¶
A rewrite rule.
Expresses lhs -> rhs, for variables vars.
Examples
Here’s a RewriteRule to replace all nested calls to list, so that (list, (list, ‘x’)) is replaced with (list, ‘x’), where ‘x’ is a variable.
>>> lhs = (list, (list, 'x')) >>> rhs = (list, 'x') >>> variables = ('x',) >>> rule = RewriteRule(lhs, rhs, variables)
Here’s a more complicated rule that uses a callable right-hand-side. A callable rhs takes in a dictionary mapping variables to their matching values. This rule replaces all occurrences of (list, ‘x’) with ‘x’ if ‘x’ is a list itself.
>>> lhs = (list, 'x') >>> def repl_list(sd): ... x = sd['x'] ... if isinstance(x, list): ... return x ... else: ... return (list, x) >>> rule = RewriteRule(lhs, repl_list, variables)
dask.rewrite.
RuleSet(*rules)¶
A set of rewrite rules.
Forms a structure for fast rewriting over a set of rewrite rules. This allows for syntactic matching of terms to patterns for many patterns at the same time.
Examples
>>> def f(*args): pass >>> def g(*args): pass >>> def h(*args): pass >>> from operator import add
>>> rs = RuleSet( # Make RuleSet with two Rules ... RewriteRule((add, 'x', 0), 'x', ('x',)), ... RewriteRule((f, (g, 'x'), 'y'), ... (h, 'x', 'y'), ... ('x', 'y')))
>>> rs.rewrite((add, 2, 0)) # Apply ruleset to single task 2
>>> rs.rewrite((f, (g, 'a', 3))) (h, 'a', 3)
>>> dsk = {'a': (add, 2, 0), # Apply ruleset to full dask graph ... 'b': (f, (g, 'a', 3))}
>>> from toolz import valmap >>> valmap(rs.rewrite, dsk) {'a': 2, 'b': (h, 'a', 3)} | https://docs.dask.org/en/latest/optimize.html | CC-MAIN-2019-13 | refinedweb | 2,092 | 54.93 |
Monads explained in C# (again)
I love functional programming for the simplicity that it brings.
But at the same time, I realize that learning functional programming is a challenging process. FP comes with a baggage of unfamiliar vocabulary that can be daunting for somebody coming from an object-oriented language like C#.
Some of functional lingo
“Monad” is probably the most infamous term from the list above. Monads have reputation of being something very abstract and very confusing.
The Fallacy of Monad Tutorials
Numerous attempts were made to explain monads in simple definitions; and monad tutorials have become a genre of its own. And yet, times and times again, they fail to enlighten the readers.
The shortest explanation of monads looks like this:
It’s both mathematically correct and totally useless to anybody learning functional programming. To understand this statement, one has to know the terms “monoid”, “category” and “endofunctors” and be able to mentally compose them into something meaningful.
The same problem is apparent in most monad tutorials. They assume some pre-existing knowledge in heads of their readers, and if that assumption fails, the tutorial doesn’t click.
Focusing too much on mechanics of monads instead of explaining why they are important is another common problem.
Douglas Crockford grasped this fallacy very well:
The monadic curse is that once someone learns what monads are and how to use them, they lose the ability to explain them to other people
The problem here is likely the following. Every person who understands monads had their own path to this knowledge. It hasn’t come all at once, instead there was a series of steps, each giving an insight, until the last final step made the puzzle complete.
But they don’t remember the whole path anymore. They go online and blog about that very last step as the key to understanding, joining the club of flawed explanations.
There is an actual academic paper from Tomas Petricek that studies monad tutorials.
I’ve read that paper and a dozen of monad tutorials online. And of course, now I came up with my own.
I’m probably doomed to fail too, at least for some readers. Yet, I know that many people found the previous version of this article useful.
I based my explanation on examples from C# - the object-oriented language familiar to .NET developers.
Story of Composition
The base element of each functional program is Function. In typed languages each function
is just a mapping between the type of its input parameter and output parameter.
Such type can be annotated as
func: TypeA -> TypeB.
C# is object-oriented language, so we use methods to declare functions. There are two ways
to define a method comparable to
func function above. I can use static method:
static class Mapper { static ClassB func(ClassA a) { ... } }
… or instance method:
class ClassA { // Instance method ClassB func() { ... } }
Static form looks closer to the function annotation, but both ways are actually equivalent for the purpose of our discussion. I will use instance methods in my examples, however all of them could be written as static extension methods too.
How do we compose more complex workflows, programs and applications out of such simple building blocks? A lot of patterns both in OOP and FP worlds revolve around this question. And monads are one of the answers.
My sample code is going to be about conferences and speakers. The method implementations aren’t really important, just watch the types carefully. There are 4 classes (types) and 3 methods (functions):
class Speaker { Talk NextTalk() { ... } } class Talk { Conference GetConference() { ... } } class Conference { City GetCity() { ... } } class City { ... }
These methods are currently very easy to compose into a workflow:
static City NextTalkCity(Speaker speaker) { Talk talk = speaker.NextTalk(); Conference conf = talk.GetConference(); City city = conf.GetCity(); return city; }
Because the return type of the previous step always matches the input type of the next step, we can write it even shorter:
static City NextTalkCity(Speaker speaker) { return speaker .NextTalk() .GetConference() .GetCity(); }
This code looks quite readable. It’s concise and it flows from top to bottom, from left to right, similar to how we are used to read any text. There is not much noise too.
That’s not what real codebases look like though, because there are multiple complications along the happy composition path. Let’s look at some of them.
NULLs
Any class instance in C# can be
null. In the example above I might get runtime errors if
one of the methods ever returns
null back.
Typed functional programming always tries to be explicit about types, so I’ll re-write the signatures of my methods to annotate the return types as nullables:
class Speaker { Nullable<Talk> NextTalk() { ... } } class Talk { Nullable<Conference> GetConference() { ... } } class Conference { Nullable<City> GetCity() { ... } } class City { ... }
This is actually invalid syntax in current C# version, because
Nullable<T> and its short form
T? are not applicable to reference types. This might change in C# 8
though, so bear with me.
Now, when composing our workflow, we need to take care of
null results:
static Nullable<City> NextTalkCity(Speaker speaker) { Nullable<Talk> talk = speaker.NextTalk(); if (talk == null) return null; Nullable<Conference> conf = talk.GetConference(); if (conf == null) return null; Nullable<City> city = conf.GetCity(); return city; }
It’s still the same method, but it got more noise now. Even though I used short-circuit returns and one-liners, it still got harder to read.
To fight that problem, smart language designers came up with the Null Propagation Operator:
static Nullable<City> NextTalkCity(Speaker speaker) { return speaker ?.NextTalk() ?.GetConference() ?.GetCity(); }
Now we are almost back to our original workflow code: it’s clean and concise, we just got
3 extra
? symbols around.
Let’s take another leap.
Collections
Quite often a function returns a collection of items, not just a single item. To some extent,
that’s a generalization of
null case: with
Nullable<T> we might get 0 or 1 results back,
while with a collection we can get
0 to any
n results.
Our sample API could look like this:
class Speaker { List<Talk> GetTalks() { ... } } class Talk { List<Conference> GetConferences() { ... } } class Conference { List<City> GetCities() { ... } }
I used
List<T> but it could be any class or plain
IEnumerable<T> interface.
How would we combine the methods into one workflow? Traditional version would look like this:
static List<City> AllCitiesToVisit(Speaker speaker) { var result = new List<City>(); foreach (Talk talk in speaker.GetTalks()) foreach (Conference conf in talk.GetConferences()) foreach (City city in conf.GetCities()) result.Add(city); return result; }
It reads ok-ish still. But the combination of nested loops and mutation with some conditionals sprinkled on them can get unreadable pretty soon. The exact workflow might be lost in the mechanics.
As an alternative, C# language designers invented LINQ extension methods. We can write code like this:
static List<City> AllCitiesToVisit(Speaker speaker) { return speaker .GetTalks() .SelectMany(talk => talk.GetConferences()) .SelectMany(conf => conf.GetCities()) .ToList(); }
Let me do one further trick and format the same code in an unusual way:
static List<City> AllCitiesToVisit(Speaker speaker) { return speaker .GetTalks() .SelectMany(x => x .GetConferences() ).SelectMany(x => x .GetCities() ).ToList(); }
Now you can see the same original code on the left, combined with just a bit of technical repeatable clutter on the right. Hold on, I’ll show you where I’m going.
Let’s discuss another possible complication.
Asynchronous Calls
What if our methods need to access some remote database or service to produce the results? This
should be shown in type signature, and C# has
Task<T> for that:
class Speaker { Task<Talk> NextTalk() { ... } } class Talk { Task<Conference> GetConference() { ... } } class Conference { Task<City> GetCity() { ... } }
This change breaks our nice workflow composition again.
We’ll get back to async-await later, but the original way to combine
Task-based
methods was to use
ContinueWith and
Unwrap API:
static Task<City> NextTalkCity(Speaker speaker) { return speaker .NextTalk() .ContinueWith(talk => talk.Result.GetConference()) .Unwrap() .ContinueWith(conf => conf.Result.GetCity()) .Unwrap(); }
Hard to read, but let me apply my formatting trick again:
static Task<City> NextTalkCity(Speaker speaker) { return speaker .NextTalk() .ContinueWith(x => x.Result .GetConference() ).Unwrap().ContinueWith(x => x.Result .GetCity() ).Unwrap(); }
You can see that, once again, it’s our nice readable workflow on the left + some mechanical repeatable junction code on the right.
Pattern
Can you see a pattern yet?
I’ll repeat the
Nullable-,
List- and
Task-based workflows again:
static Nullable<City> NextTalkCity(Speaker speaker) { return speaker ? .NextTalk() ? .GetConference() ? .GetCity(); } static List<City> AllCitiesToVisit(Speaker speaker) { return speaker .GetTalks() .SelectMany(x => x .GetConferences() ).SelectMany(x => x .GetCities() ).ToList(); } static Task<City> NextTalkCity(Speaker speaker) { return speaker .NextTalk() .ContinueWith(x => x.Result .GetConference() ).Unwrap().ContinueWith(x => x.Result .GetCity() ).Unwrap(); }
In all 3 cases there was a complication which prevented us from sequencing method calls fluently. In all 3 cases we found the gluing code to get back to fluent composition.
Let’s try to generalize this approach. Given some generic container type
WorkflowThatReturns<T>, we have a method to combine an instance of such workflow with
a function which accepts the result of that workflow and returns another workflow back:
class WorkflowThatReturns<T> { WorkflowThatReturns<U> AddStep(Func<T, WorkflowThatReturns<U>> step); }
In case this is hard to grasp, have a look at the picture of what is going on:
An instance of type
Tsits in a generic container.
We call
AddStepwith a function, which maps
Tto
Usitting inside yet another container.
We get an instance of
Ubut inside two containers.
Two containers are automatically unwrapped into a single container to get back to the original shape.
Now we are ready to add another step!
In the following code,
NextTalk returns the first instance inside the container:
WorkflowThatReturns<City> Workflow(Speaker speaker) { return speaker .NextTalk() .AddStep(x => x.GetConference()) .AddStep(x => x.GetCity()); }
Subsequently,
AddStep is called two times to transfer to
Conference and then
City inside the same container:
Finally, Monads
The name of this pattern is Monad.
In C# terms, a Monad is a generic class with two operations: constructor and bind.
class Monad<T> { Monad(T instance); Monad<U> Bind(Func<T, Monad<U>> f); }
Constructor is used to put an object into container,
Bind is used to replace one
contained object with another contained object.
It’s important that
Bind’s argument returns
Monad<U> and not just
U. We can think
of
Bind as a combination of
Map and
Unwrap as defined per following signature:
class Monad<T> { Monad(T instance); Monad<U> Map(Function<T, U> f); static Monad<U> Unwrap(Monad<Monad<U>> nested); }
Even though I spent quite some time with examples, I expect you to be slightly confused at this point. That’s ok.
Keep going and let’s have a look at several sample implementations of Monad pattern.
Maybe (Option)
My first motivational example was with
Nullable<T> and
?.. The full pattern
containing either 0 or 1 instance of some type is called
Maybe (it maybe has a value,
or maybe not).
Maybe is another approach to dealing with ‘no value’ value, alternative to the
concept of
null.
Functional-first language F# typically doesn’t allow
null for its types. Instead, F# has
a maybe implementation built into the language:
it’s called
option type.
Here is a sample implementation in C#:
public class Maybe<T> where T : class { private readonly T value; public Maybe(T someValue) { if (someValue == null) throw new ArgumentNullException(nameof(someValue)); this.value = someValue; } private Maybe() { } public Maybe<U> Bind<U>(Func<T, Maybe<U>> func) where U : class { return value != null ? func(value) : Maybe<U>.None(); } public static Maybe<T> None() => new Maybe<T>(); }
When
null is not allowed, any API contract gets more explicit: either you
return type
T and it’s always going to be filled, or you return
Maybe<T>.
The client will see that
Maybe type is used, so it will be forced to handle
the case of absent value.
Given an imaginary repository contract (which does something with customers and orders):
public interface IMaybeAwareRepository { Maybe<Customer> GetCustomer(int id); Maybe<Address> GetAddress(int id); Maybe<Order> GetOrder(int id); }
The client can be written with
Bind method composition, without branching,
in fluent style:
Maybe<Shipper> shipperOfLastOrderOnCurrentAddress = repo.GetCustomer(customerId) .Bind(c => c.Address) .Bind(a => repo.GetAddress(a.Id)) .Bind(a => a.LastOrder) .Bind(lo => repo.GetOrder(lo.Id)) .Bind(o => o.Shipper);
As we saw above, this syntax looks very much like a LINQ query with a bunch
of
SelectMany statements. One of the common
implementations of
Maybe implements
IEnumerable interface to enable
a more C#-idiomatic binding composition. Actually:
Enumerable + SelectMany is a Monad
IEnumerable is an interface for enumerable containers.
Enumerable containers can be created - thus the constructor monadic operation.
The
Bind operation is defined by the standard LINQ extension method, here
is its signature:
public static IEnumerable<U> SelectMany<T, U>( this IEnumerable<T> first, Func<T, IEnumerable<U>> selector)
Direct implementation is quite straightforward:
static class Enumerable { public static IEnumerable<U> SelectMany( this IEnumerable<T> values, Func<T, IEnumerable<U>> func) { foreach (var item in values) foreach (var subItem in func(item)) yield return subItem; } }
And here is an example of composition:
IEnumerable<Shipper> shippers = customers .SelectMany(c => c.Addresses) .SelectMany(a => a.Orders) .SelectMany(o => o.Shippers);
The query has no idea about how the collections are stored (encapsulated in
containers). We use functions
T -> IEnumerable<U> to produce new enumerables
(
Bind operation).
Task (Future)
In C#
Task<T> type is used to denote asynchronous computation which will eventually
return an instance of
T. The other names for similar concepts in other languages
are
Promise and
Future.
While the typical usage of
Task in C# is different from the Monad pattern we
discussed, I can still come up with a
Future class with the familiar structure:
public class Future<T> { private readonly Task<T> instance; public Future(T instance) { this.instance = Task.FromResult(instance); } private Future(Task<T> instance) { this.instance = instance; } public Future<U> Bind<U>(Func<T, Future<U>> func) { var a = this.instance.ContinueWith(t => func(t.Result).instance).Unwrap(); return new Future<U>(a); } public void OnComplete(Action<T> action) { this.instance.ContinueWith(t => action(t.Result)); } }
Effectively, it’s just a wrapper around the
Task which doesn’t add too much value,
but it’s a useful illustration because now we can do:
repository .LoadSpeaker() .Bind(speaker => speaker.NextTalk()) .Bind(talk => talk.GetConference()) .Bind(conference => conference.GetCity()) .OnComplete(city => reservations.BookFlight(city));
We are back to the familiar structure. Time for some more complications.
Non-Sequential Workflows
Up until now, all the composed workflows had very liniar, sequential structure: the output of a previous step was always the input for the next step. That piece of data could be discarded after the first use because it was never needed for later steps:
Quite often though, this might not be the case. A workflow step might need data from two or more previous steps combined.
In the example above,
BookFlight method might actually need both
Speaker and
City objects:
In this case, we would have to use closure to save
speaker object until we get
a
talk too:
repository .LoadSpeaker() .OnComplete(speaker => speaker .NextTalk() .Bind(talk => talk.GetConference()) .Bind(conference => conference.GetCity()) .OnComplete(city => reservations.BookFlight(speaker, city)) );
Obviously, this gets ugly very soon.
To solve this structural problem, C# language got its
async-
await feature,
which is now being reused in more languages including Javascript.
If we move back to using
Task instead of our custom
Future, we are able to
write
var speaker = await repository.LoadSpeaker(); var talk = await speaker.NextTalk(); var conference = await talk.GetConference(); var city = await conference.GetCity(); await reservations.BookFlight(speaker, city);
Even though we lost the fluent syntax, at least the block has just one level, which makes it easier to navigate.
Monads in Functional Languages
So far we learned that
- Monad is a workflow composition pattern
- This pattern is used in functional programming
- Special syntax helps simplify the usage
It should come at no surprise that functional languages support monads on syntactic level.
F# is a functional-first language running on .NET framework. F# had its own way of
doing workflows comparable to
async-
await before C# got it. In F#, the above
code would look like this:
let sendReservation () = async { let! speaker = repository.LoadSpeaker() let! talk = speaker.nextTalk() let! conf = talk.getConference() let! city = conf.getCity() do! bookFlight(speaker, city) }
Apart from syntax (
! instead of
await), the major difference to C# is that
async is just one possible monad type to be used this way. There are many
other monads in F# standard library (they are called Computation Expressions).
The best part is that any developer can create their own monads, and then use all the power of language features.
Say, we want a hand-made
Maybe computation expressoin in F#:
let nextTalkCity (speaker: Speaker) = maybe { let! talk = speaker.nextTalk() let! conf = talk.getConference() let! city = conf.getCity(talk) return city }
To make this code runnable, we need to define Maybe computation expression builder:
type MaybeBuilder() = member this.Bind(x, f) = match x with | None -> None | Some a -> f a member this.Return(x) = Some x let maybe = new MaybeBuilder()
I won’t explain the details of what happens here, but you can see that the code is
quite trivial. Note the presence of
Bind operation (and
Return operation being
the monad constructor).
The feature is widely used by third-party F# libraries. Here is an actor definition in Akka.NET F# API:
let loop () = actor { let! message = mailbox.Receive() match message with | Greet(name) -> printfn "Hello %s" name | Hi -> printfn "Hello from F#!" return! loop () }
Monad Laws
There are a couple laws that constructor and
Bind need to adhere to, so
that they produce a proper monad.
A typical monad tutorial will make a lot of emphasis on the laws, but I find them less important to explain to a beginner. Nonetheless, here they are for the sake of completeness.
Left Identity law says that Monad constructor is a neutral operation: you can safely
run it before
Bind, and it won’t change the result of the function call:
// Given T value; Func<T, Monad<U>> f; // Then (== means both parts are equivalent) new Monad<T>(value).Bind(f) == f(value)
Right Identity law says that given a monadic value, wrapping its contained data
into another monad of same type and then
Binding it, doesn’t change the original value:
// Given Monad<T> monadicValue; // Then (== means both parts are equivalent) monadicValue.Bind(x => new Monad<T>(x)) == monadicValue
Associativity law means that the order in which
Bind operations
are composed does not matter:
// Given Monad<T> m; Func<T, Monad<U>> f; Func<U, Monad<V>> g; // Then (== means both parts are equivalent) m.Bind(f).Bind(g) == m.Bind(a => f(a).Bind(g))
The laws may look complicated, but in fact they are very natural expectations that any developer has when working with monads, so don’t spend too much mental effort on memorizing them.
Conclusion
You should not be afraid of the “M-word” just because you are a C# programmer.
C# does not have a notion of monads as predefined language constructs, but that doesn’t mean we can’t borrow some ideas from the functional world. Having said that, it’s also true that C# is lacking some powerful ways to combine and generalize monads that are available in functional programming languages.
Go learn some more Functional Programming! | https://mikhail.io/2018/07/monads-explained-in-csharp-again/ | CC-MAIN-2022-40 | refinedweb | 3,258 | 54.63 |
Proximity analysis is a way to analyze the locations of features by measuring the distance between them and other features in the area. The distance between point A and point B can be measured in a straight line or along a network path, such as a road network. In this article, I will introduce you to the proximity analysis with Python.
In this article, you will explore several proximity analysis techniques. In particular, you will learn to do things such as:
Also, Read – Interactive Maps with Python.
- how to calculate the distance between points on a map, and
- select all points within a radius of an entity.
Proximity Analysis with Python
I will start this task of proximity analysis with python by importing the necessary libraries:
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
import folium from folium import Marker, GeoJson from folium.plugins import HeatMap import pandas as pd import geopandas as gpd
I will be working on the python proximity scan task using a US Environmental Protection Agency (EPA) dataset that tracks toxic chemical releases in Philadelphia, PA, USA. You can download the dataset from here. Now let’s read the data:
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
releases = gpd.read_file("toxic_release_pennsylvania.shp")
I will also be using another dataset that contains readings from air quality monitoring stations in the same city. You can download this dataset from here. Let’s read this data:
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
stations = gpd.read_file("PhillyHealth_Air_Monitoring_Stations.shp")
Calculating Distance
Now To calculate the distances between the points of two different Data Frames, we first need to make sure that they use the same Coordinate Reference System. Fortunately, this is the case here, where both use EPSG 2272:
Code language: CSS (css)Code language: CSS (css)
print(stations.crs) print(releases.crs)
{'init': 'epsg:2272'} {'init': 'epsg:2272'}
We also check the CRS to see what units it uses. In our case, EPSG 2272 is in feet. It is relatively easy to calculate distances in GeoPandas:
Code language: PHP (php)Code language: PHP (php)
# Select one release incident in particular recent_release = releases.iloc[360] # Measure distance from release to each station distances = stations.geometry.distance(recent_release.geometry) distances
0 44778.509761 1 51006.456589 2 77744.509207 3 14672.170878 4 43753.554393 5 4711.658655 6 23197.430858 7 12072.823097 8 79081.825506 9 3780.623591 10 27577.474903 11 19818.381002 dtype: float64
Using the calculated distances we can get statistics like the average distance to each station:
Code language: PHP (php)Code language: PHP (php)
print('Mean distance to monitoring stations: {} feet'.format(distances.mean()))
Mean distance to monitoring stations: 33516.28487007786 feet
Creating a Buffer
If we want to understand all the points on a map that are within a certain radius of a point, the easiest way is to create a stamp. Let’s see how to do that:
two_mile_buffer = stations.geometry.buffer(2*5280) two_mile_buffer.head()
0 POLYGON ((2721944.640797138 257149.3104284704,... 1 POLYGON ((2682494.289907977 271248.9000113755,... 2 POLYGON ((2744886.638220146 280980.2466903776,... 3 POLYGON ((2703638.579968393 233247.1013432145,... 4 POLYGON ((2726959.772827223 251134.9763285518,... dtype: object
We use folium.GeoJson() to plot each polygon on a map. Note that since the folium requires latitude and longitude coordinates, we need to convert the CRS to EPSG 4326 before plotting:
Code language: PHP (php)Code language: PHP (php)
# Create map with release incidents and monitoring stations m = folium.Map(location=[39.9526,-75.1652], zoom_start=11) HeatMap(data=releases[['LATITUDE', 'LONGITUDE']], radius=15).add_to(m) for idx, row in stations.iterrows(): Marker([row['LATITUDE'], row['LONGITUDE']]).add_to(m) # Plot each polygon on the map GeoJson(two_mile_buffer.to_crs(epsg=4326)).add_to(m) # Show the map m
Also, Read – Random Sampling with Python.
So this is how we can perform a task of Proximity Analysis with Python. I hope you liked this article on Proximity Analysis with Python. Feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to learn every topic of Machine Learning and Python. | https://thecleverprogrammer.com/2020/09/10/proximity-analysis-with-python/ | CC-MAIN-2021-43 | refinedweb | 684 | 59.8 |
Hi all.
I'm new to the forum & to be totally honest, don't have a single clue about coding (not even a 'teensy' little bit).
I was given a RCF Evox 5 speaker by a friend after he somehow managed to damage the main board & fried the onboard dsp ic that splits the sound (highs & lows).
I purchased a Teensy 4 and an audio board with the hopes of making a basic active line level cross-over for this speaker.
I went onto the website with audio design tool and put together what I thought I required to do this.
Basically using both inputs (line in) then going to 2x bi-quad filters, then each to an amp & then out.
This kinda worked as I do get audio out, but the sound is distorted on certain frequencies. I have no idea what code to use inside of the project.
I played around & tried to learn what I could from using other peoples examples & kinda managed to get a low & high output, but unfortunately it still sounds bad to me.
I don't even know where to look to find the code to use for this or where to read up on what each piece of code does, where to put brackets, curly brackets, semi-colons etc...
I even watched those Teensy audio workshop video's (all of them!!) None of them mention what code you must use after using the web based tool??
Please, please, please can someone help me with this. I have no idea what I'm doing but I am willing to learn. I'm starting to lose my mind!!
This is all the code I put in (using the tool, examples & guessing):
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioInputI2S i2s1; //xy=55,363
AudioFilterBiquad biquad1; //xy=310,341
AudioFilterBiquad biquad2; //xy=312,388
AudioAmplifier amp4; //xy=429,392
AudioAmplifier amp3; //xy=431,341
AudioOutputI2S i2s2; //xy=649,340
AudioConnection patchCord1(i2s1, 0, biquad1, 0);
AudioConnection patchCord2(i2s1, 1, biquad2, 0);
AudioConnection patchCord3(biquad1, amp3);
AudioConnection patchCord4(biquad2, amp4);
AudioConnection patchCord5(amp4, 0, i2s2, 1);
AudioConnection patchCord6(amp3, 0, i2s2, 0);
AudioControlSGTL5000 sgtl5000_1; //xy=422,586
// GUItool: end automatically generated code
const int myInput = AUDIO_INPUT_LINEIN;
//const int myInput = AUDIO_INPUT_LINEIN;
void setup() {
AudioMemory(12);
sgtl5000_1.enable(); // Enable the audio shield
sgtl5000_1.inputSelect(myInput);
sgtl5000_1.volume(1);
// Amplification
amp3.gain(7);
amp4.gain(5);
// Butterworth filter, 48 db/octave
biquad1.setLowpass(0, 200, 1);
// Linkwitz-Riley filter, 48 dB/octave
//biquad1.setLowpass(0, 200, 1);
// Butterworth filter, 48 db/octave
biquad2.setHighpass(0, 200, 1);
// Linkwitz-Riley filter, 48 dB/octave
//biquad2.setHighpass(0, 200, 1);
}
void loop() {
}
Any help / guidance will be appreciated.
Thanks in advance. | https://forum.pjrc.com/threads/59622-Help-with-using-filters-for-a-x-over?s=bf65092466d18852f2b21b5e2c28ac7d&p=230184&viewfull=1 | CC-MAIN-2020-24 | refinedweb | 463 | 56.76 |
Note that MINGW and TextPad are already installed on the PC's in Hicks 213.
Download the mingw-get-inst installer and run it on your computer. When prompted:
Verify that the install has completed successfully by going to the Start menu, opening up the MINGW shell, and typing
gcc -v
...and hitting enter. You should see some version information for the GNU C Compiler, something like this (this output is from my Mac, so yours will look different -- the important thing is that the command runs).
Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5664~105)
You will want to install a text editor that knows how to do C syntax highlighting. I like the shareware program TextPad, but you may also like Notepad++ or even Emacs (note that the last one is quite powerful but has a steep learning curve).
Once you get the editor installed, you can right-click on a C source file in the Windows explorer to associate the .c file extension with your editor of choice.
Create a folder for your programs in your Documents folder or
on your K: (or H: or whatever) drive. Let's use
#include <stdio.h> int main(int argc, char** argv) { printf("Hello, world!\n"); return 0; }
Now it's time to compile your program. Open up the MINGW shell from the start menu and type in (substituting whatever drive and path you chose to put the source file in):
cd /k/ccode/example gcc -o hello.exe hello.c ./hello.exe
You should get the output
Hello, world!
If so, you have successfully compiled your first program!
Note that unlike the DOS prompt (cmd.exe) in Windows, the MINGW shell considers drive letters to be directories, so to change to the C: drive, you would type cd /c instead of C:
"Make" is a handy utility that recompiles your programs for you by detecting when the source code is more recent than the executable. We will test it by trying to get it to recompile your hello.exe file, changing the source code, and recompiling again. We'll learn more about how to use make in class soon.
In the same directory as hello.c, use your text editor to create a file called makefile (no .c or .txt extension), containing:
hello.exe:.exe' is up to date.
Now change hello.c to print something else (maybe "Hello, world, again!") and save the file. Go back to the MINGW shell and type
make
once more. It will print the line
gcc -O3 -Wall -o hello.exe hello.c
indicating that it has recompiled your program for you. | http://www.swarthmore.edu/NatSci/mzucker1/e15/c-instructions-windows.html | CC-MAIN-2016-22 | refinedweb | 446 | 75.3 |
Ok, this has been bothering me for about 30 minutes now. I cannot figure out why this code doesnt work. It compiles with no errors, but as soon as I enter the first number, it quits and gives me an error.
Code:
#include <stdio.h>
struct rect {
float length, width, height;
};
int main() {
struct rect box;
float volume=0;
printf("Please enter the length of the box: ");
scanf("%f", box.length);
printf("Please enter the width of the box: ");
scanf("%f", box.width);
printf("Please enter the height of the box: ");
scanf("%f", box.height);
volume = box.length * box.width * box.height;
printf("The volume of the box is: %f\n",volume);
if(box.length == box.width && box.width == box.height) {
printf("The box is a perfect cube\n");
}
else {
printf("The box is not a perfect cube\n");
}
return 0;
} | http://cboard.cprogramming.com/c-programming/47652-why-wont-work-printable-thread.html | CC-MAIN-2014-35 | refinedweb | 141 | 85.18 |
How to use TensorFlow Object Detection API On Windows
Rohit Patil
Originally published at
Medium
on
・3 min read
Around July 2017, TensorFlow’s Object Detection API was released. The TensorFlow Object Detection API is an open source framework built on top of TensorFlow that makes it easy to construct, train and deploy object detection models.
What makes this API huge is that unlike other models like YOLO, SSD, you do not need a complex hardware setup to run it.
They have published a paper titled Speed/accuracy trade-offs for modern convolutional object detectors . Here they discuss various architecture available for object detection like YOLO, Faster R-CNN, SSD and R-FCN.
This API is capable of identifying many types of objects like cars, pedestrians, person, kite, dog and many more. You can find the whole list here.
I have used this API, for detecting traffic signal in a live video stream for capstone project of Udacity’s self-driving car nanodegree program. In this project we had to run the Carla (self-driving car of Udacity) on the road.
Let’s begin the setup.
- Clone the tensorflow-model repository.
- The main API documentation is at.
- Install tensorflow.
# For CPU pip install tensorflow # For GPU pip install tensorflow-gpu
- Install all other dependencies
pip install pillow pip install lxml pip install jupyter pip install matplotlib
Download Google Protobuf Windows v3.4.0 release “protoc-3.4.0-win32.zip”
Extract the Protobuf download to Program Files, specifically
C:\Program Files\protoc-3.4.0-win32
- Now cd into models\research.
cd path\to\models\research
- Execute the protobuf compile
“C:\Program Files\protoc-3.4.0-win32\bin\protoc.exe” object\_detection/protos/\*.proto --python\_out=.
This is the most important step in the installation process.
Now navigate to models\research\object_detection\protos and and verify the .py files were created successfully as a result of the compilation. (only the .proto files were there to begin with)
cd to \models\research\object_detection. Open the jupyter notebook object_detection_tutorial.ipynb. Here you can play with the API.
Problem you will probably face :
- If you move the notebook to any other directory, and run it and you will get an error
ModuleNotFoundError: No module named 'utils'
- Source of this error are these two lines in the code.
from utils import label\_map\_util from utils import visualization\_utils as vis\_util
- This error is because we are yet to inform Python how to find the utils directory that these lines use.
Issue Resolution :
- Go to System -> Advanced system settings -> Environment Variables -> New, and add a variable with the name PYTHON_PATH and these values:
- In system variables, edit PATH and add %PYTHON_PATH%.
- You will need to restart the system and then you are free to use this code anywhere in the system.
Some output samples
For experimenting with this API, I used my webcam and mobile’s camera. I used IP Webcam Android App for interfacing the mobile camera. You can checkout the repository.
rohts-patil/TensorFlow-Object-Detection-API-On-Live-Video-Feed
Thank you for reading. You can find me on Twitter @Rohitpatil5, or connect with me on LinkedIn.
Letter to Myself Ten Years Ago
Inspired by the viral 10-year challenge on social media, when people show the world what they looked like 10 years ago, I decided not to share my photos of that time.
| https://dev.to/rohitpatil5/how-to-use-tensorflow-object-detection-api-on-windows-21b4 | CC-MAIN-2019-30 | refinedweb | 566 | 55.95 |
Counting Objects in C++ -----by Scott Meyers
Counting Objects in C++
Scott Meyers
It isn't hard to keep a count of all the objects allocated for a given
class in C++, unless you have to deal with distractions.
Sometimes woul
d:
* the sidebar on placement new and placement delete.).
The naming of patterns is as much art as anything else, and I'm not very good
at it, but I'd probably call this pattern something like "Do It For Me."
Basically, each class generated from Counter provides a service (it counts
how many objects exist) for the class requesting the Counter instantiation.
So the class Counter<Widget> counts Widgets, and the class Counter<ABCD>
counts ABCDs.
Now that Counter is a template, both the embedding design and the inheritance
design will work, so we're in a position to evaluate their comparative
strengths and weaknesses. One of our design criteria was that object-counting
functionality should be easy for clients to obtain, and the code above makes
clear that the inheritance-based design is easier than the embedding-based
design. That's because the former requires only the mentioning of Counter as
a base class, whereas the latter requires that a Counter data member be
defined and that howMany be reimplemented by clients to invoke Counter's
howMany [2]. That's not a lot of additional work (client howManys are simple
inline functions), but having to do one thing is easier than having to do
two. So let's first turn our attention to the design employing inheritance.
Using Public Inheritance
The design based on inheritance works because C++ guarantees that each time a
derived class object is constructed or destroyed, its base class part will
also be constructed first and destroyed last. Making Counter a base class
thus ensures that a Counter constructor or destructor will be called each
time a class inheriting from it has an object created or destroyed.
Any time the subject of base classes comes up, however, so does the subject
of virtual destructors. Should Counter have one? Well-established principles
of object-oriented design for C++ dictate that it should. If it has no
virtual destructor, deletion of a derived class object via a base class
pointer yields undefined (and typically undesirable) results:
class Widget: public Counter<Widget>
{ ... };
Counter<Widget> *pw =
new Widget; // get base class ptr
// to derived class object
......
delete pw; // yields undefined results
// if the base class lacks
// a virtual destructor
Such behavior would violate our criterion that our object-counting design be
essentially foolproof, because there's nothing unreasonable about the code
above. That's a powerful argument for giving Counter a virtual destructor.
Another criterion, however, was maximal efficiency (imposition of no
unnecessary speed or space penalty for counting objects), and now we're in
trouble. We're in trouble because the presence of a virtual destructor (or
any virtual function) in Counter means each object of type Counter (or a
class derived from Counter) will contain a (hidden) virtual pointer, and this
will increase the size of such objects if they don't already support virtual
functions [3]. That is, if Widget itself contains no virtual functions,
objects of type Widget would increase in size if Widget started inheriting
from Counter<Widget>. We don't want that.
The only way to avoid it is to find a way to prevent clients from deleting
derived class objects via base class pointers. It seems that a reasonable way
to achieve this is to declare operator delete private in Counter:
template<typename T>
class Counter {
public:
.....
private:
void operator delete(void*);
.....
};
Now the delete expression won't compile:
class Widget: public Counter<Widget> { ... };
Counter<Widget> *pw = new Widget; ......
delete pw; // Error. Can't call private
// operator delete
Unfortunately — and this is the really interesting part — the new expression
shouldn't compile either!
Counter<Widget> *pw =
new Widget; // this should not
// compile because
// operator delete is
// private
Remember from my earlier discussion of new, delete, and exceptions that C++'s
runtime system is responsible for deallocating memory allocated by operator
new if the subsequent constructor invocation fails. Recall also that operator
delete is the function called to perform the deallocation. But we've declared
operator delete private in Counter, which makes it invalid to create objects
on the heap via new!
Yes, this is counterintuitive, and don't be surprised if your compilers don't
yet support this rule, but the behavior I've described is correct.
Furthermore, there's no other obvious way to prevent deletion of derived
class objects via Counter* pointers, and we've already rejected the notion of
a virtual destructor in Counter. So I say we abandon this design and turn our
attention to using a Counter data member instead.
Using a Data Member
We've already seen that the design based on a Counter data member has one
drawback: clients must both define a Counter data member and write an inline
version of howMany that calls the Counter's howMany function. That's
marginally more work than we'd like to impose on clients, but it's hardly
unmanageable. There is another drawback, however. The addition of a Counter
data member to a class will often increase the size of objects of that class
type.
At first blush, this is hardly a revelation. After all, how surprising is it
that adding a data member to a class makes objects of that type bigger? But
blush again. Look at the definition of Counter:
template<typename T>
class Counter {
public:
Counter();
Counter(const Counter&);
~Counter();
static size_t howMany();
private:
static size_t count;
};
Notice how it has no nonstatic data members. That means each object of type
Counter contains nothing. Might we hope that objects of type Counter have
size zero? We might, but it would do us no good. C++ is quite clear on this
point. All objects have a size of at least one byte, even objects with no
nonstatic data members. By definition, sizeof will yield some positive number
for each class instantiated from the Counter template. So each client class
containing a Counter object will contain more data than it would if it didn't
contain the Counter.
(Interestingly, this does not imply that the size of a class without a
Counter will necessarily be bigger than the size of the same class containing
a Counter. That's because alignment restrictions can enter into the matter.
For example, if Widget is a class containing two bytes of data but that's
required to be four-byte aligned, each object of type Widget will contain two
bytes of padding, and sizeof(Widget) will return 4. If, as is common,
compilers satisfy the requirement that no objects have zero size by inserting
a char into Counter<Widget>, it's likely that sizeof(Widget) will still yield
4 even if Widget contains a Counter<Widget> object. That object will simply
take the place of one of the bytes of padding that Widget already contained.
This is not a terribly common scenario, however, and we certainly can't plan
on it when designing a way to package object-counting capabilities.)
I'm writing this at the very beginning of the Christmas season. (It is in
fact Thanksgiving Day, which gives you some idea of how I celebrate major
holidays...) Already I'm in a Bah Humbug mood. All I want to do is count
objects, and I don't want to haul along any extra baggage to do it. There has
got to be a way.
Using Private Inheritance
Look again at the inheritance-based code that led to the need to consider a
virtual destructor in Counter:
class Widget: public Counter<Widget>
{ ... };
Counter<Widget> *pw = new Widget;
......
delete
pw; // yields undefined results
// if Counter lacks a virtual
// destructor
Earlier we tried to prevent this sequence of operations by preventing the
delete expression from compiling, but we discovered that that also prohibited
the new expression from compiling. But there is something else we can
prohibit. We can prohibit the implicit conversion from a Widget* pointer
(which is what new returns) to a Counter<Widget>* pointer. In other words, we
can prevent inheritance-based pointer conversions. All we have to do is
replace the use of public inheritance with private inheritance:
class Widget: private Counter<Widget>
{ ... };
Counter<Widget> *pw =
new Widget; // error! no implicit
// conversion from
// Widget* to
// Counter<Widget>*
Furthermore, we're likely to find that the use of Counter as a base class
does not increase the size of Widget compared to Widget's stand-alone size.
Yes, I know I just finished telling you that no class has zero size, but —
well, that's not really what I said. What I said was that no objects have
zero size. The C++ Standard makes clear that the base-class part of a more
derived object may have zero size. In fact many compilers implement what has
come to be known as the empty base optimization [4].
Thus, if a Widget contains a Counter, the size of the Widget must increase.
The Counter data member is an object in its own right, hence it must have
nonzero size. But if Widget inherits from Counter, compilers are allowed to
keep Widget the same size it was before. This suggests an interesting rule of
thumb for designs where space is tight and empty classes are involved: prefer
private inheritance to containment when both will do.
This last design is nearly perfect. It fulfills the efficiency criterion,
provided your compilers implement the empty base optimization, because
inheriting from Counter adds no per-object data to the inheriting class, and
all Counter member functions are inline. It fulfills the foolproof criterion,
because count manipulations are handled automatically by Counter member
functions, those functions are automatically called by C++, and the use of
private inheritance prevents implicit conversions that would allow
derived-class objects to be manipulated as if they were base-class objects.
(Okay, it's not totally foolproof: Widget's author might foolishly
instantiate Counter with a type other than Widget, i.e., Widget could be made
to inherit from Counter<Gidget>. I choose to ignore this possibility.)
The design is certainly easy for clients to use, but some may grumble that it
could be easier. The use of private inheritance means that howMany will
become private in inheriting classes, so such classes must include a using
declaration to make howMany public to their clients:
class Widget: private Counter<Widget> {
public:
// make howMany public
using Counter<Widget>::howMany;
..... // rest of Widget is unchanged
};
class ABCD: private Counter<ABCD> {
public:
// make howMany public
using Counter<ABCD>::howMany;
..... // rest of ABCD is unchanged
};
For compilers not supporting namespaces, the same thing is accomplished by
replacing the using declaration with the older (now deprecated) access
declaration:
class Widget: private Counter<Widget> {
public:
// make howMany public
Counter<Widget>::howMany;
..... // rest of Widget is unchanged
};
Hence, clients who want to count objects and who want to make that count
available (as part of their class's interface) to their clients must do two
things: declare Counter as a base class and make howMany accessible [5].
The use of inheritance does, however, lead to two conditions that are worth
noting. The first is ambiguity. Suppose we want to count Widgets, and we want
to make the count available for general use. As shown above, we have Widget
inherit from Counter<Widget> and we make howMany public in Widget. Now
suppose we have a class SpecialWidget publicly inherit from Widget and we
want to offer SpecialWidget clients the same functionality Widget clients
enjoy. No problem, we just have SpecialWidget inherit from
Counter<SpecialWidget>.
But here is the ambiguity problem. Which howMany should be made available by
SpecialWidget, the one it inherits from Widget or the one it inherits from
Counter<SpecialWidget>? The one we want, naturally, is the one from
Counter<SpecialWidget>, but there's no way to say that without actually
writing SpecialWidget::howMany. Fortunately, it's a simple inline function:
class SpecialWidget: public Widget,
private Counter<SpecialWidget> {
public:
.....
static size_t howMany()
{ return Counter<SpecialWidget>::howMany(); }
.....
};
The second observation about our use of inheritance to count objects is that
the value returned from Widget::howMany includes not just the number of
Widget objects, it includes also objects of classes derived from Widget. If
the only class derived from Widget is SpecialWidget and there are five
stand-alone Widget objects and three stand-alone SpecialWidgets,
Widget::howMany will return eight. After all, construction of each
SpecialWidget also entails construction of the base Widget part.
Summary
The following points are really all you need to remember:
* Automating the counting of objects isn't hard, but it's not completely
straightforward, either. Use of the "Do It For Me" pattern (Coplien's
"curiously recurring template pattern") makes it possible to generate the
correct number of counters. The use of private inheritance makes it possible
to offer object-counting capabilities without increasing object sizes.
* When clients have a choice between inheriting from an empty class or
containing an object of such a class as a data member, inheritance is
preferable, because it allows for more compact objects.
* Because C++ endeavors to avoid memory leaks when construction fails for
heap objects, code that requires access to operator new generally requires
access to the corresponding operator delete too.
* The Counter class template doesn't care whether you inherit from it or
you contain an object of its type. It looks the same regardless. Hence,
clients can freely choose inheritance or containment, even using different
strategies in different parts of a single application or library. o
Notes and References
[1] James O. Coplien. "The Column Without a Name: A Curiously Recurring
Template Pattern," C++ Report, February 1995.
[2] An alternative is to omit Widget::howMany and make clients call
Counter<Widget>::howMany directly. For the purposes of this article, however,
we'll assume we want howMany to be part of the Widget interface.
[3] Scott Meyers. More Effective C++ (Addison-Wesley, 1996), pp. 113-122.
[4] Nathan Myers. "The Empty Member C++ Optimization," Dr. Dobb's Journal,
August 1997. Also available at.
[5] Simple variations on this design make it possible for Widget to use
Counter<Widget> to count objects without making the count available to Widget
clients, not even by calling Counter<Widget>::howMany directly. Exercise for
the reader with too much free time: come up with one or more such variations.
Further Reading
To learn more about the details of new and delete, read the columns by Dan
Saks on the topic (CUJ January - July 1997), or Item 8 in my More Effective
C++ (Addison-Wesley, 1996). For a broader examination of the object-counting
problem, including how to limit the number of instantiations of a class,
consult Item 26 of More Effective C++.
Acknowledgments
Mark Rodgers, Damien Watkins, Marco Dalla Gasperina, and Bobby Schmidt
provided comments on drafts of this article. Their insights and suggestions
improved it in several ways.
Scott Meyers authored the best-selling Effective C++, Second Edition and More
Effective C++ (both published by Addison Wesley). Find out more about him,
his books, his services, and his dog at. | http://blog.csdn.net/LYH_Studio/article/details/1051927 | CC-MAIN-2018-05 | refinedweb | 2,532 | 52.7 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
I have extended the JiraSeraphAuthenticator to facilitate SSO to JIRA with our corporate Siteminder - this works successfully, but experiencing two issues:
1. Users are not automatically added to the jira-users group upon login and must be manually added.
I have attempted using the embedded crowd apis to addUserToGroup, but not clear on how to instantiate CrowdService. If this is the correct route to take, what needs to be configured (jira.xml?) to instantiate this class - below returns a null pointer exception?
protected static CrowdService getCrowdService()
{
return (CrowdService) ContainerManager.getComponent(crowdService);
}
2. Since implementing SSO, the login details (count, last login date) are no longer recorded for users. Please advise on what calls need to be made in the custom authenticator to continue recording the user login details.
Thanks.
Hi there
About auto-adding the users to the jira-users group, you have to enable this option in the external directory (Administration > USers Direcotry > Configuring the LDAP directory). Perhaps the following link could be useful:
Related to the user login details, this is related to the authentication method. So, I'd suggest to review this update procedure in your customer authentication. Also, the following link could be useful too:
Cheers,
Paulo Renato
Thank you for your reply Paulo.
I should have provided more detail in my current setup that is not working:
- I am using ldap for user directory (Sun directory server) and it is setup as the 2nd directorory to the Internal directory.
- It is setup as Read Only, with Local Groups and the default group membership value is already set to "jira-users".
- The jira-users group is only an internal group and not an ldap group.
- jira-users is also specified in the global permissions for JIRA Users
- So all users in the company have a user entry, but only people that need to use JIRA are in the jira-users group... which still need to be manually setup since the default in not working.
- This is the reason I was looking into adding the group assignment into the custom authenticator code.
Your second link has me wondering if I'm approaching this wrong using the crowd apis... I'm not using "stand alone" crowd for user management (as described here:).
It is only the embedded crowd that is used, so I was attempting to use this class:
com.atlassian.crowd.embedded.api.CrowdService;
Should I be using the JIRA user/group apis?
Thanks again for you advise.
Tim
I'm actually struggling with the difference between full Crowd integration and utilization of the embedded Crowd in OOTB JIRA.
What is the advantage to full integration with Crowd? We are currently not experiencing any deficiencies in the current setup except for the fact that users are not added to the jira-users group upon their initial login. I recognize that this is due to use of the custom authenticator to support Siteminder SSO, so want to explicitly include the group add in the authenticator code.
It doesn't seem that full integration will crowd would be necessary to implement this logic.
Tim, are you still using a custom authenticator for SSO with Jira 4.x and Siteminder? We're in the process of upgrading to Jira 6.0.1 but cannot get Siteminder to work. There seems to have been a change starting 5.0, but not sure what needs to be changed, server.xml/web.xml/seraph-config.xml/custom authenticator or all of the above.
If you have upgraded could really use your input:
Hi Manohar-
I upgraded from 4.x to 5.2.5 a couple months ago, but still using a custom authenticator for SSO with Siteminder. The only thing that was required to change in order to get it to work was adding a new parameter into the seraph-config.xml (insert new login.forward.path) as indicated below:
<security-config> <parameters> ... <!-- The path to *forward* to when the user tries to POST to a protected resource (rather than clicking on an explicit login link). Note that this is done using a servlet FORWARD, not a redirect. Information about the original request can be gotten from the javax.servlet.forward.* request attributes. At this point you will probably want to save the user's POST params so he can log in again and retry the POST. Defaults to undefined, in which case Seraph will just do a redirect instead of a FORWARD. --> <init-param> <param-name>login.forward.path</param-name> <param-value>/secure/XsrfErrorAction.jspa</param-value> </init-param> ... <parameters> </security-config>
I never did resolve the original issues from this post, so if you have any insight there I would appreciate hearing from you!
Also, are you by change using Siteminder SSO with Stash, Bamboo or FishEye/Crucible?
Thanks and good luck with your upgrade,
Tim
Just had a breakthrough in that the Infrastructure team rebuilt the customauthenticator jar and we are now able to access Jira through Siteminder. There are a number of errors in the log and can't access the marketplace but I'm sure those will be easier issues to fix. I haven't used your change to seraph-config.xml yet, but may try it to see if it reduces the number of errors.
Right now we're only using Jira as an atlassian product, but over time the development groups might start looking at the other tools. Siteminder is mandated by the security team so we will definitely have to use it with those tools at that time.
Good to hear you're making progress... I ran into a few additional issues also that were tied back to the Siteminder configuration:
1. 5.2 introduced some additional special characters there were restricted by the policy and needed to be added (mostly affected filters involving date criteria and issue attachments containing spaces).
2. Marketplace: This uses a head call... and the policy for 4.x only allowed Get,Post,Put, Delete operations. JIRA uses just about everything.
Question on your custom authenticator - Do you have the issues that I have outlined in this thread originally? If not, would you share will me how you got around them? Thanks!
Ugh, I posted a long answer to this and somehow got logged out and had my answer wiped out.
1. Do you have any details regarding this? i.e. code like you posted above. I'm assuming without it I'll see problems when people try to post issue attachments containing spaces etc.
2. For some reason I'm unable to access Jira Marketplace, getting an error message 'The Jira server cannot be contacted'. Wondering if this is related to what you mentioned here.
3. Regarding your thread, for the first part I didn't realize there was a way that the user could automatically be created in the backend upon their first login via siteminder. However, given that as administrator I'd have to go in anyway and update their name/email in their profile, it doesn't seem like this would be much of a time savings.
For the metrics, I'm having the same issue and thought I'd posted a question although I can't find it. We have an agent that we're trying to set up that logs in every 5 minutes to check the status of Jira. Right now, we'd see a long string of logins for this agent. I only want to see the most recent login, which I assume is what you're trying to do. If I find a solution I'll let you know.
For 1&2, I don't have the details... they were addressed by the Siteminder admins. Yours should be familiar with any policy blocks.
For #2, this was directly related to its use of HEAD call that was also being blocked by the Siteminder policy.
3. I am utilizing the corporate LDAP for user account management, so do not need to do any maintanance of name/email... just need them to be added to the jira-users group (so for me this would be a great savings and convenience to the end users).
Thanks.
Doing an SSO implementatino for JIRA is something I've been picking at for the last few weeks and I've run into the same issue. I think the issue is that there's some sort of missing information in the SSO documentation for JIRA. Even if you have the User Directory set to automatically add the user to 'jira-users' (and thus you're using the mode "Read Only with Local Groups"), this does not happen properly using any of the SSO example code that's out there for JIRA. At the same time I was debugging this, I also noticed that various ways of trying to determine if the user is already logged in get missed entirely and essentially every HTTP request to JIRA is starting a new session over again.
I believe there are some necessary calls to the embedded Crowd system to properly create the session and that would also do "first login" things properly. I'm experimenting with some code from Confluence to see if it's similar enough to hack through the issue.
FFR, this is the same issue I asked about at.
Sort of along these lines, I finally got Siteminder working with Jira 6.0.x by having someone here rebuild our Custom Jar. However when I tried to use the same Jar and server/web/seraph-config files with 6.1.x it no longer worked. So rather than perform our Production upgrade with 6.1 we have to go with 6.0.8. Not the worst thing in the world, but annoying since we're just postponing the pain. If anyone is able to successfully figure out how to integrate 6.1 with Siteminder please post the details. The actual Jira documentation for this integration out there is worthless. It has exactly the same information but with different dates, indicating its been updated when in reality it never has been:
Hi JM,
Thanks for your comments... did you have any luck with your attempts with calls to the embedded Crowd?
Manohar-
We have not yet moved to 6.1, but will be at some point and I'll update with any insight.
I have everything working to create sessions and making calls to Embedded Crowd except that I cannot get the method that actually add a user to a group to work - I get a NoSuchMethod error. So far:
CrowdService cs = getCrowdService(); // everyone has to be in a/the default group to login if( ! cs.isUserMemberOfGroup(username,DEFAULT_GROUP) ){ log.debug("user " + username + "not in group " + DEFAULT_GROUP); try{ log.debug("trying to retrieve group " + DEFAULT_GROUP); Group defgroup = cs.getGroup(DEFAULT_GROUP); log.debug("group retrieved is named " + defgroup()); } } else { log.debug("user " + username + "in group " + DEFAULT_GROUP); }
In this code username and DEFAULT_GROUP are strings that are the username and "jira-users" respectively. This *should* all work and does except for the cs.addUserToGroup(user,defgroup); actually fails on execution with:
stacktrace = java.lang.NoSuchMethodError: com.atlassian.crowd.embedded.api.CrowdService.addUserToGroup(Lcom/atlassia n/crowd/embedded/api/User;Lcom/atlassian/crowd/embedded/api/Group;)V
I'm calling it per the API documentation and other methods within the CrowdService class all work so I'm no sure at this point. Still poking at it when time permits...
Also, you might want to add the jira and seraph tags to this Answer and perhaps an Atlassian person will see this.
So I have this all working now. My issue wasn't with JIRA itself, it was with how I was building the JAR. Now that I have wrestled the Atlassian SDK into shape, everything works fine. The code to add a user to jira-users that I have working is now this:
// What group should all users belong to String DEFAULT_GROUP = new String("jira-users"); // getCrowdService() is another method in the SSO class // that returns a com.atlassian.crowd.embedded.api.CrowdService CrowdService cs = getCrowdService(); // User here is a com.atlassian.crowd.embedded.api.User // and username is String contaning the already-authenticated user User user = cs.getUser(username); // everyone has to be in a/the default group to login if( ! cs.isUserMemberOfGroup(username,DEFAULT_GROUP) ){ try{ // Group here is a com.atlassian.crowd.embedded.api.Group Group defgroup = cs.getGroup(DEFAULT_GROUP); log.debug("user to add to " + DEFAULT_GROUP + " is " + user()); } log.debug("user " + username + "not in group " + DEFAULT_GROUP); } else { log.debug("user " + username + "in group " + DEFAULT_GROUP); }
Regarding adding users to jira-user group, we have a kludge that we worked out using Jelly scripts that can extract all the users from a spreadsheet and directly import them into Jira including specifying which projects they need to be added to. I can post that to a separate Q/A if you think it would be useful.
I'm still trying to figure out how to fix the issue with spaces in the attachments so if you have any solutions out there that would be great. Not a showstopper, but annoying because it gets reported fairly frequently.
Hi
Has anyone tried Crowd-SiteMinder integration ?
Regards, Vishnu.. | https://community.atlassian.com/t5/Questions/Issues-with-customer-authenticator-used-for-SSO-with-Siteminder/qaq-p/307760 | CC-MAIN-2018-30 | refinedweb | 2,226 | 55.74 |
Visual C++ - Exploring New C++ and MFC Features in Visual Studio 2010
By Sumit Kumar | April 2010
Visual Studio 2010 presents huge benefits for C++ developers. From the ability to employ the new features offered by Windows 7 to the enhanced productivity features for working with large code bases, there is something new and improved for just about every C++ developer.
In this article, I will explain how Microsoft has addressed some of the broad problems faced by C++ developers..
Let’s take a closer look at these C++-focused advancements in Visual Studio 2010.
C++0x Core Language Features
The next C++ standard is inching closer to being finalized. To help you get started with the C++0x extensions, the Visual C++ compiler in Visual Studio 2010 enables six C++0x core language features: lambda expressions, the auto keyword, rvalue references, static_assert, nullptr and decltype.
Lambda expressions implicitly define and construct unnamed function objects. Lambdas provide a lightweight natural syntax to define function objects where they are used, without incurring performance overhead.
Function objects are a very powerful way to customize the behavior of Standard Template Library (STL) algorithms, and can encapsulate both code and data (unlike plain functions). But function objects are inconvenient to define because of the need to write entire classes. Moreover, they are not defined in the place in your source code where you’re trying to use them, and the non-locality makes them more difficult to use. Libraries have attempted to mitigate some of the problems of verbosity and non-locality, but don’t offer much help because the syntax becomes complicated and the compiler errors are not very friendly. Using function objects from libraries is also less efficient since the function objects defined as data members are not in-lined.
Lambda expressions address these problems. The following code snippet shows a lambda expression used in a program to remove integers between variables x and y from a vector of integers.
The second line shows the lambda expression. Square brackets, called the lambda-introducer, indicate the definition of a lambda expression. This lambda takes integer n as a parameter and the lambda-generated function object has the data members x and y. Compare that to an equivalent handwritten function object to get an appreciation of the convenience and time-saving lambdas provide:
The auto keyword has always existed in C++, but it was rarely used because it provided no additional value. C++0x repurposes this keyword to automatically determine the type of a variable from its initializer. Auto reduces verbosity and helps important code to stand out. It avoids type mismatches and truncation errors. It also helps make code more generic by allowing templates to be written that care less about the types of intermediate expressions and effectively deals with undocumented types like lambdas. This code shows how auto saves you from typing the template type in the for loop iterating over a vector:
Rvalue references are a new reference type introduced in C++0x that help solve the problem of unnecessary copying and enable perfect forwarding. When the right-hand side of an assignment is an rvalue, then the left-hand side object can steal resources from the right-hand side object rather than performing a separate allocation, thus enabling move semantics.
Perfect forwarding allows you to write a single function template that takes n arbitrary arguments and forwards them transparently to another arbitrary function. The nature of the argument (modifiable, const, lvalue or rvalue) is preserved in this forwarding process.
A detailed explanation of rvalue references is out of scope for this article, so check the MSDN documentation at msdn.microsoft.com/library/dd293668(VS.100) for more information.
Static_assert allows testing assertions at compile time rather than at execution time. It lets you trigger compiler errors with custom error messages that are easy to read. Static_assert is especially useful for validating template parameters. For example, compiling the following code will give the error “error C2338: custom assert: n should be less than 5”:
Nullptr adds type safety to null pointers and is closely related to rvalue references. The macro NULL (defined as 0) and literal 0 are commonly used as the null pointer. So far that has not been a problem, but they don’t work very well in C++0x due to potential problems in perfect forwarding. So the nullptr keyword has been introduced particularly to avoid mysterious failures in perfect forwarding functions.
Nullptr is a constant of type nullptr_t, which is convertible to any pointer type, but not to other types like int or char. In addition to being used in perfect forwarding functions, nullptr can be used anywhere the macro NULL was used as a null pointer.
A note of caution, however: NULL is still supported by the compiler and has not yet been replaced by nullptr. This is mainly to avoid breaking existing code due to the pervasive and often inappropriate use of NULL. But in the future, nullptr should be used everywhere NULL was used, and NULL should be treated as a feature meant to support backward compatibility.
Finally, decltype feature allows you to state, for example, an expression that has template arguments, such as sum<T1, T2>() has the type T1+T2.
Standard Library Improvements
Substantial portions of the standard C++ library have been rewritten to take advantage of new C++0x language features and increase performance. In addition, many new algorithms have been introduced.
The standard library takes full advantage of rvalue references to improve performance. Types such as vector and list now have move constructors and move assignment operators of their own. Vector reallocations take advantage of move semantics by picking up move constructors, so if your types have move constructors and move assignment operators, the library picks that up automatically.
You can now create a shared pointer to an object at the same time you are constructing the object with the help of the new C++0x function template make_shared<T>:
In Visual Studio 2008 you would have to write the following to get the same functionality:
Using make_shared<T> is more convenient (you’ll have to type the type name fewer times), more robust (it avoids the classic unnamed shared_ptr leak because the pointer and the object are being created simultaneously), and more efficient (it performs one dynamic memory allocation instead of two).
The library now contains a new, safer smart pointer type, unique_ptr (which has been enabled by rvalue references). As a result, auto_ptr has been deprecated; unique_ptr avoids the pitfalls of auto_ptr by being movable, but not copyable. It allows you to implement strict ownership semantics without affecting safety. It also works well with Visual C++ 2010 containers that are aware of rvalue references.
Containers now have new member functions—cbegin and cend—that provide a way to use a const_iterator for inspection regardless of the type of container:
Visual Studio 2010 adds most of the algorithms proposed in various C++0x papers to the standard library. A subset of the Dinkumware conversions library is now available in the standard library, so now you can do conversions like UTF-8 to UTF-16 with ease. The standard library enables exception propagation via exception_ptr. Many updates have been made in the header <random>. There is a singly linked list named forward_list in this release. The library has a header <system_error> to improve diagnostics. Additionally, many of the TR1 features that existed in namespace std::tr1 in the previous release (like shared_ptr and regex) are now part of the standard library under the std namespace.
Concurrent Programming Improvements
Visual Studio 2010 introduces the Parallel Computing Platform, which helps you to write high-performance parallel code quickly while avoiding subtle concurrency bugs. This lets you dodge some of the classic problems relating to concurrency.
The Parallel Computing Platform has four major parts: the Concurrency Runtime (ConcRT), the Parallel Patterns Library (PPL), the Asynchronous Agents Library, and parallel debugging and profiling.
ConcRT is the lowest software layer that talks to the OS and arbitrates among multiple concurrent components competing for resources. Because it is a user mode process, it can reclaim resources when its cooperative blocking mechanisms are used. ConcRT is aware of locality and avoids switching tasks between different processors. It also employs Windows 7 User Mode Scheduling (UMS) so it can boost performance even when the cooperative blocking mechanism is not used.
PPL supplies the patterns for writing parallel code. If a computation can be decomposed into sub-computations that can be represented by functions or function objects, each of these sub-computations can be represented by a task. The task concept is much closer to the problem domain, unlike threads that take you away from the problem domain by making you think about the hardware, OS, critical sections and so on. A task can execute concurrently with the other tasks independent of what the other tasks are doing. For example, sorting two different halves of an array can be done by two different tasks concurrently.
PPL includes parallel classes (task_handle, task_group and structured_task_group), parallel algorithms (parallel_invoke, parallel_for and parallel_for_each), parallel containers (combinable, concurrent_queue, and concurrent_vector), and ConcRT-aware synchronization primitives (critical_section, event and reader_writer_lock), all of which treat tasks as a first-class concept. All components of PPL live in the concurrency namespace.
Task groups allow you to execute a set of tasks and wait for them all to finish. So in the sort example, the tasks handling two halves of the array can make one task group. You are guaranteed that these two tasks are completed at the end of the wait member function call, as shown in the code example of a recursive quicksort written using parallel tasks and lambdas:
void quicksort(vector<int>::iterator first, vector<int>::iterator last) { if (last - first < 2) { return; } int pivot = *first; auto mid1 = partition(first, last, [=](int elem) { return elem < pivot; }); auto mid2 = partition( mid1, last, [=](int elem) { return elem == pivot; }); task_group g; g.run([=] { quicksort(first, mid1); }); g.run([=] { quicksort(mid2, last); }); g.wait(); }
This can be further improved by using a structured task group enabled by the parallel_invoke algorithm. It takes from two to 10 function objects and executes all of them in parallel using as many cores as ConcRT provides and waits for them to finish:
There could be multiple subtasks created by each of these tasks. The mapping between tasks and execution threads (and ensuring that all the cores are optimally utilized) is managed by ConcRT. So decomposing your computation into as many tasks as possible will help take advantage of all the available cores.
Another useful parallel algorithm is parallel_for, which can be used to iterate over indices in a concurrent fashion:
This concurrently calls function objects with each index, starting with first and ending with last. a bigger computation problem. This communication between agents is achieved via message-passing functions and message blocks.
Agents have an observable lifecycle that goes through various stages. They are not meant to be used for the fine-grained parallelism achieved by using PPL tasks. Agents are built on the scheduling and resource management components of ConcRT and help you avoid the issues that arise from the use of shared memory in concurrent applications.
You do not need to link against or redistribute any additional components to take advantage of these patterns. ConcRT, PPL and the Asynchronous Agents Library have been implemented within msvcr100.dll, msvcp100.dll and libcmt.lib/libcpmt.lib alongside the standard library. PPL and the Asynchronous Agents Library are mostly header-only implementations.
The Visual Studio debugger is now aware of ConcRT and makes it easy for you to debug concurrency issues—unlike Visual Studio 2008, which had no awareness of higher-level parallel concepts. Visual Studio 2010 has a concurrency profiler that allows you to visualize the behavior of parallel applications. The debugger has new windows that visualize the state of all tasks in an application and their call stacks. Figure 1 shows the Parallel Tasks and Parallel Stacks windows.
Figure 1 Parallel Stacks and Parallel Tasks Debug Windows
IntelliSense and Design-Time Productivity
A brand-new IntelliSense and browsing infrastructure is included in Visual Studio 2010. In addition to helping with scale and responsiveness on projects with large code bases, the infrastructure improvements have enabled some fresh design-time productivity features.
IntelliSense features like live error reporting and Quick Info tooltips are based on a new compiler front end, which parses the full translation unit to provide rich and accurate information about code semantics, even while the code files are being modified.
All in response to changes in a header file.
IntelliSense live error reporting (the familiar red squiggles) displays compiler-quality syntax and semantic errors during browsing and editing of code. Hovering the mouse over the error gives you the error message (see Figure 2). The error list window also shows the error from the file currently being viewed, as well as the IntelliSense errors from elsewhere in the compilation unit. All of this information is available to you without doing a build.
Figure 2 Live Error Reporting Showing IntelliSense Errors
In addition, a list of relevant include files is displayed in a dropdown while typing #include, and the list refines as you type.
The new Navigate To (Edit | Navigate To or Ctrl+comma) feature will help you be more productive with file or symbol search. This feature gives you real-time search results, based on substrings as you type, matching your input strings for symbols and files across any project (see Figure 3). This feature also works for C# and Visual Basic files and is extensible.
Figure 3 Using the Navigate To Feature
Call Hierarchy (invoked using Ctrl+K, Ctrl+T or from the right-click menu) lets you navigate to all functions called from a particular function, and from all functions that make calls to a particular function. This is an improved version of the Call Browser feature that existed in previous versions of Visual Studio. The Call Hierarchy window is much better organized and provides both calls from and calls to trees for any function that appears in the same window.
Note that while all the code-browsing features are available for both pure C++ and C++/CLI, IntelliSense-related features like live error reporting and Quick Info will not be available for C++/CLI in the final release of Visual Studio 2010.
Other staple editor features are improved in this release, too. For example, the popular Find All References feature that is used to search for references to code elements (classes, class members, functions and so on) inside the entire solution is now more flexible. Search results can be further refined using a Resolve Results option from the right-click context menu.
Inactive code now retains semantic information by maintaining colorization (instead of becoming gray). Figure 4 shows how the inactive code is dimmed but still shows different colors to convey the semantic information.
Figure 4 Inactive Code Blocks Retain Colorization
In addition to the features described already, the general editor experience is enhanced in Visual Studio 2010. The new Windows Presentation Foundation (WPF)-based IDE has been redesigned to remove clutter and improve readability. Document windows such as the code editor and Design view can now float outside the main IDE window and can be displayed on multiple monitors. It is easier to zoom in and out in the code editor window using the Ctrl key and the mouse wheel. The IDE also has improved support for extensibility.
Build and Project Systems
Visual Studio 2010 also boasts and on individual developer machines.
C++ build processes are now defined in terms of MSBuild target and task files and give you a greater degree of customizability, control and transparency.
The C++ project type has a new extension: .vcxproj. Visual Studio will automatically upgrade old .vcproj files and solutions to the new format. There is also a command-line tool, vcupgrade.exe, to upgrade single projects from the command line.
In the past, you could only use the toolset (compiler, libraries and so on) provided with your current version of Visual Studio. You had to wait until you were ready to migrate to the new toolset before you could start using the new IDE. Visual Studio 2010 solves that problem by allowing you to target multiple toolset versions to build against. For example, you could target the Visual C++ 9.0 compiler and libraries while working in Visual Studio 2010. Figure 5 shows the native multi-targeting settings on the property page.
Figure 5 Targeting Multiple Platform Toolsets
Using MSBuild makes the C++ build system far more extensible. When the default build system is not sufficient to meet your needs, you can extend it by adding your own tool or any other build step. MSBuild uses tasks as reusable units of executable code to perform the build operations. You can create your own tasks and extend the build system by defining them in an XML file. MSBuild generates the tasks from these XML files on the fly.
Existing platforms and toolsets can be extended by adding .props and .targets files for additional steps into ImportBefore and ImportAfter folders. This is especially useful for providers of libraries and tools who would like to extend the existing build systems. You can also define your own platform toolset. Additionally, MSBuild provides better diagnostic information to make it easier for you to debug build problems, which also makes incremental builds more reliable. Plus, you can create build systems that are more closely tied to source control and the build lab and less dependent on developer machine configuration.
The project system that sits on top of the build system also takes advantage of the flexibility and extensibility provided by MSBuild. The project system understands the MSBuild processes and allows Visual Studio to transparently display information made available by MSBuild.
Customizations are visible and can be configured through the property pages. You can configure your project system to use your own platform (like the existing x86 or x64 platforms) or your own debugger. The property pages allow you to write and integrate components that dynamically update the value of properties that depend on context. The Visual Studio 2010 project system even allows you to write your own custom UI to read and write properties instead of using property pages.
Faster Compilation and Better Performance
In addition to the design-time experience improvements described so far, Visual Studio 2010 also improves the compilation speed, quality and performance for applications built with the Visual C++ compiler, as a result of multiple code generation enhancements to the compiler back end.
The performance of certain applications depends on the working set. The code size for the x64 architecture has been reduced in the range of 3 percent to 10 percent by making multiple optimizations in this release, resulting in a performance improvement for such applications.
Single Instruction Multiple Data (SIMD) code generation—which is important for game, audio, video and graphics developers—has been optimized for improved performance and code quality. Improvements include breaking false dependencies, vectorization of constant vector initializations, and better allocation of XMM registers to remove redundant loads, stores and moves. In addition, the__mm_set_**, __mm_setr_** and __mm_set1_** intrinsic family has been optimized.
For improved performance, applications should be built using Link Time Code Generation (LTCG) and Profile Guided Optimization (PGO).
Compilation speed on x64 platforms has been improved by making optimizations in x64 code generation. Compilation with LTCG, recommended for better optimization, usually takes longer than non-LTCG compilation especially in large applications. In Visual Studio 2010, the LTCG compilation has been improved by up to 30 percent. A dedicated thread to write PDB files has been introduced in this release, so you will see link time improvements when you use the /DEBUG switch.
PGO instrumentation runs have been made faster by adding support for no-lock versions of instrumented binaries. There is also a new POGO option, PogoSafeMode, that enables you to specify whether to use safe mode or fast mode when you optimize an application. Fast mode is the default behavior. Safe mode is thread-safe, but slower than fast mode.
The quality of compiler-generated code has been improved. There is now full support for Advanced Vector Extensions (AVX), which are very important for floating-point-intensive applications in AMD and Intel processors via intrinsic and /arch:AVX options. Floating-point computation is more precise with /fp:fast option.
Building Applications for Windows 7
Windows 7 introduced a number of exciting new technologies and features and added new APIs, and Visual Studio 2010 provides access to all the new Windows APIs. The Windows SDK components needed to write code for native Windows APIs are included in Visual Studio also makes it easier for you to write applications for Windows with the help of a beefed up MFC. You get access to substantial Windows 7 functionality through MFC libraries without having to write directly to native APIs. Your existing MFC applications will light up on Windows 7 just by recompiling. And your new applications can take full advantage of the new features.
MFC now includes improved integration with the Windows shell. Your application’s integration with Windows Explorer can now be much better by making use of the file handlers for preview, thumbnails and search that have been added in this release. These features are provided as options in the MFC Application Wizard as shown in Figure 6. MFC will automatically generate the ATL DLL project that implements these handlers.
Figure 6 MFC Application Wizard with File Handler Options
One of the most noticeable user interface changes in Windows 7 is the new taskbar. MFC allows you to quickly take advantage of features like jump lists, tabbed thumbnails, thumbnail preview, progress bars, icon overlay and so on. Figure 7 shows thumbnail previews and tabbed thumbnails for a tabbed MDI MFC application.
Figure 7 Tabbed Thumbnail and Thumbnail Preview in an MFC Application
The ribbon UI now has a Windows 7-style ribbon, too, and your application can swap the UI on the fly any time during development from several Office-style ribbons to the Windows 7 ribbon by using the style dropdown as shown in Figure 8.
Figure 8 Ribbon-Style Dropdown in an MFC Application
MFC enables your applications to become multi-touch aware and calls appropriate messages for you to handle when the various touch events occur. Just registering for touch and gesture events will route those events for your application. MFC also makes applications high-DPI-aware by default so they adapt to high-DPI screens and do not look pixelated or fuzzy. MFC internally scales and changes fonts and other elements to make sure your UI continues to look sharp on high DPI displays.
In addition to the new Windows 7 features, some other Windows features that have existed since Windows Vista but were not included in previous releases of MFC have been included now. For example, Restart Manager is a useful feature introduced in Windows Vista that enables an application to perform an application save before terminating. The application can invoke this feature and then restore its state when restarting. You can now take full advantage of Restart Manager in your MFC application to handle crashes and restarts more elegantly. Simply add a line of code to enable restart and recovery in your existing application:
New MFC applications get this functionality automatically by using the MFC Application Wizard. The auto-save mechanism is available to applications that save documents, and the auto-save interval can be defined by the user. Applications can choose only restart support or application recover start (applicable to Doc/View type applications) in the MFC Application Wizard.
Another addition is the Windows Task dialog, which is an improved type of message box (see Figure 9). MFC now has a wrapper for the Task dialog that you can use in your applications.
Figure 9 Task Dialog
MFC Class Wizard Is back
Not only has new functionality been added in the MFC library, this release also makes it easier to work with MFC in the Visual Studio IDE. One of the most commonly requested features, the MFC Class Wizard (shown in Figure 10), has been brought back and improved. You can now add classes, event handlers and other elements to your application using the MFC Class Wizard.
Figure 10 MFC Class Wizard
Another addition is the Ribbon Designer, which allows you to graphically design your ribbon UI (instead of defining it in code as in Visual Studio 2008) and store it as an XML resource. This designer is obviously useful for creating new applications, but existing applications can also take advantage of the designer to update their UIs. The XML definition can be created just by adding a line of code temporarily to the existing code definition of the ribbon UI:
The resulting XML file can then be consumed as a resource file and further modifications can be made using the Ribbon Designer.
Wrapping Up
Visual Studio 2010 is a major release in the evolution of Visual C++ and makes lives of developers easier in many ways. I have barely scratched the surface of various C++-related improvements in this article. For further discussion on different features, please refer to the MSDN documentation and to the Visual C++ team’s blog at blogs.msdn.com/vcblog, which was also used as the basis for some of the sections in this article.
Sumit Kumar is a program manager in the Visual C++ IDE team. He holds an MS degree in Computer Science from the University of Texas at Dallas.
Thanks to the following technical experts: Stephan T. Lavavej, Marian Luparu and Tarek Madkour
MSDN Magazine Blog
More MSDN Magazine Blog entries >
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. | https://msdn.microsoft.com/magazine/bf9bbe21-ca63-422d-8bfd-2c2f1514b93b | CC-MAIN-2017-39 | refinedweb | 4,324 | 51.18 |
Part 1: Using WebORB to access ActiveRecords from a Flex application. 5); }
IntroductionThere are several ways a Flex front-end can connect to a Rails application: via a RESTFul services (xml over html), via SOAP, and now also using WebORB from Midnight Coders (see). WebORB for Ruby on Rails is a server-side technology enabling connectivity between Flex and Flash Remoting clients and Ruby on Rails applications. WebORB and Flex provides an efficient way of encoding and decoding data using a binary protocol named AMF3 (Actionscript Message Format (I think)). This format is recognized by the Flash Player and provides an efficient way to communicate between a Flex application and a Ruby On Rails server.
This article will only investigate the WebORB usage, and we will not look into using SOAP or a RESTFul api. Part 1 of the article will show how to setup the Rails and the Flex applications to use WebORB, and how to retrieve data from the server. In subsequent parts of this article, I will comment my findings regarding updating data, security and performance issues and other aspect I discover during my investigation.
As you may not know, with Lee we wrote a similar server-side technology 18 months ago (flexonrails.com) which was based on AMF4R, but we where not satisfied with our findings at that time, nor with the qualitify of one of the library we where using, and the demand for integrating Flex and Ruby On Rails was non existent at that time, certainly due to the high price tag of Flex and the fact that not many developers were interested in both of these technologies as Flex was geared towards the enterprise and RoR was an open source framework. Since then Flex is free (not FlexBuilder, nor the DataServices), but everything we do in this article can be developed and deployed using free tools. Also Adobe is pushing quite hard to appeal to the open source community. I started this project using FlexBuilder for Mac, but I will also show how to compile the samples and tests using the flex command line compiler (mxmlc).
To download WebORB and to set it up I am following the instructions of. So for more details go see
For this article I will create a “fictional” application. For my customer I am directly integrating with the existing application. In fact using this fictional application will allow me to test the WebORB in many different ways. Note that my customers current front-end application is really cool. It is written in plain-old Rails, aka Ajax, html, css, rjs. Nevertheless we wanted to investigate if we can achieve similar functionality with less code using Flex and to identify the cost and benefits of such a development. I will spend a couple of days over the next weeks for this investigations.
These are the steps I followed for this article
1. Create a Rails app and add the WebORB plugin 2. Write a simple unit test to access some data using a RemoteObject a. create the Flex application using FlexBuilder. b. create the Customer ActiveRecord c. Write the FlexUnit test d. Write a small script to compile a Flex app from the command prompt. e. make the test pass. 3 . Use fixtures 4. Create a model (db+active record) 5. Write a test to retrieve the model 6. Provide a way to use fixtures from FlexUnit, so we can do some more testing.
1. Create a Rails app and add the WebORB plugin* Go to the folder where you want create your rails application and issue the following command:
rails rails
./script/plugin install
2. Write a simple unit test to access some data using a RemoteObject
We will put the flex applications in a folder named “flex” and put this folder next to the “rails” folder we create just before. Now lets download FlexUnit from. See Adobes wiki for more information ()
2.a) Creating a project in FlexBuilder* Create a FlexBuilder project (select Flex Data Services)
Root Folder: /Users/daniel/MyStuff/Projects/WebORBInvestigation/rails/config
Root Url:
Root Folder points to your Rails application config folder
Root Url points to the weborb controller.
* In the project properties set
Output folder: /Users/daniel/MyStuff/Projects/WebORBInvestigation/rails/public/flex
Output folder URL:
- Add the flexunit.swc (in the /bin folder of the FlexUnit downloads). A .swc is the compiled version of the FlexUnit framework.
2.b) create the Customer ActiveRecord
./script/generate model Customer
This generate the following files: exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/customer.rb create test/unit/customer_test.rb create test/fixtures/customers.yml create db/migrate create db/migrate/001_create_customers.rbNow edit db/migrate/001_create_customers.rb as follows:
class CreateCustomers < ActiveRecord::Migration def self.up create_table :customers do |t| t.column "name", :string t.column "address", :string end end def self.down drop_table :customers end end
rake migrate
./script/console >> Customer.create(:name => "Daniel", :address => "Denver") >> Customer.create(:name => "Samuel", :address => "Geneva") >> exit
2.c) Write a flex unit testOne of the issues with Flash and Flex unit testing of remote calls is the asynchronous nature of the remote calls. FlexUnit was based on JUnit and was mainly created for synchronous call testing. On one large project we dealt with this issue by splitting each test in two phases. The first phase performing calls and collecting data, we called it CallSequence, and the second phase to test the returned data. Since then, FlexUnit was extended with a nice feature allowing to test asynchronous calls. Look for the usage of the TestCase.addAsync method. It allows to notify that the current test method is waiting for a callback.
With this knowledge in mind let’s dive into writing the test. We want to retrieve the list of customers, ensure that their are two customers, and verify the name off one of the customers. This is what the test looks like:
package { import flexunit.framework.TestCase; import mx.rpc.remoting.RemoteObject; import flash.events.Event; import mx.rpc.events.ResultEvent; import mx.rpc.events.FaultEvent; public class WebORBReadOnlyTest extends TestCase { public function WebORBReadOnlyTest( methodName:String = null ) { super( methodName ); } // This method triggers a remote call and defines the event handler for the asynchronous response. public function testGetCustomerList():void { var asyncCall:Function = addAsync(onCustomerListResult, 1000); var dataService:RemoteObject = new RemoteObject(); dataService.destination = "DataService"; // Default WebORB ActiveRecord accessor dataService.addEventListener("result", asyncCall); dataService.addEventListener("fault", asyncCall); dataService.list("Customer"); } // This is the even handler trigger by the asynchronous response, let assert that we received what we expected. private function onCustomerListResult(event:Event, token:Object=null):void { assertTrue(event is ResultEvent); var data:Object = ResultEvent(event).result; assertEquals(2, data.length); assertEquals("Daniel", data[0].name); } } }
We also need a test runner
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:Script> <![CDATA[ import flexunit.framework.TestSuite; private function runTests():void { var ts:TestSuite = new TestSuite(); ts.addTestSuite( WebORBReadOnlyTest ); testRunner.test = ts; testRunner.startTest(); } ]]> </mx:Script> <!-- flexunit provides a very handy default test runner GUI --> <flexunit:TestRunnerBase </mx:Application>
2.d) Compile the unit test
The following script compiles the application from the command line (on OSX). That is, not using FlexBuilder. You may need to adapt for your needs. On windows it may be easier and you can maybe just refer to the mxmlc.exe. Not that I had to patch the flex-config file due to an compilation issue due to some missing fonts. You can try without the patch first. Let me know if that worked.
FLEX_HOME="/Applications/Adobe Flex Builder 2 Beta/Flex SDK 2/" cp flex-config-patched.xml "$FLEX_HOME/frameworks/" java -Xmx384m -Dsun.io.useCanonCaches=false -jar "$FLEX_HOME/lib/mxmlc.jar" -load-config "$FLEX_HOME/frameworks/flex-config-patched.xml" -library-path+=../flexunit/bin/flexunit.swc WebORBTestApp.mxml cp WebORBTestApp.swf ../../rails/public/flex
2.e) Run the unit test
Make sure the server is running and launch the flex test application.
Note that I had some red bars before I got the test to pass, but I wanted to spare these details.
Ok, this is quite some work just do test the dataService.list(“Customer”) call. However now I have an environment which I can use to go crazy on testing various aspects of the Flex and Ruby On Rails integration using WebORB.
3 . Extend WebORB to allow to write a FlexUnit test using fixtures
Without fixtures this test wouldn’t be very useful. We need a way to reset the fixtures between each test method invocation.
3.a) First let’s add a mechanism to reset the fixtures using WebORB
create the app/services/ActiveRecordService.rb file (note this is the naming convention for the WebORB services, I would rather use active_record_service.rb but I haven’t tried if that works.)
require 'weborb/context' require 'active_record/fixtures' class ActiveRecordService def create_fixtures(table_names) Fixtures.create_fixtures("#{RAILS_ROOT}/test/fixtures/", table_names, {}) end end
Now configure WebORB to recognize this new service. Add the following code to the config/WEB-INF/flex/remoting-config.xml file
<destination id="ActiveRecordService"> <properties> <source>ActiveRecordService</source> </properties> </destination>
A server restart is required when changing ActiveRecordService. When invoking create_fixtures this reloads the fixture based on the provided table names, however it overwrite the tables content of the database mode (development, test or production) for which you server is currently running in. I use the development mode during this exercise, so my weborb_development tables will be loaded with the fixtures.
3.b) Now let’s invoke the create_fixtures from our flex unit test.Warning, I haven’t found a nice way (yet) to transparently invoke the create_fixtures from the setup of the test. So for now each test method we will have three methods 1) that notifies that the test method is asynchronous and invokes the create_fixtures methods, 2) the callback of the create fixtures that will perform the ‘real’ remote call we want to perform, and 3) the callback of the ‘real’ remote call to perform the assertions. That’s when you wish that Flex supports directly synchronous calls. However this can be wrapped way nicer than I just did. I will certainly refactor this once I need to write more tests. Edit the rails/test/fixtures/customers.yml as follows:
first: id: 1 name: Daniel address: Littleton another: id: 2 name: Samuel address: Bernex
The test now looks as follows:
package { import flash.events.Event; import flexunit.framework.TestCase; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.rpc.remoting.RemoteObject; import mx.rpc.AsyncToken; import mx.collections.ItemResponder; import mx.controls.Alert; public class WebORBReadOnlyTest extends TestCase { public function WebORBReadOnlyTest( methodName:String = null ) { super( methodName ); } // The mechanism to invoke the server side create_fixtures method is still a little clunky here. // This should be part of the setUp method, which doesn't support asynchronous setUp for now. // So writing a test with fixture now requires three method (that's the really clunky part!) // 1. the testXXXXX method that must call the getActiveRecordService and the create_fixture method. // 2. the method that will actual call the server (here. doGetCustomerList) // 3. the result handler for the abort call that will perform the assert. public function testGetCustomerList():void { // getActiveRecordService - Signal to TestCase that this is an asynchronous test // and pass end point of the test method (in this case the onCustomerListResult method) var activeRecordService:RemoteObject = getActiveRecordService(onCustomerListResult); create_fixtures(["customers"], doGetCustomerList, activeRecordService); } private function doGetCustomerList(activeRecordService:Object):void { activeRecordService.list("Customer"); } // This is the even handler trigger by the asynchronous response, let assert that we received what we expected. private function onCustomerListResult(event:Event, token:Object=null):void { assertTrue(event.toString(), event is ResultEvent); // First param is message. var data:Object = ResultEvent(event).result; assertEquals(2, data.length); assertEquals("Daniel", data[0].name); assertEquals("Littleton", data[0].address); } private function getActiveRecordService(resultHandler:Function, timeOut:Number=2000):RemoteObject { var asyncCall:Function = addAsync(resultHandler, timeOut); var activeRecordService:RemoteObject = new RemoteObject(); activeRecordService.destination = "ActiveRecordService"; activeRecordService.addEventListener("result", asyncCall); activeRecordService.addEventListener("fault", asyncCall); return activeRecordService; } private function create_fixtures(table_names:Array, callback:Function, callbackData:Object):void { var activeRecordService:RemoteObject = new RemoteObject(); activeRecordService.destination = "ActiveRecordService"; var call:AsyncToken = activeRecordService.create_fixtures(table_names); call.addResponder(new ItemResponder(onCreateFixturesResult, onCreateFixturesFault)); call.callback = callback; call.callbackData = callbackData; } private function onCreateFixturesResult(event:ResultEvent, token:Object=null):void { event.token.callback(event.token.callbackData); } private function onCreateFixturesFault(event:Event, token:Object=null):void { fail("Failed to create fixtures. "+event.toString()); } } }
4. Implementing a deep find
With the default WebORB’s DataService implementation you cannot extract a Customer and his relationships (we will add them shortly) in one call. However this is where the AMF protocol really shines as nested structure can be serialized over http in one call. This is similar to what XML could provide but allows strongly typed objects to be mapped between Flex and Ruby On Rails. The current Customer model is not very representative for an application, so let’s extend our model as follows:
I know you may want to argue why is the ship_to/bill_to on the customer and not on the order. Hey, it’s just for testing purpose for now, just to have some richer relationships between objects :-)
4.1 Extending the Modelthe following command to generate the new models
./script/generate model Address ./script/generate model Order --skip-migration ./script/generate model Item --skip-migration
class CreateAddresses < ActiveRecord::Migration def self.up create_table :addresses do |t| t.column "street", :string t.column "zip", :string t.column "city", :string end create_table :orders do |t| t.column "customer_id", :integer t.column "created_at", :datetime end create_table :items do |t| t.column "order_id", :integer t.column "quantity", :integer t.column "product", :string end remove_column :customers, :address add_column :customers, "bill_to_address_id", :integer add_column :customers, "ship_to_address_id", :integer end def self.down drop_table :addresses drop_table :orders drop_table :items add_column :customers, :address, :string end end
class Customer < ActiveRecord::Base has_many :orders belongs_to :bill_to_address, :class_name => "Address", :foreign_key => "bill_to_address_id" belongs_to :ship_to_address, :class_name => "Address", :foreign_key => "ship_to_address_id" end class Address < ActiveRecord::Base belongs_to :customer end class Order < ActiveRecord::Base belongs_to :customer has_many :items end class Item < ActiveRecord::Base belongs_to :order end
first: id: 1 name: Daniel another: id: 2 name: Samuel
first: id: 1 street: First Street. zip: 80246 city: Littleton another: id: 2 street: Other Avenue. zip: 1200 city: Bernex
hardware_order: id: 1 customer_id: 1 bill_to_address_id: 1 book_order: id: 2 customer_id: 1 bill_to_address_id: 1
media_center: id: 1 order_id: 1 product: iTv quantity: 1 screen: id: 2 order_id: 1 product: 200" LCD Screen quantity: 1 remote: id: 3 order_id: 1 product: Remote Control quantity: 1 book1: id: 4 order_id: 2 product: Agile Web Development With Rails, 2nd Edition quantity: 1 book2: id: 5 order_id: 2 product: Mastering CSS quantity: 1
4.2 Add get to ActiveRecordServiceThe rails ActiveRecord.find method allows for the :include option to specify what relationship should be retrieved as part of the find. This will allow to perform 1 call and retrieve the customer, his address and all of his orders and order items.
Let’s extend ActiveRecordService as follows (we show only the new methods):
class ActiveRecordService # Allow for a deep fetch (find_by_id with :include options) def get(model_name, id, options={}) model_class = Object.const_get model_name find_options = {:include => options['include']} # Here we limit options for now. result = model_class.send(:find_by_id, id, find_options) puts result.inspect result end def find_all(model_name, options={}) model_class = Object.const_get model_name find_options = {:include => options['include']} # Here we limit options for now. result = model_class.send(:all, find_options) puts result.inspect result end end
4.3 Call the new get method from our flex unit test); }
Now that is getting more interesting. From flex in the doGetCustomerFirstCustomer method the following call activeRecordService.get(“Customer”, 1, options); returns the customer his addresses, his orders and all order items. It would be even nicer if we could call Customer.find(1, options).
i love the article on weborb and ruby!
keep up the great work, i look forward to seeing your future posts.
I wish you would have not spared the details about the red bars. My tests are failing.
Hi Stuart,
Please send me the details of your error here or to daniel@onrails.org. I could maybe point you in the right direction.
sent you an email.
I am new to flex. I am using flex builder 3 and rails for developing a application. I have tried all options but not able to configure flex builder 3 to use it with weborb(remote object). Does any one know how to do that? Please help me out. | http://onrails.org/articles/2006/10/29/part-1-using-weborb-to-access-activerecords-from-a-flex-application | crawl-002 | refinedweb | 2,744 | 50.53 |
I know there is documentation, however, can someone give a simple example (with steps) for installing/using a python module from the native python library in Splunk? If it is not native please example how to install it into SPL v 6.2.3
Any explanation how to get started with python in Splunk is appreciated.
Thank you
Generally speaking, you write a Python script that performs the needed functions and place it in your app's 'bin' directory. The script is then invoked either by a custom search command. See.
Hello, I was the same problem with Mysql module that I was install on my Centos server
Splunk didn't work with this library, because splunk has they own python library...then you can fix it only added on the begin your script all libraries of python and also you must to add the python Centos library too... as this way
[root@xxxx]#find / -name site-packages
/usr/lib/python2.7/site-packages
/usr/lib64/python2.7/site-packages
/opt/splunk/etc/apps/SplunkSAScientificPythonlinuxx8664/bin/linuxx8664/lib/python2.7/site-packages
/opt/splunk/lib/python2.7/site-packages
[root@xxxx]# whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/include/python2.7 /opt/splunk/bin/python /opt/splunk/bin/python2.7 /usr/share/man/man1/python.1.gz
include all at begin your script
import sys
sys.path.append('/usr/bin/python2.7')
sys.path.append('/usr/lib/python2.7/site-packages')
sys.path.append('/usr/lib64/python2.7/site-packages')
And that's it , you can run mysql module without any problem and create your alerts with this module.
import mysql.connector
I hope that this fix will help you
Joel Urtubia Ugarte
Generally speaking, you write a Python script that performs the needed functions and place it in your app's 'bin' directory. The script is then invoked either by a custom search command. See.
Hi Rich, I don't have an option to accept your answer. If your comment an answer then I will accept it. Thanks
That makes sense. Thank you
Python is built-in to Splunk so no installation is required. What do you want to do with Python? Are you creating a scripted input or something else?
Scenario: I need to look at all incoming email domains (e.g. sender@domain.tld) and compare them to a white list of domains to see if the new arrivals are typo-squatting, fuzzing, etc. (e.g. sender@domaininc.tld). I am not looking for exact matches but permutations of the white list.
I have tried "cluster" but it slows the search to a crawl. Therefore I was thinking of using some python scripts to do some of the heavy lifting (comparing). Maybe I am off track...
If you have any suggestions please let me know.
Of course, I am also interested in using python for other SPL enhancements as well.
Thank you | https://community.splunk.com/t5/Developing-for-Splunk-Enterprise/How-to-use-python-library-in-Splunk/td-p/279688 | CC-MAIN-2020-40 | refinedweb | 499 | 66.44 |
On Wed, 11 Aug 2010, Cyril Brulebois wrote: > right after installing debbugs-local, I had to resort to using dpkg -L > on it to determine which files it installed, given man debbugs[tab] > wasn't finding anything. Any particular reason to have different names > for package and binary? > > Not that it's important, just wondering whether that's on purpose. ;) Yeah, it's on purpose. It's a local debbugs version, thus local-debbugs; the package namespace, though, is debbugs, thus debbugs-local. However, given that at least four people have asked this very same question, it seems clear that it's not obvious to anyone else, so I probably need to drop in a debbugs-local symlink. | https://lists.debian.org/debian-debbugs/2010/08/msg00028.html | CC-MAIN-2017-26 | refinedweb | 118 | 61.87 |
tetrix in Scala: day 12
Yesterday we've created two stage actors so the agent can play against the player. To make things more interesting, attacking was implemented which sends junk blocks to the opponent.
unfair advantage
Thus far, the agent has been tuned to delete as many lines as it can. But yesterday we introduced attacking, which only kicks in after deleting two or more rows. This gives human side, who are aware of this change, an unfair advantage. Let's see what we can do.
Let's track line counts by the lines deleted in an action:
case class GameState(blocks: Seq[Block], gridSize: (Int, Int), currentPiece: Piece, nextPiece: Piece, kinds: Seq[PieceKind], status: GameStatus = ActiveStatus, lineCounts: Seq[Int] = Seq(0, 0, 0, 0, 0), lastDeleted: Int = 0, pendingAttacks: Int = 0) { def lineCount: Int = lineCounts.zipWithIndex map { case (n, i) => n * i } sum def attackCount: Int = lineCounts.drop(1).zipWithIndex map { case (n, i) => n * i } sum ... }
Here's modified
clearFullRow:
private[this] lazy val clearFullRow: GameState => GameState = (s0: GameState) => { .... val s1 = tryRow(s0.gridSize._2 - 1, s0) if (s1.lastDeleted == 0) s1 else s1.copy(lineCounts = s1.lineCounts updated (s1.lastDeleted, s1.lineCounts(s1.lastDeleted) + 1)) }
Now modify the scripting test a bit to print out the attack count:
println(file.getName + ": " + s.lineCount.toString + " lines; " + s.attackCount.toString + " attacks") (s.lineCount, s.attackCount)
Here are the results:
lines : Vector(34, 34, 32, 52, 29) attacks: Vector(4, 3, 3, 3, 1)
I can see how crevasse penalty can work against attacking, so let's increase the height penalty ratio from current 11:10 to 6:5.
h11:c10:v0 = lines : Vector(34, 34, 32, 52, 29) // 34 +/- 18 h11:c10:v0 = attacks: Vector(4, 3, 3, 3, 1) // 3 +/- 2 h6:c5:v0 = lines : Vector(31, 26, 25, 50, 29) // 29 +/- 21 h6:c5:v0 = attacks: Vector(4, 1, 0, 5, 1) // 1 +/- 4
The median actually dropped to 1. To apply the pressure to keep blocks as a chunk, we should bring back the cavity analysis:
h11:c10:v1 = lines : Vector(27, 30, 24, 31, 34) // 30 +/- 4 h11:c10:v1 = attacks: Vector(0, 3, 2, 3, 1) // 3 +/- 3
Maybe the problem with the cavity analysis is the the penalty calculation was too harsh in comparison with the others. Instead of piling up penalties for each block covering a cavity, why not just use height * height like crevasse:
val coverupWeight = 1 val coverups = groupedByX flatMap { case (k, vs) => if (vs.size < heights(k)) Some(coverupWeight * heights(k)) else None }
We'll denote this as
w1,
w2 for the amount of
coverupWeight.
h1:c1:w1 = lines : Vector(21, 14, 16, 23, 12) // 16 +/- 7 h1:c1:w1 = attacks: Vector(2, 0, 2, 2, 1) // 2 +/- 2 h11:c10:w2 = lines : Vector(22, 24, 28, 50, 37) // 28 +/- 22 h11:c10:w2 = attacks: Vector(1, 0, 2, 7, 1) // 1 +/- 6 h11:c10:w1 = lines : Vector(39, 24, 20, 51, 34) // 34 +/- 17 h11:c10:w1 = attacks: Vector(2, 1, 1, 7, 1) // 1 +/- 6 h22:c20:w1 = lines : Vector(39, 24, 24, 50, 34) // 34 +/- 17 h22:c20:w1 = attacks: Vector(2, 1, 3, 7, 1) // 3 +/- 4 h11:c10:w0 = lines : Vector(34, 34, 32, 52, 29) // 34 +/- 18 h11:c10:w0 = attacks: Vector(4, 3, 3, 3, 1) // 3 +/- 2 h2:c1:w1 = lines : Vector(16, 10, 6, 18, 14) // 14 +/- 8 h2:c1:w1 = attacks: Vector(1, 0, 0, 1, 0) // 0 +/- 1
Another possibility may be to further weaken the penalty by using a constant instead of height, which we will use
k1,
k2:
h11:c10:k2 = lines : Vector(34, 34, 32, 38, 29) // 34 +/- 5 h11:c10:k2 = attacks: Vector(4, 3, 3, 5, 1) // 3 +/- 2 h11:c10:k1 = lines : Vector(34, 34, 32, 38, 29) // 34 +/- 5 h11:c10:k1 = attacks: Vector(4, 3, 3, 5, 1) // 3 +/- 2 h11:c10:k0 = lines : Vector(34, 34, 32, 52, 29) // 34 +/- 18 h11:c10:k0 = attacks: Vector(4, 3, 3, 3, 1) // 3 +/- 2
In terms of the attacks per lines h11:c10:k1 is looking good, so we'll use this for now.
android
It would be cool if we can show this game off on a cellphone, so let's port this to Android. First install Android SDK or update to the latest SDK if you can't remember the last time you updated it by launching
android tool from command line:
$ android
As of August 2012, the latest is Android 4.1 (API 16). Next, create an Android Virtual Device (AVD) using the latest API.
Next we need sbt's android-plugin. Create
project/plugins.sbt and add the following:
resolvers += Resolver.url("scalasbt releases", new URL(""))(Resolver.ivyStylePatterns) addSbtPlugin("org.scala-sbt" % "sbt-android-plugin" % "0.6.2")
And add the following to
project/build.scala:
lazy val android = Project("tetrix_android", file("android"), settings = buildSettings ++ Seq( platformName in Android := "android-8", versionCode := 7 ) ++ AndroidProject.androidSettings ++ AndroidManifestGenerator.settings ++ TypedResources.settings ++ Seq( )) dependsOn(library)
When you reload sbt, we should be able to launch emulator as follows:
> project android > android:emulator-start test_adv16
To install your app on the emulator and start it:
> android:start-emulator
To install on a phone:
> android:install-device
hello world
An Android apps consists mainly of activities, views, and threads. For tetrix, we just need to get a handle to the
Canvas object to draw things, so activities and views become fairly simple. I will stuff most of the logic in a thread, which I am not sure is the right approach.
Here's the activity class:
package com.eed3si9n.tetrix.droid import android.app.Activity import android.os.Bundle class MainActivity extends Activity { override def onCreate(savedInstanceState: Bundle ) { super.onCreate(savedInstanceState) setContentView(R.layout.main) } }
The layout file is
android/src/main/res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: <com.eed3si9n.tetrix.droid.MainView android: </LinearLayout>
This points to
MainView:
package com.eed3si9n.tetrix.droid import android.content.Context import android.util.AttributeSet import android.view.{View, SurfaceView, SurfaceHolder, GestureDetector, MotionEvent} class MainView(context: Context, attrs: AttributeSet) extends SurfaceView(context, attrs) { val holder = getHolder val thread = new MainThread(holder, context) holder addCallback (new SurfaceHolder.Callback { def surfaceCreated(holder: SurfaceHolder) { thread.start() } def surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { thread.setCanvasSize(width, height) } def surfaceDestroyed(holder: SurfaceHolder) {} }) setFocusable(true) setLongClickable(true) setGesture() def setGesture() { val gd = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { override def onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean = { thread.addFling(velocityX, velocityY) true } }) setOnTouchListener(new View.OnTouchListener() { def onTouch(v: View, e: MotionEvent): Boolean = gd.onTouchEvent(e) }) } }
Finally, in order to manage my own repaint, I am going to run a thread in an infinite loop:
package com.eed3si9n.tetrix.droid import com.eed3si9n.tetrix._ import android.content.Context import android.view.{SurfaceHolder} import android.graphics.{Canvas, Paint, Rect} class MainThread(holder: SurfaceHolder, context: Context) extends Thread { val quantum = 100 var canvasWidth: Int = _ var canvasHeight: Int = _ val bluishSilver = new Paint bluishSilver.setARGB(255, 210, 255, 255) override def run { var isRunning: Boolean = true while (isRunning) { val t0 = System.currentTimeMillis withCanvas { g => g drawText ("hello world", 10, 10, bluishSilver) } val t1 = System.currentTimeMillis if (t1 - t0 < quantum) Thread.sleep(quantum - (t1 - t0)) else () } } def setCanvasSize(w: Int, h: Int) { canvasWidth = w canvasHeight = h } def addFling(vx: Float, vy: Float) { val theta = math.toDegrees(math.atan2(vy, vx)).toInt match { case x if x < 0 => x + 360 case x => x } // do something } def withCanvas(f: Canvas => Unit) { val canvas = holder.lockCanvas(null) try { f(canvas) } finally { holder.unlockCanvasAndPost(canvas) } } }
The above would print out "hello world" at 10 frames per second. The rest is just the matter of hooking things up.
akka 1.3.1
I chose the latest stable Scala 2.9.2 and Akka 2.0.2, which was the latest when I started. The problem is that Akka 2.0.2 doesn't seem to work on Android easily. On the other hand, for older version of Akka there's an example application gseitz/DiningAkkaDroids that's suppose to work. It wasn't much work, but I had to basically downgrade Akka to 1.3.1.
Here are some of the changes. Instead of an
ActorSystem,
Actor singleton object is used to create an actor. Names are set using
self.id:
private[this] val stageActor1 = actorOf(new StageActor( stateActor1) { self.id = "stageActor1" }).start()
Grabbing the values from
Future is much simpler. You just call
get:
def views: (GameView, GameView) = ((stateActor1 ? GetView).mapTo[GameView].get, (stateActor2 ? GetView).mapTo[GameView].get)
Instead of the path, you can use
id to lookup actors:
private[this] def opponent: ActorRef = if (self.id == "stageActor1") Actor.registry.actorsFor("stageActor2")(0) else Actor.registry.actorsFor("stageActor1")(0)
I had to implement scheduling myself using
GameMasterActor, but that wasn't a big deal either.
UI for Android
Android has its own library for widgets and graphics. They are all well-documented, and not that much different from any other UI platforms. I was able to port
drawBoard etc from swing with only a few modification.
var ui: Option[AbstractUI] = None override def run { ui = Some(new AbstractUI) var isRunning: Boolean = true while (isRunning) { val t0 = System.currentTimeMillis val (view1, view2) = ui.get.views synchronized { drawViews(view1, view2) } val t1 = System.currentTimeMillis if (t1 - t0 < quantum) Thread.sleep(quantum - (t1 - t0)) else () } } def drawViews(view1: GameView, view2: GameView) = withCanvas { g => g drawRect (0, 0, canvasWidth, canvasHeight, bluishGray) val unit = blockSize + blockMargin val xOffset = canvasWidth /) }
withCanvas is a loan pattern that ensures that the canvas gets unlocked. The only thing is that there's no keyboard on newer phones. Here's how we can translate gesture angles into actions:
def addFling(vx: Float, vy: Float) { val theta = math.toDegrees(math.atan2(vy, vx)).toInt match { case x if x < 0 => x + 360 case x => x } theta match { case t if t < 45 || t >= 315 => ui map {_.right()} case t if t >= 45 && t < 135 => ui map {_.space()} case t if t >= 135 && t < 225 => ui map {_.left()} case t if t >= 225 && t < 315 => ui map {_.up()} case _ => // do nothing } }
Let's load it on the emulator:
> android:start-emulator
It was a bit shaky but it did showed up on the emulator.
I was hoping it runs on multicore androids, and it did! It ran smoothly on a borrowed Galaxy S III.
Anyway, this is going to be the end of our tetrix in Scala series. Thanks for the comments and retweets. I'd like to hear what you think. Also, if you are up for the challenge, send me a pull request of a smarter agent-actor that can beat human! | http://eed3si9n.com/node/87 | CC-MAIN-2017-34 | refinedweb | 1,795 | 57.06 |
Introduction
This article will teach you how to authenticate users with Django in a simple, quick, and secure manner. You'll also learn how to require authentication on certain pages of your website, and how to gracefully handle login and logout functionality.
The target audience is people who have had minimal experience with Django, and are aware of how Django works in a basic manner.
What Are We Building?
To demonstrate how user authentication works, we'll be building an extremely minimalistic website and user portal. We'll create a home page that directs users to the web portal (which is for authenticated users only). We'll create a login page, a logout page, and a basic web portal home page.
The goal of this article is not to teach you web design, or how to make websites, but merely to show you how simple user authentication can be with Django.
What's Needed?
- Django 1.0 or later.
Create a New Project
Before we get started, create a new Django project. For the rest of this article, we'll be building a website for the fictitious company “Django Consultants”.
Be sure to create a user account when you run the:
python manage.py syncdb
Command, as you will need that later to test your login.
Determine URLs
There are many ways to design a website, but I prefer to build the URL schema first, then build the site to match the URL schema. So let's decide on what URLs we will need now. If you are going to build a real website and not just this simple example, feel free to add whatever else you need.
- / - main page - Show the company logo and direct users to a login portal.
- /login/ - login page - Allow users to log in.
- /logout/ - logout page - Allow users to log out.
- /portal/ - portal home page - Main web portal page. Should require authentication to be visited.
This should be sufficient for what we are doing.
Configure Django Settings
Below is my settings.py for the project. Make changes where necessary.
Take note of the LOGIN_URL setting. This needs to be changed to whatever URL your login view will be at. For us, this should be /login/, as that is the URL we decided will supply users with a login page.
Everything else is pretty standard. Nothing special going on.
Write Our urls.py
Now let's write our main urls.py file which will control what content is served based on our URL schema.
There are two things to notice here. First off, the login view:
(r'^login/$', 'django.contrib.auth.views.login')
Is defined as using 'django.contrib.auth.views.login' which is a pre-defined view for logging in users. We won't need to make any changes to this, as it does all of the Django magic to securely authenticate users.
Next, you'll notice that the view for our web portal will be part of a separate application:
(r'^portal/', include('portal.urls'))
You don't have to do it this way, but breaking your website up into independent applications is useful for keeping logic separated. For example, a login and logout are useful to have as part of your main site (eg: not in an application) because you may have multiple parts of your website that perform different actions but that all require authentication for users to access. In our case, one of these applications will be a user portal, so we'll be making it into a separate application.
Writing the Views
Now that we've defined the URLs for our site, let's go ahead and write the views that our main site will use. Here's the views.py:
Since the login page already has a view defined (thanks to django.contrib.auth), we only need to define our main page (which will tell users to go to the portal) and a logout page that allows users to logout anywhere on the website.
The main_page view is pretty simple, it just renders an index.html template (don't worry, we'll write all of the templates later).
The logout_page view calls the logout function on the request object. This magically logs users out and kills their sessions. After logging them out, we then direct them back to the main page of the website. You can always spice this up (by adding a custom log out page or something), but for simplicity's sake, we will just send them back home.
Create the Portal Application
Now let's create our web portal application. We'll call it portal and it will be used to display the portal homepage and other portal functionality (if you choose to add it):
Determine the Portal URLs
Again, let's quick write up a URL schema for our portal application. If you are designing an actual website, you'll want to add more functionality. For now, all we will do is create a single page (that will be accessed via /portal/) which gives users some basic options.
- / - main page - Will display the home of the login portal and give users a menu of options.
Write the Portal urls.py
Now that we've come up with a schema for our portal application, let's implement it and write the urls.py:
Nothing complicated here. Moving on.
Write the Portal Views
Now let's write our portal views:
This is where things get interesting. Since we decided a while back that our /portal/ page was going to require users to be authenticated, we are going to import the login_required function from djang.contrib.auth. This decorator allows us to specify which views require users to be authenticated to use! All we need to do is place
@login_required
Above each view definition that we have which requires user authentication, and BAM. Everything magically works!
If you were to visit /portal/ without being logged in, the login_required function would see that you are not authenticated, and would read the variable value in your settings.py file called LOGIN_URL which currently contains '/login/', and would then direct you to the login page. Pretty awesome right? Full user authentication in only 1 line of code!
Creating the Templates
Now that we've done all the hard work, let's go ahead and write our templates.
To start, let's create all of the necessary directories and files:
Next, let's define a generic template (base.html) for our main pages to use as a generic template. Since I like to do things fancy, we might as well make it HTML5 :)
Now that we have a base template, let's create the main page of the website (index.html) as our main_page view renders:
At this point, we've got the basic templates done for the main page of our website. Mind you, they are very basic. The next thing we need to do is create a template for our user portal page. So let's do that:
This is a generic template which will be used for all portal pages. As you can see, there isn't much functionality except to return to the main page and logout. If you are developing an actual portal, you'll obviously want to add lots more features! Now we'll create the actual portal home page:
This page is special in that it uses the:
{{ user.username }}
Variable to print the user name of the logged in user. The Django authentication system passes the user object to each template that requires authentication (using the login_required decorator), that we can use to fetch information on the user. In this case, we are going to display a simple welcome message.
The last thing we need to do is create a template for our login page (remember that it uses the magical view that we didn't have to write?) Here it is:
Now, as you can see, we create a form which performs a POST to itself. This lets the django login view do its magic. The interesting thing here are the hidden fields and how they are processed:
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% else %}
<input type="hidden" name="next" value="/portal/" />
{% endif %}
The hidden field next is special to the login view. It determines where the user is re-directed to after logging in. Let's say, for example, that a user visits our homepage, and clicks the link there that directs them to /portal/. Since /portal/ requires authentication, it will direct the user to the URL /login/?next=/portal/. This GET argument is sent automatically by the login_required decorator to help inform the login page of where to direct the user after they've logged in.
Our code above says "If the user requests a page, and they are not authenticated--then direct them to the login page, and after they've logged in send them back to the page they originally requested. If the user simply visited the /login/ page directly, then by default send them to /portal/ once they've logged in.
This is the correct way to handle login and redirection in complex websites as it gives users the maximum amount of flexibility. Don't you just hate it when you try to visit a website and get into an important protected section, only to discover that after you've logged in you are redirected to the main page instead of the page you were trying to get to? You won't have that problem using Django's auth as long as you implement the login template as we did above.
Test It Out
We're done. So give everything a test. Go to your django_consultants directory and run the command
python manage.py runserver
To start up the development webserver. Then open a browser and visit.
You should be greeted by the main page, and provided with a link to log into the web portal. So click the portal link, and since you are not authenticated, you will be directed to the login page.
Now log in using the username and password you generated when you ran
python manage.py syncdb
And you'll see the portal home page! Feel free to play around with logout / login / etc.
Where to Go From Here
For more information and advanced usage of Django authentication, check out the official documentation here:. The best way to learn is to play around with things, test them out, and get a good feel for how everything works.
Conclusion
Hopefully this article has helped you understand how Django authentication works, and how easy it is to add secure authentication to your website without going through too much trouble. If you have any questions, suggestions, or anything else, leave a comment and I'll try to answer it. | http://neverfear.org/blog/view/97/User_Authentication_With_Django | CC-MAIN-2016-50 | refinedweb | 1,807 | 72.56 |
I am making a program that calculates the price of apples (its a school one). To throw in a twist they made it so when you buy one apple you get one free. I am not aloud to use the "if" feature in this program. It is driving me crazy, I don't know how to make it so when I buy 3 apples it shows up as 2 dollars because of this whole buy one get one free thing.
Here is the code I have so far.
Code:#include <cstdlib> #include <iostream> #include <string> using namespace std; double apple (double first,double second); int main(int) { //vars string username; //Users name. double usra,usrap=1.00; //Users choice of Appales. double usro,usrop=1.50; //Users choice of Oranges. double applecal; //Apple calculations. double orangecal; //Orange calculations. //vars end //sig cout<<"*********************************************************"<<endl; cout<<"* *"<<endl; cout<<"* Nicks Grocery store *"<<endl; cout<<"* *"<<endl; cout<<"*********************************************************"<<endl; cout<<endl; //sig end //Program cout<<"Welcome to Nick's Grocery Store."<<endl; cout<<endl; cout<<"****Todays Specials.*****"<<endl; cout<<"*Buy one Apple get one *"<<endl; cout<<"*free! *"<<endl; cout<<"*-----------------------*"<<endl; cout<<"*Each Orange you buy *"<<endl; cout<<"*deducts 1% off your *"<<endl; cout<<"*bill. *"<<endl; cout<<"*************************"<<endl; cout<<"Max of 100 items per customer"<<endl; cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"<<endl; cout<<endl; //Asks for Users name. cout<<"Enter your name :"; cin>>username; cout<<endl; //Asks how many Apples the User wants. cout<<"How many Apples would you like "<<username<<" :"; cin>>usra; cout<<endl; //Asks how many Oranges the User wants. cout<<"How many Oranges woukd you like "<<username<<" :"; cin>>usro; cout<<endl; cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"<<endl; applecal= apple(usra,usrap); cout<<applecal<<endl; //Program end } double apple(double first,double second)//Math for Apples { return first*second; } | http://cboard.cprogramming.com/cplusplus-programming/74341-buy-one-get-one-free-problem.html | CC-MAIN-2014-23 | refinedweb | 287 | 66.44 |
from
It’s cool, and shit.
I really couldn’t stand the CommonJS
require() implementation that started
shipping with Node as of v0.1.16. So, I sat down to design, and
later (when it was met by deaf ears), implement, a
replacement. This is that; originally implemented as a part of
poopy.js,
from has now split off into its own project.
The
from system supports Python-style ‘index’ files for packages, as well as
an analogue to Python’s
import … from feature.
from also features Ruby-
style ‘a file is just a package’ (which also, more importantly, could be
thought of as ‘a package is just a file’), and quite a few concepts I haven’t
seen in any other
require()-esque system to date.
All in all, there’s two halves to
from. There’s the ‘dumb’ half, which
simply operates on paths you give it, and the ‘intelligent’ half, that locates
and operates on packages of its own volition.
from also supports modifying how files are handled once they are found,
through
import() and
export(). We’ll get to that later.
frombasics
Every
from method works in basically the same way: A file is located, and
then it is evaluated. If, within that file, you (the package author) utilize
the
return keyword, then the value you choose will be returned to the
person acquiring your code via
from.
In other words,
from will help users find your code, but it’s up to you
what your code gives back.
Also,
from is fully asynchronous, in true Node spirit. Every
node API
method returns a
process.Promise; you’ll have to either provide a callback
to be executed when the target is acquired, or use
Promise.wait() to force
a sync
from.
from.absolute()and
from.relative()
The first half, the ‘dumb’ half of
from, is very basic. It’s provided
through two APIs; the
absolute() API and the
relative() API. The former,
absolute(), works exactly as it sounds: it, given an absolute path,
evaluates the file found at that path, and hands you the result.
from.absolute('/foo/bar/baz/qux.js').addCallback(function (qux) { // … });
The second of those two,
relative(), bears a little more discussion. It
locates files relative to the file calling out to
from, i.e. the
requesting file. Unfortunately, doing so is not all that easy; due to various
restrictions,
from.relative() can only operate within
from’s ‘world,’ so
to speak. Specifically, this means it won’t operate in a file you run with the
node binary, nor will it work in a file you acquired with
require()
instead of
from.absolute() (those two are, in fact, the same thing; the
node binary simply
require()s the file at the path you give it on the
command line).
var aQux = from.relative('baz/qux.js').wait();
To work around this, I provide
node-from as a binary that preemptively
initializes the
from interface, such that
from.relative() (and, as you’ll
see later,
from.package()) can operate as designed. Any JavaScript file run
from the command line with
node-from will have all of the
from APIs
immediately available for use.
> node-from baz/qux.js
from.package()
Most of
from’s usefulness comes from its package support. Given some library
paths (usually already provided through
process.paths, which defaults to a
system-wide
lib/node/libraries directory, and a user-local
~/.node_libraries directory), it will find and acquire code distributed in a
‘library.’
from.package('aPackage/thing').import().wait;
Unlike most package managers, there are no ‘gems’ or ‘eggs’ (I’m looking at
you, Ruby glares), thus greatly reducing complexity. A ‘library,’ for all
from cares, is simply a distributed folder of code, with a sub-folder named
‘lib’ that is full of code (specifically, full of ‘packages’). These package
libraries will generally be structured like this:
myLibrary/ ChangeLog lib/ aPackage.js LICENSE README
from supports this, though it also supports more complex structures, such as
the following:
myLibrary/ bin/ a_package (+x) ChangeLog lib/ aPackage.js aPackage/ something.node subPackage/ subPackage.js bit.js otherBit.js separatePackage/ separatePackage.js LICENSE README
There’s a lot more to be said about how
from.package() expects libraries of
packages (and the packages themselves) to be structured, and what it supports;
you can read
STRUCTURE.markdown for more information on that
topic than will be presented here.
from supports moving objects back and forth between the compilation units of
the requesting file, and the
from’d file. Specifically, you can ship values
to the target file with
export(), and retrieve them from it with
import().
export() will make values available to the scope of the file you are
acquiring. This is useful inside libraries, to make your root objects
available to subpackages.
// Exposes `thing` from this scope as `parentThing` in the `from`’d file var subThing = from.relative('myThing/subThing.js') .export({ 'parentThing' : myThing }).wait();
import() preforms the opposite task, of bringing values from the file you
are acquiring into your context. However, you also have to pass it a target
object into which you wish the elements to be imported, or it will use the
GLOBAL namespace (which is, generally, a bad thing).
// Exposes `foo` and `bar` from `subThing.js` on `myThing` from.relative('myThing/subThing.js').import('foo', 'bar', myThing);
Unfortunately, there’s no easy way to distribute or install packages for
Node.js at the moment. On top of that, if there were, it would probably be
specific to packages prepared for
require()’s broken semantics, and thus be
incompatible with
from anyway.
This means installation … is a bit of a bitch.
from
First off, you have to get the
from source. If you have
git, that’s as
easy as:
git clone git://github.com/elliottcable/from.git elliottcable-from
If not, you have to acquire a tarball of the source, and extract it:
> wget '' \ -O 'elliottcable-from-Master.tar.gz' > tar -x -f 'elliottcable-from-Master.tar.gz'
from
We want to move the
from source such that it will be accessible to
require() and
from… while also ensuring the
node-from binary is in
your
$PATH.
My preferred method is to store (or link) the
from sourcecode in your
user-local
~/.node_libraries folder, then link the
from.js file itself
into that same file, and finally link
node-from into your user-local
~/.bin folder (ensuring that folder is in your
$PATH). For instance:
> mv elliottcable-from*/ $HOME/.node_libraries/from > ln -s from/lib/from.js $HOME/.node_libraries/from.js > ln -s ../.node_libraries/from/bin/node-from $HOME/.bin/
You could just as well install
from into the system-wide directories as a
root user, but that’s even more painful.
Hopefully, someday, we’ll have a friendly package management system to do this for us; today is not that day. | https://www.npmjs.com/package/paws | CC-MAIN-2017-26 | refinedweb | 1,144 | 66.13 |
Thin is fast, I don’t think I need to prove that again. But what I’d like to showcase now is Thin extensibility. Most of it is due to Thin being based on Rack. It’s also why lots of framework are supporting Thin already.
Can Thin replace all images with LOLCAT pics on my site when it’s my birthday of a leap year, plz, plz, plz? Cause it should!
Yeah, you’re not the first one to ask.
config.ru file
require ‘open-uri‘ require ‘hpricot‘ class LolCater def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) if iz_ma_burdae? && leap_year? doc = Hpricot(body) doc.search(‘img‘).set(‘src‘, lolcat_pic_url) body = doc.to_html end [status, headers, body] end private def iz_ma_burdae? Date.today.month == 11 && Date.today.day == 7 end def leap_year? Date.today.leap? end def lolcat_pic_url doc = Hpricot(open(‘‘)) pic = (doc/‘div.snap_preview img‘).first.attributes['src'] end end use LolCater run Rack::Adapter::Rails.new(:root => ‘/path/to/my/app‘)
That’s called a Rack middleware. It must have a
call method and receive a Rack app as the first argument of
new. You then tell Thin to use this middleware when running your Rails application. Save the file as
config.ru. .ru is for Rackup config file.
You can now launch your application with the
thin script:
thin start --rackup config.ru
Wai-wai-wait that means I can built my own framework in like 30 LOC and use all of Thin goodness?
Right! You can start a cluster of your lolcat image replacer app like you would for a Rails app, but specify the
--rackup option, which tell Thin to load your application from this file instead to go with the default Rails adapter.
thin start --rackup config.ru --servers 3
In fact, here’s a lil’ framework I built in 35 LOC:
# Start w/ thin start -r invisible.rb require ‘tenjin‘ module ::Invisible class Adapter def initialize @template = Tenjin::Engine.new(:postfix=>‘.rbhtml‘, :layout=>‘../layout.rbhtml‘, :path=>‘home‘) @file = Rack::File.new(‘public‘) end def call(env) path = env['PATH_INFO'] if path.include?(‘.‘) @file.call(env) else _, controller, action = env['PATH_INFO'].split(‘/‘) Invisible.const_get("#{(controller || ‘home‘).capitalize}Controller").new(@template, env).call(action || ‘index‘) end end end class Controller def initialize(template, env) @template, @status, @env, @headers = template, 200, env, {‘Content-Type‘ => ‘text/html‘} end def call(action) send(action) render(action) unless @body [@status, @headers.merge('Content-Length'=>@body.size.to_s), [@body]] end protected def render(action=nil) @body = @template.render(action.to_sym, instance_variables.inject({}) {|h,v| h[v[1..-1]] = instance_variable_get(v); h}) end end end require ‘app/controllers‘ run Invisible::Adapter.new
Full code on my github repo:.
And you know I can’t help myself but benchmark it:
merb-core: 1865.19 req/sec
invisible: 2428.17 req/sec
(Disclamer: it’s just for fun, don’t use that framework ever or I will come in your house when you sleep and steel all your left foot socks).
Democratizing deployment
I don’t know if you get what this means? It means, deploying a Rails or Merb, Ramaze, etc, app is just a matter of writing a simple Rack config file and playing w/ the –rackup option. It’s all the same script and tools now!
For example, there’s a Ramaze Rack config file in example/ramaze.ru, so to deploy your Ramaze application you would.
thin start --servers 3 --rackup ramaze.ru
Or create a config file and install it as a runlevel script:
thin config --rackup ramaze.ru -C myapp.yml edit myapp.yml sudo thin install # Installs the runlevel script mv myapp.yml /etc/thin/myapp.yml
Or if you prefer to monitor your clusters with God, check out the sample God config file that is a drop-in replacement for Thin’s runlevel script.
Happy hacking & deploying!
You have a bug in LolCater#is_ma_burdae?
def iz_ma_burdae?
Date.today == Date.new(1981, 11, 7)
end
That would only return true on the day you were born (in 1981!), which will never happen again.
yay, thanks for catching this, now I can hope my birthday to come again next year!
I’m a bit late to comment on this post, but here I am anyways.
When I started developing Halcyon with Rack, I didn’t really comprehend the implications of serving Halcyon; I thought I’d have to write the server, et al. But with Rack and now Thin supporting Rackup config files, I have decided to remove all of the “server” code from Halcyon and just depend primarily on Thin (though with the rackup runner the deployer can use whichever inferior server the deployer chooses to run with).
This makes my framework a great deal simpler, thankfully. Now I can focus on more important issues rather than serving and performance (well, on the performance of serving Halcyon apps, anyways; performance is always a concern).
hey matt,
That’s very cool. Rack is changing a lot of stuff in the web ruby world these days and it’s all for the best. We can now all focus on what makes our app special.
well done, guy
so you’re saying that being thin is an advantage on being a better gymnast? I’m a gymnast and im not thin but im not fat and i do fairly well for a starter. im doing a report on why gymnasts like me go anorexic and this popped up. it could be helpful to my paper for school.thanks much. | http://macournoyer.wordpress.com/2008/02/09/the-flexible-thin-anorexic-gymnast-that-democratized-deployment/ | crawl-001 | refinedweb | 929 | 67.65 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?: 1974 .
FOREWORD
We are happy to present to all members of the Divine Life Societies in India and abroad as well as to spiritual seekers in general, these thoughts of Revered Sri Swami Chidanandaji that cover a variety of matters, all of which are however connected directly or indirectly with spiritual life and ethical ideals of man. These expressions of his inner feelings and thoughts were communicated from time to time to the world of seekers and spiritual aspirants, through a series of letters which Revered Swamiji wrote each month addressing the members of the Divine Life Society all over the world. They appeared under the caption of: “The President Writes” and later on as: “Sivanandashram Letter”. The contents of this present handy little book comprise such monthly letters written over a period of five to six years soon after the passing of the Most Worshipful Master, Sri Swami Sivananda Gurudev. From the Holy Ashram in Rishikesh Revered Swamiji kept contact with the spiritual fraternity of all sincere seekers striving to lead a divine life by means of these monthly letters. These letters bring you in touch with Swamiji’s views and vision which he seeks to share with you all. We owe this publication to the generous and loving gift of Mother Yvounne Lemoine of France, who had the eager desire that some inspiring teachings of Revered Swami Chidanandaji must be made available especially to the seekers in France and other European countries as well as the West in general during the occasion of his present birthday on 24th September 1974. Thus the present volume comes as a Birthday Gift from Mother Yvounne to all those who have had the opportunity of meeting Swami Chidanandaji and listening to his teachings during his travels abroad. Our deepest appreciation of her generous goodwill towards all. A special word of thanks is due to the Manchandani Brothers Proprietors of the Nilum Printing Press who very kindly worked with great earnestness to accomplish the printing work within less than three weeks in order to bring out this book in time. Our very grateful thanks to them. 24th September 1974 DIVINE LIFE SOCIETY
iii
CONTENTS
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii To Awaken You Sivananda Gurudev Came. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Who Is Divine Mother Durga? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Let Virtue Rule Thy Life! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Start A New Life Now . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Resolve To Follow Divine Life . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Noble Task Of True Discipleship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Strive To Live Ideal Life . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 May The Great One Inspire You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Make Renunciation The Basis Of Your Life And Actions. . . . . . . . . . . . . . . . . . . . 16 Enshrine Thy Guru In Thy Heart! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Practice Gita Teachings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 How Best To Celebrate Sivananda-Jayanti. . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Ma Anand Mayee Graces Sivananda-Jayanthi-Celebrations. . . . . . . . . . . . . . . . . . . 24 Strive To Make Life A Perennial Divali . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 The Mystery Of The Supreme Divinity Is Revealed In Srimad Bhagwad Gita And The Bible . 29 The Holy Trail Blazed By The Lives Of Saints . . . . . . . . . . . . . . . . . . . . . . . . . 32 Tour In The South. Meeting With Dadaji. The Chandigarh Conference. . . . . . . . . . . . . 34 The Spirit Of Mahasivaratri. Tour Of Gujarat . . . . . . . . . . . . . . . . . . . . . . . . . . 38 The Birthday Of Lord Rama. Glory To His Name . . . . . . . . . . . . . . . . . . . . . . . . 39 Fresh Beginnings: New Undertakings. Gurudev’s Birthday Anniversary. Special Message To Sadhaks Who Attended Sadhanasaptah At Headquarters During July 1965. . . . . . . . . . . 42 th Swami Chidananda’s 50 Birthday Message. . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Sow the Seeds of Love, Peace and Brotherhood . . . . . . . . . . . . . . . . . . . . . . . . . 46 Pray for Others . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Cosmic Love—The Very Basis Of Divine Life . . . . . . . . . . . . . . . . . . . . . . . . . 51 Propagation Of Spiritual Knowledge. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 Be A Hero In The Battle Of Life . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Proposed Pilgrimage From Himalaya To Malaya . . . . . . . . . . . . . . . . . . . . . . . . 57 The Malayasians’ Profound Devotion To Gurudeva’s Mission . . . . . . . . . . . . . . . . . 59 Thanks And Deep Appreciations To Seekers Of Malaysia And Hong Kong . . . . . . . . . . 60 Montevideo—Strong Hold Of Gurudeva’s Mission . . . . . . . . . . . . . . . . . . . . . . . 63 Kalki—Avatar Of Hope, Foretold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 Srimad Bhagwad Gita And Gospel Of Divine Life Are Identical . . . . . . . . . . . . . . . . 70 Forget Not The Goal Lead The Divine Life . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 Tamaso Ma Jyotir Gamaya . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 The Gita And The New Testament . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 My Message Of Truth For The New Year . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 In The Blessed Company Of Holy Saints . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 Vast Field Of Divine Life Activities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 The Ramayana—The Light-House Of India . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Divorce Not Religion From Your Daily Life . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Satsang Is God’s Gift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
iv
Service To Suffering Humanity Is The True Worship Of God . . . . . . . . . . . . . . . . . 97 Bharatvarsha Is Home Of Premabhakti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Sivananda—Shining Embodiment Of Divine. . . . . . . . . . . . . . . . . . . . . . . . . . 104 Let Us Invoke Mother’s Divine Benediction . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Let The Light Of Virtue Ever Shine Bright In Your Character. . . . . . . . . . . . . . . . . 109 Spiritual Awakening—Purpose Of Human Life . . . . . . . . . . . . . . . . . . . . . . . . 112 Glory Of Gurudev’s Universal Prayer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Live Divinely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Holy Mission Of Gurudeva . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 Wonderful Is The Significance Of Mantra-Writing. . . . . . . . . . . . . . . . . . . . . . . 124 Let Us Wake Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Hearty Send Off From Bombay And Warm Reception At The Durban Sivananda Ashram . . 129 Sivananda’s Mission Spreads Across The Ocean. . . . . . . . . . . . . . . . . . . . . . . . 134 Sivananda’s Birthday Must Be A Day Of Retrospect And Spiritual Reassessment And Self Scrutiny . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 Gandhijee—Personal Gospel Of Divine Life . . . . . . . . . . . . . . . . . . . . . . . . . . 140 Guru Nanak—World Awakener Of Modern Age. . . . . . . . . . . . . . . . . . . . . . . . 143 Swami Venkatesananda And Swami Sahajananda Living Miracles Of Gurudeva . . . . . . . 147 Mysterious Working Of Gurudeva’s Grace. . . . . . . . . . . . . . . . . . . . . . . . . . . 150
v
Sivanandashram Letter No. I
TO AWAKEN YOU SIVANANDA GURUDEV CAME
Blessed Atma-Swarupa! Dear & Revered Member,! In earnest prayerfulness and deep worshipfulness at the sacred feet of blessed Master, our Gurudev Swami SIVANANDA I speak this above admonition unto you all, upon this first occasion, I have of addressing you all, through the pages of your own Wisdom Light monthly journal. I humbly speak thus in the holy Name of our Guru Sivananda Dev, as the merest instrument of His, through whom He carries on now, His sacred mission, of loving and ceaseless spiritual service of you all. My heart’s fervent prayer is that this servant of His even as He worked all His dedicated and noble life during the past more than thirty momentous years. In this life I shall strive to translate this prayer into personal action and live to serve. This shall be my endeavour as a servant of Satgurudeva and as His instrument even as it is of my worthy Gurubhais here at this Ashram. In this endeavour His spiritual Presence shall be my guide and His grace, my sustainer, and His remembrance, my strength. May the Divine inspire and help me in this sacred labour of love! Gurudev Sivananda came to awaken you all. He came, lived, taught and worked to awaken, inspire, guide, lead and to illumine. Swamiji awakened you to the true meaning and Goal of your life, inspired you to aspire and strive for that Goal, guided you on your path towards its attainment and led you onward towards illumination. You who have been most fortunate as to receive His awakening spiritual impulse and to get the inspiration of His thrilling teachings and be guided by them, you must now go onward and rise upward upon the spiritual Path with keen aspiration, perseverance and zeal. Let unabated be thy enthusiasm and sustained be thy fervour. Be a sincere seeker and an earnest Sadhak. With joy lead the Divine Life. Adopt the twin motives of Sadhana and Selfless Seva. Become established in truthfulness. Deviate not from Virtue. Pure be thy heart and mind. Let kindness and love dwell in your thoughts, words and actions. May the spirit of Gurudev and His universal teachings light up your life and make all your actions luminous with the rare quality of Dharma and spirituality. God bless you! 1.10.1963 —Swami Chidananda.
1
WHO IS DIVINE MOTHER DURGA?
Sivananda Ashram Letter No. II
WHO IS DIVINE MOTHER DURGA?
Blessed Immortal Atman! Dear & Revered Member! Om Namo Narayanaya. Jai Sivananda! When this letter reaches you, we would have just passed the solemn, auspicious and most joyous period of the sacred nine-day worship of the Divine Mother. It is now the holy period of Navaratri as I write this for your November Wisdom Light. The atmosphere is surcharged with deep devotion to Maha-Devi and vibrant with the fervour of worshipfulness, adoration and prayer. Our thoughts are filled with the glorious Divine Mother, and Her Blessed and wondrous manifestation as Durga-Lakshmi-Saraswati. She is the great Mystery, the inscrutable Power of the Supreme Brahman, who holds in Her Hands both bondage and Liberation. The Grace of the Divine Mother it is, that enables you to walk the path of Divine Life. Through Her benign blessings you are able to shine as a sincere spiritual seeker and a man of Dharma. To worship the Mother with Devotion is to be immediately uplifted by Her Strength and Power. She works within your inner being as the triple force of destruction, evolution and illumination. Destroying the impure and vicious aspects of one’s lower nature, the unworthy, base, and bestial in the individual personality, and helping evolve the human nature into sublime heights of goodness, nobility and the purity of beauteous virtue. She illumines the Jiva with supreme divine wisdom. Thus the Divine Mother is the very life and support of the aspirant’s spiritual Sadhana. She makes your quest fruitful with Attainment. The Divine Mother grants Kaivalya Moksha or eternal release and immortality. To worship and to adore the Blessed Mother is to welcome Her Divine Help in working out your highest good and everlasting welfare. When you thus seek Her divine aid, Her compassionate response is immediate. She sets to redeem you in Her own way. She sends experiences both pleasant and painful, through trials and difficulties. She moulds and strengthens you, through sorrow and suffering, She refines and purifies your nature. She enriches and blesses you with spiritual experience and raises you to exalted heights. She makes use of your very life and its experiences to make you perfect and bestow upon you divine Peace and Joy and the Illimitable Splendour of Self-realization. Therefore, O Beloved Seeker! learn to accept the joys and sorrows, the temptations and the trials of your life with wisdom and understanding. Seek to recognise their hidden meaning and purpose for your own evolution and supreme good. Find Her Divine Hand behind all occurrences and see the Mother’s Will working through them. Then will you behold your entire life as the expression of the Mother’s immeasurable Love for you. Resolutely overcome all defects, faults and wrong tendencies in your nature and behaviour. Develop noble character. Grow in virtue. Ever walk upon the path of perfect righteousness. Seek the Immortal, Be thou an embodiment of Divine Life. Let the sacred name of Gurudev Sivananda be glorified by thy true discipleship into him. Personify his ethical and spiritual teachings. May the world find in you a source of inspiration. Let thy presence elevate all.
2
ADVICES ON SPIRITUAL LIVING
May the Divine Mother shower Blessings upon you! Jai Sivananda! 1-11-1963 —Swami Chidananda
Sivananda Ashram Letter No. III
LET VIRTUE RULE THY LIFE!
Blessed Immortal Atman! Dear and Revered Members! Om Namo Narayanaya! Jai Sivananda! Salutations and adorations at the Feet of the Universal Being, the one Divine Reality, whom the prophets of all religions have realised in the innermost depths of their illumined Superconsciousness. May the Light of that supreme Divinity fill our lives, on this auspicious occasion of the celebration of the Bharatavarsha’s national festival of lights, Dipavali, with His Divine Grace! May the choicest Blessings of God and Gurudev grant you all inner spiritual illumination. Since all of you are devoted to the ideals of divine living, you would readily find the rows of lights lit for the Festival, illuminating the very meaning, purpose and Goal of human life. This earthly life is a glorious opportunity, granted to the individual soul to attain the conscious knowledge of its eternal oneness with the illimitable Light of Cosmic Consciousness. This gift of human life is a rare opportunity, a splendid change, given to us by the benign Hand of the all-merciful God, for transcending all limitations, bondage, sorrow, suffering, pain, grief and weaknesses of all sorts, and for attaining that unlimited glory and that experience of immeasurable peace which emerges from your union with the Divine. That is the goal; that is the central meaning of life; that is the prime purpose of your existence here upon the earth plane. With all its defects and imperfections human life has this great redeeming feature, that it is a passageway to the Light of Immortality. Live life in the Divine. Recognise your existence here as such and live in the light of this recognition, of this inner awareness, this inner knowledge. Let each day dawn for you as a fresh opportunity and occasion opening up before you to move one step further towards this great attainment of Divine Realization. Within yourselves, let there be, everyday, a Festival of Lights. And while you live a life of such unceasing and blessed quest towards the supreme Attainment, live a life of great virtues, a life of simplicity, humility, nobility. Let all your life be a radiation of Virtue—the inner perfection that is inherent in each soul. Let life be an outflow and expression of the goodness, that is the truth of your being, because you are made in the image of God. Like Him, you are Divine, Goodness, Purity and Truth. Let your life, therefore, be an active manifestation of these divine qualities which are the essential part of your innermost reality. Thus alone would you prove that you have caught the true significance of the
3
LET VIRTUE RULE THY LIFE!
outward ceremony of lighting several rows of lights that the observance of the Dipavali festival enjoins. Live, then, the life Divine. Blessed Self! Withdraw the senses from the objects; withdraw the mind from the senses and establish yourself in your inner divine Centre. Be the unchanging one amidst the changing body-and-mind-personality. Let the spiritual Principle in you prevail. Let the spirit Divine enshrined in you express itself in all its glory, express itself through a life of Yoga, through the thought and motives of the mind, through the actions and deeds of the body. Let all actions be full of love, goodness and purity. That is real Divine Life. Gurudev Sivananda always insisted on living a life of virtue. For, the life of virtue is the common basis of all Yoga, no matter whether it is Karma Yoga, Bhakti Yoga, Jnana Yoga or Hatha Yoga. A life of purity, virtue, goodness, self-control, selflessness, humility, forms the common foundation of Yoga, of all spiritual attainment and all practical religion. This is the basis, the indispensable preparation. Sincere aspirants can never afford to neglect or overlook this vital truth of spiritual life and realization—that Divine Unfoldment is based upon a life of purity, goodness, truth, selflessness and humility. Practise daily the virtues, Gurudev has listed in his “Song of Eighteen Ities” “serenity, regularity in Sadhana, magnanimity, absence of vanity,—ego. Ego is the great stumbling block. It is the great stone-wall that prevents the individual from rising upwards to the Universal Consciousness. Ego individualises consciousness; it is the seat of all petty likes and dislikes, all clingings, identification and selfishness. It is a false superimposition. The real personality, the real Consciousness Divine is forgotten and this erroneous identification with the body and the mind gives rise to the “I”-idea. It creates this false human personality and makes you forget your true Immortal Consciousness. You think of yourself as Mr. so, as this little mind and when the mind is in a wave of anger, you say, “I am angry”. How can that wave touch you, you who are the Changeless consciousness Supreme? But you lose knowledge and awareness of your true Nature and identify yourself with every passing wave and phase of body and mind. That is bondage; that is ignorance. Be large-heated; embrace all; feel oneness with all; realise the infinite inner Divine Self. Be tolerant towards all; regard all people as your own Self, and thus develop virtues and lead the sublime life, a real Christ-like life which all great saints and mystics have embodied in themselves. All those who have reached spiritual Illumination, have themselves been the very personifications of Virtue. Thus we see there is a fundamental connection between a life of virtue and the highest spiritual experience. Therefore, lead the Life Divine. May your inner life be a perpetual festival of Lights! 1st December 1963 —Swami Chidananda
4
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. IV
START A NEW LIFE NOW
BLESSED ATMA SWARUPA, Om Namo Narayanaya: Namaskara. May the Grace of Gurudev Swami Sivananda illumine this NEW YEAR with the brightness and radiance of Hope, Aspiration, and Inspiration. God grant you all Auspiciousness, Blessedness, Prosperity and Success. I wish you Happiness, Health, Progress upon the spiritual Path, and triumph over troubles, tensions and problems of life. May this New Year herald for you many more years of joy, peace, and plenty. With this fourth Sivanandashram Letter, we leave behind a year that has been heavy with many sombre events, and look forward on to a fresh New Year, in which the world might emerge once again, from shadow into bright light, even like the sun unclouded. Traditionally too with the Makarasankranti in January, the sun takes once again the auspicious northern-path, Uttarayana. At this juncture of mankind’s periodical reckoning up the debit and credit of life and of the taking of earnest resolutions, I speak to you all to say, “Blessed Seekers upon the path to Divinity. This year dawns for us without the outward physical presence of the one who was our guide and inspirer in our spiritual life. We have not him to whom our yearly resolutions were addressed hitherto. But this very absence entails the necessity of taking certain new resolutions that were not taken hitherto. These I shall mention. But, even before anything the first and the chief of them shall be that you make your life a dynamic expression of the practical gospel of Sivananda. This is Divine Life.” Beloved Member, in addition to your routine new-year-resolutions as a Sadhaka, the dawn of 1964, should see you getting ready to take up the work of Gurudev as his worthy child, pupil and spiritual representative wherever you are. Be you a follower or a disciple or even just a devotee of the Holy Master Sivananda, let your resolve be on record that you determine now at the dawn of this New Year to practise and to propagate his Divine life teachings every day of your life. Resolve that you will observe the principles of Satyam (Truth), Ahimsa (harmlessness), and Brahmacharya (Purity). Resolve that you will strive each day to be good, to do good, to be kind and compassionate to one and all. Resolve to excel in service, to progress in devotion, to persist in meditation and aspire for realization. Resolve to be charitable and pure, to be detached from worldliness and passing earthly objects and to attach yourself to Dharma and the spiritual ideal of life. Resolve to love all, to see the Lord in all, and to serve the Lord in all. Resolve to adapt, adjust and accommodate to yourself to all changing circumstances, to be tolerant towards all faiths and religions, and to ever seek to unify all by seeing the good in all, and the underlying unity in the midst of apparent diversity. Resolve thus to make your life Sivanandamaya. Let Sivananda radiate through your pure thoughts, your noble feeling, your kind words, and your selfless actions. Thus resolve to make Gurudev Sivananda immortal through your life and actions. I have more to say, but that I shall keep for the Letter of February. For the present I shall confine this letter to this main request to you all. Thus loftily resolve and act upon this resolves with sublime determination. May the idea, the will and the Bhav fuse together into an irresistible
5
START A NEW LIFE NOW
dynamic urge to do all that is conceived and to do it now. This would verily constitute the true fulfilment of discipleship in this age when ideals need to be actualised through living practice, I invite you to write to me your ideas briefly on the question of, “the duty of individual disciples towards Gurudev, and how disciples all over the world can each serve the great cause of dissemination of spiritual knowledge and the spread of Divine Life.” I shall be glad to receive and consider these letters for the benefit of all. Anyone who communicates to me on this specific matter, may kindly write upon the cover, “Sivanandashram Letter No. 4”, thus underlined. God bless you all, and grant you Vichara and Viveka, firm determination, strong will power, unshakable faith, Sadhana-shakti and supreme attainment. Greetings again, and the very best good wishes in the name of worshipful Gurudev Sivananda. 1st January 1964 —Swami Chidananda
Sivanandashram Letter No. V
RESOLVE TO FOLLOW DIVINE LIFE
BLESSED ATMA-SWARUPA: May the abundant Grace of the ever-munificent Lord Shiva, the easily-pleased-one, shower upon you on the eve of the most blessed Mahashivaratri day. In continuation of letter number four that appeared here last month, I have now to enlarge upon the theme of spiritual RESOLUTIONS which formed the central subject of that previous letter. Mention was made therein (vide page 11) that more was to be said and it would be said now. What is the place of resolution in the path of Sadhana? What part does such a resolution play in your life? The answer is that resolution is the very basis and origin of all endeavour and achievement. Spiritual aspirations and efforts are no exception to this. All the more is it so in the spiritual field. Specially because, here you are mostly to struggle alone. The comfort and consolation, the support and strength of group endeavours are not so much available to the Sadhakas as they are to people in other fields of secular endeavour. The spiritual seeker does not move in a set-up like that of a whole company of soldiers moving resolutely forward into determined action upon the battle-field. Because, spiritual aspirants and Sadhaaks are a scattered brotherhood, a small minority in this world, manfully endeavouring to ever press forward the Divine Goal in the face of a thousand obstacles and adverse currents. Great resolution is essential. See what Gurudev himself says upon this point. Here are his words, “The spiritual path is thorny, precipitous and rugged. Temptations will assail you. Your will, sometimes, become weak. Sometimes there will be downfall or a backward pull by the dark Asuric antagonistic forces. In order to strengthen your will and resist the unfavourable currents, you will have to make, again and again, fresh resolves. This will help you to ascend the ladder of Yoga, vigorously and quickly. Stick to them tenaciously. Watch the mind carefully and keep a daily spiritual record.”
6
ADVICES ON SPIRITUAL LIVING
When you make these resolves, stand before the Lord’s picture, with folded hands, and pray devoutly for His grace and mercy. You will doubtless get immense strength to carry out these resolves. Even if you fail in your attempt, do not be discouraged. Every failure is a stepping-stone for success. Make a fresh resolve again with more firm and fiery determination. You are bound to succeed. Conquest over the weakness will give you additional strength and will-force to get over another weakness or defect. The baby tries to walk, gets up and falls down. Again it makes another attempt. Eventually, it walks steadily. Even so, you will have to fall down and get up again and again, when you walk in spiritual path. In the long run, you will steadily climb up to the summit of the hill of Yoga and reach the pinnacle of Nirvikalpa Samadhi”. Thus we see Iccha-Shakti is the motive force behind all Kriya or activity. Hence the ancients have clearly mentioned “SUBHECCHA” as the first level or Bhumika of the spiritual ascent when they enumerated the Sapta-Jnana Bhumika. With equal emphasis has the blessed Lord declared unmistakably that right resolution verily becomes turning point in one’s life. (vide Bhagavad Gita Chapter 9, verse 30). Such resolution is Daivi Sampatti. Such resolution does not contradict surrender or humility for it indeed constitutes the very expression of perfect trust in the Lord’s Divine support and our faith in His graciousness to sustain us in our spiritual life. Now coming to our specific position as the disciples at the feet of Sadguru-Dev Sivananda, there are certain definite points for you to resolve upon as the members of the Divine Life Society. You must embody Gurudev’s teachings. And the essence of his practical instructions to you on the spiritual path have been summed up in five or six important admonitions of his. These, every member of the Divine Life Society must have at his finger-tips. They should be engraved in your heart, to follow them and to incorporate them in your life would be totally fulfilling Gurudev’s concept of Divine Life. It will make your very life a living exposition of Gospel of Sivananda. Sri Gurudev laid the greatest importance to the observance of these sets of his personal teachings which I now give for your close attention. They are contained in the following:— 1. The RESOLVE FORM with its 18 items. 2. Twenty spiritual instructions. 3. The science of seven cultures. 4. A daily routine Time-table with well thought out, systematic programme from dawn till night. This may not be rigid but flexible according to dictates of common-sense. 5. The daily spiritual diary to be maintained in order to cheek up both upon your resolve from as well as your daily routine. 6. The Universal prayer beginning with “O Adorable Lord of Mercy and Love”, which produces a complete pattern of the sublimest ideals of Divine Life in practice.
7
RESOLVE TO FOLLOW DIVINE LIFE
These six things constitute Gurudev’s complete method for quick evolution and dynamic spiritual progress. They stand for the heart of Gurudev Sivananda’s teachings. During more than 35 years of ceaseless spiritual propagation and dynamic awakening work Gurudev has consistently hammered upon these teachings, tirelessly preached them and broadcast to every nook and corner of the world. Even if all the rest of his spiritual literature were to be taken away from this earth, these six things alone would be amply providing the fullest spiritual guidance and practical teachings to the entire world. They alone would be enough to sustain the spiritual life of humanity. The teachings contained in these six items are comprehensive and are quite capable of guiding you and taking you right up to the great goal of highest spiritual attainments or highest Kaivalya Moksha. Take definite resolves and record them in resolve form. Draw a daily routine and follow it. Maintain spiritual diary. Follow twenty spiritual instructions. Live in the spirit of Sadhana Tattwa. Translate the Universal prayer into your actual life. Yes, the Resolve form, the twenty spiritual instructions, Spiritual Diary and Sadhana Tattwa represent Gurudev himself. They are the whole of Gurudev’s teachings to modern humanity, in a nutshell. Enter into the spirit of these teachings. Assimilate these teachings. Make them your own. Live them. Thus you will be granted the highest spiritual blessedness and will attain the goal of all spiritual Sadhana. They can bring you face to face with God. May Sat-Gurudev make himself manifest to you through these six important Sadhanas of his. May His grace enable you to fulfil these in your life and become the partakers of the highest experience of Divine Bliss, Spiritual Illumination in this very life. Jai Gurudev Sivananda. Your in the Lord, 1st February, 1964 Swami Chidananda
Sivanandashram Letter No. VI
NOBLE TASK OF TRUE DISCIPLESHIP
Blessed Atma-Swaroop: Beloved Seeker of Truth, Om Namo Narayanaya. Namaskars. May the Sunshine of Joy, Health and Well-being illumine your life with the advent of bright Spring season with its beauty and fragrance of colourful flowers and fresh leaves upon the waking branches of wind-swayed trees. I am happy to tell you that several earnest disciples of Sri GURUDEV felt it their duty to respond to the “Sivanandashram Letter No: 4” and so I have their valuable thoughts and suggestions upon the question of—“The duty of individual Disciples towards Gurudev” and how, the disciples all over the world can each serve the cause of Dissemination of Spiritual Knowledge and the spread of Divine Life—sent in by them after reading the January issue of Wisdom Light. This present issue is therefore, going to bring to you their sincere views upon this all important subject of the practical implication of true discipleship and its active expression in the form of earnest Guru-Seva. All letters received here, cannot naturally find
8
ADVICES ON SPIRITUAL LIVING
sufficient place for inclusion in the pages of this publication, but this certainly does not at all mean that some were considered as of less value or importance and not given place. Far from it. Actually, whether published or not, all the responses received are being given our close attention and every idea placed before us, is being considered carefully. I am most thankful indeed to the many good friends and well-wishers to will thus graciously given their time and thought, to have responded to the previous letter. In doing this very act they have indeed fulfilled a vital part of their spiritual obligation towards their Guru’s spiritual Mission. They have verily exercised the privilege of their discipleship by their guru’s genuine interest in the progress of life-work and his handiwork namely, the Divine Life Society. An appreciable number of earnest disciples taking keen interest in their Guru’s good work will ensure the enduring progress of this holy movement which he has left to them as a heritage. He has left this work to their hands as a part of their spiritual evolution and an essential part of their Yoga and their Jivana-sadhana. Gurus are of two kinds. The one lives a lofty spiritual life and living thus he continuously instructs and guides his disciples to individually practise and live this ideal life themselves and attain the experience which he reached. The other lives a lofty life, instructs and inspires disciples to do likewise AND UNDERTAKES A GREAT HUMANITARIAN TASK AND LEAVES THIS IDEAL WORK TO HIS FOLLOWERS TO CONTINUE and bless others and bless themselves thereby. Why certain sages develop into one type and certain others into the other type is a matter we have no knowledge about. May be it is that the needs of particular times call forth men suited to fulfil them, may be it is the prarabdha that decides this. Whatever it be, it is God’s will that brings this about and the world is the gainer for it. Jagadguru Adi Sankaracharya was an uncompromising Absolute Monist Kevala Advaitin. He declared the Atman alone to be the sole Reality. Yet, he undertook to clean up Hinduism of all malpractices and launched a great revival and established a well-conceived institution to carry on this work in an organised and systematic manner. And the great following of his Monastic and lay disciples have been keeping alive this institution and furthering his work through this centuries since his day. Thus we see that this twofold trend in the Gurus upon the Indian spiritual scene is not in any way new nor by any means unusual or contrary to previous tradition. Our worshipful GURUDEV has been indeed a very combination of both this trend, making himself a confluence of a powerful spiritual ideal, at once lofty and sublime, and a most significant spiritual work at once noble and great. You, my blessed Sadhak, are a disciple of Satguru Sivananda, the holy saint and loving helper of all mankind. Ideal discipleship would be manifested in you when you live the Divine Life and also further the Divine Life work in the service of mankind. The first part of this is an individual process. The second part of it requires the harmonious co-ordination with other D L members in your own city, town or village. Contact fellow-members. If there is a branch of the Divine Life Society in any place, it is the scared duty of each and every individual member of that place to get in touch with the branch workers and to participate and to actively help in the programmes of the branch. Many a time the branch people do not know of the presence of enrolled members in their own town or city. This would not be. Also disciples even if they are non-members in the formal way, must take joyous interest in making contact with other disciples who are known to be in the same town or locality. And to further Gurudev’s work one does not necessarily have to constitute a Branch (though it is good to do so) but
9
NOBLE TASK OF TRUE DISCIPLESHIP
may arrange Satsangs, discourses, Asan classes even upon the individual level. In short, let me tell you this, an integral part of your spiritual life and Yoga Sadhana is propagation of the Divine Life Gospel and spreading Gurudev’s teachings in selfless spirit of Karma Yoga and Guru-seva and Ishwara-arpana. Jai Gurudev: Regards, prem and Om: 1st March, 1964 —Swami Chidananda
Sivanandashram Letter No. VII
STRIVE TO LIVE IDEAL LIFE
Blessed Atma Swaroopa! Beloved Seeker of Truth, Om Namo Narayanaya. Namaskars. Om Sri Ram. Sri Ram. Sri Ram. Sri Ram. This is a great and glorious month. It is verily a month full of rare blessedness and sanctity. For, this month we have the precious occasion and opportunity of offering our adorations to the grand ideal of our Nation, the supreme divine Person who stands for us all, as the greatest model of Perfection in life, nature, conduct and character, namely, the most blessed “LORD RAMA”. The entire Nation will celebrate the divine Jayanthi or holy Birthday anniversary of Rama upon the 20th April: Bhagwan Ramchandra Maryada-Purushottama, who embodies in Himself and expresses through every movement of His life the highest exemplary behaviour in all fields of human relationship. The story of Rama’s divine life is the story of sublime Idealism in actual practice. Its inspiration is perennial. Its appeal is Universal. Its wonderful power to elevate and to transform is unfailing. Its sublimity is unequalled. Ramayana is a treasure of Indian Culture, and National Heritage of utmost importance and significance of the very survival of our noble expiration and aims. To worship in RAMA is to reassert our unshakable faith in Idealism in life and to pledge a new our loyalty to the concept of Dharma and Adhyatma-lakshya in life. Rama is the life-breath of India’s moral life and ethical structure. Without Rama there is no Dharma and without Dharma there will be no India! We shall try in this letter to receive some Light from the glorious RAMAYANA. May you all prepare yourself to worship the Divine Rama upon the approaching sacred anniversary. Purify your heart with humility, devotion and worshipfulness of spirit. Repeat His DIVINE NAME with great feeling and intense reverence. Ram-Nam is India’s great Mantra of this age. It alone can make your life meaningful and purposeful in a world where the true meaning of life is lost in Hedonism and this disillusionment and frustration has overcome the majority of human beings.
10
ADVICES ON SPIRITUAL LIVING
Your life here is a means to the attainment of a glorious purpose. The aim of life is the attainment of the Divine Perfection. This earthly life is full of miseries, sorrows, defects imperfections and limitations. To overcome all limitations, to cross beyond sorrow and pain and to attain Immortality and Divine Bliss is the goal of life. By realising God one reaches this goal and becomes internally free. Such realization and freedom is achieved by living an ideal life, by practising self-control and by worshipping God. Purity, self-restraint and worship constitutes the essence of Spiritual Life. Every Divine Incarnation comes to give this message of God-attainment, to remind mankind of its importance and glory, and to disclose the inner secrets of Spiritual Life and attainment, by the lofty examples of His own ideal life and conduct. In the Divine Leela of Rama’s Avatara, we get much light and guidance and derive great inspiration upon the inner part of spiritual attainment. Different ideal personalities in the Nara-Leela of this great Avatara exemplify the different factors that characterize your ideal approach unto the Divine. Bharata, Sita, Lakshmana and Hanuman are the personified expressions of the different factors that make up or constitute our ideal approach unto the Divine. Uninterrupted, continuous worship of God is the very essence of Spirituality. Worship that is characterised by the total absorption in the object of worship ultimately leads to Realization. Worship to be effective and fruitful must become gradually so intense that yourself is completely forgotten and God alone fills your concentrated and one-pointed mind. There must be no thought of self. The mind must be filled with God. The only meaning in one’s life must be the love of God. Worship should become a positive passion and must be felt as more important than anything else in this world. You must understand that life itself is a worship. Life is meant primarily to be lived as an active worship of Divine, as a glorification of the Lord. Such worship has the power to awaken the Divinity that is dormant within every human soul. It will transform you into a Divine being. The ideal prince Bharatha verily made himself the very embodiment of such passionate, continuous, all-absorbing worship of Sri Rama. He forgot the world, he forgot himself and he forgot everything in his whole-souled devotion and adoration of the Lord Rama through Rama’s sacred Padukas. Day and night, Bharatha was seen absorbed in the divine contemplation of Rama. Rama pined to see him. The moment His mission at Lanka was over, he sent Hanuman in great haste to go in advance to meet Bharata and announce his arrival to him. By true worship such as was demonstrated by Bharata, one powerfully draws the Lord to himself and makes the Divine one’s own. The bliss of this spiritual union with the Divine is the fruit of such worship. It is indescribable. Remembrance of Bharata, contemplation on his personality will create in you the Bhava of such worship. Meditate upon the moving and inspiring life of this great prince among Bhaktas. You will imbibe the spirit of his deep devotion and passionate adoration of the Divine Lord Rama. Such devotion is the real wealth of wealths and the greatest pleasure in your life. Acquire this and attain immortality and bliss. Self-restraint is the key to mind-control. The outgoing tendencies of the senses and their constant movement towards the fulfilment of the senses make the mind restless and agitated. Such a mind does not turn to God. Such a mind finds it impossible to worship with one-pointedness. Practice of self-control, checks the outward tendencies of the senses and helps you to attain calmness of mind. Self-control is distasteful and painful in the beginning. It becomes interesting, pleasant and joyful at a latter stage. Practice of self-control should be a daily discipline willingly
11
STRIVE TO LIVE IDEAL LIFE
imposed upon themselves. It is a sign of our superior human nature. You will reap benefits in every way, physical, mental, moral and spiritual, by the practice of rational self-restraint. A self-restrained man alone can do effective service to his fellow-beings. Self-controlled person alone can truly worship God. Otherwise, with the thoughts scattered over innumerable objects and a mind distracted by various desires, you cannot truly worship or effectively serve the Society. The quality of service of a concentrated mind of a self-controlled person is bound to be ten times superior to the indifferent service that is done by a person who is himself a slave of his desires, cravings, personal ambition and secret passion. Service demands sincerity of purpose, earnestness and dedication. It demands readiness to sacrifice and willingness to bear and undergo troubles and difficulties with equanimity of mind. Nowhere in the annals of our Spiritual history do we find a more shining example of such a perfect self-control, immense self-sacrifice and unrelenting and unremitting service than in the amazing personality of the great heroic Lakshmana. Moderation, abstinence, the balanced life guided by the principles are all essential parts to self-control. Self-control implies Self-mastery. It is the bed-rock of all achievements, secular or spiritual. To the man of religion it must be the very life-breath. Without self-control there is no Sadhana. Without Sadhana there is no Self-realization. Without Self-realization you can neither have peace nor bliss nor freedom. He who wishes to be with the Lord must willingly part with the little self. He must be prepared to discard all thoughts of petty happiness and self-satisfaction upon the lower plane. The princely Lakshmana turning away from the comforts of Palace, pomp and royal living, chose to follow his Divine brother and voluntarily accepted the hardship of the severe discipline and self-denial. Thus he attained the unique and incomparable blessedness of continued Divine presence of Bhagwan Ramchandra. The approach to the Divine experience is an ascent into purity. Spiritual life is a gradual but unceasing growth into the perfection of purity, Atman, all the absolute Divine essences variously spoken of as Amala, Vimala, Nirmala, Nitya, Shudha and Niranjana. Spiritual growth and progress implies a process of transforming yourself from the impure into the absolutely pure. He who approaches the Divine should go into the Divine Nature. The pure alone can have access in the realm of Divine Experience. Blessed are they that strive to be pure in thought, word and deed and make their life an embodiment of Purity. The Divine Sita and the great Hanuman stand as resplendent exemplars of this sublime ideal. Noble Sita was a blazing fire of Purity. She stands as the loftiest example of shining Purity in all the annals of Indian tradition towering high above all personalities and forever a source of living inspiration in the Hindu Society. Even amidst the severest of tests, trials and tribulations Sita adhered to the ideals without swerving even by a hair’s breadth. No harm dared approach this fire of Chastity, Purity and highest Virtue. Equalling her in this rare virtue, shining as a symbol of supreme Purity, the heroic Hanuman strides across the sacred pages of the holy Ramayana. Hanuman is the Brahmacharin par excellence of Indian religious history. He is the object of worship and Ishta Devata of all those who aspire after life of perfect purity, continence and self-control. Personalities of Hanuman and the Divine Sita give unto us the secret key to success in this life of Purity. Ceaseless service and total dedication sum up this Spiritual secret. To Mother Janaki nothing existed in the world except her Rama. Hers was a life totally dedicated to her Lord ever since the moment her hand was placed in Rama’s palm by her sage father King Janaka. Rama was her life’s breath. There existed no other thought in her mind except Rama. No other place in her heart except for her Rama. Being absorbed thus in Ram, day and night dwelling in thought and feeling upon Him, Sita was filled with the Divine Fire which no impurity could dare to approach. And Hanuman too was similarly absorbed in Rama’s thought, in
12
ADVICES ON SPIRITUAL LIVING
His dedication to Rama Seva. Ceaseless service of his Divine Master because the passion of his life ever since their first meeting in the hallowed ground at Kishkindha. Dedicated selfless service transmuted the energy of Hanuman into pure Daivee Shakti. The impossible became possible to the power of purity of this great Brahmacharin. Service of Lord Rama was the sole passion of Anjaneya’s exalted life. This obtained for him the unique and coveted blessedness of an eternal place at the Divine Lotus Feet of Bhagavan Ramachandra. Purity, dedication and devotion of this mighty servant made him one of the dearest objects of the Divine Lord Bhagavan Ramachandra. Where this total dedication for spiritual ideals is, there the seekers shine with Purity. O my beloved friends, become absorbed in unceasing selfless service of saints, holy people, elders and of all. Be totally dedicated to the glorious spiritual ideals. You will rise to the highest purity and come face to face with God. Lead the Divine Life. Live up to your ideals. Grow in Purity. Practise self-control. Dedicate yourself to the regular worship of the Divine. This sublime way of life unfolds itself before the votary of the holy Ramayana. Bharata, Lakshmana, Sita and Hanuman give you a dazzling revelation of this radiant path into perfection, Purity, self-restraint and dedication unto worship are ideals to be ever pursued with unabated zeal and earnestness. There are those who would say that ideals are impracticable. I say unto all such that it were far better to be impractical idealists than to successfully be practical bests. Without Idealism humanity is savage. Take away idealism, then the jungle will invade the most urbane society. Ideals need not be totally and entirely realised in practical life. Nevertheless, without them we shall perish as a civilisation and a culture. Ideals should ever be pursued. No matter how difficult of attainment they may seem, yet in constantly striving to approach them, lies the true greatness of a people. Such ideals impart the quality to our life and give it the correct direction. What our life is, depend upon what our ideals are. To move constantly towards definite, lofty ideals is the greatest blessedness in the life of any individual. Ideals are important not because they are immediately and fully practicable, but because they impart the right pattern to the practical living of our lives, individually as well as collectively, here and now. Ideals come foremost. Then follows the practice. And to one who is truly earnest nothing is impracticable. The practice may not be easy but to strive your best to practise, is your duty. Trust in Lord Rama, take His Divine Name and start to lead a sublime life of noblest idealism. You will triumph over all obstacles and shine resplendent as a true child of Bharatavarsha. Om Sri Ramaya Namah! God be with you! 1st April 1966 —Swami Chidananda
13
MAY THE GREAT ONE INSPIRE YOU
Sivanandashram Letter No. VIII
MAY THE GREAT ONE INSPIRE YOU
Blessed Seekers after Truth, The present month is a month of powerful reminders to certain most sublime and sacred ideals that have formed vital factors in the evolution of our great country’s unique culture and view and way of life. We had occasion to note last month how the great ideals propounded and radiantly expressed through the Divine Leela of Ramavatara continued to be moving force in the stream of our nation’s social life and ethical consciousness. We saw how sublimity and purity of your national character both in the individual as well as in collective social life had their very basis and their sole hope in the adoption of these ideals. Solemn reminders to ideals upon a still higher dimension of our life, in a more inward and deeper depth of our being come to us during the course of this month through the occurrence of a number of anniversaries in this current month of May. The Religious Calendar announces the occurrence of the thrilling birth anniversary of the valiant Parashurama, the glorious Sankara Jayanti, the holy Narasimha Jayanti and the sacred and solemn Buddha Jayanti. These great anniversaries have the specific purposes of the periodical re-infusing of fresh vitality into those living ideals that form the very soul of the Bharateeya Samskriti. They have the specific purpose of recreation of the renewed waves of a living faith, inspired enthusiasm and dynamic dedication. These anniversaries are effective periodical reassertions of our abiding loyalty to enduring cultural values and provide indispensable recurring occasions for the vigorous re-adoption into our lives of concepts and principles, aims and ideals that constitute the living roots and life breath of our national life. It would not be an untruth to say that these numerous anniversaries provide in fair measure the factors that have been the subsistence and the support of the fabric and the structure of our ancient Way of Life. They impart unbroken continuity to it. Blessed Sadhak: Let us move along the luminous pathway of esoteric understanding and an inner vision to look for a moment into the heart of these anniversaries. Let us have a glimpse into their hidden meaning and message that they come to convey. While bowing in devout homage to the radiant Parashurama, valour Incarnate, may you recognise and receive the message of supremacy of the subtle over the gross. His life is a call for overcoming of the Rajas, of passion and of desire by their relentless higher dynamism of a purified Sattva. The Leela of this Avatara breathes the eternal lesson of the unfailing triumph of the spiritual over the merely temporal and material. It is the repeated and continued predominance of Sattva Guna that makes for the perfect establishment of supreme virtue or Daivi Sampatti in this human field (“Kshetra”) and paves the way for Divine Attainment. This sums up the very essence of the inner Yogic process that transforms the individual from Tamas and Rajas into pure Sattva and thence transports him into highest spiritual super-consciousness. The nation also venerates and pays homage to the greatest of its philosophers, the brilliant and peerless world teacher, Jagadguru Sri Adi-Sankaracharya of immortal renown. To him India owes an unforgettable debt of gratitude for his exposition of the pure Vedantic doctrine of the absolute Unity of the ultimate Reality and the Oneness of all mankind in the spirit. He reasserted the
14
ADVICES ON SPIRITUAL LIVING
truth that all faiths and religions led to the same ultimate Truth and thus stood for the perfect reconciliation of apparently conflicting faiths under the universal banner of Advaita Vedanta. Tolerance is the great gift of Sankaracharya’s life and teaching and equal vision and brotherhood, his message to mankind. Love all see Atman in all names and forms and attain the great Reality in this very life, here and now. Become a Jivanmukta. This is his call to us all. The nature of God is an indescribable Divine mystery. God is love. This transcendental infinite love is simply beyond the ken of human mind and intellect. Words fail to define it. Yet, aspects of Divine power can at times take such awesome and terrible manifestations that one is puzzled how to reconcile them with the All-Love that is the Divine. The Lord Himself describes his advent as, ‘Paritranaya Sadhunam Vinasaya Cha Dushkritam’ i.e. for the protection of the good, for the destruction of the wicked. The latter expression may well take on the appearance of such modes as normally prevail upon this plane of relative phenomena. Nevertheless, the perfect love of the Supreme Divine Essence remains uncontradicted despite the transient modes assumed by its manifestation. Delving into this mystery one comes to know that even the most awesome expression is but a manifestation of that Highest Love. This immediate co-existence of factors that seemingly contradict and exclude each other according to the normal human standards is found marvellously expressed in the divine Narasimha Avatara. Bhagavan Narasimha combines fearful grandeur with perfect protection. The destructive divine might of Narasimha was entirely to rescue the boy-devotee Prahlada from the villainous persecution of the Asura. It was to keep up the great promise “Na Me Bhaktah Pranasyati”, my devotee shall never perish. Narasimha is the mighty symbol of eternal Divine protection. Prahlada is the living symbol of the great way. Deep devotion, firm and an unflinching faith and trust, complete self-surrender and a constant ceaseless remembrance of the Divine constitute this way. It is the Supreme Bhagavata Dharma, the one unfailing path to God-realisation. The sure and certain method of attaining God-realisation. Blessed are the pure in heart who follow this Supreme path of devotion and surrender, for they shall be dearly beloved of the Lord. They shall ever abide in Him. The beautiful, serene full moon of the auspicious month Vishakha shall shed its soft radiance on the 25th of this month. All nature rejoiced upon this great day and the celestials showered flowers, for the great Buddha made his advent upon this most memorable day. His great call to right living, his message of the Good Life and his unforgettable shining example of supreme virtue have left an indelible impress upon the consciousness of people of Bharata. His love and compassion, gentleness and peace are the essence of ethics and Dharma. Dharma forms the bed-rock of our culture. Dharma is the sole basis of supreme attainment in human life. This is the first of the great fourfold Purusharthas that impart the correct direction to our lives and govern and regulate our activities and endeavours. The goal of Divine Realisation is the highest ultimate attainment to be striven for. Without the first the last is impossible. Without the primary basis the Ultimate goal shall ever remain an idealistic Utopia. With the perfect fulfilment of Dharma, the realisation of Moksha and experience of Jivanmukti becomes a practical possibility. The noble way of Dharma demonstrated by the great Buddha makes for human happiness in our lives here and now, while transcendental realisation emphasised by the great Sankaracharya renders it into an eternal experience that shall for ever lift you into a realm of perennial Bliss and infinite Peace. Buddha bade mankind to seek the solution to life’s problem through diligent self-effort, ennobling of the human nature by the adoption of a perfectly virtuous life. Purity of personal life
15
MAY THE GREAT ONE INSPIRE YOU
can alone ensure your welfare, bring happiness and grant peace. Abandon Virtue and you destroy your welfare and usher in untold sorrow. Happiness is where Virtue abides. Sorrow is the direct fruit of vice and evil living. Grow into goodness and the inner godly nature will manifest itself in thy life. You will attain the Highest by the merit of thy blameless life. Waste no time in dry discussion and vain debate but rather LIVE THE NOBLE LIFE: Living inspiration we thus receive from these four great expressions of the Divine Essence; the radiant Parashurama, the mighty and majestic Lord Narasimha mellowed by the melting devotion of Prahlada, the Prince among lovers of the Lord, the great Sankaracharya and the noble Gautama Buddha. The Jagadguru, inspired World teacher Sankara uncompromisingly holds aloft before our gaze the grand Transcendental Goal of human life. Buddha’s lofty example and unforgettable teachings state the indispensable basis of this sublime attainment. Prahlada demonstrates the one sure and unfailing method of attaining this Divine Goal. Parashurama emphasises the need for ceaseless, unremitting endeavour in this process. The Avatara Narasimha gives perfect assurance of absolute and fullest protection of Grace to one who launches forth upon this noble path of purity unto perfection. Beloved Seekers: followers of the Divine Life diligently strive to become established in Virtue and advance in Devotion. Be ceaseless in thine Worship. The Goal of God-realisation be ever before thy vision every moment of thy life. This is the Ancient Way of Bharatavarsha. This is the Way to Peace, Joy and eternal Welfare. There is no other way. Onward upon this Path. God be with you. May you reach the other shore—Immortality. Om Tat Sat Yours in Sri Gurudev 1st May 1964 —Swami Chidananda
Sivanandashram Letter No. IX
MAKE RENUNCIATION THE BASIS OF YOUR LIFE AND ACTIONS
BLESSED ATMASWAROOP: Om Namo Narayanaya. Namaskars. Greetings to you from this Holy Abode of Sri Sadguru Bhagawan Sivananda Maharaj. May this letter from this sacred Ashram find you all in good health, peace and joy. Let Guru Kripa bring into your life the Light of Discrimination, Strength of Self-Control, the Joy of Selflessness and the Loftiness of Loving Service and Spontaneous goodness or Paropakara.
16
ADVICES ON SPIRITUAL LIVING
This month holds for us a message of significance and importance. It brings to memory of a momentous event that resulted in an immeasurable good and blessedness to countless soul in this troubled century. Exactly forty years ago, in the June of the year 1924, Gurudev Swami Sivanandaji renounced his secular career to embrace a life of Sannyasa. He entered into the glorious path of Nivritti, plunged into a period of asceticism, seclusion, intense Sadhana and deep meditation. Thus he attained realisation and launched his great mission of spiritual awakening to inspire mankind and guide the seekers along the path of Divine Life and God attainment. His renunciation resulted in world welfare. Verily Tyaga is indeed for Loka Hita. We celebrate the auspicious and holy anniversary of Gurudev’s renunciation and Sannyasa this month. I would urge you all to reflect a while upon this great ideal of Tyaga. What is the role of Tyaga in your life? Is renunciation a negative movement? Does renunciation imply denial of the world and your relation to it? Is Tyaga a virtue for Sannyasins alone? What is true inner significance of Tyaga? Dispassion and renunciation comprise the key to inner peace. Such peace alone makes happiness possible. Without peace, there is no happiness. Thus, it is clear that any one who wants peace and happiness must cultivate Vairagya and Tyaga. Attachment and selfishness constitute terrible bondage. Vairagya eradicates attachment. Tyaga cuts at the root of selfishness. They make you free and bring you peace and joy. Life is a great and sublime Yajna. Yajna means self-offering, a noble giving of oneself for the good and the benefit of others. Paropakara is the overall governing principle of man’s life. You can engage yourself in doing good to others, in bringing happiness into the lives of others, only when you shed your selfishness. This is real renunciation. The secret of renunciation is the renunciation of selfishness, egoism and personal desires. Renounce personal selfishness and live in the world, enjoying what Providence brings to you as your due. This is an admonition of the Seer of the Isopanishad. We now see that renunciation is a virtue and a noble quality to be cultivated by every individual in human society. By this alone will the principles of Yajna and Paropakara be fulfilled. Tyaga is not the monopoly or the exclusive duty of the Sannyasins. It is a pervasive virtue that is to permeate and penetrate into every moment of your daily life. Then alone will your entire life flower forth into a thing of countless blessings unto your neighbour and of the society. The loving mother is a true Tyagi. She renounces personal comfort, conveniences and happiness for the sake of her children and their welfare. The father of a family denies himself and renounces many a personal pleasure and profit to serve his family and children. The devout wife renounces all personal considerations to serve and to care for her Lord and Master. The faithful servant renounces personal happiness and comfort to serve his master and carry out his behests in loyalty and devotion. The doctors and nurses renounce sleep, rest and comfort and even forego food at times to look after the sick and the suffering. A brave patriot and soldier stands ready even to renounce his very life for the sake of his country’s safety and welfare. A true social worker and leader of the people renounces everything to dedicate his life for his people’s welfare. A true teacher renounces all personal ambitions and desires in life and dedicates himself to bring the light of learning, knowledge and wisdom to the young people who pass under his care. A saint renounces the whole world and everything in it to worship God and to serve mankind. It is this quality alone
17
MAKE RENUNCIATION THE BASIS OF YOUR LIFE AND ACTIONS
that ennobles human nature and makes life beautiful. Renunciation in the individuals renders sweet all relationship he has with the rest of mankind. Yes, renunciation is to be understood as a pervasive virtue, which rises Vyavahar to pure heights, and adds to the joy, welfare and unity amongst the mankind. Beloved seeker, reflect well over this universal aspect of Tyaga. Renunciation alone enables you to become selfless. Selflessness is soul of life. Selfishness is the bane of mankind and the root of all conflicts, problems and unhappiness. By renunciation, rout out selfishness and become a blessing unto others. Diligently cultivate renunciation in your everyday life. Practise renunciation day after day at home, in thy family, with thy neighbours, playing thy profession, walking the streets, in the market place, everywhere act with renunciation. Grow in this great quality day by day. Never allow selfishness to make your life ugly. Permit not pernicious desire and personal avarice to poison thy life. Shine resplendent with the radiance of true renunciation. Be rooted in true Tyaga. In thought, word and deed, be egoless and selfless. Renounce desire and be filled with peace. Renounce petty selfishness. Become a personification of Paropakara. Renounce Egoism; become an embodiment of egoless simplicity, humility and purity. Such a life is even greater than the life of mere external Sannyasa, which may not be filled with this spirit of real renunciation. Thus has Sri Sadgurudev taught this servant of His. Even so do I speak this unto you in the name of Sri Gurudev, through these pages that bring the Light of His Wisdom to you, who are dear to him. Beloved Brother in the Spirit: Live to uphold this noble ideal of our great culture. Become a Tyagamurti in all walks of life. Even the care that you bestow upon yourself and your personal welfare, let it be based upon Tyaga. Look after yourself that you may preserve and keep fit this body instrument of thine so as to make it an effective instrument for service unto others and to achieve their maximum good and bring happiness into the lives of all. May your life be a witness to this great virtue and left all that you do, be a demonstration of what this noble principle of Tyaga truly means. I close now with my best regards and Prem. We are moving towards a very sacred and significant event, namely the auspicious Punyatihi Aradhana of the first Anniversary of Gurudev’s Maha Samadhi. At this Holy Ashram of Sri Gurudev, we are all earnestly engaged in drawing up a suitable spiritual programme of earnest Sadhana during the whole week, leading up to the Punyatihi anniversary on the 2nd of August. More of this we shall dwell upon in the coming issue of Wisdom Light. Until then, may you all dwell in the abiding peace and bliss of Divine Grace and Blessings. Jai Gurudev. 1st June 1964 —Swami Chidananda
18
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. X
ENSHRINE THY GURU IN THY HEART!
BLESSED ATMASWAROOP, BELOVED SEEKER OF TRUTH, Om Namo Narayanaya. Namaskars. Your blessedness and unique good fortune in this present life is something for which you have to constantly lift up your heart in gratitude and thankfulness to God. Rare indeed is it to obtain a human birth; rarer still is to have aspiration for Moksha; and rarest of all, is the blessedness of the contact of association with an illumined saint and sage. O, Beloved Seeker: Can you realise now your blessedness? Endowed with the first two, you have had the greatest boon in the form of your contact and association with the Holy Master, the illumined Sadguru, Pujya Swami Sivananda. Awaken to this holy privilege. Count this blessedness rightly. Understand your wonderful good fortune. Be fully worthy of it. Ceaselessly seek the immortal. Aspire for liberation. Adore the Divine. Worship Him in gratitude. Pray to Him in thankfulness. Realise the grace. He has showered upon you. Utilise this wonderful life. Rise to sublime heights. Shine radiantly as an ideal person and a noble seeker and sadhaka. Prepare to worship the Holy Sadguru. The sacred Guru Purnima now draws high. It is the great day of all days to every sincere seeker and disciple. Cast you thine eyes back upon this previous year. See how you hast lived these 12 months. Has your life been a divine life? Have you radiated the Master’s Gospel through daily activities? Have you served thy neighbours selflessly? Have you engaged in humble Seva? Have you increased in thy love and devotion to God and Guru? Have you shared and given what He has granted you? Have you diligently sought to purify yourself and cultivate noble virtues in thy nature? Have you remembered God constantly and meditated upon him? Have you aspired after Divine Realisation with sincerity and earnestness and intensity of purpose? Gurudev insists that from the very commencement of our sadhana, we should hold before the mind the ideal of an integral and harmonious development of all the aspects of the personality. Therefore the Sadhaka’s daily routine must contain element of all the four Yoga Margas. The mainstay of the daily routine should be the spiritualisation of the entire life of the Sadhaka. The goal of life should be ever remembered. This goal is the attainment of God-realisation. Whatever the external form the Sadhaka’s life be, the aim of his life should be God-realisation. Keep up the Nishkamya Bhavana in all your daily activities. This is the ‘easy sadhana’ of Gurudev. Never miss an opportunity to serve humanity. Are you striving to be a true Sadhaka? Are you engaging in earnest sadhana? For, primarily Gurudev came to teach us the essence of Sadhana. He came to train and guide us in practical spiritual life. He wanted that our life should be ‘sadhanamaya’. Plunge into Sadhana; that is Sivananda; that is true discipleship, Sadguru Swami Sivananda stands for spiritual Sadhana in life.
19
ENSHRINE THY GURU IN THY HEART!
Be intent on Sadhana. Make your life an integral Sadhana. Stick to your path of Sadhana. Combine all your paths as harmonious helps. Without Sadhana, Self-realisation cannot be had, Sadhana is indispensable. Regularity in Sadhana is indispensable. Sincerity and earnestness are the essential conditions for the fruition of all Sadhana. Make the coming 10-day period from Guru Purnima to Aradhana the commencement of new life of earnest and sincere spiritual Sadhana. Be sincere. This is the key-note of spiritual Sadhana. Let these 10 days be a period of intense spiritual Sadhana, for you, no matter where you are; at home, or at the Ashram. Let this period inaugurate a future of life-long dedication to ceaseless spiritual sadhana, in and through your ordinary daily life in this world. To be a disciple is to be a Sadhaka; always remember this. Gurudev asks you; He looks and sees and tries to perceive what you—His disciple—have been. Look at thyself. Try to be transformed. Aspire nobly. Prepare to worship the Sadguru upon the holiest of Holy days—auspicious Guru Purnima. As the sacred Guru Purnima approaches, with its period of Sadhana, leading upto the solemn Maha Aradhana next month. I send out to you all, my prayerful good thoughts for your all-round welfare, spiritual progress and divine illumination. Even as the moon receives on the full moon day the glorious radiance of the sun in the fullest measure and shines brilliantly; even so, upon this sacred Guru Purnima Day, may you all receive the radiant spiritual light of Gurudev Sivananda in the fullest measure and shine brilliantly with Wisdom, Bliss and Divine Life. May joy and Blessedness be yours. God bless you. My regards, Prem and OM to each one of you. Jai Gurudev Sivananda: Sivanandashram, 23.6.64. At His Feet, Swami Chidananda
Sivanandashram Letter No. XI
PRACTICE GITA TEACHINGS
Salutations to you all, from this sacred Samadhi Shrine of Sri Satgurudev. The holy name of Sivananda has filled the Ashram with its solemn sound this day as devout disciples and devotees congregated for this most auspicious Puja of the Guru. The heavens blessed the day with heavy downpour of rain. A period of serene silent meditation in the early morning attuned the hearts and minds of the earnest seekers with the holy Spiritual presence of Gurudev. Peace and calm pervaded the morning hour. After sunrise, at 8-30 A.M. the principal Puja to Gurudev through His sacred Samadhi commenced with auspicious Abhisheka, Archana with deep devotion, Alankara with profusion of flowers and garlands and Arati. Lord Gurunatheswar Siva shone radiantly with the beautiful silvered Seshanaga and Prabhavli presented by the devotees of Rasipuram. It was a glorious sight. The soft marbled beauty of the Samadhisthan was brought out more fully by the colourful floral adornments. The Divinity of Gurudev was felt in all hearts.
20
ADVICES ON SPIRITUAL LIVING
25 and 26th: The earnest Sadhana has now commenced. Prayer for world welfare and silent Meditation occupies the early morning hour. Worship, Japa, Kirtan, Bhajan, Sravan, Swadhyaya keep all devotees continuously absorbed in God-Remembrance and prayerful mood. They are finding it verily a period of spiritual renewal and revitalization. I have no doubt that most of you too, who have not come to Ashram, have been carrying out a similar programme of Spiritual Sadhana, inward contemplation and worship in the holy memory of Gurudev. Taking advantage of this wave of worshipfulness, seekers all over the world are renewing their inner contacts with their Holy Master Sivananda. As I write these lines my prayers are going out to you, to one and all of you, that the Grace of the Divine and the choicest blessings of Gurudev Sivananda may be showered upon each one of you in abundance. May you all now enter into a new life of spiritual Blessedness rich with higher Experiences. The nation will now turn its heart and mind towards the great ideal of the land, namely, the resplendent Lord Krishna. For on the 30th August we shall celebrate the joyous Krishna Janmashtami Day. Krishna is the Divine Darling of millions of devout hearts. Contemplation of His life is a soul-purifying Spiritual exercise, at once sublime and blissful. Turn to the lofty message of the Lord, the Gita Sandesha of unattached living and selfless loving services unto all beings. Adopt His admonition of constant God awareness during all your activities. Remember—maam anusmara, mayi eva mana aadhatsva, mayi buddhim niveshaya—root yourself in God and perform all activities with joy. May Lord Krishna bless you. At the time of the sacred Maha Puja during the Punyatithi Aradhana day (2nd August), I shall remember you all and offer flowers to Gurudev on your behalf. I shall take extra dips in the holy Gauge for your sake when I bathe upon that most auspicious Day. I shall do Parikrama around the holy Samadhi Shrine thinking of you all. About this worship, in my next letter. Until then Jai Gurudev. My regards, Prem and Pranams, July 1964 Swami Chidananda.
21
HOW BEST TO CELEBRATE SIVANANDA-JAYANTI
Sivanandashram Letter No. XII
HOW BEST TO CELEBRATE SIVANANDA-JAYANTI
Immortal Atmasvaroopa: Blessed Seeker of TRUTH: Om Namo Narayanaya: Loving Namaskars. Glory be to the Divine and to Gurudev, the visible expression of the Divine upon this human place. My salutation to you all, travellers upon the shining highway of Divine Life, pilgrims to the shrine of the Eternal. Jai Sivananda: This letter is the holy Sivananda JAYANTI letter. It brings you my special Birthday-greetings for the auspicious 8th September, which is a great day to us all. It is a day which held the seeds of our blessedness and Spiritual awakening. Upon this day 77 years ago, there took place the dawn of our good fortune or our Bhagyodaya. At the close of the last century, this day granted to us our wonderful Spiritual guide, our inspirer, friend and well-wisher. On this holy day was born our spiritual father, our Gurudev. Sivananda JAYANTI is the day of auspiciousness, joy and extreme sanctity. His advent meant a Spiritual rebirth to all of us who were born into Divine Life through our contact with Gurudev Swami Sivanandaji. Upon this day, the true significance of that ancient prayer of our land— Asato ma sadgamaya Tamaso ma jyotirgamaya Mrityorma amritam gamaya dawned upon us in a luminous way. For, verily, that great soul who took birth upon that day came into your life, awakened your spirit and set you upon the road to the great Reality, Light and Immortality. Such is Sivananda JAYANTI. May your thoughts flow towards his sacred feet in worshipfulness and love! May the Bhava and Bhakti of your heart wind their way up to him now in his tranquil transcendence and silent splendour. May all your energies be directed and applied with determined will and devout loyalty to the vigorous furtherance of his Spiritual Mission of awakening Divinity in the hearts of men. May your time, energy and abilities be dedicated to the leading of the divine life of the Truth, Purity, and Selflessness which Gurudev demonstrated. This is indeed the great privilege of your discipleship. This is indeed the most fitting token of your devotion. Such is indeed the celebration of Gurudev’s sacred JAYANTI. Now a word about the recent Aradhana. It is my deep privilege to tell you all that on the 2nd August upon the most holy Punyatithi Aradhana Day you all did offer worship to Gurudev’s Divine Presence through this servant, who represented you all. In keeping with my solemn promise to you in the August, Sivanandashram Letter, I stood in the holy river Ganges, thought of you all, adored Mother Ganga in your name, and took the sanctifying dips on behalf of you. Then filling a vessel with the Sacred waters. I went up to the Samadhi Shrine, the Gurusthana, vibrant with his silent
22
ADVICES ON SPIRITUAL LIVING
Presence, and offered the Ganga-water in ceremonial Abhisheka for your sake. I then offered flowers and worshipped Gurudev’s marbled Charan-Paduka feeling myself only as a representative of you all in the presence of Gurudev. Thus while I apparently worshipped yet, in reality, YOU offered worship. When the elaborate Puja was ultimately concluded by midday and the rush of devotees was over, I went silently and did Pradakshina (Prikrama) around the Samadhi. And while I thus Perambulated it was verily you who walked around the holy one. While this servant thus worshipped, a photograph was taken, perhaps in the next issue you will see it. A special event that took place during the Aradhana, I wish to recount for your benefit. One day the glory of the Divine Name and the Supreme importance of Japa Sadhana was discoursed upon. In this connection it was later on mentioned how the method of Mantra Purascharana found an effective way of progressing in Japa. I called upon the assembled Sadhaks to come forward and undertake such Mantra Purascharana right then. Numerous Sadhaks readily took the pledge to start and complete Mantra Purascharana before the end of Chaturmasa (i.e. 15th November, 1964). Forms were signed to confirm this undertaking. All commenced it in the Ashram during the Aradhana Period itself. One of the Sadhaks has even continued the Japa in the Ashram itself and will be concluding it by the holy Krishna Janmashtami Day. We are arranging for the customary sacred Havan at the conclusion of this Sadhak’s Purascharana. She is the venerable Mrs. Raj Devi Shivraj of Delhi. Despite considerable bodily discomfort, she had determinedly persevered in her Purascharana. She deserves our congratulations. Two days after Gurudev’s Birthday falls the Vinayka Chaturthi or the holy Ganesha Chouth. Lord Ganesha represents the Divine power in the functions as a force overcoming all obstacles and bestowing success to all undertakings. Therefore, he is called variously Vighna-Vinayaka, Vighneshwara, Siddhi-Vinayaka etc. It is a day of supreme and unique importance on which to commence any new undertaking in your life. Do not let this rare occasion go by. Make new resolutions. Commence any fresh activities. Start any important programme which has been eluding you so far. Ganesh Chouth is wonderful juncture to assure successful commencements and obstacles-free progress in undertakings. Worship Lord Ganesh upon this day. Offer your adorations. Make auspicious beginnings of worthy achievements. May Lord Ganesha bless you with all success, prosperity and progress. I am glad to tell you that Sri Swami SIVANANDA CULTURAL ASSOCIATION, DELHI with its newly constituted executive body is launching into a new programme of public Satsangs in different parts of the Capital to spread more effectively the gospel of Good Life, Pure Conduct, and Divine Living. As an inauguration of these new activities, the Association has decided to celebrate public function of Sivananda Jayanti on 13th of the month (13-9-1964). On the day before, it being second Saturday, it will also hold certain programmes. This servant is to go to Delhi to attend this two-day programme. Incidentally, this enables Delhi devotees to attend the Ashram Jayanti Celebrations on 8th September, I wish the Sivananda Cultural Association all success during the year ahead of them. From Delhi to Dehra Dun, en route return to Ashram, I go because Dehra Dun devotees would like to revive the activities of that centre which have ceased due to misfortune and bereavements of the main organisers of the Divine Life Branch there. Sri Chandravati Singh, Mr. & Mrs. B.N. Kaul, the family of our late revered Gurubhai Dr. R.R. Anand and other friends intended
23
HOW BEST TO CELEBRATE SIVANANDA-JAYANTI
to arrange some Satsang function. I must not forget to tell you that during Sadhana week preceding the Punyatithi Aradhana, many Sadhaks took down notes of important talks and discourses, Dr. Sivananda Adhvaryoo of our Gujarat Centre proposes to compile, edit and bring out a Sadhana Souvenir. It is in preparation. I look forward to its early publication, may be before the end of this year. This reminds me, the present letter now completes a full year of the Sivanandashram Letters. This one, as you will see is the letter No. 12. I hope they have conveyed, to some extent at least, the Bhava with which our worshipful and beloved Satguru Sivananda is making this servant of his work and offer his Seva to His Divine Life fraternity, scattered throughout this country and abroad. These letters, it has been my intention are to convey to you my true feeling my wishes for you and ideas of how we may serve the cause of Divine Life. I am happy to have this opportunity and privilege of thus speaking to you all through these lines. I must now conclude for to be too lengthy would mean depriving you of other matter that comes to you through this “Wisdom Light”. May God bless you all. May health, strength, prosperity and joy be with you all the days of your Life. Be always happy. Work with good cheer. Lead a pure life. Be rooted in God-remembrance. Jai Gurudev Sivananda. With regards, Prem and Om, Ananda Kutir 1st September, 1964. Yours in Gurudev, —Swami Chidananda
Sivanandashram Letter No. XIII
MA ANAND MAYEE GRACES SIVANANDA-JAYANTHI-CELEBRATIONS
Immortal Atmaswaroopa: Blessed Seeker of Truth, Om Namo Narayanaya. Loving Namaskara. Salutations in the name of Gurudev Sivananda and in Divine Life. Your worshipful offering and wonderful response has enabled us here to conduct this year’s birthday Anniversary of Gurudev in a very befitting and satisfactory manner. I am very thankful and grateful indeed for this noble help that came from very amongst you. Last year upon this date I could not participate in the Birthday functions because the Sivananda Cultural Association of Delhi had insisted upon my presence at their function where the Foundation Stone for their Sivananda Satsang Hall was laid by H.E. Rashtrapatiji. This time however, Gurudev granted me the privilege and joy of joining the Gurubhais in this auspicious worship of our holy Master. It was grand and elevating. All gathered devotees felt blessed by this solemn, sacred annual worship.
24
ADVICES ON SPIRITUAL LIVING
A coloured Pada-Puja full pose was set up on Gurudev’s big sofa-chair under the spangled pink canopy of a silk umbrella. A profusion of floral garlands and coloured flowers adorned the glowing picture of the Master. The sandalwood Padukas, which Gurudev used to wear during Pada-Puja time, were placed in the centre of a huge brazen plate around which devout disciples sat in a ring for the Puja. There was Abhisheka, with chant of Purusha Sukta, and then offering of fragrant Chandan and Kumkum. Then commenced the Archana and flowers started raining from all directions through numerous hands. Prasad was offered. Beautiful Arati then followed to the singing of the new Arati composed by the family of Chaman Lal Ji of Chaudausi. He and his daughter Gita were present to lead the Arati upon this auspicious day. A beautiful silken cloth, covered with Pranava-Mantra designs all over, was offered by them for Gurudev’s decoration during the Puja of that day. A wonderful event of this occasion was the visit of the Holy Mother, Sri Ananda Mayee Ma, the great saint well known in India and abroad. This worshipful Mother, a great soul illumined with spiritual radiance graced us all with Her Darshan and blessed with her Satsang all the assembled devotees in the Bhajan Hall upstairs. She arrived first at the Sivananda Eye Hospital at the eager request of Dr. S-Hridayananda Mataji, who wished MA to come and sanctify the hospital by her presence and benediction. After a brief halt there and some little refreshment the holy Mother left for the Samadhi, up the hill. She was highly pleased to see the hospital and know of the good work, being done for countless eye-patients. Offering Her Pushpa-anjali at the Samadhi of Satgurudev, MA shone with a rare light of Divine Prem. Her regard for Gurudev is really immense. She was received by Rani Kumudini Devi of Hyderabad as she arrived at the entrance of Bhajan Hal and then conducted a special dias arranged for her. Swami Vidyanandaji, and his students, gave a Veena recital chanting Sanskrit compositions of great saints, and also did Sankirtan. A blissful atmosphere prevailed, and we all felt spiritually uplifted by Holy MA’s divine presence. I share this wonderful experience with you all, through these lines. I take this opportunity to send you all my greetings and Good wishes for the holy Navaratri period and Dussehra. My VIJAYA greetings specially to Calcutta Gurubandhus and all devotees throughout Bengal. May the Divine Mother PARA-SHAKTI shower her grace and Blessings upon all of you and grant you all prosperity, happiness, success and highest spiritual blessedness. Worship the Mother with the deepest devotion, one-pointed mind and heart and pray to her to make you childlike in nature, namely, innocent, simple, pure, humble, and egoless and unattached. To be born anew in absolute simplicity and humility of nature is the true means of drawing close to God, the Universal Mother Principle, that broods over all existence with Cosmic Love and Protective Grace: Jai Ma Durga: Last month’s function organised by the S. S. Cultural Association at Delhi was indeed very successful and satisfactory. Well attended and keenly appreciated by all who attended them, both the Satsangs created a spiritual atmosphere effectively. It was very glad to participate and observe the success of this programme which was Gurudev’s Birthday celebration for the public of Delhi. The two big sized coloured pictures (one was a huge photo-enlargement) of Gurudev dominated the stage and looked beautiful and grand. Exquisite rendering of devotional Bhajana in classical style
25
MA ANAND MAYEE GRACES SIVANANDA-JAYANTHI-CELEBRATIONS
by artists like Shanta Saxena and others was highly elevating. I am looking forward to this month’s Satsang which will probably be on 10th and 11th Oct. Very glad to tell you all that the Andhra Pradesh D. L. Societies have ultimately fixed up the dates for their 8th Annual D. L. S. Conference. It is to meet at Mehbubabad on 11th, 12th, and 13th December. I have just received a telegram, a few days ago from Sri B.V. Guptaji of that place, who is the convener. I urge upon all the Andhra Pradesh centres of Divine Life to arise and join up and help him in every way to make this year’s Conference of theirs a thorough success, even as the last one of Tanuk was successful. This is their promise as also mine to personally attend it. I hope to meet organisers of all the A.P. DLS. branches in December at Mehbubabad. Tanuk and Hyderabad branches must give special help to Sri Gupta Saheb in every way. Winter weather is gradually setting in now and the breeze has become a wind and it now has a chilly edge that makes you want to draw your cloth closer around you. End of last month after two days of almost non-stop rain the Ganges rose up in flood. One wondered if Gurudev’s Kutir would be threatened like last year. But fortunately the rain ceased on the third day and the flood level slowly subsided. Today the sun shone bright and the sky is a beautiful blue and it seems that the rains have taken leave of us for the present. The thatched shed we had put in front of Sri Gurudev’s sacred Samadhisthan for the Aradhana functions of 2nd August has indeed weathered the season. It has now become very helpful and convenient for devotees and worshippers, who are visiting the Samadhi in increasing numbers. Our brother Sri Swami Sharadanandaji who was for five years in the icy upper Himalayas near Gomukh and Gangotri has now returned to Ashram and is taking keen interest in imparting Yoga-training to eager young seekers, who came to this place, seeking practical Yoga instructions. Some students from France are also reaping the benefit of his kind and selfless efforts in this direction. Thus the work of Gurudev goes on under His benign inner guidance and unseen help of His Spiritual Presence. May Gurudev’s benediction be upon you all. I shall now leave you to prepare yourselves for the forthcoming solemn and auspicious nine-day Pooja of the blessed Divine Mother of the Universe—the great Bhagawati Para-Shakti. Worship Her with all thy heart’s deepest devotion reverence and loving adoration. May SHE grant you all health, long-life, prosperity, all divine Aishvaryas and Vidya, Pushti, Tushti and Parama Shanti. Glory be to the MOTHER. Hari Om Tat Sat. I close with regards, Prem and Pranama. Sivanandashram, 1st October, 1964. Yours in Gurudev Swami Chidananda
26
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XIV
STRIVE TO MAKE LIFE A PERENNIAL DIVALI
IMMORTAL ATMA-SWAROOPA: BLESSED SEEKER OF TRUTH, Om Namo Narayanaya: Loving Namaskaras. Salutations in the holy name of Gurudev Sivananda and in Divine Life. Let me first of all offer you my best Goodwishes and Greeting for a Bright and HAPPY DIVALI DAY. May Joy, Brightness and Auspiciousness fill your life and may Divine Mother Lakshmi smile upon you as prosperity, plenty and progress in everything you do. Happy DIVALI to you and to all in thy home and thy friends too. The spirit of Divali is the spirit of gladness and friendliness unto all life. Joy is the essential nature of Man and love and friendliness is to man the natural relationship with his fellow-beings. The significant act during Divali is the lighting of lamps to brighten every nook and corner so that all darkness is put to flight. In your life the Light of virtue, purity and goodness shall verily banish the darkness of impurity and evil. Joy comes where virtue abides. Peace prevails where goodness fills the heart. Suffering and sorrow are the result of selfishness and hatred. Ignorance is the source of evil. Wisdom is the Light to dispel this Darkness of spiritual Ignorance. The Presence of God pervades this universe. O Man: Know this and live in virtue and holiness. For thou art ever in the Presence of the Most High. HE alone is the reality indwelling all names and forms and all beings are verily His moving tabernacles. This is Wisdom. Light up thy life with this wisdom and dispel the darkness of worldliness and materialism from your life. Live to bring the light of Joy into the lives of one and all. Light up bright little lamps of kind words, kind actions, helpful deeds, loving good thoughts and smile upon one and all by looking upon everyone as your own. No one is a stranger to you in this universe. All are your own. Thus love all and seek to serve and to bring comfort, joy and well-being into the lives of all. By your own life strive to make life a perennial Divali unto others. Within the interior of thy own being do likewise and light the lamps of devotion and prayerfulness. Let not the darkness of desire or of selfishness mar the inner chamber of thy heart-shrine. Bright and clean keep thy heart fit to install the Lord therein and to worship Him with the flowers of Devotion, Truth, Self-control, Forgiveness, Compassion and Penance. Feel happy at the happiness of others; then your life will become filled with the Radiance of a constant Joy which nothing can mar. The selfish individual has a very limited unit of happiness available to him. But who finds joy in making others happy, his happiness is ever expanding and knows no limit. This is a secret of Divali. The more lamps you light the greater the radiance you become bathed in. Is it not happily significant that the Divali follows soon after the nine-day worship of the Divine Mother? Does this not perhaps give you an insight into a great and sublime Law of Life? He who adores the Divine and propitiates the Universal Mother draws down the Grace of the Supreme and finds his life becoming filled with Light, Joy and Auspiciousness. Life smiles upon him and he
27
STRIVE TO MAKE LIFE A PERENNIAL DIVALI
now rejoices in the blessed radiance of God’s Grace. Navaratri brings Divali in its wake. Therefore, O Man: worship the Divine and reap joy and peace. This season holds for you a great lesson on the place of wealth in human life. You know very well indeed that all great Teachers of Mankind, all saints, sages and holy men have declared that money is the root of all evil. It is the seed of sorrow and the prolific source of corruption and sin and vice. Kalipurusha is said to have made gold the seat of his residence. Renunciation of money has ever been the indispensable condition of entry into spiritual life. Renunciation of ‘Kanchana’ is the first step in the quest of God. Yet in the Divali season we know that heaps of coins, silver and gold are actually worshipped in many parts of India. Lakshmi Puja is widely observed by the business communities everywhere. What does this mean? Is it totally against tradition and accepted beliefs? No, this is not so. There is a deep lesson in this. It serves to teach you the sanctity of wealth. Money and wealth are manifestations of the Divine Mother Maha-Lakshmi and are truly a sacred trust placed at your disposal to be used for the purest purposes and in the noblest way. Money does not constitute evil. Greed for money is evil. Living for money is the worst evil. Sheer selfish utilisation of money is the bane of human life. Money can ennoble or degrade according to man’s concept about it and attitude towards it. With money you can build a hospital or erect a slaughter house. With money you can raise a temple and a house of prayer or start a gambling house or a liquor shop. It can be utilised to help countries and people or to make war and destroy. You can use wealth to ennoble human nature or to debase human lives. It can bring happiness or cause sorrow. This is money. Regard it as a sacred trust to enable you to fulfil your moral obligations and duties and use it selflessly for Paropakara and Lokahita. Charity is the main function of wealth. Its secondary function is one’s own survival and comfort. Charity is a great purifier. It “covereth a multitude of sins”. Exclude all greed and selfishness in regard to wealth. Know it to be Divine Shakti. Treat it with reverence. Approach it with purity of heart. Utilise it WORSHIPFULLY. This is Lakshmi Puja and its lesson. It is in this light that wealth has been given a place in human life by our ancients. Thus conceived, has it been included as one of the four Purusharthas by our sublime Culture. Acquired honestly and by pure means, handled without greed or attachment and utilised in reverence and worshipfully, your wealth can enhance Dharma, purify your life, free you from bondage and take you towards Moksha. It becomes filthy Lucre when you abandon Dharma for the sake of money and sacrifice virtue at the altar of Kanchana. Remember this and keep up the sanctity of wealth and utilise it worshipfully All auspiciousness will come into your life. Perhaps, you know that during this month four great Spiritual Anniversaries sanctify our lives. The six-day worship of Lord Kartikeya or Skanda commences on the 5th and concludes on 10th. Then we have on 14th November, the Yajnavalkya Jayanti of tremendous significance in our Culture. The discourse between sage Yajnavalkya and Maityeri is one of our most treasured heritages. Next comes the holy Tulasi Puja, a sacred day for all devout ladies. Tulasi symbolises the ideal feminine virtue in this Land. Women all over India worship the sacred Tulasi praying to be blessed with the precious wealth of modest purity, modesty, chastity and Pativrata Dharma. This is the bedrock of Indian Spirituality. The full-moon this month marks the birth Anniversary of the most worshipful saint GURU NANAK. He came to spread the true religion of Spiritual living in
28
ADVICES ON SPIRITUAL LIVING
this land of five rivers. He restored the spiritual ideals to our religion which was being weighed under the mass of dry ritual. Religion is to be lived not merely believed in. A life of truth, selflessness, devotion unto God, love of all beings, Purity of conduct and humility, selflessness and compassion constitute the true religion that the great Guru Nanak proclaimed. O beloved seeker: What most precious wealth does not our Cultural heritage hold for us? Leaving this priceless treasury of gems why should you imitate the West and run after the worthless fashions and meaningless values. Enrich yourself with that which is your own by inner wealth of Mother India which knows no parallel and is inexhaustible. Come: be a true child of Bharatavarsha: Be a true heir to great illumined men of wisdom who founded our culture. Manifest Divine life. Be a noble Sadhak. May God bless you. I close with regards, and Pranams. Jai Sri Gurudev. 1-11-64 Swami Chidananda.
Sivanandashram Letter No. XV
THE MYSTERY OF THE SUPREME DIVINITY IS REVEALED IN SRIMAD BHAGWAD GITA AND THE BIBLE
Immortal Atma-Svarupa: Blessed Seekers of Truth: I greet you all in the name of our blessed Lord Gurudev Sivananda and in Divine Life. I greet you all in the name of our blessed Lord Jesus the Christ, the Great Messenger of God, who incarnated upon earth to teach men for all times, that way of life that brings you face to face with God. In the history of mankind, there has rarely been a life as holy, as pure, as divinely compassionate and sublimely truth-filled as the life of Jesus. He was the very personification of loftiest virtue. Very few in all the range of human history have been the beings so full of a motiveless, spontaneous and all-encompassing love and Divine compassion radiated through every atom of this Godly being. Jesus verily lived the highest ideal of Divine Life. This month is the holiest of all months in the calendar for it is the blessed advent of this great Teacher of mankind. Christmas is the holy period for Spiritual joy and inspiration unto a higher life. The pattern of life demonstrated by Jesus is one of intense and almost effortless doing of good deeds to help others and to bring joy into their life. His ideal saintly life rested upon a foundation of deep devotion, prolonged prayer, much penance and inner contemplation. His was not a soft life of ease or comfort. Austere simplicity, strenuous and rugged open air life, food that chance had brought and no fixed abode,—such was the life of the Master. His flaming spirit of renunciation, his absolute desirelessness and his total surrender to the will of God constitute his fundamental call to modern man. Humanity of today has created a Hell upon earth for itself by its extreme egoistic self-will, its insatiable desires without end and its intense greed and clinging attachments. To live as Christ lived
29
THE MYSTERY OF THE SUPREME DIVINITY IS REVEALED IN SRIMAD BHAGWAD GITA AND THE BIBLE
would be to free oneself at once from this binding net of man-made sorrow and to experience peace and joy of God’s Kingdom hereupon earth. If only the world today could observe Christmas instead of celebrating it, it would soon be walking out of darkness into light. May the spirit of Jesus help man to move towards God. The Lord be with you: May His Light lead you on the pathway of life through all the coming years. In this month of Margashirsha it is that, many centuries ago, Lord Sri Krishna delivered His immortal message to mankind through His disciple Arjun. Sacred Gita Jayanti is to be observed on the 15th of December, throughout the length and breadth of India. Arrangements are afoot to conduct this memorable Anniversary at Kurukshetra continuously for a period of eighteen days (from December 15th, 64 to January 1st, 1965) with a programme of holy gatherings, religious Conferences and Spiritual discourses. This servant of the Master has been invited to participate in at least one entire day’s programme there. It is possible I may make this immediately after conclusion of the Chandigarh All-India Divine Life Conference which ends on 27th December, 1964. On the 28th or 29th December I am thinking of taking as many of the delegates and functionaries of the Conference as are willing to accompany and go to Kurukshetra for a day’s camp and service there. It will be as Gurudev may wish it to be. I would urge everyone of you to take to a systematic study of (and a devout and humble study at that) the Bhagavad Gita and the New Testament of the Bible from this month onwards. This will bring about a transformation in your entire life, I promise you. And if possible make your acquaintance with Thomas A’ Kempis’s “Imitation of Christ” as well as the 11th Skandha of the Bhagavata Mahapurana. An English translation of this letter text is available from the Ramkrishna Mission Publication Department. Srimad Bhagavad Gita and the 11th Skandha of Srimad Bhagavta Maha Purana, containing as they do the direct personal teachings of Bhagavan Himself, sum up the entire range of spiritual wisdom and highest Upadesha. The mystery of the Supreme Divinity is revealed therein. Learn from this world. There is much it has to teach. Life itself is a school. Life is full of essence. Everything perceived through the senses could verily be more than books and sermons if you would learn to see the hidden wisdom underlying such perception. All your experiences come with a message to you. Those who have eyes, can see. Be a learner always. Wisdom can be gathered between each sunrise and sunset. Thus at each eventide can you find yourself wiser than you were at daybreak. Even the very elements exist to teach. Thus declared the great teacher of mankind Sri Dattatreya, the Parama Avadhuta. This shared wisdom of his is to be got in the 11th Skandha as well. The holy Birth Anniversary of the Lord Dattatreya that occurs on the 18th, brings to my mind this great wisdom-treasure imparted by Avadhuta Dattatreya to the great Yadu. Study it in Adhyayas 7, 8, 9 of Skandha 11. Last month has been a month of great spiritual activity in different parts of India. An important one among them has been the Maha-Rudri-Yajna conducted at Amritsar in Punjab under the direct personal blessings and presence of their exalted Holiness, the three great Jagadguru Sankaracharyas of Dwarka, Joshimutt and Puri. Blessed indeed were the fortunate souls to have the Darshan of these great Spiritual luminaries. The Vedanta Conference of H. H. Swami Nirmal and the Punjab Gita Conference of H. H. Vedavyasji created Spiritual waves too. This servant’s visit to Lucknow, the Capital of Uttar Pradesh provided scope for much spiritual service. Two new branches of the Divine Life Society have been started in Aligarh. This month too is proving to be a
30
ADVICES ON SPIRITUAL LIVING
month of much activity. I am soon to leave to South for the 8th Andhra Pradesh Divine Life Conference at Mehbubabad. Shall be at Hyderabad on 8th December and attend the conference at Mehbubabad on 11th, 12th and 13th December. On my way back to North to participate in the 17th All India Divine Life Conference at Chandigarh I shall break journey for a day at Kirkee (Poona) to meet the Divine Life workers of that branch as also to go to have Darshan of the venerable Sadhu T.L. Vaswanji and offer my love and respects to the holy man of God. There was deep affection and Spiritual friendship between revered Sadhuji and our worshipful Gurudev. From Poona straight North to be in good time for the Chandigarh Conference. Significantly, this conference opens upon the holy Christmas Day. I am hoping to be back at the holy abode of Sri Gurudev by the 31st of December to be present at the sacred Pratishtha Anniversary of the holy Sri Vishwanath Mandir of the Ashram. This also means the new year’s eve, for the Mandir Anniversary is on the last day of the year. Before I close now let me request all of you to sing the most sacred and exalted Mantra of this Kali Yuga, namely, the supreme MAHA MANTRA. It was in this month (on the 3rd) twenty-one years ago that Gurudev initiated the Akhanda Maha Mantra Kirtan Yajna at the Ashram Bhajan Hal for World-welfare and peace. This great Mantra raises you to sublime level of God Experience: Hare Rama Hare Rama Rama Rama Hare Hare Hare Krishna Hare Krishna Krishna Krishna Hare Hare Repeat this every night before you retire, breathing a prayer for the world-welfare and peace. May God bless you. With my deepest regards and Pranams, Jai Sri Gurudev. Ananda Kutir 1st December, 1964. Yours in Sri Gurudev, Swami Chidananda.
31
THE HOLY TRAIL BLAZED BY THE LIVES OF SAINTS
Sivanandashram Letter No. XVI
THE HOLY TRAIL BLAZED BY THE LIVES OF SAINTS
Immortal Atma Swarupa! Om Namo Narayanaya! Jai Gurudev! Please accept my most reverential salutations at thy holy feet and my loving greetings and good wishes for this NEW YEAR. May all health, prosperity, happiness and fulfilment be yours throughout this year and the years ahead. God grant you joy, wisdom and grace and bless you, thy home and all that are dear to you with auspiciousness and highest good. My prayerful good thoughts go out to you all, wherever you may be, and I seek from the Almighty thy welfare and advancement, here in this world, as also thy highest blessedness and illumination in the spiritual realm. May the Divine abide with you! And may you abide in Him! At this auspicious beginning of a bright New Year, let us sanctify ourselves by the devout remembrance of the great holy men of God, the saints, sages and divine messengers of this world, who have declared to us the true meaning and lofty purpose of our life, shown us the way of its fulfilment, and inspired us to follow this holy upward path towards God and divine experience. Let us sanctify ourselves by remembering their ideal lives and exalted teachings. Turn your thoughts now, and lift up your thoughts to a devout and joyous contemplation on sage Vyasa and Vasishtha, on Narda and Valmiki. Contemplate on the glorious Lord Buddha, Jesus the Christ, prophet Mohammed, the noble Zoroaster (Zarathushtra), Lord Mahavira, the holy Guru Nanak. Think of the great saints and sages of all ages, like Yajnavalkya, Dattatreya, Sulabha and Gargi, Anasooya and Sabari, Lord Gauranga, Mirabai, Saint Theresa and Francis of Assisi. Remember St. Augustine, Jallaludin Rumi, Kabir, Tukaram, Ramdas, Ramakrishna Paramhamsa, Vivekananda and Rama Tirtha. Adore in thy heart the sacred memory of Mahatma Gandhi, sage Ramana Maharishi, Aurobindo Ghosh, Gurudev Sivananda and Swami Ramdas. They verily are the inspirers of humanity towards a life of purity, goodness and godliness. Their lives, their lofty examples, their great teachings constitute the real wealth and greatest treasure of mankind today. To think of these saints, to carefully study their lives and to live by their teachings is the only way of rising above suffering and sin, of going beyond pain and death, and attaining true peace and perennial joy in the Divine. There is no other path to true welfare and blessedness than to follow the footsteps of the holy men and saints. There is no greater blunder than to forget the saints and live an aimless life. It is a great loss to waste away your life in meaningless pursuits of fleeting sensations and perishable objects here. There is no greater folly than to ignore and neglect the teachings of these great souls and destroy your own welfare and weep at the time of death. Beloved child of God! Awaken to thy great heritage. Walk the way of purity, truth and goodness. Serve the world and worship God. Diligently work out thy supreme welfare. Fulfil Dharma at every step. Remember God at every moment. You do not belong to this material world. Beyond this physical and mental existence, there is a life spiritual. Therein lies your true avocation and true and loftiest function. Live in this Spirit. Know thy true Swarupa. It is Satchidananda. Thou
32
ADVICES ON SPIRITUAL LIVING
art immortal Spirit. Thou art the deathless Soul. Thou art eternal Self. Thou art divine. Live divinely. Live in God. Wherever thou art, whatever thou doest, in whatever condition you are whether in joy or sorrow, whether in health or illness, whether at home or in foreign land—live in God always, everywhere, in all conditions. This is wisdom. Herein is happiness. Herein lies thy true good. Do not postpone for tomorrow that which you ought to, and must, do today. “Tomorrow” is a deceptive thought that ensnares soul the unwary and binds him in the net of forgetfulness. Time is fleeting. Days, nights and years pass away. Death snatches you suddenly. This rare opportunity is lost. Beware. Remember death Cultivate virtue. Do good deeds. Live for God. Do not waste time. Be up and doing. Utilise every moment in virtuous living and spiritual Sadhana. Remember death. There is no pleasure in the perishable objects of this world. There is no true happiness and peace here. Senses deceive. Mind is the enemy. Samsara is full of defects, pain, bondage, fear and a thousand afflictions. You must transcend them all by attaining God and realising the self. This is the true aim of life. This is life’s ultimate goal. God is bliss. God is peace. God is eternal life. To attain Him is to go beyond all sorrow, pain and suffering and enter into a state of unalloyed joy, fearlessness and freedom. This is the supreme blessed state you have come to achieve. The sure and unfailing way to this attainment is shown by the radiant lives of saints. Live in the light of their shining lives. Thus is the path unto perfection. By their lives, the saints show you the gateway to God. O man wander not any longer in this vast forest earthly existence. Tread the radiant path that leads to Divinity. Start now upon this auspicious period of a New Year. One more year has gone by. Life is shorter and time flies away. Be wise. Be resolute. Heedfully awake, alertly vigilant, sincerely aspiring and earnestly striving and praying, live wisely and move towards God, and thus make a true success of this precious life of thine. May God bless you all. May the spiritual benedictions of all the holy saints and sages be upon you! May you lead a divine life and attain your highest welfare here and now. With regards, Prem and Pranams, Yours in Gurudev, 1st January, 1965 —Swami Chidananda
33
TOUR IN THE SOUTH. MEETING WITH DADAJI. THE CHANDIGARH CONFERENCE
Sivanandashram Letter No. XVII
TOUR IN THE SOUTH. MEETING WITH DADAJI. THE CHANDIGARH CONFERENCE
Immortal Atma Swarupa! Blessed Seeker after Truth! Om Namo Narayanaya! Salutations in the name of Gurudev Sivananda. I greet the Lord in you all and pray that the blessings of the Lord of the Universe, Bhagawan Vishwanath, may ever be upon you and fill your life with auspiciousness, joy and prosperity. I write this to you in the fond belief that the first month of this year has been for you one of peace, good health, harmony and Spiritual progress. May this month be a blessed one too. Similarly also be the months coming ahead. I want to express my thankfulness to the numerous good friends in India, as well as from several countries abroad, who have remembered me with so much love, and sent in their Christmas and New Year’s greetings, and expressed their great goodwill towards this servant of Gurudev, as well as, other Ashramites of this abode of Gurudev. Trying though I am to acknowledge all of them individually, I still take this opportunity of saying, “Thank you very, very much indeed” to every one of these gracious souls. May they ever dwell in the remembrance of the Supreme Lord, who is the sublime connecting link between us all here. Those of you who constantly endeavour to remember God and to be aware of His ever-Presence, with such I am always close in Spirit. I say that we are together when we strive to keep ourselves in the presence of the One Reality. True spiritual brotherhood is wrought by the oneness of our common goal and the common centre of our abidance, namely, God. Man’s true relationship is with God and God alone. All other relationships are transient, fluctuating and essenceless. He who loves mankind for the sake of the Divine that indwells man, such a one has verily established oneness with humanity. This relationship is based upon the eternal essence of our existence. Could not this also be the basis of the universal weal and world peace? You will be glad to know about some specially interesting Divine Life activities that took place in the closing month of the recent year. This servant has been absent from the Headquarters Ashram practically whole of December and a good part of last month, i.e. January 1965. Soon after returning from Aligarh at the end of November last, I left on tour on my way to Mehboobabad, near Hyderabad, Andhra Pradesh. The first halt was at Delhi, en route to the South, to fulfil a few engagements at the Capital. On December 6th, there was a wonderful Satsang arranged by our devoted Gurbehn Srimati Vanibai Ram (known here as “Sivananda Vani”) at the house of the Honourable Reddy Ji. That evening, H.H. Sri Swami Parvathikar Maharaji held the audience spell-bound and thrilled, by a wonderful musical recital upon the Svara Mandali and rare Rudra Vina. He lifted our hearts into sublime heights by his music, which in places was almost all-inspiring in its solemnity and subtle and ethereal melody. It was a rare spiritual treat offered in worshipfulness at the feet of Lord Badri Narayan by this unique Nada Yogi, Parvathikar Maharaj. During that Satsang, Sir K C. Reddy Ji made a beautiful speech. Next day I had the joy of visiting the Swami Sivananda Rehabilitation Centre which is being conducted by another noble Gurbehn, the very sincere Mrs. Varalaxmi Rao. She has established it for the training of members of
34
ADVICES ON SPIRITUAL LIVING
lower-scale income group families in different handicrafts, so that they are enabled to supplement the main wage-earner’s income. This is very beautiful enterprise and I wish it success and much future development. On the morning of the 8th December, this servant arrived at Hyderabad and my heart still heaves with joy, when I remember the wonderful welcome and the love that was showered upon this servant by all those devotees in Hyderabad that day. The devoted Sri Sivananda Kumndini Devi, Sri B. Ramadasji (or the A. I. R.), the very earnest seeker Sri Vijayarangamji, Sri Rajeswara Rao, Sri Gautam and numerous others came and met me in the name of Gurudev’s work. Revered Sri Subba Rao Garu, Gitavyas, was graciously present in all affection. We had some public lectures, morning prayer-gathering at “Sivananda Griha”, and also visited the Leper Colony run by Rani Kumudini Devi at Kukkutapalli. I still remember the nice visit to the Bolaram Branch, whose members meet near the Hanuman temple. Then we all went to Mehboobabad for the Eighth Andhra Pradesh Divine Life Conference. It was in every way a very satisfactory and successful conference. Very inspiring programmes of spiritual discourses, thrilling Nama Sankirtan, religious music, Asana demonstrations, etc. provided a spiritual feast for crowded audience. Dr. Menon from Warangal conducted Prabhat pheri with his party and filled the town with divine vibrations of the Lord’s Name. Sri Avadhutendra Swami’s Kirtan was unforgettable. So was Sri Sadhu Janabai’s discourse on Gita. All the arrangements were perfect. Due to Shri Surendra Reddy’s earnest selfless efforts, numerous delegates were looked after excellently. But for his wonderful thoughtfulness and consideration, coupled with the great kindness and care of blessed mothers Kumudini and Niranjani, this servant of Gurudev would never have been able to stand the strain of the Conference programme. So bad indeed was his physical condition at that time, but these three were veritable angels. They took care of every little detail of his physical requirements and comforts. God bless Surendra Reddy. This young man is an inspired Karma Yogi. I must also congratulate Sri B. N. Guptaji whose pious Sankalpa was the very root of the Conference. Other Branches cooperated very beautifully and nobly in guiding the three-day programme. I was happy to meet (as I had eagerly expected to meet) good friends like Sir N. S. V. Rao, Dr. Gopal Krishan Murthy, Tettali Ramachandra Rao, etc., from Tanuku. Gita-Vyas Sir Subba Rao Garu was of immense help to this servant in interpreting English talks in Telugu to the assembled people. The Conference was, indeed, an expression of Sri Gurudev’s Achintya Sakti. All glory to the living Spirit of Gurudev Sivananda! He continues to inspire us to awakening. On December 14th, we drew back to Hyderabad, reaching there at 2 P.M. That evening there was a visit to Medichal for a Satsang at that Branch at the pressing request of young Subba Rao. From Medichal we went to Trimulgherry E.M.C. for a Satsang arranged by Sri Gautam of the Centre. It was a great joy to visit that beautiful temple with its big Satsang Mantap and speak to the assembled Army personnnel, who listened with rapt attention. That night we left by train for Kurnool, where we arrived next morning. There, the foundation-stone was laid for a Sivananda Ashram close to the river Tungabhadra. Sivananda Sirnivasa Rao had arranged nice programmes which included an address at the local Mahila Mandal. We stayed at the home of the pious and noble Mr. Pasupati, retired Headmaster of the local High School. During this period we were taken for a visit to nearby Alampur across the river, to see the very famous temple of Lord Siva, where
35
TOUR IN THE SOUTH. MEETING WITH DADAJI. THE CHANDIGARH CONFERENCE
Adi Sankaracharya has established a Sakti-peetha by doing the Sri Chaka Sthapana. Here, Sri Anasooya Mata, our Gurubehn, a Vendantini, entertained the entire party at her ancestral home. From Kurnool we were taken to Hospet at the earnest insistence of Gurudev’s great devotee and disciple Sri G.T. Veeriah. This devotee’s Bhakti-bhav is unique and wonderful. He had arranged his son’s marriage on the day after our arrival (17-12-64) and invited all his friends. This wonderful man converted his marriage house into a Satsang Bhawan and a veritable temple of Sivananda Gurudev. Gurudev’s picture shone resplendent on a beautifully decorated altar. The marriage was performed at this altar, under the gaze of Gurudev as it were. And your Swami Chidananda was made to bless the young couple as the representative of Gurudev. To this wonderful family, Gurudev is living reality. The entire family is simply filled with Guru-prem. Their devotion, their faith, their Bhav is some thing which I cannot adequately describe, and the special point about this marriage was that this alliance was personally blessed by Sri Gurudev himself seven or eight years ago, when both the families had come on pilgrimage to this Ashram, and the betrothal was solemnised at Sri Gurudev’s Kutir on the Ganges bank. Gurudev placed both his hands on the head of the boy and the girl who were young children at that time. The photograph taken at that time is still treasured in their home and it was very much on display during the auspicious event. At Hospet, Sri Murlidhar took us to the Tungabhadra Dam Project where the Engineer-in-Charge very kindly took us round and explained all the workings of the power plant. We also visited the famous ruins of Hampi. This Sevak had the privilege of addressing the public of Hospet that evening and giving a talk to school and college students. It seemed that the entire town cooperated in the two-day functions. Hospet was a feast of love. Gurudev’s name spread everywhere. The next halt, Kirkee, Poona, Sri Sirvaramakrishnan and Sri Srivinasanji of Kirke Branch had arranged a very nice programme of Satsangs, public lectures and talks to students. The most blessed event here was the unique opportunity I had of placing my head at the holy feet of our beloved and worshipful Dadaji Sadhu T.L. Vaswani Maharaj. I was filled with happiness. I considered myself most sanctified by this holy God-man’s Darshan. I treasure the warm embrace of divine love in which he graciously enfolded this servant of Gurudev during the prayer gathering in the sun-lit garden of his Mira Centre. My thanks go to Sri J. P. Vaswani who arranged for this spiritual meeting and to Sri Gangaram Sajandasji, his beloved colleague. They are rare flowers in the spiritual garden of adorable Dadaji. We left for Bombay on 20th December. Sri G. V. Parameswaranji of Divine Life Society Branch had arranged a Satsang that night at his home in Khar. I was glad to meet there H. H. Swami Sivananda-Krishnananda Mata and also to listen to the beautiful Bhajans by Premanand of Ananda Ashram, Kanhangad. Thence, the Chandigarh D. L. S. Canference summoned me North once again. This Conference, conceived by H. H. Sri Swami Premanandji Maharaj, executed with the wonderful help and noble efforts of Sri Ravindra Nath Ji, Sri L. R. Magon, Sri Suraj Prakash, Sri Har Datt Sharma and others was a grand success. It was inaugurated by Comrade Ram Kishan, the Chief Minister of Punjab, who gave a thrilling speech upon the need for ethical values of public life. The full report of this Conference appears in the Branch Gazette as well as in the Divine Life Magazine. The highlight of this Conference was the thrilling speeches by H. H. Sri Swami Nirmal Maharaj of Amritsar. He is a wonderful man. En route to the Conference, we had very nice Satsang at Delhi at the residence of Sri K. C. Reddy Ji, now Rajyapal of Madhya Pradesh.
36
ADVICES ON SPIRITUAL LIVING
Your servant was able to be back at the Ashram on the 31st December, just in time to participate in the holy worship to celebrate the Anniversary of the Pratishtha ceremony of the Ashram Viswanath Temple. There was a grand Maha Puja at mid-day. We had a special Satsang at 3 P.M. in the afternoon on that day; and that night the usual Satsang went on till 12 mid-night (it was the last Satsang of the departing year 1964!) when we marked the advent of the New Year with chanting of the Divine Name and prayers for the world welfare. Thus we moved into 1965. We wished one another “Happy New Year” and retired to sleep. December was practically a month of travels and the carrying of Gurudev’s message and the Divine Name into distant corners of Bharatvarsha. Beloved Seekers, I send you greetings of joy and auspiciousness for the occasion of the beautiful and colourful BASANT. February 6th is Basant Panchami. May the Gods smile upon you and rain down blessings to make your life flower forth into gladness, rejoicing and plenty. This month also celebrates the holy and inspiring memory of the great Guru of the heroic Shivaji Maharajah. You will know the name of this august saint SAMARTHA RAMDAS, a God-realised soul who spread the message of Dharma and courageous faith in defence of sublime principles against all odds. He preached the gospel of Ram Nam and Ram Bhakti as the supreme path for your welfare, here as well as hereafter. Ramdas stood for sterling character, devotion to duty, service of mankind and dedication to divine worship. Study his wonderful books Dasabodha and Manache Shlok. May His blessings be upon you all! Now, just before I conclude, I exhort you all to prepare to observe the most holy and sacred Sivaratri festival that falls on the last of March. Meditate on Lord Siva. He is the embodiment of perfect mastery over external nature (Prakriti or lower self) and perennial abidance in the Divine Reality within. All Siva Bhaktas should commence a Purascharna of the Panchakshari Mantra from the moment that this line is read by them. Make up your mind to complete five lakhs of Japa (Aksharalaksha Japa) by the first of March. Perform a Havan on Sivaratri Day. If not, repeat some extra Malas of Japa in lieu of Havan. Lord Siva will be immensely pleased and will shower His divine grace upon you. May all health, prosperity, joy and blessedness be unto you. Om Namah Sivaya! Jaya Gurudev Sivananda! God bless you. With regards, Prem and Om, Ananda Kutir, Rishikesh 1st Feb. 1965 Yours in Sri Gurudev —Swami Chidananda
37
THE SPIRIT OF MAHASIVARATRI. TOUR OF GUJARAT
Sivanandashram Letter No. XVIII
THE SPIRIT OF MAHASIVARATRI. TOUR OF GUJARAT
Immortal Atma Swaroopa! Blessed Seeker of TRUTH! Om Namo Narayanaya. The Divine Grace of the Lord of the Universe, Jagadeeshwara Mahadev, the Vishwa Natha, shower upon you and fill your life with Light, Joy and supreme Peace of Atman! Maha-Siva-Ratri, one of the holiest of holy days in this land of ours, would have been observed from the Himalayas to Kanyakumari by the time this letter comes to you. Worship of the Great God with intense devotion and holy fervour would have been witnessed all over India and the spirit of worshipfulness and adoration would have purified the Nation’s atmosphere with its unique spiritually sanctifying touch. Devotion should pervade the entire life-process of man here on earth. To live is to adore the Divine each moment of your life. To know and to be aware that God resides in all living beings, nay, in all things animate and inanimate, is verily the source of all righteousness. This knowledge is the root and support of Dharma. No man would injure another when he is intensely aware that God is in him. For he would be directly offending Him! Therefore, see Him in all and act with devotion and reverence towards all. Sarvam Shivamayam, Sarvam, Vishnumayam. Thus let thy heart whisper within with every beat. Let thy blood flow to the rhythm of this sublime truth. Let thy body pulsate to the note of this constant assertion—every thing is permeated with the Divine Essence! Then indeed will every act of yours become a sacred sacrament, a spiritual Yajna, Mahapuja. This is the glorious truth about your life. Arise to the dawn-light of this luminous Vision. See God here and now! And worship Him here and now. In this lies the grandeur and the blessedness of human life. Gracious, most gracious indeed is the Lord. Avail of His Grace Divine, the ever-present Love that is ceaselessly pouring upon us all. The irony of human life is not the withholding of Grace by a remote Divinity, but actually, man’s rejection of the ever-present Love and Grace, running madly after egoistical pursuits and fleshy sensations. He would rather dedicate his entire life to his five senses than open his heart to the descent of Divine Love and Grace that seeks to enfold him in its infinite compassion and uplift him to the supreme blessedness. Modern men and women should consciously seek to feel and recognise the nearness of God and the fact of His Love. This is an important task in your life. Your life is not just fleshy sensation and silly sentiment. Cultivate the deeper level of thy inner being. Become increasingly conscious of thy close kinship in your essential nature with the Cosmic Being. You are never apart from him. You are linked and spiritually related to Him every moment of your life and eternally. This knowledge is the only real Bread of Life that nourishes your being as no other earthly nutriment shall ever be capable of doing. This knowledge is not only the Bread of Life, but is Life itself. O Man! Be nourished by this life-sustaining Divine Manna! God is nigh. His life sustains you. He is your breath, your life, your strength and your support. In Him alone is your Peace and Joy. Abiding in Him, you lack nothing. Leaving Him, you are as nothing and are verily beggared. The Lord is
38
ADVICES ON SPIRITUAL LIVING
your supreme wealth of wealths. May Shiva, the ever-propitious, the ever-auspicious one be gracious unto you. Last month I had an opportunity to visit, after many years, the devotees of Divine Life in the cities of Rajkot and Ahmedabad in Gujarat state. The Rotarians had arranged a noble Drishti-dana Yajna at Rajkot, and Dr. Adhwaryoo, Gurudev’s great devoted messenger in Gujarat, was in charge of the surgical work there. It was an intense four days of Satsangs, lectures, visits and meetings for this servant. Went back one day to blessed Virnagar, holy centre of Divine Life in Gujarat (I call it Anand Kutir in Saurashtra) for meeting all old friends there. Wonderful work they did at Rajkot Eye-camp. The Ahmedabad visit too was indeed very nice and satisfactory in Seva. Paid homage to the memory of the holy saint, Gita-vyas Sri Swami Vidyanandji Maharaj of Gita-prachar fame when I visited the Gita Mandir for the main public meeting of the city. Sri Surya Kant B. Shah, the able secretary of the Ahmedabad Divine Life Society Branch had well organised the entire programme, including a successful Press Conference and lectures at the Gujarat Vidyapeet as well as the Jyoti Samaj, a premier women’s social-service organisation in the city. My visit to the Sabarmati Ashram for evening prayer hour while at Ahmedabad and my visits to the Rashtriya Shala and the Vidya Vihar at Rajkot were memorable indeed. Those places made me feel the vital presence of the spirit of Mahatmaji by their ideal atmosphere. Advent of the spring season is at hand. All life is renewed now. May there be fresh awakenings unto Divine Life and spiritual aspiration within your heart! God bless you. With Regards, Prem and Pranams, 1-3-65 Yours in Gurudev —Swami Chidananda
Sivanandashram Letter No. XIX
THE BIRTHDAY OF LORD RAMA. GLORY TO HIS NAME
Immortal Atma Swaroopa! Blessed seekers after Truth! Om Namo Narayanaya. Om Sri Ram Jaya Ram Jaya Jaya Ram! I wish you all a very, very happy and auspicious NEW YEAR. Upon this eve of the commencement of the first month of Chaitra, at the advent of spring when you are about to celebrate the festival of Yugadhi, I send you joyous greetings for this New Year and my love and good wishes for your health, happiness, prosperity, all-round progress and success. May God grant you all that is auspicious and blessed throughout this New Year.
39
THE BIRTHDAY OF LORD RAMA. GLORY TO HIS NAME
One of the wonderful facts about our Vedic New Year is that it opens with a most auspicious holy day of festive worship. The month of Chaitra ushers in the Sri Ramanavami, which is the sacred Birthday of Lord Rama, the grand Avatara who personified Dharma in all its aspects and perfection. The advent of this Avatara heralded the resurgence of Dharma and the establishment of the rule of righteousness and the moral order. Even as the divine Sri Krishna is the beloved and darling of India, so, too is Lord Sri Rama the ideal and hero of India. His Avatara Leela is the thrilling indication of the sublime heights to which the human individual can attain and should strive to attain. As a divine Avatars, He constituted an approach to God-realisation, which is the goal of your life. Devout worship of Rama leads to God-consciousness. He is a link and a channel between you and the transcendental Absolute Reality. The Lord of Khosala, the crest-jewel of the Royal race of Raghu, is the incarnated personification of the Supreme Divinity, the Paramatman or the Para-Brahman of the Upanishads. Rama Bhakti is an unfailing way to eternal emancipation from the thraldom of birth and death. His Divine Name “RAMA” is the ark which takes us safely across the turbulent ocean of Samsara to the far shore of immortality and beatitude. This Divine Name is verily the inexhaustible mine of all auspiciousness, the destroyer of the impurity of this iron age, the holiest of holy things, the saviour of this world. It is a seed of supreme satisfaction and veritable bestower of all boons. It is a gateway to the kingdom of blessedness. The glory of Ram Nam verily beggars description. Its greatness is unfathomable. Human speech and intellect ever fail to assess its supreme unparalleled worth. Ram Nam is the most precious, priceless jewel in the treasury of our holy land’s spiritual culture. I boldly assert that it is this great Ram Nam that is sustaining Bharatavarsha today. O beloved children of India! Come, come adopt the Ram Nam way of life. Saturate yourself with Ram Nam. Bathe in the divine nectar that ceaselessly showers from Ram Nam. Ram Nam is the quintessence of the Divine Grace. Ram Nam is your greatest benefactor, dearest friend and unfailing companion. Chant Ram. Sing Ram. Let the tongue repeat Ram Nam is an unbroken and continuous stream. Root yourself in Ram Nam. Enshrine Ram Nam in your heart and mind. Let Ram Nam resound from every cell and pore of your body. Let Ram Bhakti radiate from your entire being. Ram Ram Ram! Om Sri Jaya Ram Jaya Ram Jaya Ram! Make your life thrill with Ram Nam. Let your heart throb with Ram Nam. Let your breath flow with the rhythm of Ram Nam. Let blood course through your entire being in unison and tune with Ram Nam. Make your life a veritable joyous song of Ram Nam. Supreme blessedness shall accrue unto you. Freedom, fearlessness and joy will fill the entire being. In this age, there is no greater or more effective and unfailing method of God-attainment than the practice of the wondrous Divine Name. The Name of God is verily God Himself. Supreme Divinity is present here, for you, as God’s Name. Name and God are not two. They are one and the same. Name is God! What shall any one say about the power, the greatness and the glory of the Divine Name of Rama! Divine name will bring you face to face with God. It will grant you Mukti here and now. It will burn up all impurities. It subdues the turbulent senses. The power of the Divine Name calms the surging passions. It restrains the outgoing tendency of the mind and subdues its restlessness. The scattered mind now becomes indrawn and one-pointed. Ram Name tames the arrogant ego and renders it Sattvic and holy. Purifying the heart, the Divine Name creates devotion and arouses Divine Bhav within your heart. It drives the mind inward and leads to a state of meditation. Repeated persistent Japa of the Divine Name rends the veil of ignorance and brings on the resplendent experience of God-vision.
40
ADVICES ON SPIRITUAL LIVING
Have faith. Be simple and pure. Tread the path of truthfulness. Become selfless. Serve all. Develop noble character. Give up anger, hatred and selfishness. Overcome greed by generosity and sympathy. Overcome hatred by love and forgiveness. Overcome all restlessness through sincere belief and firm faith. Become rooted in Ram and Ram Nam. O seeker! Know that this entire world is verily the manifestation of Ram and His divine power and glory. Now sing with saint Tulsidas: Siya Rama Maya Saba Jaga Jaani Karahun Pranama Jori Juga Pani That is, “Knowing that the entire world is permeated by Lord Rama and His power, I salute (everything) with both hands folded together”. Whatever you see, hear, touch, taste and smell, all is indeed the manifestation of Rama alone. Recognise all sounds to be Rama Nama in infinite variation. Ram Nam is the quintessence of the Divine Grace of the Supreme. Beloved and worshipful Gurudev Sivananda Swamiji Maharaj mentioned Namopathy as the unfailing divine-medical treatment for the eradication of the dire disease of Ajnana and Samsara. This is the literal truth. Believe and be blessed. Blessed Sadhaks, come now, let us meditate upon Sri Ram. Set aside everything. Become silent. Sit on the Asana. Close your eyes. Behold Sri Rama with the inner eyes, standing before thee, radiant and gracious. He pours his love, compassion and Divine Grace upon you now. Visualise Him vividly in the heart-shrine. Bask in the radiance of His spiritual presence. Repeat Ram Nam. Cast away all other thoughts and repeat Ram Nam. Forget the world and body. Think Ram and Ram alone. Repeat Ram Nam in continuous, unbroken Japa and remembrance. Dwell in Ram and repeat: RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM RAM (ten times) I leave you now silently and joyously in the glorious presence of Rama. May you be absorbed in Ram. May Ram Nam, Ram Prem and Ram Bhajan enrich your life. Om Sri Ram Jaya Ram Jaya Jaya Ram! Glory be to Lord Rama! Glory be to Ram Nam! May God bless you. With regards, Prem and Pranams, Ananda Kutir. 1.4.1965 Yours in Lord Rama, —Swami Chidananda
41
FRESH BEGINNING: NEW UNDERTAKINGS. GURUDEV’S BIRTHDAY ANNIVERSARY. SPECIAL MESSAGE TO SADHAKS WHO ATTENDED SADHANASAPTAH AT HEADQUARTERS DURING JULY 1965.
Sivanandashram Letter No. XX
FRESH BEGINNINGS: NEW UNDERTAKINGS. GURUDEV’S BIRTHDAY ANNIVERSARY. SPECIAL MESSAGE TO SADHAKS WHO ATTENDED SADHANASAPTAH AT HEADQUARTERS DURING JULY 1965.
Immortal Atma Swaroopa! Blessed Seeker after Truth, Om Namo Narayanaya, Loving Namaskars. Greetings in the name of Gurudev Sivananda. Every one of you, all over India and the world has been in my mind during the recent period of the auspicious GURU PURNIMA and the sacred PUNYATITHI of holy Master’s Mahasamadhi day. We have worshipped on your behalf and also prayer has been offered that Divine Grace of Gurudev may be granted to you all the days of your life. I am aware that you are being greeted through this page by this servant after a lapse of full four months. This letter last appeared in April issue of Wisdom Light. Since I started on tour, the May, June, July and August issues did not contain the Sivanandashram Letter. There was very little free time during travel and public engagements to devote to writing work and when this servant did get some time he found there was not much surplus energy left for this task. This was Gurudev’s will, I suppose, and so I was resigned to the situation. Returning to Ashram at last (that was on 7th July). I found myself right in the centre of the pre-Guru-Purnima activities that had commenced humming all over the Ashram. The Virnagar party of Sadhaks under revered Sivananda-Adhvaryooji had already arrived even before my return and prayers, classes, Satsang and similar programmes were in full swing. This year’s Sadhana period was unprecedented and even after the Aradhana functions, various activities continued right up till beginning of August. Now, after the devout annual worship of Bhagawan Ganesh (Lord Vighneshwara or Vinayaka) we look forward to an auspicious period of fresh beginnings and new undertakings, attended by unhampered progress and success. For, Lord Ganesha is verily the remover of all obstacles and difficulties and the giver of success. May His Divine Grace be upon one and all of you, dear readers, and may He bless and help you as the Vighna-vinashaka and the Siddhi-dayaka. May the Lord of Shiva’s retinue be propitious unto you! Gurudev’s Birthday Anniversary this year must be to you a day of retrospect and spiritual reassessment and self-scrutiny. It must also be a day of rededication and zealous renewal of vows regarding your spiritual practices and inner life. Because we see that full two years have now gone by, since the passing into eternity of our worshipful Gurudev and it is needful to study yourself to see how you have fared on the Path without support of His personal guidance and the push of His actual presence. This passage of time also means to us that we have drawn nearer to our final hour of destined departure from this world of mortality. As days fly past the end too approaches the nearer. Hence you must always be up and doing in the Life Spiritual. Go onward until you attain the Goal. Ceaselessly endeavour into perfection. Each day live fully. Unrelaxing vigilance be your safeguard. May all the sublime spiritual qualities, that Gurudev embodied in his lifetime, be reborn within your
42
ADVICES ON SPIRITUAL LIVING
being in all their glory and spiritual power. May the power and spirit and light of Sivananda be born afresh within you upon this sacred anniversary. I have a special message to such of you who attended the Gurupurnima-Aradhana Sadhana programme here in the month of July. You were all given a Printed Form headed “My Resolves” and containing two parts “A” and “B”. The latter contains seven items, plus some sub-heads including one about Jnana Yajna. Please look up your copy of the Form at home and see how far you have been trying to fulfil these undertakings. The Mission is no doubt expanding and spreading. But it is very necessary that individual seekers must also make steady progress in their Sadhana life. This I expect and look for amongst all the members of this Society created by Gurudev. During the past two years gone by many D.L.S. Conferences have been conducted, numerous books of Gurudev have been published, new Branches have been inaugurated, the Divine Life message has been taken into all parts of the country and in countries abroad too and all this is doubtless good. But equally important is that you all grow and develop in Virtue, Renunciation, Sadhana, self-restraint and austerity. That you grow in prayer, in meditation, Vairagya and Wisdom day by day. More important that you excel in Service, Devotion, Meditation and God-realisation. Many of the members have undertaken to carry on Mantra Purascharana. A few fortunate Sadhaks stayed here after the Aaradhana and did Japa in the Ashram itself. Even as she did last year, the revered and worthy Shrimati Rajwati Shivraj of Delhi and her friend Sri Mohan Devi Mehta both completed two Purascharana of their Ishta Mantra during July/August. Besides them Shrimati Kamala Devi Seth, the daughter of Sri “Maharaj” Pannalalji of Amritsar, also did Anushthana of Mantra Japa for three weeks. While congratulating these worthy Sadhaks, I, at the same time, commend their example to you all. I shall close now and do so with my earnest prayer to the Divine Mother, Whose annual worship is approaching near, to shower Her loving Grace upon you and grant you the fulfilment of all your right desires and Sattvic Sankalpas. May mother guide you along the radiant path that leads to your highest welfare and supreme and divine Felicity! Surrender yourself unto the Divine Mother and attain Immortality, Fearlessness and Freedom! Jai Gurudev! With Regards, Prem and Om, Yours in Sri Gurudev, 1st September, 1965 —Swami Chidananda
43
SWAMI CHIDANANDA’S 50 BIRTHDAY MESSAGE
TH
Sivanandashram Letter No. XXI
SWAMI CHIDANANDA’S 50 BIRTHDAY MESSAGE
This is actually the MESSAGE of His Holiness Sri Swami Chidanandaji, given on the auspicious occasion of his 50th Birthday which was celebrated in the Ashram on the 24th September, 1965, on a moderately grand scale and dignified manner. The same is reproduced below as the Ashram Letter. Beloved Atmaswaroopa! Om Namo Narayanaya! Jai Gurudev Sivananda! May His blessings be upon you all! May this letter find you all in excellent health, good cheer and peace of Divine contemplation. Blessed Self! You are now called upon to manifest in life the Truth, you have received and absorbed from Gurudev, when He lived. By the Divine will of God, a time has now come, a time of trial, testing and strengthening. Life now asks you to practise and to prove that your awakened spiritual consciousness within is more than the mere physical and mental part of your being. All that you have up till now heard, read, learnt, believed and reflected and meditated upon must now be lived with calm resolution, strong determination and firm faith. In the challenging context of this modern world your Mother-country finds itself confronted by asuric forces of Adharma and wickedness that threaten to destroy our sacred culture. You are all involved in this struggle being part and parcel of the Mother-country. In this situation I address you all, as seekers and Sadhaks leading the Divine Life of Yoga and Seva. I call upon you all to keep up high, the great tradition of Vedanta and Bhakti, of Yoga and Tapasya which is the life-breath of your time culture. I want you to be practical Vedantins, dedicated devotees and courageous Karma-yogins. Gurudev expects this of you and Bharatavarsha needs this from you. Live up to the Ideal of the fearless Sadhaka. Be a true Yogi and Bhakta, keen in Seva and unshakenly firm in Nishtha. Remember that your life is rooted in a grand culture that is based upon the Immortality of the Self and the passing nature of earthly wants. EVEN THIS WILL PASS AWAY! I AM IMMORTAL. Live in the light of this Truth. Practise this truth and be fearless child of the Divine. I wish to urge you all to remember that you are spiritual aspirants and Sadhaks. Remember that you have been inspired and guided by the sublime ethical and spiritual teachings of Sadgurudev Sivananda. Remember again that Gurudev ever laid emphasis upon Karma Yoga, selfless service. Remember also that he admonished every disciple and student to fulfil his duties without fail. Do your duty in spirit of worshipfulness and dedicate it to God. Thus Gurudev gave importance to the performance of unattached Nishkamya Karma Yoga and carrying out Swadharma. He never approved of shirking of duties or neglect of Karma Yoga. Service also was supreme Yoga to him even as meditation and worship. When duty calls, as it does at this present moment, convert yourself into a ready and willing servant of anyone or any situation that needs your seva. Heed this reminder of Sri Gurudev’s practical instructions to be ready to serve. Serve all.
th
44
ADVICES ON SPIRITUAL LIVING
Serve the general public and the country at large. Serve in all ways you can or are called upon to do. Serve, regarding your actions as worship, considering duty as devotion and seeing the Lord alone. Be firm in faith. Be unshaken in your trust in the Divine. Be bold and fearless in the face of all the vicissitudes and changes. Face with calmness and with cool courage all events and occurrences. Know that the supreme inner director of all movements in this Universe is the Divine-Being, the Paramatma. Rooted in His remembrance, worship Him through duties faithfully done. The DIVINE is present Here and Now. Knowing that the name and forms of this created universe are subject to decay and dissolution you should act your part in the scheme of things as dictated by the situations in which the Lord places you. You are where you are, and what you are, due to the Will of Lord, who is the Supreme inner Ruler of all the created Universe. Based upon this awareness act. With this knowledge and perception do that which you see to be your duty as an individual in human society. Gurudev Sivanandaji was dazzling Sun of Vedanta. He ever addressed you as “BLESSED IMMORTAL ATMAN!” Never as “My dear So-and-so or Such-and such”. It was always IMMORTAL ATMAN or SELF. Proclaim this great Truth. Hammer this idea into each and all. Rouse a courage, a Fearlessness and a Strength from within the depths of their beings. Make them bold and strong with Soul-force. Tap the source through collective Sadhana at every week-end and create spiritual power from within. Work to spread that calmness and fortitude that springs out of such inner strength. Specially work to educate the womenfolk and the school-going children in the control of emotions and in the basics of dealing with emergencies. I and all here in the Ashram, we do pray that God would set right men’s hearts and minds and soon make their actions Sattvic and benevolent. We wish, hope and pray for this. Until this prayer is granted may you all be guided to trust in the Lord and do your duty with supreme spiritual heroism. To be a Dheera is the call of your cultural genius! A clear word of caution is to be given here. Let not the activity break away from its mooring in the purity of Sattva. Act, but be based on Sattva always. Work with understanding and with love. But never allow Hatred to stir within your being. HATRED is NEVER GOOD. Not under any circumstances, at any time or for any reason whatsoever. It is the direct contradiction of the Divine in every way. By no means can it be allowed to have entry into the truth-seeker’s heart. Do your duty with your body and mind but retain the purity and sensitivity of your spiritual nature. God is love. You are a ray of that Eternal Light! You are Divine! Be rooted in divinity. Act with consciousness of your divine nature. Face all situations unflinchingly. Do duties resolutely. Engage in action wisely. Fulfil Dharma unattachedly. But at all times cherish only LOVE in your heart. Love God, Love the whole Universe. Never swerve from the path of your duty. Verily be rooted in Love. Thus uphold the Ideal of Divine Life here and now! May God bless you! Co-operate in all works of public safety, service and welfare. Be ready to become volunteers. Offer your willing services to the agencies set up for various aspects of national Seva. Be a true Karma Yogi and a Bhakta who is ever a Dasa of Lord manifesting in and through all beings. I close with nay regards, Prem and Pranams. Jai Gurudev Sivanandaji! Om Tat Sat! D.L.S.H.Qs. Sivanandanagar, 24-9-1965
Yours in Gurudev, Swami Chidananda.
45
SOW THE SEEDS OF LOVE, PEACE AND BROTHERHOOD
Sivanandashram Letter No. XXII
SOW THE SEEDS OF LOVE, PEACE AND BROTHERHOOD
You will be all worthy of this great Mother, who sustains your life and that of your children and those unborn yet to come. Do your duty to posterity by sowing seeds of Love, peace and brotherhood for the welfare of the generations to follow in the future ahead. Let Love triumph and Peace prevail in this, your country. O my brothers of all creeds, faiths and communities! Beloved Immortal Atman! Blessed Seeker of Truth, Om Namo Narayanaya. Loving Namaskars. Peace Be Unto All! May individuals, groups, communities, countries, hemispheres and the whole world be blessed with the grace of Peace and Love! After last month’s message at the time of writing this letter an anomalous peace has been restored upon the battle-front by which the recent 20 days’ war has come to a close but not so the hostilities. Hence the call to duty, to vigilance and sacrifice to safeguard Freedom, Unity, Virtue and Dharma is reiterated now in all its solemnity and urgency. Be heroic, without hatred, ready to swiftly chastise, yet without anger, strike fiercely in defence yet without cruelty, and be immediately generous where you find true innocence or real remorse. In the just cause of National Dharma be irresistible and strong as an elephant, and quite fearless as the lion. Ever be ready to give battle with the boldness and the power of a million celestial angels of heaven. Victory is to the Devas never to the Danavas. Nevertheless, sincere efforts for peace should be earnestly pursued by those at the helm of affairs. Desire for peace yet perfect readiness to fight in defence of freedom—this is the noble way before the nation. And we ceaselessly PRAY FOR PEACE AND GOODWILL each and every day without fail at this holy Ashram of Gurudev Swami Sivanandji Maharaj. Dipavali has come and gone with subdued observance due to the grave uncertainty of the present period. Within Bharatavarsha there is more need for the lighting of Lamps other than those that burn with oil and wick. There is need to light up the Lamps of religious brotherhood, intercommunal love and harmony, all-over unity of our people from the Cape to the snow-capped Himalayas. Lamps of mutual understanding, united patriotism and single-hearted love of freedom should light up all hearts and mind throughout every city, town, village, hamlet and nook of our nation. Feel India is India. It is neither a Hindu India nor Muslim India nor Parsi India nor Sikh India nor Christian India nor any Communal India whatsoever. India is Bharata Mata, the beloved mother of all these children, who are nourished by the food of her sacred soil, her life-giving waters, her freedom-air, her love-filled dawn, noon and dusk and her just rule of equality and peaceful co-operation and fellowship. India is the India, whose God is the universal father of humanity and the God of love, who embraces all mankind as His own. Be yet all worthy of this great Mother, who sustains your life and that of your children and those unborn yet to come. Do your duty to posterity,
46
ADVICES ON SPIRITUAL LIVING
by sowing the seeds of love, peace and brotherhood for the welfare of the generations to follow you in future ahead. Let love triumph and Peace prevail in this, your country, O my brothers of all creeds, faiths and communities! This November is a month of remembrance of eternal Ideals. The Supreme Spiritual Values that constitute the very heart and essence of our oriental view of Life find their grandest assertion in the ancient Upanishads. The birth anniversary of one of the greatest towering personalities in the Upanishads is upon November 3rd, namely the YAJNAVALKYA JAYANTI. The august Sage Yajnavalkya is verily the gland sire of the masters of divine wisdom of that wonderful period. He shone supreme in the assemblage of Sages in Janaka’s royal court with none to equal him, none to challenge his Wisdom and perfect mastery of the spiritual love. Acquaint yourself anew with his thrilling expositions of the eternal supremacy of the spiritual Ideal before man in that unique and unrivalled dialogue between this great Sage and his wife Maitreyi of immortal fame. All things in this universe are dear to man because of the ATMAN, which alone is the central Truth and imperishable essence of all things. ATMAN or the SPIRIT is THE ONE ULTIMATE AND SUPREEME VALUE. For the Atman alone is real, being the one eternal, immortal, everlasting principle. Wake this Immortal Atman in and through all the movements of thy life, O man! Sri TULSI PUJA on 6th November holds aloft before the women in India the sublime ideal of marital fidelity and chastity. Sri Tulsi symbolises the Maha-Pativrata. This is the supreme Dharma of the Ideal Indian woman and wife. Loyalty to her lord and perfect chastity and purity in thought, work and deed is the concept of the ideal woman the fulfilment of which makes her worthy of worship and the highest reverence. The true Pativrata Sthree is indeed a veritable goddess upon earth. She verily purifies nay sanctifies the ground that she treads upon! Let the women of India hearken to this reminder evoked by the holy Tulsi Puja day. Then holy Guru Nanak and the holy Sant Jnaneshwar are honoured by millions this month upon the 9th and 21st respectively. Guru Nanak lived and preached the oneness of mankind and the essential synthesis of apparently divergent creeds and faiths. He propagated the one common spiritual message that formed the universal basis of all religions and teachings of all prophets. Sant Jnaneshwar similarly cut through theological differences and proclaimed the oneness of God, equality of all men and the supremacy of true devotion over dry metaphysics and mere occult power of Yoga. Both these great saints alike declared the superiority of LOVE or BHAKTI as the path to spiritual Perfection and the way to Divine Experience. They stressed on the need of real Surrender to the Divine and purity and humility in all our dealings here. The practice of Virtue and Good Conduct was emphasised as more important and indispensable than theoretical knowledge of scriptures unaccompanied by virtuous living. These two great souls fought superstition, simplified religion, revived Divine Name and established Bhakti, Sadachara and spirit of Service unto mankind by their personal example, lofty and immortal teachings. May the message of Guru Nanak and Sant Jnaneshwar live and work in your heart always. May their divine wisdom-teachings guide on the path of life and lead you to supreme blessedness. Commence the serious study of Bhagawad Gita in preparation of the forthcoming Gita Jayanti next month. Also, before closing I wish to mention with keen appreciation the Sankalpa of certain D.L.S. branches to organise district level Divine Life Conference this year. This they have resolved in pursuance of my suggestion made in an earlier letter. The secretary of Pattamadai
47
SOW THE SEEDS OF LOVE, PEACE AND BROTHERHOOD
D.L.S. branch has written to me a very sincere and enthusiastic letter in this connection and I am very happy that he is going ahead with the preparations. I have advised Sri Krishna Iyer to invite revered Swami Sivasat-Chitanandji of Amrita Ashramam to guide him in the proceedings of the conference. I draw your attention to the extracts of the teachings of holy Guru Nanak Dev and of Sant Jnaneshwar Maharaj elsewhere in this issue. May the blessings of these two great Masters be upon you! My best regards, Prem and Pranams to you! Jai Gurudev Sivananda! Om Tat Sat! D.L.S. HQs., Sivanandanagar, 1st Nov 1965 Yours in Gurudev —Swami Chidananda
Sivanandashram Letter No. XXIII
PRAY FOR OTHERS
Embody Lofty Principles when harsh Realities of the external world make feelings to run high. Be brave in Goodness. Be Righteous in Adversity and Humble in Virtue. BELOVED IMMORTAL ATMAN! Blessed Seekers of Truth. Om Namo Narayanaya. Loving Namaskars. Peace be unto all. May all individuals, groups, communities, countries and the entire Universe be blessed with the Grace of Peace and Love. At this holy Ashram of Gurudev Swami Sivananda we pray every day for peace and goodwill amongst all men and nations. In this fair land may peace, goodwill and understanding prevail from the Himalayas to the distant Cape and from the eastern hills of Assam to the westernmost deserts of Sindh and Baluchistan. May the nation be once again left free to pursue its serene tenor of peaceful constructive activities for progress in its economic, social and cultural life! The present year is now drawing to a close and all seekers should be taking a glance back in retrospect to examine the year that has gone-by and to evaluate what each one has done during this period and how much has been achieved. A great question that stands before everyone of you is verily, how much time has been well utilised? And how much time has been ill spent or wasted away, for verily upon this question hangs the very problem of life and of living. What is your life, if it is not the time at your disposal? Life is time! Your life is nothing but the time you have got. As you use time even so is your life utilised. Waste of time is destruction of life. Abuse of time is the degradation and ruin of life. Good and proper utilisation of time is the glorious fulfilment of your life. Time well and wisely spent is life grandly lived. It brings joy, beauty and achievement. Has this year been thus utilised? Thus will you examine the last eleven months gone by upon this last month of the year as it now speeds past you to soon end and bring in the new year 1966. Retrospect, reflect and resolve rightly for the year ahead. May God bless you.
48
ADVICES ON SPIRITUAL LIVING
With the coming of December, winter has set in and the advent of cold days has brought about the season of cold-misty mornings, late sunrise over the mountain across the holy river Ganges, biting winds, long nights and short days. Everyone has now to bring out sweaters and blankets. And the miracle of God’s creation is such that while human beings shiver, the water-fowl has appeared before the Ashram and happily and nonchalantly swim about on the Ganges and dive again and again into the cold sparkling waters to hunt after the fleeing fish. They live on the water all the 24 hours of day and night and I see them and simply marvel at God’s wonderful world. The Ganges water is crystal clear. When I occasionally go in the boat to visit our venerable Yograj Gaur Prasad, on the other shore, I clearly see the sands and the boulders of the river bed and the shoal of fish crowding under the boat to receive bits of bread thrown by devotees to feed them. A dip in the Ganges at this time is at once a challenge, an adventure and an act of austere endurance. But it can also be wonderfully invigorating and vitalising and enjoyable when it is bright and sunny upon a clear day, specially at mid day, when the morning winds have stopped. When I contemplate the increasing cold here, my mind goes to our heroic and brave jawans, encamped in the forbidding icy regions of the Himalayas border lines much above the snow lines in high altitudes, beyond 18000 or 20000 feet. It is terrible indeed, the cold there, much more than any thing that the people in the plains can even imagine. To expose the hands and feet would be just agonising and yet they have to endure this terrible bone-cutting cold and freezing weather and be alert and active to safeguard your freedom and to protect and defend your country and all that you hold dear and holy in it. I request you all to ceaselessly remember these brave sons of India, your brothers in arms, in your daily prayers. May you all pray to the Lord to graciously look after these brave souls who are risking their very lives to safeguard Dharma and to keep sacred Bharatavarsha free and secure. Let us not forget these people. Let us pray for them. They who are out of sight, let them not be out of your heart. Remember them and work hard to do your part of this noble task. Save for them and also dedicate a member of Mahamrityunjaya Mantra Japa to these toiling ones in the snowy fastnesses of the remote North. They are much closer to me here and hence I feel much for them whenever the cold wind of Rishikesh catches me and makes me suddenly shiver. Yes, you must learn to pray for others. Was this not one of the deepest lessons that Lord Jesus taught through His life and teachings? Ever and anon Jesus prayed to the Almighty for the sake of mankind. His prayers were as much for others as it was for himself. This sublime truth He demonstrated right up to the last moment of His life when He uttered the supreme prayers to the Lord on behalf of those very people who were putting Him to death. He prayed for others, nay He verily lived for others. In times such as these, when harsh realities of the external world make feelings to run high, and you are apt to forget basic principles and ideals in which our lives should be rooted, it becomes vitally important to remember and draw inspiration from such lofty lives, as of Jesus Christ. Nothing that happened to Him in His short yet intense life, was ever allowed to divert Him from His ideal of perfect goodness. He embodied the goodness that He taught unto others. As a nation and a people we too must strive at all times to evolve and to embody those lofty moral principles which we wish to raise aloft and hold before other nations for their guidance. While never fearing or hesitating to do that which is good and right, we should ever be at the same time steadfast in goodness and in righteous conduct. The Gospel of the Bhagavad Gita whose Jayanti falls on 4th December proclaims such conduct as the ideal for the man of action to follow. The life and personality of Christ is indeed a
49
PRAY FOR OTHERS
living exposition of the message of the Bhagavad Gita. Jesus personified the ideal of the Gita. To be brave in goodness, to be righteous in adversity and to be humble in virtue—this embodies the great teachings. Commence a very systematic and regular study of the sacred Bhagavad Gita from the day this letter reaches you. Absorb the life uplifting philosophy of the grand Gita Gospel. Try and receive the Gita into your heart. Practise its wise precepts. Live the teachings of immortal wisdom. He who follows the Gita will understand Jesus really. And he who adores Jesus and tries to follow Him is really a votary of the Gita. Upon the 8th of December take out your copy of the Srimad BHAGAVATAM, the MAHA-PURANA. Turn to the Eleventh Skandha. Read therein the chapters dealing with the teachings of the Avadhoota Dattatreya. Sublime and inspiring at once deeply instructive are his talks with king Yadu in the chapters 7, 8 and 9. They impart wonderful lessons on Life. We have the Dattatreya-Jayanti on the 8th and the Ashram will worship at the little shrine in the forest upon the Dattatreya Hill, beside the Ashram upon this day. May the great soul’s benedictions be upon you all! Before closing this letter I like to send my very best GOODNESS FOR A MOST HAPPY CHRISTMAS and A VERY BRIGHT AND JOYOUS NEW YEAR TO ONE AND ALL OF YOU IN EVERY part of the world. HAPPY CHRISTMAS TO YOU! HAPPY NEW YEAR TO YOU! AND GOD BLESS YOU! On the 31st December you know that the Vishwanath Mandir was consecrated in 1943. The 22nd Anniversary worship will be conducted with due ceremony and solemnity. I shall remember you all on that day and worship on your behalf and send you the sacred Prasad of that special worship of New Years Eve. Hare Rama Hare Rama Rama Rama Hare Hare Hare Krishna Hare Krishna Krishna Krishna Hare Hare. JAI GURUDEV! Regards, prem, pranams, D.L.S. Hqs. Sivanandanagar December 1965 Yours in Gurudev, —Swami Chidananda
50
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XXIV
COSMIC LOVE—THE VERY BASIS OF DIVINE LIFE
Beloved Immortal Atman, Blessed Seekers after Truth, Om Namo Narayana. Loving Pranams, Homage unto the Divine. May the Grace of the Supreme Being be upon you all; Glory to the Lord; My humble and sincerest GOODWISHES & GREETINGS to you for Joy, Prosperity and Success during this NEW YEAR. May Happiness and Spiritual progress mark all its days and may good thoughts, sweet and kind words and noble selfless deeds of help and service unto others fill the entire year ahead. You are Divine. Therefore let Divinity radiate from you in everything that you think, say and do. Live to express the perfect God-Essence that dwells within you. Let all the movements of your daily life be filled with the light that illumines the innermost shrine of your spiritual “heart” which is the divine centre of your real being. Beloved Friend: you are the moving temple of God. God is within you as on all-pure and bliss-filled Divine Presence. That God is Love: Unlock the food gates of the Ocean of Divine Love within thee, and let flow that love over all the universe. Love all. Encompass everything here with that Love. Live Love. Think Love. Speak Love. Do deeds of loving kindness and goodness in all the actions of your day-to-day life Even the most trifling of actions do with love for God. Do all things for Him. Fill your mind with loving thoughts towards all created beings and things. Fill your heart with pure feelings of kindness, compassion, affection, friendship and genuine love towards everything upon earth. Regard none as thine enemy. Feel all as thine own. For we are brethren in the divine, all being children of God. Merciful be thine attitude towards all creatures and things here. Speak gentle words alone, of friendship and divine brotherhood in the Lord. Utter soft speech that brings happiness unto others and helps them to bear the trials and burdens of this life. Kind words affectionately uttered bring heaven down to man on earth. Unkind and harsh worlds contradict the Divine Law of Life and thus take the joy out of life and cause pain. Therefore beloved seeker: fulfil the Law by filling your speech with Love and thus helping to bring light into the lives of all. Engage in actions of loving-kindness which the noble brothers of the sublime Buddhist faith refer to by the beautiful term “Metta”. It is the expression of the highest principle in man. It is impersonal, universal, motiveless love toward everyone and everything. It leaves no place for anything else except such love in your heart. Such love is Divine. It makes you Divine by enabling you to rise up into Divine Experience. Love is the one and only Law that can bring solace, peace and happiness to mankind in this world. It is the higher principle with which man can overcome the grievous results of his past folly, blindness, wickedness, selfishness and the sufferings created by them. Love will give back to World Humanity the Peace, Safety and Security which it has lost through the transgression of this supreme principal of life, namely, Loving Kindness. Blessed Seekers, strive to restore unto humanity peace, joy and welfare by practising the rule of cosmic love or Vishwa-Prem and living a life of loving goodness and kindness unto all.
51
COSMIC LOVE—THE VERY BASIS OF DIVINE LIFE
Spiritual Life means unfoldment of the hidden Divinity within you. It implies the manifestation of this inner Divine nature which is your real self. Yoga is the process for bringing about this inner awakening, unfoldment and manifestation. All Sadhana is for manifesting this Divinity of your true Swaroopa: fact of divine experience. A life that contradicts LOVE in any manner cannot become spiritual or grow on divinity. It cannot progress towards God because He is attainable through Love. Because HE IS LOVE: God is love. Anything in your life that contradicts LOVE, know it to be undivine. It is not “daivi-sampatti” expounded by Lord Krishna. Selfless Love, Compassion and friendliness are divine, Sattwic and, therefore, help spiritual unfoldment, Hatred, anger, dislike, ill-will, prejudice, envy, jealousy, intolerance, harshness, selfish and resultant unkindness are the negation of Love and hence are great obstacles to spiritual advancement as they are undivine expressions of your lower earthly nature. They must die and the nature, the inner man should be cleansed of this dross before the Light of Truth can flood your inmost beings and grant you Illumination, Divine Experience and Immortality. Love is the great and marvellous power that can effectively root out all evil in man and transform him and make him godly. Love is the greatest purifying force on earth. It makes your life divine. It is therefore the very basis and support of Divine Life as expounded by Gurudev, worshipful and beloved Sivananda Swamiji. Therefore overcome all blemish through the sanctifying power of pure selfless love of all and attain the goal of God Consciousness, my beloved Atman. God Bless you. Glorious NEW YEAR unto you. My deepest regards, love and prostrations to you all, souls journeying onward unto Divine Perfection. D. L. S. H. Q. Sivanandanagar January 1966 Yours in Sri Gurudev —Swami Chidananda
Sivanandashram Letter No. XXV
PROPAGATION OF SPIRITUAL KNOWLEDGE
Beloved Immortal Atman! Blessed Seekers after Truth, Om Namo Narayanaya. Salutations in the name of Gurudev Sivananda. I wish to express my great thankfulness to the numerous devotees and friends in India, as well as from several countries abroad, who have remembered me with so much kindness and love, and sent their affectionate Christmas and New Year’s greetings, and expressed their sincere goodwill for this servant of Gurudev as well as other Ashramites. Trying though I am to acknowledge all of them individually I avail myself of this opportunity of collectively conveying my grateful thanks to all of these blessed and gracious souls. May they ever dwell in the remembrance of the Supreme Lord, Who is the sublime connecting link between us all here. Let us
52
ADVICES ON SPIRITUAL LIVING
contemplate that we are together when we strive to keep ourselves in the presence of the one Reality, because true spiritual brotherhood is wrought by the oneness of our common goal and the common centre of our abidance namely God. We have to constantly remember that all other relationship except that of God, are transient, fluctuating and essenceless. He who loves mankind for the sake of the Divine that indwells man, has verily established oneness with humanity. As you all know, this servant has been away from the Headquarters for the whole of January. Half of February also shall be spent in touring and visiting Divine Life branches in Bengal and other states. In spite of my desire to do so, I regret, it is not possible at this moment to give you a detailed account of the uplifting activities of the Divine Life Society that took place in the past month of this protracted tour of mine of Southern and Eastern parts of India. I, therefore, restraint myself here merely by telling you that all the programmes throughout my tour in the state of Maharashtra, Andhra & Orissa were very well organised and this servant had the blessed opportunity of addressing vast congregations, meeting many persons, visiting several holy shrines and places of Pilgrimage. The mission of Gurudev and the message of Divine Life was spread far and wide in an organised and grand manner. The Divine Life Conferences at Viajayawada in Andhra and at Puri in Orissa were crowned with resounding success. I want to express my gratefulness to numerous capable organisers, devotees and selfless workers who strove hard to organise the programmes, making every arrangement for our comfortable stay and journeys and thus became worthy instruments of God and Gurudev in this great endeavour. Although the reports of these programmes etc. will be published in the ‘Branch Gazette’ and ‘Divine Life’, I shall try to say something more specific in my next letter, if possible. In my letter of 15th January, published in the Branch Gazette of the same month, I paid my homage and offered prayers on the sudden and shocking demise of our revered Prime Minister Sri Lal Bahadur Shastriji. In fact when India had not yet recovered from the shock of his loss, it was stunned once again by the passing of most revered and beloved Sadhu T. L. Vaswaniji Maharaj at Poona on the 16th January. With deep regret I received the news. During my visit to Poona in the third week of December, 1964, I had the most blessed occasion and the unique opportunity of placing my head at the holy feet of our beloved and worshipful Dadaji—Sadhu Vaswaniji Maharaj. I vividly recollect how I was filled with happiness at the time and considered myself most sanctified by his holy Darshan and the warm embrace of Divine Love in which he graciously enfolded this servant. Now that has become a thing of the past, he will yet always remain as an evergreen memory and refreshing inspiration. Very recently, on the 4th January, 1966, I visited the St. Mira School at Poona, founded by Revered Dadaji and had the privilege of addressing the students there. Revered Dadaji’s life was devoted to the propagation of the spiritual message, and though he was a devoted scholar of the scriptures of all faiths, his writings were simple and forthright. He believed in aiming his message to the heart of his reader rather than his head. He was a great Bhakta and had fittingly named one of his journals and many educational institutions after the celebrated Bhakta Mira. Gentleness personified, his very presence filled the atmosphere with love. Though he is no more among us physically, he is present everywhere in spirit to guide and inspire all who listen to the message of his life and work. May his loving guidance continue to lead us on the path of righteousness and Bhakti. The Punyatithi of Sri Samartha Guru Ramdas falls on 14th of this month. A saint and a realised soul of a very high order, he was deeply distressed with the historical conditions of the
53
PROPAGATION OF SPIRITUAL KNOWLEDGE
motherland of that time. He placed his wisdom and statesmanship at the disposal of Shivaji. Shivaji Maharaj was so devoted to him that at the climax of his career and the heyday of his empire he laid his entire kingdom at the feet of his Guru and thereafter acted only in the capacity of his minister. He even replaced his royal standard by a saffron flag. Living in close proximity of a great empire-builder, Samartha Ramdas remained steadfastly rooted in his renunciation and devotion to Lord Ram. Ram Nam were his life. His Punyatithi is a day for us to rededicate ourselves to duty and devotion. Beloved Aspirants: This month also marks that great festival and fast, Mahasivaratri on the 18th. This at once reminds me of the hungry and tired hunter of the Sivaratri Vrata Katha, who even when he unwittingly performs the Vrata attains Lord Siva’s grace. It is a beautiful poignant tale, which all of us know. This allegorical tale teaches us that Jiva (the hunter) with great effort pursues sense objects, but thwarted in this quest of the unreal falls asleep, that is, turns away from them and fasts (shuns sensuality) and wakes up to realise that he is in the midst of the forest—darkness of ignorance. He then climbs the tree of knowledge and keeps vigil against falling a prey again to his senses. He uninterruptedly performs the Puja of Lord Siva and attains unity with Him. This points the way to the life of a Sadhak aiming at God-realisation. Let the lives of you all follow this pattern; may you all reach your goal of God-realisation; let all observe this great Vrata in its true spirit and invoke the grace of Gauri and Shankar. Om Namah Sivaya Om Namah Sivanandaya God Bless you all. With regards, Prem and Om, 1st February, 1966 Yours, in Gurudev Swami Chidananda
Sivanandashram Letter No. XXVI
BE A HERO IN THE BATTLE OF LIFE
Beloved Immortal Atman! Blessed Seeker After TRUTH! Om Namo Narayanaya! Salutations in the holy name of worshipful Master Sivananda. I send you my greetings for the joyous Holi, the festival of Spring, the bright season of flowers, when the breeze comes to you filled with the fragrance of blossoms, and the sky is radiant with a warm brightness, after the chilly dullness of cold winter. May the fresh breeze of the Lord’s Divine Grace waft Peace, Joy and Universal Love into your heart and lift up your life into a higher realm of spiritual vision and beauty. May this festival of Holi not only mean joy and brightness to you but may it also bring Purity and Holiness into thy life. Spring connotes the springing up into activity of fresh life impulses after a period of dormancy and inactivity. So too may it be in thy own life.
54
ADVICES ON SPIRITUAL LIVING
Blessed Sadhak. Let the new season bring into your life fresh enthusiasm, new aspiration and vigorous quest after Dharma and Divine Realization. I wish you a new awakening and a new vision and new conquests and victories in the inner realm of the spirit. May God bestow upon you great achievement in self-culture, Yoga Sadhana and integral spiritual life. Glory be to Gurudev Sivananda! Glory be to Divine Life of Yoga Vedanta! This servant had the holy privilege and joy of serving spiritual aspirants and Gurudev’s work during this past one month and fifteen days through the entire month of January and up to the middle of February. On the morning of 17th February (Thursday) I arrived back at the Ashram and received the loving blessings and kind welcome of the gracious Guru Bandhus at the Ashram. Then we went directly from the road up to the sacred Samadhi shrine of Gurudev and worshiped here, as it was the day of the special weekly worship, being Thursday. The next day, the Holy Mahashivaratri day the all night worship and vigil at the temple of the Lord of Universe (Viswanath) commenced at 8 p.m. This servant took bath at 10 p. m. and joined the worship at the temple where he offered Puja to Bhagwan Viswanath with Abhisheka, Archana, etc. on behalf of you and prayed for and invoked the lord’s Divine Grace upon you for your health, happiness, welfare and highest spiritual Blessedness and Divine Peace and Bliss. The Ashramites and numerous visiting devotees all chanted Kirtan of Lord’s Divine Name, prayed and worshipped at the Temple that night upto the Brahma-Muhurta the next dawn at 4.30 a.m. It was indeed an inspiring holy night, solemn and yet filled with fervour. On the 20th this servant had the unique blessedness of going on foot to the holy shrine of Nilakanth Mahadev, seven miles from the Ashram, on the other side of Ganga, across the majestic Manikoot Pravat. Dr. Sivananda-Adhvaryoo and family, who had come to Ashram specially for the Mahasivaratri function, expressed a desire to make this short but strenuous Yatra, and so went in a party of ten persons through the forest, up steep mountain footpaths to this ancient temple, situated in the heart of the hills, a mile below the temple of Bhuwaneshwari. It was a chill winter day and night we spent there offering worship to Bhagwan Nilakanth Mahadev under a towering ancient Peepul tree. Returning to the Ashram on 21st evening Adhvaryooji left the next day, and I found myself in the midst of much work, accumulated during my month-and-a-half’s absence. I want to avail this page to express and convey my many thanks to all of you who worked so wholeheartedly in arranging the various programmes during my recent tour through Poona, Hyderabad, Vijayawada, Enkatagiri Town, Kothapalam, Gudivada, Chevendrapalayam, Tanuku, Undrajavaram, Relangi, Kovvur, Chodavaram, Berhampur, Chatrapur, Khallikote, Khurda Road, Puri, Cuttack, Bhuvaneswar, Calcutta and Lucknow. My grateful thanks to the wonderful work done by the organiser of the two conferences at Vijayawada (A.P.) and Jagannath Puri (Orissa) and the devotees headed by Sri Venugopal Reddy Garu at Kothapalam. They have all shown rare devotion to Gurudev and his Spiritual mission of Divine Life and have worked with the noble spirit of dedication and selflessness. It is indeed a blessing to have such Guru-Bandhus and devotees sincerely eager to serve their Holy Master’s cause. God shower His Grace upon you all. During this tour I availed the opportunity to visit and pay my homage to the following holy places:
55
BE A HERO IN THE BATTLE OF LIFE
The sacred Samadhi of the late Holiness MALAYALA SWAMIJI MAHARAJ at Vyasashram, Yerpedu, Srikalahasthisvar Bhagwan of Kalahasthi the renowned Deity Who revealed Himself to the wonderful devotee Kannappah Nayanaar, the sacred Samadhi of Beloved SWAMI RAMDAS (PAPA) of Kanhangad where I also sanctified myself by the holy Darshan of Mother KRISHNA BAI MATAJI, the Darshan of the well-known Vdanti saint of Andhra-Pradesh SWAMI PRANAVANANDAII MAHARAJ of Pranav Ashram at Gudivada, Lord SRI JAGANNATH (in whose blessed presence I remembered you all), Divine Mother KALI of DAKSHINESWAR, the sacred Samadhis of SWAMI VIVEKANANDA, BRAHMANANDA, Sri SRI MA (The HOLY MOTHER) and the shrine of Bhagwan Sri SRI RAMAKRISHNA DEV at Belur Math, where I had Darshan of his Holiness Sri SWAMI VEERESHWARANANDA MAHARAJ, the Ramakrishna Institute of Culture where I had Darshan of Pujya Shri Swami Ranganathananda Maharaj and the beautiful new temple of VAIKUNTHANATH also in Calcutta. Then on my way back to Rishikesh this servant went to meet Paramahamsa Swami Satyanandaji at his Bihar School of Yoga at Monghyr (Bihar) and bowed adoration before the Akhand-Jyoti lit in memory of Gurudev in the main assembly hall of the School, then to sacred Varanasi where I met Swami Nijabodha Maharaj, an elder Guru-bhai after more than 15 years and Sri Shridhar Bhatt Maharaj, the Incharge of the Sringeri Sankara Mutt in Kashi. While in holy Kashi this servant worshipped Lord Vishweswar to heart’s content one day invoking His Grace upon each and every one of you. On the day of Holi Poornima is the birthday anniversary of the great Gauranga Mahaprabhu, the supreme devotee of the Lord. Sri Krishna Chaitanya was Bhakti incarnate and gave new life in this Kali-Yuga to practice of the Lord’s divine NAME and to SAMKIRTAN YOGA. He called upon man in this Iron Age to live a life of true humility renouncing pride, arrogance, haughtiness and egoism, to bear with utmost fortitude all vicissitudes in life. Shun honour and renown but ever give respect to everyone without distinction an to ceaselessly worship the Lord with whole hearted devotion. With courage and determination conquer this demon Ahankara (egoism) and be humble, be a hero in the battle of life and bear afflictions boldly and with endurance know that Divinity resides within all beings and therefore honour all beings and everywhere, at all times, in all conditions ever remember, love and worship the Supreme Being with unbroken devotion and faith. Become divine and attain the highest bliss, peace, and felicity here and now. Now repeat for a while the MAHA-MANTRA which Gauranga Mahaprabhu propagated into the four corners of the land. “Hare Rama Hare Rama Rama Rama Hare Hare Hare Krishna Hare Krishna Krishna Krishna Hare Hare” Thus auspicious by the life when the New Year commences this month with the advent of Chaitra Sukla Paksha when Phalgun ends presently. God bless you. With my best regards, Prem, Pranams. Sivanandashram 1st March 1966. Yours in Sri Gurudev —Swami Chidananda
56
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XXVII
PROPOSED PILGRIMAGE FROM HIMALAYA TO MALAYA
Blissful Immortal Atman, Beloved Seeker After Truth, Om Namo Narayanaya. Greetings in the name of Swami Sivananda. This month, through the will of the Lord and worshipful Gurudev’s mysterious hand, this servant of his has to visit Malaysia. This journey is to me in the nature of a pilgrimage rather than a spiritual tour because Malaya is sacred to us as a land where Sadgurudev in his poorvashram toiled incessantly as Dr. Kuppuswamy to bring solace and relief to the suffering people about a half century ago. It is the land wherein through fiery Karma Yoga, dynamic selfless service he attained purity of heart, Viveka, Vichara and keen aspiration for God-realisation. It is the country of his great renunciation. From Malaya he came to Himalaya. Singapore Joharbaru, Penang, Seremban are all names familiar to us due to their frequent mention by Gurudev in answer to our question regarding to that wonderful period of his life. Wonderful because it was rich with radiance of his exuberant personality, his Universal Fellowship, his Spontaneous charity, his magnanimity and lofty humanitarianism. It is replete with thrilling incidents of his generosity, love and rare equal vision. The Capital of Malaysia is Kuala Lumpur, and there is a Centre of our Divine Life Society in the city and a Sivanandashram at its outskirts near Batu Caves at the foot of a mountain. In this Ashram, the Society members are installing a life-size marble statue of worshipful Gurudev Sivanandaji unto a special altar in their main Prayer Hall. The auspicious moment for it is on 9th April and I have been invited to preside over this unique function. I shall be leaving Delhi on Tuesday the 5th April to arrive the same evening at Kuala Lumpur. The next three days will be spent in public engagements. On the 9th the consecration will be solemnised in the forenoon according to traditional ritual and colourful ceremony. In the afternoon will be a great public gathering in which peoples of all faiths will participate and bless the new Prayer Hall. Sri Swami Pranavanandaji (formerly Sri Ponniah) is back to Kuala Lumpur, after a successful tour of South India and Ceylon, awaiting arrival of this servant on 5th evening. They have arranged for a tour through important cities of Malaysia after finishing the Kuala Lumpur programme in the second week. I have written and requested the organisers to try and locate the various spots connected with Gurudev’s residence and work while he was in Malaya during the first quarter of this present century. I wonder if there are also persons alive who have met him there during the period, prior to his renunciation and journey to Himalaya to take up Sannyasa life? May be there are and I shall be able to meet them. If I do I shall certainly tell you about them when I write next. After this pilgrimage to this Theatre of Gurudev’s Seva, Karma Yoga and Tyaga, I shall next be proceeding to Hong Kong for a ten-day-programme at the very pressing request of numerous Hong Kong devotees. There is an excellent Yoga Centre running there, originally established by Yogi-Raj Sri Swami Vishnudevanandaji Maharaj, which is now successfully doing excellent Yoga work in Canada and the U.S.A. This Yoga School having numerous enthusiastic students is actually sponsoring my visit to Hong Kong. I shall tell you something about their
57
PROPOSED PILGRIMAGE FROM HIMALAYA TO MALAYA
activities after seeing them, when I return to India in the month of May. I think I shall be back in the Ashram by the end of the third week of May. I must tender my apology to some of the foreign Centres of the D.L.S for disappointing them on the present account. They seem to have been given the impression that I am soon to take a tour round the world. So many of them wrote very eagerly and asked for more details. I had to tell them all that actually I never had any plan for a world tour at this time. My trip abroad was mainly to attend the Kuala Lumpur functions in Malaysia and to tour that country and Hong Kong. This I had to agree to upon the loving insistence of the Divine Life Organisers of these two places. However, to obtain endorsement upon the Passport for any future use, certain other Centres also were informed about my travel and they had sent out invitations to me under the impression and hope that I would immediately undertake a visit to their countries too. They will kindly pardon this unintentional false hope given to them. The Ashram has just now celebrated the holy Sri Ramanavami festival. Special prayer have been offered for all of you and I remembered all members and devotees generally and specially Sri Hiralal Mehta, a noble devotee and solicitor of Bombay and his family, the pious Srimati Saraswati Mehta, Hemlata Mehta, Ajit Mehta and others who are the donors of Bhagwan Sri Ramachandra, Mother Sita, Sri Lakshmana and Hanumanji now showering their grace from the holy Mandir at the Ashram. May Lord Rama grant Sri Hiralalji and his entire pious family health, long life, peace, bliss, prosperity and immortality. This holy Ashram of Gurudev is now looking forward to the summer season with its vacation visitors and the opening of Badrinath and Kedarnath Yatra with their stream of Pilgrims from all parts of India. This year the Badri Yatra has been rendered so easy due to extension of motor road that Badrinath is now only two days distance from Rishikesh. Times are changing. Everything is moving fast, too. Blessed seekers? May you, too, proceed vigorously on the path and rapidly reach the goal of Kaivalya Moksha. Move forward steadily and attain the Supreme Divine experience. I draw your attention to the special article in this month’s Divine Life Magazine regarding the state of the Divine Life Organisation and its present work since the Maha Samadhi of Sadgurudev in 1963. This year Guru Poornima falls on 2/3 July. I welcome all of you for the holy event. Such of those who are unable to attend the ten-day-function may carry out a similar programme of ten-day-Sadhana from 3rd to 12th at their own home or in their centre Divine Life Society. May God bless you. With regards, Prem Om, Yours in Gurudev April, 1966 Swami Chidananda
58
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XXVIII
‘OM’
THE MALAYASIANS’ PROFOUND DEVOTION TO GURUDEVA’S MISSION
Blissful Immortal Atman, Beloved Seeker After Truth, Om Namo Narayanaya. Salutations in the name of worshipful Gurudev Sivananda. Though this letter of mine bears the title ‘Sivanandashram Letter’, I am writing it to you all from the far-off Crown Colony of Hong Kong. A large group of ardent devotees of Revered Gurudev, who have made their homes here, and who with His Grace and blessing are the leaders of both the spiritual and temporal life of this beautiful and thriving colony, have by their kind and loving invitation enabled this servant to visit this place. I reached here in the afternoon of the 27th of April and have been here for three days. According to my programme about which I had written in my letter in the last issue of ‘Wisdom Light’, I came here after a busy, extremely rewarding three weeks in Malaysia. I would like to take this opportunity of telling you briefly about some of the activities in Malaysia. This humble servant was overwhelmed by the gracious display of devotion and affection for Revered Gurudev that was shown by the members of Malaysia Branch of the Divine Life Society and the public of Kuala Lumpur. In the public meeting on the 7th April the humble agent of Gurudev was showered with the affection and devotion that could come to him only through Gurudev’s Grace. The insisting love of the Malaysian devotees, led by His Holiness Sri Swami Pranavanandaji Maharaj, had brought me to Kuala Lumpur for the main purpose of officiating at the opening ceremony of the new Ashram building and unveiling the life-size marble statue of Revered Gurudevji on a special Pedestal at Batu Caves near the city. 9th April was the day on which a grand meeting was held under the Chairmanship of the Hon’ble Dato V. T. Sambanthan, P.M.N., Minister of Works, Posts and Telecommunications in the Malaysian Government. After the opening ceremonies, which were performed by this sevak, Sri Swami Pranavanandaji, the Chief High Priest of Malaysia (Buddhist), the Bishop of Kuala Lumpur, the President of Singapore Ramakrishna Mission, as also Mohammedan and Sikh leaders of the community spoke highly about the mission of Gurudev and the importance of Divine Life. This servant spoke on “The Secret of Right Worship and God-Vision.” It was a soul-stirring and elevating experience. I remembered all of you when offering my prayers to Revered Gurudev’s image and on behalf of Divine Life members all over the world. I prayed for his illuminating light to guide our halting and faltering steps towards spiritual perfection. The rest of my time in Malaysia has taken up by a series of lecture meetings in Kuala Lumpur and other parts of the country. At all stations, this humble servant was drenched with the spontaneous affection of Gurudev’s devotees. Before coming here it was my ardent desire to see some persons who knew Revered Gurudev during his stay here. The desire has been amply fulfilled and I have been fortunate in meeting persons who had known Swamiji Maharaj, while he was here between 1913 to 1923. For want of space and time, I am obliged to differ dilating on this phase of
59
THE MALAYASIANS’ PROFOUND DEVOTION TO GURUDEVA’S MISSION
my tour to a subsequent letter. I would like to end this one by thanking here all the principal persons who took a leading part in organising this visit to Malaysia. I would like to name them and render my thanks to them individually, but for fear of omitting important names in a hurry, I end this letter by thanking all those, who, by their active and sincere efforts, have helped to make the tour of this humble servant a very instructive and memorable experience for him. During this month of May would be celebrated the Narasimha Jayanti on the 3rd, the Buddha Jayanti on the 4th and Ganga Dussera on the 29th. These dates mark the occasions on which Lord’s Supreme race manifested itself in some way or the other on behalf of the devotee. Elsewhere in this issue, would be features high-lighting the significance of these manifestations. True to our hoary tradition, these narrations bespeak the unfailing nature of Divine Grace and its constant availability to those who seek it. Unwavering devotion of Prahlada, selfless search of Truth of Bhagwan Tathagata and compassionate efforts for the liberation of the ancestors by Bhagiratha are rewarded by this Grace. It is my constant prayer to the Almighty that He similarly Grace the efforts of you all. May God and Gurudev shower their blessings on you all. With regards, Prem and Om, Yours, in Gurudev. —Swami Chidananda
May, 1966
Sivanandashram Letter No. XXIX
THANKS AND DEEP APPRECIATIONS TO SEEKERS OF MALAYSIA AND HONG KONG
Blissful Immortal Atman! Beloved Seeker after Truth, Om Namo Narayanaya. Salutations and Greetings in the holy name of Gurudev Sivananda! May the grace of the Divine be upon one and all of you! I send you my loving good wishes from the sacred abode of Gurudev by the holy Ganges once again after an absence of one month and a half from headquarters. On Sunday, the 22nd May I arrived back at Sri Gurudev’s Ashram a little before sunset in the evening of a very warm day. My heart was filled with joy by the loving welcome extended by the many Guru-bandhus who cherish a gracious regard toward this servant of Gurudev and His institution and its work. Though fatigued by much journeying yet I was not unwilling to climb up with them all to the holy Samadhi Shrine of our worshipful Master and offer my homage there as also at the Sri Vishwanath Mandir. We then went over to the Bhajan Hall where your servant spoke to the assembled Ashramites and visitors and conveyed to them all the love, regards and greetings of their fellow-seekers in Malaysia and Hong Kong and South India, (Karnataka). They were also told about the wonderful devotion of the seekers and spiritual aspirants of Malaya have for Gurudev Swami Sivananda and His noble spiritual work and His Divine Life Message. The inspiration of
60
ADVICES ON SPIRITUAL LIVING
speaking to people fully receptive to your message was also related and I spoke to them also about the perseverance of the Hong Kong D.L.S. Yoga Institute group in keeping up the Yoga activities initiated there by His Holiness Swami Vishnudevanandaji Yogiraj nearly nine years ago in 1957. The Chinese students of Swami Vishnu Ji have now become very excellent instructors, many of them and are conducting regular Yoga classes in different parts of the city with great earnestness and tenacity. An admirable feature of their Yoga activities is their unfailing regularity over these past nine years. I have been extremely pleased with their work. They have acquired the spirit of service to a considerable degree thanks to the influence of Swami Vishnudevananda, their teacher. I am making this letter brief, as the travel has tired me somewhat physically and the summer heat has been fully turned on this week with 111 degree F. in the shade. Caught between the two hillsides on north and south, this tiny valley is seared with burning hot winds during the day and through a good part of the evening and early night. The ice cold Ganges is the sole saving grace in this place at this time of the year. A last bath at 10 p.m., before bedtime relieves the body of the heat of the daytime. Leaving Hong Kong on the evening of Tuesday, 10th May, I entered India via Calcutta and landed at Bombay airport at midnight. Friends of the Bombay Divine Life Centre had graciously denied themselves sleep and turned up at the Airport to receive me. After the usual formal delays inevitable in re-entry, we reached residence a couple of hours after midnight as the flight also was about an hour late on that day. Two days, comparatively quiet ones at Bombay, with only an evening Satsang each day, I left for Bangalore on the 13th May and arrived there in the afternoon. Upon arrival I had the good fortune of having the holy Darshan of a large number of devotees and Sadhaks who had all come to Bangalore for the forthcoming D.L.S. Conference to take place on the morrow (14thMay). Sri T.M. Sreenivasan, the Convener was there to meet this Swami upon arrival as also veterans like V.L. Nagarajan, Balu and others. The three-day Conference was a good success and was inaugurated by His Holiness the Jagadguru Sankaracharya of the Sharada Peetha of Dwaraka in Western India and addressed by eminent speakers like Sri R.R. Divakar, Mir Iqbal Hussein, Swami Poornananda Teertha Maharaj, Sri Y. Ramachand, Smt. Grace Tucker, G.V. Hallikere, G. Venkatasubbiah, M.P.L. Sastri Ji, the Hon. Dr. K.L. Shrimali Ji, H.H. Radhakrishna Swami and others. The Upanishad Chanting by Kumaris Jayashree, Surekha and Shanta was most thrilling indeed. I wish these gifted children will keep on progressing along this line. It seems they are from the Malleswaram Divine Life group. Congratulations. The conveners of this first All-Karnataka Divine Life Conference deserve our special congratulations and thanks also for bringing out a very nice and valuable Souvenir which was released during the very first day of the Conference. Well done! While at Bangalore I took the opportunity of visiting and paying my respectful homage to the renowned saint His Holiness SWAMI ANAND ASHRAM MAHARAJ, Chitrapur Mutt, the religious head of the Saraswat community as he happened to be camping at Bangalore at the time. Gurudev held him in much regard. I also had the happiness of meeting my old friend Sri Swami Sureshanandaji of the Ramakrishna Mutt at Basavangudi, who kindly took me to their beautiful Ashram one evening when I was able to bow down in reverence before Sri Sri Ramakrishna Dev at the shrine just at the evening Arati time. Immediately after the Conference a trip was undertaken to Tirukoyilur to visit the well-known Jnanananda Tapovanam, the holy Ashram of the renowned
61
THANKS AND DEEP APPRECIATIONS TO SEEKERS OF MALAYSIA AND HONG KONG
venerable saint and Siddha-Yogi Pujya Sri SWAMI JNANANANDA GIRIJI HAHARAJ. On our way back on the morning of the 17th we stopped at the holy Sri RAMANASHRAM in Tiruvannamalai to adore in silence the Great Sage of Arunachala whose radiant Presence pervades that Ashram at the foot of sacred Arunachala Hill. It was a hot midday hour, yet Sri Venkataramanji, the President in-charge, very graciously welcomed this servant and was extremely hospitable and courteous. As I wished to see some literature of the Ashram he insisted upon my receiving the books I asked for as a gift saying, “This is Bhagavan’s Prasad. You must receive it.” I remember this gesture with sincere appreciation. After return and a farewell Satsang gathering at the holy Ram Mandir of Malleswaram, we left for Bellary for a programme there on the 18th May. Back at Bangalore on the next day, the 19th I had the great joy of visiting the new PANDURANGA TEMPLE being built by Keertana Kesari Dasaratna Sri Bhadragiri Kesavadasji at Purandharapura (Rajajinagar) and worshipping the beloved Lord Vitthala present therein. The kindness of the Bhakta Mandali there was great indeed! Then, just before leaving for Bombay at midday there was a final Satsanga at the house of the devotee Sri Venkatachalapathy at Nandidurg extension where the D.L.S. members from Tumkur had a pair of silver Guru-Charanas consecrated with prayers and special chanting of the Lord’s Name, for being taken and kept for worship at Tumkur. Sri SWAMI DEVANANDAJI, who had been valuably helping me together with Swami Raghunathanandaji during my entire stay at Bangalore for the Conference, took leave of me at the airport to take his train for Venkatagiri Town where he went to represent Sri Gurudev and my self at the All-India D.L. Conference there. Arriving at Bombay the same afternoon this Sevak spent a very quiet evening by the seaside at Juhu at sunset. That day, 19th May happened to be a very significant anniversary for me because it was upon this very day full twenty-three years ago that I had for the first time in my life, the sanctifying Darshan of the lotus-feet of Satguru Bhagavan Sivananda Dev at Ananda Kutir by the holy Ganges bank when the evening twilight was fading away on 19th May 1943. We had a little Kirtan when the hour arrived and returned to Pramod Villa at Khar at about 8.30 p.m. I spent that night at the home of Sri G.V. Parameswaranji of Bombay D.L.S and left the next morning for Delhi en route Ashram which, as mentioned already, was reached on Sunday 22nd May after a day’s break at Hardwar for Darshan of Goddess Mansa Devi and Mother Chandi Devi on the mountain top across the Ganga. From here, Gurudev’s holy abode, I wish to say my thanks and deep appreciations to all the good friends and seekers of Malaysia and Hong Kong who have shown me and my helper Devendar Bhargav so much kindness, hospitality and gracious care during our entire tour in their country during the six weeks from 5th April to 10th May. I shall be writing to all these wonderful people of the different centres such as Kuala Lumpur, Raub, Seremban, Ipoh, Penang, Prai, Singapore, Johore Baru, Kluang, Sungai Siput, Kuala Kangsar, Taiping and Hong Kong and Kowloon. Besides H.H. Sri Swami Pranavanandaji, Sri Thuraiappahji Maharaj, Sri Sivananda Boteju and Sri Arunachalam (whose loving kindness and help I have no adequate words to express). I also remember with special affection such persons as Sri Karthigesu of Kampong Attap, K.L., Sri Chen Yoke Chen, Sri Rasaratnam and family, Tan Sri Dato V.T. Sambandan and the gracious Datin who are both great devotees of Bhagavan Sri Ramakrishna Paramahamsa Deva and Sri Ma Sarada Devi, Mr. and Mrs. T. Mahesan of the Chinmaya Mission, Mrs. Ariyanayagam of Raub, Krishna Pillay of Raub, the revered Dr. C.H. Yeang of Penang, Sri Ramanujam of Singapore, Dr. Vasudevan of Kluang, Sri M.S. Kandiah of Ipoh, Sardar Sri Kripal Singh Gill of D.L., Sri Lall of K.L., Sri N. Thambidurai of Seremban (who arranged for our Port Dickson Retreat), Sri S. Narayanan and Sri S.
62
ADVICES ON SPIRITUAL LIVING
Sivagnanam of Seremban, Mrs. R. Senan of Penang, Sri Linga Nathan of Radio Malaysia who kindly came and interviewed me at Batu Caves Sivanandashram. I remember also the very gracious hospitality and kindness of His Holiness Sri Swami Siddhatmanandaji Maharaj of the Ramakrishna Mission Ashram at Singapore who invited me for the blessed birthday anniversary of Bhagavan Ramakrishna Dev and Swami Vivekananda celebrated at their Ashram on 23rd April when I also had the holy pleasure of meeting H.H. Sri Swami Chidatmanandaji Maharaj of the Mayavati Advaita Ashram in the Himalayas. The latter Swamiji was on a visit to Singapore at that time. At Hong Kong great has been the kindness and Seva of Sri Khanchand H. Moorjaniji, Sri Virumalji, Sri Uttam Chand, Sri J. K. (“Raja” of Gurudev), Mrs. Thelma Heitmeyer v.c. of the Yoga Institute, D.L.S., Mr. Li Che-Kong, Yogiraj Au-Yeung Hao-Man, Mr. Lo Wing-Lok, Mr. Wong Kang-Sai, Mr. Wong Ping Lai and others. Mr. Heitmeyer though busy was yet graciously helpful many a time. My meeting with the most venerable Sri Dinshaw Paowalla alias RAMDAS and mother Banu Ruttonjee was memorable and I shall ever cherish it in my memory. The authorities of the Hindu Association and Temple where I stayed merit my grateful thanks. May God bless them all! My regards to you, dear Reader. God Grace you too! I take leave of you until the first week of next month, July, when we shall be observing the most sacred Sri GURU PURNIMA DAY. Prepare for it with more Japa of your Guru Mantra and a Mandala of Sadhana from now up till the Third Anniversary of the Holy Mahasamadhi day of Gurudev. May His benedictions ever be upon you! Yours in Gurudev, 1st June, 1966 —Swami Chidananda
Sivanandashram Letter No. XXX
MONTEVIDEO—STRONG HOLD OF GURUDEVA’S MISSION
Blissful Immortal Atman! Beloved Seeker after Truth! Om Namo Narayanaya. Salutations and greetings in the holy name of Gurudev Sivananda. May the grace of the Divine be upon you. As I write this letter I hear the rushing waters of the Ganges and see the clouds upon the mountain top and the entire mountains’ side green with fresh forest foliage, for the monsoon rains are upon us now. The intense heat of the last few weeks has now given place to heavy downpour of rains and the Ganges is in flood. The earth and the forest that had been parched and dried up have now become soaked and green everywhere. The Badri-Kedar Yatra has been in full swing and a record number of pilgrims have travelled this year for the holy Darshan in these sacred shrines It is a great joy to note that our country’s beloved Prime Minister Srimati Indira Gandhiji has also availed herself of an opportunity of visiting the Holy Badrikashrama Punyakshetra and obtained the blessed Darshan of Bhagawan Narayana. India is a land of faith and devotion. Religion is our very life. It is but fit and proper that the leaders of people
63
MONTEVIDEO—STRONG HOLD OF GURUDEVA’S MISSION
should themselves set the right example of piety, righteousness, love of God and service of mankind. Today the world is facing hard times. An uncertain future seems to loom ahead of the nation. India is the part of this world situation and thus we too are facing numerous problems. Want, scarcity, near-famine condition, economic plugs present a complex situation for both people as well as their administrator to deal with. Each and every individual must participate in resolving it and everyone must help in easing the pressure by voluntary self-denials and self-imposed austerity cheerfully adopted with spiritual courage. All these things will pass away by and by. Firm trust in God, complete reliance in His Divine Name and unremitting fulfilment of Dharma will bring you safe through all crises and victories in all situations. God is the Supreme Director of this Universe. He is the Invisible Inner Controller of all things. He listens even to the footfall of an ant. He repairs the damage of even the wing of a little fly. Have faith. He is the Solver, the real Solver of all problems. He Himself is the real solution too, to all your troubles. Know Him to be thus and the burden will be lifted from your shoulders. Strive with calmness and courage to overcome all adversities. Repose thy faith in God. To make effort is man’s duty. Results are safe in Divine hands. Wisdom and Justice prevail in Divine dispensation. Earnestly act with optimism and good cheer. Rely on God and do the needful. Where there is distress, bring relief, where there is despair, strive to infuse hope. Where there is want, give generously. Where there is famine, feed the hungry. Where there is disease, bring aid to heal and restore health. Let every man be such a helper and bringer of relief in the name of God. Thus may the whole nation become firmly based upon self-help and spontaneous selfless service. This is the need of the hour. This month commences with an extremely solemn and auspicious day, namely the day of Vyasapuja, also known as Guru Purnima, This is a day specially observed during each year as a day of grateful adoration of the great Masters of Wisdom, all the Brahma-Vidya Gurus of most ancient times as well as of today. This is an effective and powerful reminder to you all that your greatest wealth and treasure in life is the Wisdom teaching of these illumined spiritual Masters. For, it is the nectar of their Divine teachings alone which can destroy death and suffering and bestow upon you immortality. This alone can make you eternally free. This Jnana is therefore your most precious heritage. The unbroken lines of spiritual teachers or Gurus have handed down these teachings through each succeeding generation and thus kept alive radiant fire of living Wisdom that burns away the dross of worldliness and makes man Divine. To them, we owe the deepest debt of gratitude. The sacred Gurupurnima day is thus a glorious day set apart for Guru-worship so as to enable us to express our gratitude, reverence, love and adorations to the great Masters of humanity, through solemn worship and homage. Guru Puja is offered on this full-moon day of the month of Ashadha throughout the length and breadth of our blessed mother country. From the Himalayas to Cape Comorin this land will be filled with fervour of Gurubhakti, the fragrance of humble discipleship and thrilled with the vibrations of worship, glorification and dedication. You will be inspired by the lives and the lofty teachings of the great Gurus of all times. Shri Vedavyasa Bhagawan is adored everywhere as the great father of our country’s culture. He is one of the brilliant lights upon the spiritual firmament of Bharatavarsha. Let us also adore upon this day Lord Jesus, Zoroaster, Moses, Mahavira, Buddha, Krishna, Mohammed, Nanak and the great Acharyas.
64
ADVICES ON SPIRITUAL LIVING
May the choicest blessings of all the great saints of ancient times as well as present modern times be upon you all. Be guided by their Divine teachings, lead a pure life and attain blessedness. As you all know this year the Guru Purnima falls on the 2nd July and the holy Anniversary of Gurudev’s Mahasamadhi on the 12th July. This ten-day period is a time of Sadhana and total spiritual renewal. Observe it as such. Simplicity, austerity, earnestness and prayerfulness should mark this period. Observe Mouna or silence as long as possible during these ten days. Practise self-control. Engage in spiritual practise as much as time permits you. Here at Headquarters, Sivanandashram, simplicity will mark the entire function and due to food-scarcity conditions in the country and famine-like situation in certain areas, we have cancelled the idea of any large scale public feeding on the Aradhana day. There will be no Bhandara here but instead the Ashram is donating a sum of Rs. 1008/- in the sacred memory of Gurudev to the Prime Minister’s Relief Fund. I suggest that each one of you may similarly contribute your own mite directly whatever such relief fund there is in your own state or send it to Delhi. Next to Jnana Dana, Anna Dana is verily the greatest of Yajnas in this Iron Age. Individually and collectively help the Government by all possible means in overcoming the problem of food-scarcity. Do not waste food. Be frugal. Miss a meal. Eat moderately. Learn to use non-cereal food. Fast on Ekadasi. Share what you have with others in need. May God bless you. Thus will you please Sri Gurudev. By the time it reaches you the Aradhana functions would have commenced. The entire Ashram will be absorbed deeply in Sadhana programme. I must conclude now. However, before closing I wish to share with you a beautiful letter filled with sincere Bhava and the spirit of devotion, enthusiasm and dedication to Gurudev’s spiritual teachings and His Divine Life Mission. This letter is from “Centro Sivananda de Estudios Yoga Vedanta” Del Uruguay which means, the Sivananda Centre of Yoga Vedanta Studies of Uruguay. This is our Divine Life Branch at Montevideo, capital of Uruguay in South America. They are an exceptional group of very earnest Spiritual seekers with genuine aspirations and devotion to the ideal of God-realization. They are one of our best groups abroad and are working in a very systematic way with well organised regular activities. The letter has been singed by 17 of the Sadhakas of the Centre (There was no more space for further signatures!) Montevideo, May 21, 1966. H.H. Sri Swami Chidanandaji Maharaj, President of the Divine Life Society, RISHIKESH. Revered and beloved Swamiji, Today it is exactly five years ago that for the first time the Uruguayan ground was blessed with the touch of your holy feet. With gratitude and devotion in the heart, we remember that on this day you started the spreading of Sri Gurudev’s teachings here, planting the seed of the Uruguayan branch of the Divine Life Society, which is growing steadily; thanks to God’s and the Masters’ Grace, as well as to the gracious guidance of beloved Swami Shivapremanandaji.
65
MONTEVIDEO—STRONG HOLD OF GURUDEVA’S MISSION
On this occasion we reaffirm our ideal to contribute with our effort so that the glorious blessings which this Centre received may flower as a stronghold of Sri Gurudev’s mission in this area. With the best wishes for your good health and personal welfare, we are always, with Prem and Om, Yours, and here follow the many signatures. Among others I recognize the familiar signature of Roberta Dix, Lotti Dix, M. Luisa Costa, C. W. Hartschuh, H. Hartschuh, de Bouton, Ledia Pesquera etc. Most certainly this growing plant of Uruguayan Divine Life will grow further into a towering tree spreading ITS Branches not only all over Uruguay but throughout many countries of South America where Gurudev’s teachings are so much pressingly needed at this time. This servant is most gratified indeed to read the beautiful 3rd paragraph of their letter wherein they reaffirm their objective of strengthening their noble work. This indeed is a spirit which we require from each and every individual member and each and every organised branch of the Divine Life Society. What more can I say unto you all than what I have just now said, as we are gathering together to pay our reverential homage to our spiritual Master, on the holy occasion of the 3rd Anniversary of Gurudev’s departure from this world of physical manifestation. As the sacred day draws near even as our beloved friends of the Uruguay Centre, May all of you also similarly reaffirm your ideals to contribute your efforts so that the glorious blessings of Gurudev’s teachings and Divine Life Mission may become firmly and strongly established in the place where you, dear Reader, His devotee and representative are living. The outer expression of true love is service. Those who cherish such love unto Gurudev’s feet cannot but actively serve Him through His Divine Life Institution. When you love you naturally serve whom you love. May you all rededicate yourself afresh to such love and service upon the sacred Guru Aradhana day. May Gurudev’s choicest blessings shower upon you and grant you joy, peace, and immortality. With regards, Prem and Om, Yours in Gurudev, —Swami Chidananda
July, 1966
Sivanandashram Letter No. XXXI
KALKI—AVATAR OF HOPE, FORETOLD
Blissful Immortal Atman! Beloved Seekers after Truth, Om Namo Narayanaya. Om Namo Bhagavate Sivanandaya! Accept my salutations and good wishes in the holy name of Gurudev Sivananda. May the Lord’s grace be upon you. I write with great joy because I have had the unique privilege of offering my devout worship on behalf of your good self and each and every individual member of the Divine Life Society, to our beloved Gurudev upon the solemn occasion of the 3rd anniversary of His
66
ADVICES ON SPIRITUAL LIVING
Mahasamadhi. This worship was done on the 12th of July, the sacred Punyatithi and this Aradhana Puja took about four and half hours time. It commenced at about 9 a.m. and concluded at 1.30 pm. During the sacred Abhisheka I entered the holy shrine with all of you in my mind and making a Sankalpa for Gurudev’s choicest blessings, performed the worship. May joy, peace and plenty fill your life. You know, July has been momentous month, the high lights of this eventful period has been the most holy GURU PURNIMA day, the eight-day-period of SPIRITUAL SADHANA, the Annual General Body meeting of the Divine Life Society (on 11th July, 1966), the release of the previous year’s Sadhana Week Special Souvenir and to crown all of this, the auspicious and most inspiring PUNYATHITHI ARADHANA. You will see the graphic report of these sacred observances in the Ashram News in Divine Life Journal. I may state that this year’s Spiritual Sadhana period has been the most satisfying and gainful one. The earnestness, the co-operation and the eager participation on the part of the numerous Sadhaks was most gratifying and I must congratulate each and every one of them for the spiritual quality and Bhav which they manifested. May they progress upon the same pattern! One important decision that has been taken is to make available to all the members (I am referring to you, dear friends) of the Divine Life Society a substantially enlarged and improved Divine Life Magazine every month and to simultaneously raise the annual Membership Fee. One suggestion for the new figure was Rs. 6 per year. But this was reconsidered by the General Body and the enhanced Annual Fee of Rs. 5 was readily agreed upon by the meeting. This will come into effect next year from 1st January, 67. All of you will very kindly bear this in mind when you are renewing your Membership towards the close of this present year and remember to send two and a half rupees extra with the usual two and half rupees. Because henceforth five rupees will be the Annual Fee. However, the admission Fee for new members will be the same as it has been previously. I wish to draw your attention to the increased benefits you are going to derive as a member from the next year. Now please follow me. At present you are only receiving Wisdom Light alone every month. From next year receive the monthly Divine Life Magazine also as well as Health and Long Life and the Branch Gazette too, all in one. All these you will get due to the fact of your membership alone, without having to subscribe separately for these other journals. As it is, if any one subscribes for all four journals, his aggregate payment will have to be approximately Rs. 12. But a member will get these included in his Annual Fee of Rs. 5 only. How we shall be able to do this you will just now see. It has been proposed to include the contents of these four journals in a single magazine, namely the Divine Life monthly which will consequently be considerably enlarged, thus giving place to the combined matter now appearing separately in the other three journals, i.e., Health and Long Life, Wisdom Light and Branch Gazette. The ‘Divine Life’ will be the sole Official Journal of the Divine Life Society. All members of the society will receive it; all the D.L.S. branches too. Though the other three journals will be stopped, yet in fact, you will continue to get all of them in and through the Divine Life Magazine. You may please look out for detailed announcement in this regard published elsewhere in this journal. The matter is being finalised at the headquarters. The enlarged monthly D.L. journal that you will get from January, 1967 onwards will be double the size of the Wisdom Light in dimension (namely ‘Divine Life’ size) and will contain approximately 50 pages. In terms
67
KALKI—AVATAR OF HOPE, FORETOLD
of your present Wisdom Light journal that you are just now reading at this moment that new journal would contain nearly 100 pages. This year you might have seen from last month’s letter, I had decided to restrict the feeling on the 12th July and confined it to the attending Sadhakas, Bhaktas and Guru Bandhus instead of a general Bhandara. Why this was done was made perfectly clear in page 200. I shall make a slight diversion here and tell you the criticism sent in by one revered reader. The worthy reader writes: “The Sivanandashram Letter No. 30 (in the July issue of the “Wisdom Light”) gives rise to a mixed feeling of comfort and sorrow. Comfort at the idea that solemnity and simplicity will be the mark of the Aradhana Celebrations and sorrow at the foot that this great spiritual Institution has chosen to woo the Government by a donation to the Prime Minister’s Relief Fund in preference to the mass-scale feeding of the poor, on the most solemn occasion of the Aradhana day...... May Gurudev guide us to better times and rational functioning in consonance with the lofty ideals of the D L. Mission. Pranams.” I wish to thank the reader for presenting so frankly his point of view. But at the same time I must confess that I had not even the remotest idea of wooing the government or agency in what I did. This notion never entered my head and came as a surprise to me when the above mentioned letter was received here. The only idea that was present in my mind as well as the minds of my revered brother, Swamis here was the thought of poor people on the brink of starvation in areas under famine conditions. This is a fact. And actually this proposal when put before all the assembled devotees here was hailed by every one as a very proper and timely measure and the spirit in which it was done to be laudable. I have even received another letter conveying “Grateful thanks for this thoughtful gesture.” I thought I might share with you these views and opinions and just give you an idea how a self-same matter is viewed differently by different people. I might just as well draw the attention of all readers including the kind writer of the aforesaid letter to the significant fact that the alternative purpose for which a sum of money was diverted in lieu of Bhandara here was practically and identical purpose as, the Bhandara, namely feeding of poor people. Let me end this matter now. This year the Badrinath Yatra has been unprecedented with many hundreds of thousand of devout pilgrims crowding to visit the holy Himalayan Shrines of Badrinath and Kedarnath. There has been a continuous stream of pilgrims pouring into Rishikesh since April. Road has been taken right up to Badrinath township and so the bus transport brings the pilgrims very near to the temple of Lord. While this is extremely convenient to all people and saves a lot of time (today you can leave Rishikesh for Badrinath and be back at Rishikesh on the fifth day after having Darshan) yet this has taken away a good deal of the spiritual elation and inspiration that the Yatri used to get when he trekked 20 miles from Joshimutt to Badrinath. But change is the nature of things. One comes to accept it ultimately. There is a lull in the Yatra just at present due to the onset of rains last month. Torrential rains in the hills flood the Ganges and the waters rose so much last week that Shri Gurudev’s Kutir which is sacred and a holy monument to countless disciples, had to be totally vacated of all things. The waves splashed water on to the verandah. However, this was a mild thing compared to the flood of September, 1963 when precisely 60 days after His passing, the holy Ganges entered the Kutir and flooded it with her waters to a height of nearly four feet. You are having this month two Annual holidays, the Kalki Jayanti on the 21st and Sri Tulsidas Jayanti on the 22nd. Kalki Jayanti is actually the anticipation of a future advent. It makes
68
ADVICES ON SPIRITUAL LIVING
the date foretold in the scripture, of the birth of the tenth and final incarnation of Lord Narayana. Kalki is the irresistible Divine power manifested to annihilate the forces of darkness that have gathered volume in the Iron age. It is an Avatar of hope for all humanity weighed down and crushed under the tyranny of evil and godless wickedness. Dharma prepares man to merit the protection of this power Divine. The sublime theme of the Sri Rama-avatara brings out in significant symbology this aforementioned process of the initial triumph of dark-Wickedness over chaste-Virtue and the ultimate vanquishing of the former by the Divine Power for the vindication of goodness and its release from the cruel thraldom under demoniacal evil. The great saint poet Sri Tulsidas has brought this truth home to millions through his Immortal, Exquisite poetic rendering the Ramacharitamanasa. May the whole world work for the advent of victorious Divinity that may end the rule of Adharma and restore the kingdom of righteousness upon this world of God. When this letter reaches you there would be approximately 30 days for the auspicious Birthday Anniversary of Sri Gurudev. This year the sacred Krishna Janmashtami falls on the 7th Sep; which means 8th September is Navami Tithi. A significant coincident indeed. For the Navami Tithi is the day of Gurudev’s Mahasamadhi in the month of Shravan. So, this year the exit as well as the advent dates are both Navami. It is, as though to indicate to us that He is always present. If he left us on Navami, he has come amongst us on Navami too. True indeed is this, for though he left us in the body yet the same moment he was born in spirit within our hearts as the Immortal ideal to live for and to strive for and realise in our very life. Such a conjunction this significant occurred once twenty years ago in 1946 when 7th of September was the sacred and joyous Sri Krishna Janmashtami day. I would like to suggest to all devotees of Lord Krishna who worship Him as their Ishta Devata that they may commence a special 30 days Anushthana from 7th August to 7th Sep. of the sacred Dwadashkshari Mantra “OM NAMO BHAGAVATE VASUDEVAYA”. Repeat it every day at least a minimum of 12 Malas, which means 108x12 1296 times. You may repeat more Malas like 24 or 36 daily. This would constitute a befitting, solemn preparation for observing that great annual day sacred worship. And how very significant indeed does beloved Gurudev’s Birthday seem in the context of the forth-coming two holy Anniversaries of Kalki Jayanti and Tulsidas Jayanti! For Gurudev’s advent and his noble life of sublime spiritual work did verily constitute this process of a determined attempt to oppose the forces of Godlessness, Adharma and wanton wickedness of the present day world and establishing the Divine Life in human society. Truly we may say that Gurudev Sivananda has been one of the foremost amongst messengers of the Divine in the 20th century, who proclaimed the Gospel of goodness and brought in a better balance between good and evil in this age that seems to be turning away from the Light. As long as the memory of such great ones is cherished actively by modern mankind there is still great hope of emerging from darkness into the light of goodness and Godliness in the not too distant future. May the hand of God help us and the Light of God guide us in working towards such a day. OM NAMO BHAGAVATB VASUDEVAYA. OM NAMO BHAGAVATE SIVANANDAYA. Beloved seekers, may God bless you and all. With regards, Prem and Om, August, 1966 Yours in Sri Gurudev —Swami Chidananda
69
SRIMAD BHAGWAD GITA AND GOSPEL OF DIVINE LIFE ARE IDENTICAL
Sivanandashram Letter No. XXXII
SRIMAD BHAGWAD GITA AND GOSPEL OF DIVINE LIFE ARE IDENTICAL
Immortal Atma Swarupa! Blessed Seekers of Truth! Om Namo Narayana! Loving Pranams. Glory to Lord Krishna and to Sri Gurudev Sivananda, the visible expressions of the Absolute Divine Reality. Salutations to you in their holy names. Om Namo Bhagavate Vasudevaya, Om Sri Sivanandaya Namah. Upon you all, travellers upon the shining highway of Divine Life, pilgrims to the radiant Shrine of Eternal Bliss, may their Divine Love and benedictions ever shower in abundance. Be ever vigilant and ever be pressing forward towards the Grand Goal of your life. Be active in Vichara (right enquiry) and alert in Viveka (discrimination). O traveller, do not tarry on the way. O bold Sadhaka, stick to the Great Ideal at all cost and struggle bravely towards it. Every day, every minute, earnestly strive to live the perfect pure life. Divine you are. So Divinely live while life lasts. Every thing is here evanescent. This life of yours is a two-days fair, the meeting of souls in a market place. Soon there will be end of it. What are you doing about it? All things shall perish and pass away. This is a non-eternal play of sound and colour, of names and forms. O man, seek the Eternal. Therein alone is true happiness, true peace and Bliss Divine. Time flies away. You were an infant, then grew up into youth, attained your prime and moved towards middle age. When chill winter of old age descends upon you what will you gather and take upon the journey? How much falsehood, unkindness, egoism and anger how much rudeness and dishonesty and how much impurity and selfishness has accumulated upon your head. Will these serve to make your life sweet or take you towards that sublime attainment for which God has given you this precious body and mind? Beloved friend, human life is too precious to be spent away in heedlessness and to be wasted in unwise sense pleasures that only bring suffering and misery in the end. Forgetting God and turning away from Him, do you ever think that you will succeed in attaining happiness here. A great mistake, a great folly. There is no greater blunder. This is miserable blindness. Neglect of spiritual Sadhana is the most dangerous calamity that can befall humanity. All things may be postponed but to attain happiness without adoring God, this is absolutely impossible. This human life is too precious to be lost in delusion and ignorance. Wake up, O wake up. This world is passing through times of great uncertainty. The caprice of nature visits man with innumerable sudden and unexpected catastrophes. Floods and famines volcanoes and earthquakes, cyclones and hurricanes, wars and pestilences and accidents galore are taking their terrible tolls before your very eyes even as you watch and see your near and dear ones and cherished objects go the way of destructions. From all sides come reports of pain and death. Day by day, year after year, countless lives thus come to an end abruptly. What have you learnt? Do you alone feel secure in the midst of this inevitable process? Have you got in your shirt pocket the sealed guarantee that you alone live to be a hundred summers? Do not deceive yourself. Be wise. Live nobly. Practice virtue.
70
ADVICES ON SPIRITUAL LIVING
Be thou a Yogi, one who tries to attain God. Even such is the clear call of Lord Krishna, “Tasmaat Yogi Bhavaarjuna” that He gave to us through the Gita. Do Sadhana. Lead a Divine Life. Infinite blessedness will be yours right here and now. This year the sacred Sri Krishna Jayanti (Janmashtami) closely precedes Sri Sivananda Jayanti. The auspicious Birth Anniversary of Lord Krishna falls on the 7th Sep. and the joyous Birthday of Gurudev is on 8th Sep. Thus we celebrate twin Jayanties this month. With sincerity, earnestness, keen interest and enthusiasm practice the Gospel of the Gita and the Gospel of Divine Life. They are identical. These both mean one and the same thing. Sri Gurudev Sivanandaji proclaimed anew the message of the Gita in the modern world. Divine Life is a practical exposition of the way of the Gita. What Lord Krishna did in Dwapara-Yuga, even that Sri Gurudev did in this century. The one delivered the message in Kurukshetra and the other did it in Rishikesh. Only Lord Krishna addressed it to one individual, whereas Gurudev addressed all mankind. During Lord Krishna’s lifetime only three individuals got to know of His wonderful Divine Message but through Gurudev the Divine Wisdom and spiritual message came to be the possession of countless thousands of people during His own life time. Verily, this is a marvel and a miracle that demonstrated the benign compassion of the Lord to awaken struggling humanity and draw souls towards Himself with a view to confer upon them Divine Blessedness. Thus the Lord works through His saints, sages and Godmen. They are His messengers. To follow them is to soon cross beyond all sorrow and suffering and reach the realm of eternal sunshine, perennial joy and supreme peace. With the approach of these Jayanties my thoughts dwells again and again upon the Divine words and wisdom-teachings of Bhagavan Sri Krishna and Sadgurudev. I ponder the central message contained in their teachings “Having attained to this impermanent and joyless world, do thou worship Me”. “Those who seek to approach Me alone cross over the formidable ocean of Maya which is indeed difficult to over come”. “My Supreme Abode is that having reached which there is no return (into this mortal world)”. And Gurudev’s words declare emphatically that God-realisation is the goal of life. You should attain this through selfless service, devotion, meditation and wisdom. Virtue, worship and Vichara are the base to illumination. To unfold your Divine consciousness in and through the normal life in the world is Gurudev’s special message for this age. It is by the spiritualism of your normal daily activity through an open attitude of worshipfulness and dedication of all actions to the Lord that you achieve Yoga in the midst of apparent Vyavahara. Detach your mind from the perishable objects of this world and attach it to the lotus feet of the Lord. Purify, concentrate, meditate, realise. So says Sivananda. Let the inspiration of these Divine teachings take fresh birth within your aspiring heart upon this holy Krishna Janmashtami and Sivananda Jayanti. This month marks the 80th Birthday (79th Anniversary) of our holy Sadguru. May His spirit of renunciation, service, devotion, aspiration and dedication fill you and make your life and speed up your progress towards Light, Joy and Blessedness. We will be pleased to know that Andhra Pradesh Divine Life Society has already announced their provincial Conference this year. The forthcoming Conference is being convened by Sri T. Venugopala Reddy Garu (President of the Hyderabad Maradipalli D. L. Branch) with the help of Sri Vijayaranagam Garu and others. Sri Venugopal Maharaj is doing this in his capacity as the Organiser of the newly opened D. L. Branch of Kothapalam which is his home place. This is ten miles from Gudur station on the Grand Trunk line. Dates of the Conference are closing days of
71
SRIMAD BHAGWAD GITA AND GOSPEL OF DIVINE LIFE ARE IDENTICAL
December. A Souvenir is going to be issued on the occasion of the conference. All D. L. Branches as well as members and devotees of Sri Gurudev throughout Andhra Pradesh are requested to joyously give their fullest co-operation to the Conference. Orissa state has decided to repeat its Conference this year. This will be its second provincial Conference and is likely to take place in every way to S. C. Debo, Prof. Durlab Chakaravarthy and others who will organise it. This year our enthusiastic and progressive group of Rajkot D.L.S. Centre in Gujarat have decided to convene the all Gujarat Divine Life Conference in the month of November under inspiring and memorable occasion. They have taken a promise from me to attend this blessed Conference. You will perhaps remember that Sri Sivanaada Adhvaryooji has Convened the All-India Divine Life Conference for the year 1967 at Patan in North Gujarat. News from Delhi D.L. Society brings the welcome information that the construction work of the Sivananda Satsang Bhavan has at last been taken up by Sri Swami Sivananda Cultural Association which coordinated the activities of all the Delhi Divine Life Centres. We wish speedy progress to this construction work and early completion of it. I look forward to the day when I shall have the joy of taking part in the inaugural Satsang held under the roof of the completed Satsang Hall. May the willing co-ordination, ready generosity and enthusiastic exertion of one and all of the members of the S.S.C. Association bring about this desired consummation. Thus Gurudev’s work gradually grow and moves onwards for the benefit of many and for the glory of Sanatana Dharma as well as Universal Spirituality. All Religious are one. All mankind one. All faiths lead to the common goal of humanity which is one. May you all live to proclaim this oneness through love and through service. God bless you. OM NAMO BHAGAVATE VASUDEVAYA, OM NAMO BHAGAVATE SIVANANDYA. With regards, Prem and Om, Yours in Sri Gurudev, September, 1966 Swami Chidananda
Sivanandashram Letter No. XXXIII Golden Jubilee Message.
72
ADVICES ON SPIRITUAL LIVING.
73
FORGET NOT THE GOAL LEAD THE DIVINE LIFE, Sept. 24, 1966 —Swami Chidananda
Sivanandashram Letter No. XXXIV
TAMASO. Through this letter I wish you a bright and happy DIWALI, and send to you, and all, my greetings for this season of illumination. To all members and friends of Gujarat, Saurashtra, I send my best and good wishes for a very happy New Year. May this New Year be full of auspiciousness, blessedness, prosperity, success and happiness. Together with outer lamps lit by human hands, let there also shine forth the bright Lamp of Divine Life, lit by the hand of God, within the mansion of your heart. Let the supreme joy of virtue, goodness and service sweeten your days and grant you Divine happiness. With the approach of Diwali, my thoughts are drawn to our ancient prayer “Tamaso ma Jyotir Gamaya” which expresses the central concept of our culture and constitutes the very essence
74
ADVICES ON SPIRITUAL LIVING
of our sublime idealism, namely a reaching out towards Light. Verily, how great indeed is the need to reinstate this concept into its lawful place in our country and its life today! The Divine essence is symbolized by light. Its negation or rejection is darkness. Dharma or the rule of righteousness is an emanation of the Divine expressed upon the human place. Dharma is the God-Light in man’s life. When this light is denied expression, then the darkness of falsehood, selfishness, greed and hatred come to prevail. Pride, violence and hatred hold sway over affairs of men. The beauty of goodness gives place to the ugliness of vicious wickedness. From this darkness man must seek relief and realise into the Light of pure living, for sorrow and suffering, misery and degradation grow in such spiritual darkness. The darkness of Amavasya at Diwali time is insignificant before the great darkness of Godless Hedonism that is gathering around the present generation of mankind, enveloping life in its dire folds. The Light of Dharma alone can banish it. This Light has to be invoked from within you. Dharma is the radiance emanating from the soul of man, who is essentially Divine. Every citizen of Bharata-Desa is potentially the custodian of Dharma, and as such responsible for its active evolution and dynamic manifestation. Will you fail in this duty? Or will you awake from this slumber and Light up the lamp of Dharma in your life, right now this Diwali day? As I write these lines I am suddenly aware that the very name of this journal carries particularly appropriate significance for this occasion! This the ‘Wisdom Light’ that enters into the midst of darkness to banish it with its luminous message of spiritual life, Dharma and ethical idealism. The resplendent light of Gurudev’s noble spiritual teachings has taken the darkness out of the life of many a soul all over the world during these past two score years. The flaming torch of Yoga, and Vedanta, of Niti and Sadachara, he has handed down to you, that you too may be a bringer of light wherever you go, by your Divine Life of Seva, Bhakti, Dhyana and Jnana. Beloved seeker, light up the bright Lamp of selflessness and service, of devotion and worship, of discipline and meditation and luminous God-awareness. May this Light of Divine Life bring relief to humanity suffering the bitterness and pain of its own thoughtlessness and Godlessness. May God speed you across this vale of this gloom and speed you on towards that Immortal Light. This is Supreme Bliss and Infinite Peace. A number of significant days of annual national observance occur within this current month, and you should give some thought to each one of them without fail. I therefore touch very briefly upon them here for your information and benefit. Advent of great men and of great days serve to bring about in us a renewed awareness of our duties and the ideals upon which our concept of duty in its manifold aspects is based. Besides Diwali, the festival of Lamps, you have the auspicious Lakshmi PUJA (12thNov), the Govardhan and Go-puja (13th), The Skand Shashthi Puja (13th to 18th), the Yajnavalkya Jayanti (22nd), and Hari-Prabodhini Ekadashi (23rd) and Utthana Dvadshi (24th) as also Tulsi Puja (24th) and last, but not least Sri Guru Nanak Jayanti (27th). These great sacred days of deep significance sanctify this month and render it a period of reflection and meditation. Time and space permit of only brief mention of their central message to us today. And here I state them for you. Lakshmi Puja; “Money is the root of all evil” thus say the prophets and the sacred scriptures. LAKSHMI is the GODDESS of Wealth. Why then worship this Goddess of the “root of all evil”?
75
TAMASO MA JYOTIR GAMAYA
Money is evil because man is wicked. Money turns good when man becomes good himself. The quality assumed by money mechanics is acquired from the nature of the use thereof. Man ennobles or corrupts money equally as money is capable of corrupting man if evil is inherent in him. Money is power potential par excellent. Use or abuse of this power decides whether it elevates or degrades society. Election time demonstrates its vile abuse. Flood and famine relief activities show its noble higher use. To present to us the right attitude towards money its sacred status is vividly brought before our gaze by revealing to us the deity presiding over this power, namely Lakshmi Devi. Annual Lakshmi Puja is the solemn occasion to relive this Bhav and to pledge yourself to handle money with reverence and humility, knowing that it is to be treated as a manifestation of Divine power given to you to elevate and ennoble yourself through its right use. It is to be used as a means of protecting Dharma and an aid of attaining Moksha. This is the lofty role of “Artha” If this is forgotten then it verily becomes “Anartha”. Viewed thus money should evoke not greed but an attitude of hallowed worshipfulness in the heart of the one who handles it with high purpose. It is verily Vishnu-Shakti. GO-POOJA: Even today 80% of Bharatavarsha is rural in India and the nation is mainly agricultural. In spite of advent of modernism and technology, cattle still constitute the main wealth of the farmer and his family. Second to a piece of land ‘Go-dhana’ is the Indian’s Moola-dhana. To safeguard the welfare of the country’s cattle and to improve their condition is therefore a vital national service of utmost importance and very great significance. The Go-Puja day, far from being just a day of religious worship amongst pious people, should be elevated to its rightful status as a national festival of Pan-Indian significance, even as the Van-Mahotsava. Go-mata is not just a mere sentiment. It is a socio-economical fact further sanctified by a spiritual aspect. Ponder this angle of approach to this seemingly simple and even superstitious worship. SKANDA-SHASHTHI: Skanda also known by the names Karthikeya and Subrahmanya is mentioned in the scripture as the brother of Lord Ganesha. He is the embodiment of Divine power triumphantly subduing and overcoming demonical forces. The world today is seen to be in the grip of such forces on a wide-spread scale. Human actions have assumed a dire nature in numerous countries of the world. India being no exception. Hatred, hostility, belligerence, falsehood, treachery, cunningness, subversion, destruction, violence these are indulged in with relish and avidity. Wickedness with deliberate intent is fast becoming a normal characteristic of countless men today. To invoke Divine power is evidently only the last resort in seeking to deal with this state of affairs. This traditional six-day annual worship of Lord Skanda constitutes such an appeal to and propitiation of the darkness destroying Divine power. YAJNAVALKYA JAYANTI: Bharatvarsha is one of the unique nations in whose culture the fundamental value is the spiritual reality and the ethical ideal that leads to the realisation of the former. The widespread ills and distress of our nation is directly the result of our having rejected this Supreme eternal value and substituted it by vain shibboleths and slogans of an empty age. Yajnavalkya, the towering man of Divine wisdom who strides across the ancient Upanishadic scene asserts with his thunderbolt authority the unassailable supremacy of these eternal values. Come, read the immortal dialogue between Yajnavalkya and Maitreyi, wherein this great sage imparts his
76
ADVICES ON SPIRITUAL LIVING
wondrous teachings to his aspiring wife, who seeks to know the highest value on earth. This day should inspire you to seek more of this wisdom personified in Maharshi Yajnavalkya. PRABODHINI EKADASI, UTTHANA DWADASI AND TULSI POOJA When the Chaturmasya period ends, its conclusion is announced by Prabodhini Ekadasi, which embodies at once a spiritual truth, as well as a message. When the Divine within man slumbers then his life becomes a tale of endless sorrow and suffering. To awaken the Divine within is to put an end to all sorrow and suffering. Prabodhini Ekadasi indicates such awakening. Ekadasi is the day of fast, penance and prayer. This conveys the very significant spiritual law that the awakening of the higher self can only be brought about when the lower self is denied and mortified through the wide austerity. Denying sensual food to the gross appetite in man is the condition prerequisite to inner spiritual awakening which alone leads to the true attainment. Once awakened this higher consciousness must be given dynamic manifestation in your life. This is the message of Utthana Dwadashi. In every Indian home this great awakening and this setting into dynamic motion of the awakened spiritual force has to be brought about in our nation from a spiritual regression and if our culture is to be converted into a living a force that would make Bharatavarsha move forward into a glorious tomorrow. This essential movement towards a lofty destiny has to be brought about by the Matri-Shakti of India’s women. In it their lies the key to a resurgent India and their power is the sublime, all-inspiring Shakti of Pativrata-dharma. Tulsi is a Mahapativrata in your sacred tradition. The nation invokes this ideal and we affirm with faith in the Pativrata-Dharma by this worship of Mahapativrata Tulasi. GURU NANAK JAYANTI Virtue is the very essence of spiritual power. God is the source of all virtue. To be linked with him is to radiate virtue. The Divine Name and His constant remembrance is the means of thus remaining linked with Divine. Such unbroken communion with God is the very essence of life and the secret of all success and fulfilment in life. Thus taught the great Guru Nanakdev, whose Jayanti will be observed upon the full moon day at the end of this month. Glory to Guru Nanak and his immortal teachings. The true welfare of India lies in honouring such saints and following their teachings. The Summer departs and we see the shorter day and morning winds rendered chill by the snow-falls upon the heights of the holy Badrinath, Kedarnath and Gangotri. Sacred Mother Ganges who nearly entered Gurudev’s holy Kutir on her banks has now receded, and the Kutir is once again as it was during His life-time. The Sadhaks and Sannyasins of Sivanandashram have to come wrapped up in their shawl or chaddar for the early dawn prayer and meditation meeting at 4.30 am. The evenings too are gradually becoming quite cool, bringing a pre-indication of the approaching cold season. While for the Ashrama this is a prelude to comparatively quieter period with lesser bustle of Yatris and visitors until next April, yet for this servant this is the other way. Because this coming Winter starts a period of strenuous touring in different parts of India where Divine Life Conferences are organised. You will be glad to know that Rajkot Divine Life enthusiasts have decided to make their proposed Conference the All-India Divine Life Conference for 1967, instead of the Gujarat State Divine Life Conference as originally announced. They have my hearty congratulations and my best good wishes for fullest success. All those interested are requested to
77
TAMASO MA JYOTIR GAMAYA
contact Sri Pranlal B. Mehra, Divine Life Society, Foldage Industries premises, Rajkot, Saurashtra; or Dr. Sivananda Adhwaryoo, Virnagar (Via Atkot), Dt. Rajkot, Saurashtra. Then, the Orissa Divine Life Central Committee has now announced the dates of their two conferences for the next year, D.L.S., Conference, at Puri to be on 21st and 22nd Jan. and D.L.S. Conference at Kutak 24th and 25th Jan. 67. Those who wish to attend may contact Shri. S.C. Debo, Ramachandra Bhavan, Khallikote, Distt. Ganjam (Orissa). The tenth Andhra Pradesh Conference stands confirmed for Dec. 31st, 1st and 2nd Jan. 67 at Nellorepalle, Kothapalam, about 10 miles from Gudur railway station Madras-Bezwada line. You may contact Sri T. Venugopala Reddy, D.L.S. Opp. St. Jones Sardar Patel Road, Maradipalli, Secunderabad A.P. By the way I must not forget to tell you that the All-India D.L.C. is to take place in the first week of Feb. 67 the dates of which are 5th, 6th, 7th and 8th. The conference will conclude of 8th Feb. Before departing for the South A.P. & Orissa programmes I shall be, when this issue reaches your hand, with Yogi Purush Sri Karuna Maharaj and Yoga teacher Swami Sivananda, and shall also be required to tour the Punjab D.L.S. Centre in the beginning of Dec. The A P. tour will be for about three weeks and the Orissa tour ten day. It is thus that Sri Gurudev observes a higher kind of Diwali by awakening the bright light of virtue, goodness, spiritual living and love of God in the darkness of Kaliyuga. May His Light shine forever and illumine the path of life to lead humanity to the great goal of God-realisation and human perfection. May God bless you all. A bright and happy Diwali to you all. With regards Prem and Om, At the feet of Gurudev, —Swami Chidananda
1st November, 1966
Sivanandashram Letter No. XXXV
THE GITA AND THE NEW TESTAMENT
Immortal Atma Swarupa. Blessed seeker after Truth! Loving Namaskars. Greetings and goodwishes in the holy names of Lord Jesus and of Lord Krishna Whom we remember with deepest adorations and worshipful love during this closing month of this present year. Two memorable dates associated with these two world teachers occur closely together this year. The inspiring Anniversary of blessed Lord Krishna’s Divine discourse (Bhagavad Gita) given to the blessed birth of Jesus Christ happen this year on 23rd Dec. and 24th Dec. The main point of my letter to you here is to pray to you all to open your hearts to the Divine Messages of Krishna and Christ and thus help to restore Love, Peace and Joy in today’s world. Beloved friends, Jesus seeks today entry into your hearts. Even so thus Lord Krishna, the call of Whose seeks to reach your hearts and awaken in it a longing within you for the life Divine, a life pure with Truth, Love, Selflessness and Brotherhood. Hearken to Their call O citizens of the world. Receive the Gita and the New Testament at one and the same. They differ not in the essences. For they come from but one source only. The Eternal Divine speaks to Man through the words of Jesus Christ and Sri Krishna. Blessed are those in this modern world of greed, falsehood, who will follow the simple yet sublime teachings of these Divine Teachers of humanity. The hope of the world, the
78
ADVICES ON SPIRITUAL LIVING
welfare of man, the guarantee of survival and the key to happiness lie in following the Wisdom teachings and the way of life bestowed to you through the Gita and the New Testament. Therein is presented the solutions to the problems that confront mankind in this conflict-filled world of this atomic century. Proclaim and broadcast this Krishna-Christ message of Love, Compassion and Service. Propagate far and wide and to every corner of the earth, these true and pure teachings of Jesus and Janardan, unfettered by narrow doctrinaire and dogma, bigotry or fanaticism that plague vested religion. Practice it at home. Personify it in yourself. Live it in your daily life. Help to establish goodwill amongst mankind, peace on earth by the resolute rejection of the selfishness, anger and greed which are gateways to perdition. Through friendliness, kindness, gentleness and genuine humility (Maitri, Karuna, Mardava and Nirahankara) help to make the Kingdom of Heaven prevail upon earth. Let this be your main aim, ambition and self-chosen task in the coming New Year that now approaches. May the twin Lights of the world illuminate your heart with Divine Wisdom and Love. After midnight vigil of Christmas Eve, this servant of Gurudev will have to leave for Andhra Pradesh to attend its Tenth Annual D.L. Conference. This time, I am travelling by train specially to make a halt at Bhopal, en route at the request of Sri Girdhar B. Chandwaney of the Divine Life Society of Bhopal. Therefore, the very first programme of Satsang discourses, etc., will be at the Bhopal D.L.S. this year’s tour. The dates are Dec. 26th and 27th. Our party will arrive on 26th morning and depart on 28th morning for Gudur and thence to Kottapalam which we reach on 29th Dec. Devotees in and about Bhopal area may contact Sri Girdhar B. Chandwaney, Secretary, Divine Life Society Branch, near Safia Abi Masjid, Noor Mahal Road, Bhopal (M.P.). Now, I have to make a special request. The Ashram needs a qualified Medical Practitioner for the hospital here at the D.L.S. Headquarters. The services of a doctor are required specially for the General Hospital but also for the Eye Hospital as revered Mataji Swami Hridayananda finds the pressure of working single handed telling upon her health and likes to have some relief through the help of a suitable doctor who would also be able to look after the part of the work now shouldered by her alone. As I had promised to take an early step in this matter I include this information in this letter. If any of you can help us to meet this need for a qualified doctor for our General Hospital mainly but with knowledge of eye-work also, I shall be grateful. I would prefer a comparatively young and active person but with a spirit of service if not actively spiritually-minded. Reasonable pay and living arrangement would be provided. A bachelor or a widower is preferred for the post. If you have any suggestion please write to us and address the letter to Sri Swami Krishnanandaji Maharaj, General Secretary, D.L.S., P.O. Sivanandanagar, Ditt. Tehri Garhwal, U.P. Write on the envelope ‘personal’. To all our friends in other countries I wish a MOST HAPPY CHRISTMAS and a wonderful NEW YEAR. May god bless you all. May the beauty of Christ-Love and radiance of Krishna-Light enrich and illuminate your life. May your days be filled with auspiciousness and blessedness. May you abide in Joy, Bliss and Immortality. Om Jesus! Jai Sri Krishna! With regards, Prem and Om, Yours in Sri Gurudev —Swami Chidananda
1st December, 1966.
79
MY MESSAGE OF TRUTH FOR THE NEW YEAR
Sivanandashram Letter No. XXXVI
MY MESSAGE OF TRUTH FOR THE NEW YEAR
Immortal Atma-Swarupa, Blessed seeker After Truth! Om Namo Narayanaya. Loving Namaskars. A bright joyous auspicious New Year to you. I salute you all in the holy name of Gurudev and wish you prosperity, happiness and all blessedness in His Name during this new year and during many more years in the future. God bless you. The duty and function of all things in this universe are governed by the law of Rita and Satya. This implies Truth or in other words being true to one’s essential real nature by adhering to it and expressing it. One who does it is fulfilling his duty and thus sustaining Dharma. This is what upholds the universe. Such a line of conduct maintains stability in human society, conduces to normalcy of events and occurrences and leads to commonwealth and welfare. Truth is the basis of human welfare. Everything good and beneficial rests upon truth. Gross negation of truth ends in chaos. Hence the significant declaration: God is Truth. To be true to one’s own essential nature is the highest Dharma. This is the Godly path. This is Divine Life. This leads to happiness, security and supreme welfare. The duty and function of rice is to give heat, light and to burn. The duty and function of air is to blow and waft odour. The duty and function of water is to flow and cause sweetness. The duty and function of earth is to be steady and to impart firmness to anything that takes its support. The duty and function of ether is to pervade and offer a field for the manifestation of sound. Akasa is a medium of Sabda. The duty and function of each element is thus the faithful expression of its inherent quality and nature. This is irreversible. If they were not to be true to themselves and go contrary to this, the result will be utter confusion and cessation of the orderly progress of things. Similar too is the case with man. The duty and function of man is to be thoughtful and reasonable and to manifest his inner essential nature which is Divine and therefore of the nature of goodness peace, auspiciousness and beauty. If he makes his life and conduct a process of such self-expression, his very being becomes a blessing to society as a whole. But if his life and conduct contradict this living Truth within him, then his very being falsifies his essential nature and becomes a source of evil and pain in this very world. His life becomes a living lie. The law of truth is now contradicted. The result is pain and destruction. Truth saves. Falsehood poisons the very root of human progress and world-weal. The great sin of this age is crucification of Truth. The world malady of today is a cult of falsehood. Man has forgotten to be true. Man is taught false hood, practises falsehood and prides himself in falsehood. Thus he forfeits the grace of God. For God is Truth. You must live to express your higher nature. This will be possible only with the different aspects of your being fulfilling their respective functions dutifully. The body is to work obediently to carry out the obligatory duties. It is not to function as manifold avenues for imbibing sensual
80
ADVICES ON SPIRITUAL LIVING
pleasures. The mind should function for reflective thought and not for producing unbridled desire. The heart is to act as a source of sublime sentiments and noble emotions mitigating and sublimating the primitive instinctive urges of your gross being. The heart is not meant to be seat of hatred and passion. The function of the intellect is to regulate through reason the upsurge of emotion in your heart. Intellect should not be the source of pride, superiority and bigotry. If these faculties function upon truth, then you have an active, thoughtful, compassionate and stable individual. Divinity manifests itself from within in such a life. His conduct shines with the light of Truth. In such a life you are true to the higher Self, you are true to your culture, and you are true to your Motherland. You are then a true Bharatiya. A Nation that is true to its central culture survives, flourishes. Great is the importance of truth in our national life as much as it is in your individual life. In this New Year may we enter into an ever-growing realisation of this important fact. Thus is my message of Truth for this New Year. Beloved readers; take up this message for your life: May this message be the Mula-Mantra of your personal life. May truth be the Maha-Mantra of your social life. May Satya be your Aradhana Devata. May Truth be the deity that presides over your professional activities. He who injures Truth verily destroys himself. He who upholds truth in all the spheres of his life secures peace, happiness, honour and Divine Grace. He is the real helper of humanity and servant of the world. He by his life and conduct makes mankind retrace its course from darkness to light, from strife to peace and from hatred to goodwill and love. O Ye Citizens of Bharatvarsha, raise the banner of Truth as your emblem and aim. Silence all slogans. Chant Truth as the National Mantra. Let the silence of purity hush your heart and keep out the den of false slogans and empty words. Truth is the way by which mankind must regain mutual trust, harmony and freedom from fear. Truth will save India and the world for an honourable future. Live Truth. Let Truth see the light of the day. May this New Year mark for us all a glorious entry into Truth. God be with you. By the time you read this, this servant will be in South India on a spiritual tour. The same message, the call to Truth will be given at all places to be visited during this Andhra Pradesh, Orissa, Gujarat tour. Sri Satgurudev Swami Sivanandaji was the embodiment of Satya. Thus will this servant strive to bring the holy Master’s spiritual word to the people who seek light. May Truth sustain us in our march towards the eternal reality that is Brahman, the Ekam Sat! Om Tat Sat! Om Shanti! Jai Gurudev Sivananda! With regards, Prem and Om, 1st January, 1967 —Swami Chidananda
81
IN THE BLESSED COMPANY OF HOLY SAINTS
Sivanandashram Letter No. XXXVII
IN THE BLESSED COMPANY OF HOLY SAINTS
Immortal Atma-Swarupa, Blessed Seeker After Truth! Om Namo Narayanaya! Loving Namaskars. Salutations and greeting to you in the holy name of Sri Gurudev Sivananda. May God bless you! This letter is being written to you from Utkala- Pradesha (Orissa), the territory sanctified by blessed Lord Jagannatha, who presides over this part of Bharatavarsha from the sacred city of Puri. May the Divine Grace of Sri Jagannath Bhagawan ever be upon you all. This time I shall take you along with me quickly over a tour of A.P. and Orissa, where as you know this servant of Gurudev has travelled to attend two Divine Life Conferences, namely, the 10th Andhra Pradesh and the 2nd All-Orissa Divine Life Conference. Our party and myself left for Delhi on the morning of the 25th December, 1966 reaching there in the evening. We could not leave as usual by train the previous night because the 24th was the important annual day of holy Christmas observance and so I had to participate in the Ashram until midnight in this celebration of joy and adoration. It was a wonderful occasion. Upon reaching Delhi the next day I had the happy good fortune of meeting and paying my homage to His Holiness the Jagadguru Sankaracharya Swamiji Maharaj of Sringeri Peetha, the renowned Southern monastic seat established by the great Adi-Sankaracharya. His Holiness is most gracious, highly enlightened and benevolent monk combining within himself high erudition, renunciation and holiness with an unassuming simplicity, affability and charming manners, at once dignified as well as friendly. He was pleased to receive me with kindness, made enquiries about Gurudev’s Ashram and its activity and received with keen interest and frank appreciation a packet of Gurudev’s spiritual books that I offered to him. Outside, under a special pandal, a large gathering had assembled for a lecture meeting and eagerly awaiting His Holiness’ appearance. So, after talking to me for sometime, he rose up to go to the meeting inviting me to come along and participate. The holy Swamiji desired that I should also address the gathering briefly and as I had to catch the evening Grand Trunk Express he asked me to speak first listening appreciatingly and with affectionate approval to the words of this servant at Gurudev’s feet. I took leave of H.H. Sri Jagadguru immediately and proceeded to go to revered mother Sitabai’s place where supper had been arranged for the entire party. After an excellent supper, light and nutritious, we drove to the New Delhi station. I missed Sri S. Sundaram of Amexco this time as he was laid up with ‘flu’. He very kindly looks after most of my travel arrangements these days ever since God brought us together in 1959 when I was preparing to visit the United States and Canada on Gurudev’s Mission. At the Station a good number of friends, all Gurudev’s Delhi devotes, had turned up to see us off. The entire Dr. Munjal household was there as also Mr Sud, Mr. Massand, brother C. K. Harchandani, with his unfailing supply of Horlicks, mother Laxmiji, and a number of others. There
82
ADVICES ON SPIRITUAL LIVING
was Kirtan, Japa, Om Chanting etc., until the train moved off. We reached the historic city of Bhopal next morning. 26th and 27th, there were programmes of Satsang and lectures at Bhopal arranged by that city’s Divine Life Society Branch. Revered Mata Gurupremanandji with her devotees had come from her Ashram at Indore and participated in all the Satsangas. Sri G.B. Chandwani arranged programmes nicely and revered K.C. Reddyji Maharaj very graciously extended his hospitality to me with my party and looked after us with great kindness and love. He and his good wife are an ideal couple. Early morning on the 28th we journeyed to Kothapalam, the venue of the 10th Andhra Pradesh D.L. Conference. Reaching there on the 29th, myself with two other Sadhus, one the revered Avadhutendra Swami, a great Sankirtana Bhakta of Andhra Pradesh and the other the 80-year old Hatha Yogi Pujya Swami Atmanandaji, were all taken in procession in a vehicle decked with beautiful floral decoration in artistic design. There was great enthusiasm and chanting of God’s Name by the people. After a days rest on the 30th the Conference was inaugurated on Saturday on 31st before a vast assembly of several thousand people assembled in a very huge pandal specially erected for this Conference gathering. The three days of programme was veritable spiritual feast, thrilling, inspiring and elevating. This Conference, the efforts of Sri T. Venugopala Reddyji and his entire family was a unique event memorable for the fact that it was held in a small village more than 15 miles distance from the nearest railway station and yet the sessions were packed with vast crowds participating for hours on end. A beautiful Souvenir has been published by the Conference and a wonderful feature was the printing of ten thousand copies of a hundred-paged book of Gurudev’s teachings for free distribution for every one who attended the Conference. This was through the generous munificence of mother Anusuya Deviji of Maripada who donated a sum of Rs. 3000/towards this Jnana Yajna. The Yoga Museum and photographic exhibition in this Conference were very successful, interesting features. All praise to the dedicated and devoted efforts of Sri Venugopala Reddy, brother Srinivasa Reddy, their father Narasimha Reddy and their associates and volunteers. On the 3rd January, we had the pleasure of visiting the ideal educational Centre and Harijan’s Seva Institution of the well-known philanthropist and social worker Sri Gopalakrishna Reddy at Vakadu. We also went up and offered our worship to Lord Bhimeshwar Mahadev at the hill-top temple near Vidianagar, the college campus created by the same Gopalakrishna Reddy Gaur. The next day on 4th January, we journeyed to the famous holy Shrine of Tirupati and worshipped Lord Venkateshwara in his abode amidst the seven hills. The temple authorities had very kindly provided facilities for Darshan and worship in this wonderful shrine. On the day we arrived we did some spirited Sankirtan in the Kalyan Mandapam within the temple. The next day they had arranged for a talk to the students at the Venkateshwara University. It was a very well attended lecture that was listened to with rapt attention. A number of Gurudev’s books were presented to the College Library. On Friday 6th January, we journeyed down to Viyasashram, the well known hermitage of the famous Sage, the late Sri Malayal Swamiji Maharaj at Yerpedu, where I was extremely happy to meet once again Sri Swami Vimalnandji, the present head of the Ashram, the beloved disciple and successor of late Holiness. The Sadhus as well as all the students of the two
83
IN THE BLESSED COMPANY OF HOLY SAINTS
Vidyalayas very much enjoyed the movie films showing scene of our previous visit to the Ashram in the same month last year. I must say here that throughout this present tour in every place beginning from Bhopal at the very start, the movie film showing had been a huge success. It is some thing thrilling and wonderful for the people in these distant Southern parts to be able to have the colourful and breathtakingly beautiful views of the majestic Ganges, holy Rishikesh, the Himalayan mountains and the Sivanandashram. What is more, thousands who had not had the good fortune of Darshan of Sri Gurudev Swami Sivanandaji get the rare blessedness of gazing at his majestic form and getting a glimpse of his Ashram’s life as he went about attending to various tasks and special celebrations. Everywhere people were fascinated and asked for more. Next we drove to Gudur for an evening lecture and from there reached Manbolu for two days halt with a very well attended Satsang for the general public. On Sunday the 8th, we went over to Nelore for a public lecture there and a Satsang the next morning at the well known Annadana Samaja. Thence, we journeyed to the famous hill-top shrine of Lord Mallikarjuna Mahadev at Srisailam. Our party conducted two Satsangas here, one at the Suryasimhasana Matha and the other at the main temple before Lord Shiva’s sanctum. Here as elsewhere I was required to give my talk in the Telugu language. I was glad that grammarians or school examiners were not present, otherwise they might have been shocked at my language. But, nevertheless, my vocabulary seems to be quite sufficient for effectively conveying Gurudev’s message of Divine Life and Yoga Vedanta to the Telugu speaking people of Andhra Pradesh. 11th evening found us at Guntur after a drive of about 145 miles from Srisailam. We had to break for lunch enroute at Vinukoada where arrangements had been made at the local Dak Bungalow. This place is believed to be the spot associated with that episode in the Ramayana when Lord Rama first heard the news about Sita’s forced abduction by Ravana through the dying Jatayu. Hence, the significant name Vinukonda in Telugu (Vinu meaning to hear, and Konda meaning a hill), that is, the hill where Sri Rama first heard about Sita’s fate. The traditional Sanskrit name for this place is Sruta-Giri. Quite a crowded Satsang developed here very soon after our arrival at the Dak Bungalow at midday. Now for Guntur. One of the high-lights of my over night’s stay at this place is our visit to the famous Sri Rama Nama Kshetra in this city. This is indeed a very unique institution, nay, hallowed place of pilgrimage glorifying the Divine Name of Rama. Sri Gurudev Sivanandaji had a special place in his soft heart for this very holy institution which he admired greatly. Sri Sita Rama Nama Sankirtana Sangham was the parent institution, out of which this unique Sri Rama Nama kshetra developed as a devout memorial to the Rama Bhakta Sri Ragam Pichchiah Das by his two loving sons Sri Ragam Anjaneyulu and Sri Ragam Venkateshwaralu. Countless crores of Sri Rama Nama are being written and also chanted by devotees all over the country through the living inspiration of this unique Kshetra dedicated to the Divine Name. The present Director of this place expressed his great gratitude to Gurudev Sivanandaji for his continued encouragement to their sacred work through all the bygone years. The Guntur public meeting was well attended and message earnestly received. Leaving Guntur on the 12th, we arrived at the Rajahmundry in chill cloudy and drizzling weather after passing the long Godavari Anicut (Dam). It was a tedious drive. When we finally
84
ADVICES ON SPIRITUAL LIVING
arrived it was raining steadily. My health had a set back here due to constant travels. Until here all our travel was by car ever since our arrival at Kothapalam on 29th December. At Rajahmundry our host was the revered Sri Swami Karunyanandji Maharaj, founder of the Gautami Jivakarunya Sangham. It was wonderful to meet him because he happens to be an old associate of Gurudev during the latter’s early Rishikesh days. This Swamiji was with Gurudev from 1927 to 1933 when he left Rishikesh and came and founded this humanitarian institution in his home province. The Swamiji related to me many interesting events and experiences with Gurudev at Swargashram and Muni-ki-Reti. I wish I could tell more of that here but I am obliged to reserve it for some other occasion, due to lack of space. Sri Swami Karunyanandji is personification of selflessness in the spirit of service. We also visited the well know Ashram of Her Holiness Sadhu Mataji, one of the earliest disciple of H. H. Malayala Swamiji. She was one of the foremost Sannyasins of Andhra Pradesh. From Rajahmundry we drove on to Shanti Ashram near the Totapalli Hills for the Darshan of H.H. Sri Swami Omkarji Maharaj. Arriving after dark at night, we were received by the children of the orphanage who sang ‘Hare Rama Hare Rama Rama Rama Hare Hare,’ the Mahamantra in the tune of Gurudev. Swami Omkar received us very graciously and to be with him was an experience of Divine Peace and holy inspiration. He read out to us from his “Cosmic Flashes” and ‘In the Hours of Silence’! We heard his peace prayer repeated by his devoted disciple Sri Jnaneshwari Devi and it was most stirring experience. 14th was the day of perfect peace at Shanti Ashram which is the veritable abode of Shanti indeed. Revered Swami Omkarji graciously presented me and others with a number of his books. We went over the extensive estate covering two hundred acres of his Ashram and were very glad to see different departments like hotel, the school, the printing press, the shrine of prayer, Kailas Giri, the sites for Vedantins, lady Sadhaks etc. We also saw the new Rama Tirtha Institute of Peace taking shape in one part of the estate. During that evening gathering I met the venerable Swami Ramananda Tirtha, who is taking up the work of this new Institute of Peace. The Ashram was preparing for the Golden Jubilee Celebrations of Shanti Ashram as well as Sri Swamiji’s 72nd Birthday and the happy inauguration of the proposed Rama Tirtha Institute of Peace at the hands of Sri Jayaprakash Narayan on 21st January. The children of the orphanage gave us a preview enactment of the nice little drama they had got up, called the Golden Garland (Svarnamala), specially for the occasion of the Golden Jubilee. We all enjoyed. Sri Swamiji gave his beautiful message and so too did revered Swami Ramananda Tirtha. Early next morning, we departed reluctantly from Shanti Ashram after bidding farewell to Swamiji and others carrying his loving invitation to visit him again. We next drove to the sea side city of Visakhapattnam or Waltair about 90 miles from Shanti Ashram. Here too we were lodged at Shanti Ashram at sea side where Swami Omkar lived for many years and performed penance. I was put up in a cottage previously occupied by the late sister Sushila Devi of loving memory, who was the presiding angel of the Shanti Ashram in her earlier days and who had nobly dedicated herself to the Mission of Peace. One public meeting was the sole engagement in this city and Swami Karunyanandaji Maharaj who had provided his motor car from Rajahmundry onwards saw us off at the Railway Station the next morning on our way to Berhampur. I wish to mention two thing here. One was that from 4th January onwards Sri T. Venugopala Reddy of Kothapalam had put his car at our disposal for all our travels upto the 12th January when we left Guntur for Rajahmundry. This was very gracious of him and the second matter was the wonderful help given to us throughout these tours by
85
IN THE BLESSED COMPANY OF HOLY SAINTS
our beloved S. Vijayarangam Guru of Hyderabad, who had made the most thorough arrangements down to the minutest detail for this entire tour right up to our departure from Andhra Pradesh for Orissa on the 16th January. But for him this well conducted and systematic tour covering practically almost the whole of Andhra Pradesh would have been impossible. God bless him. Visakhapattnam was actually our last camp in A. P. But at the 11th hour we were made to visit two more places on our way out of Andhra Pradesh into Orissa for inaugurating two branches of the Divine Life Society, at Palasa and Sompeta. Therefore. I had to detrain at these two places in A.P. and inaugurated the D.L. Branches and thus arrived late at night at Berhampur where one batch of our party had reached in advance, directly from Waltair. After three day’s halt at Berhampur and some Satsang programmes including the inauguration of the Annual Cultural week at the local Khallikote College, I drove over to Cuttack, with my Orissa host Sri S.C. Debo, Retd. Principal of the Govt. Art College, visiting the Chatrapur and Rambha D.L. Branches on the way to attend the 2nd All-Orissa D.L. Conference. With regards, Prem and Om, February, 1967 Swami Chidananda
Sivanandashram Letter No. XXXVIII
VAST FIELD OF DIVINE LIFE ACTIVITIES
Immortal Atma-Swarupa! Blessed Seeker After Truth! Om Namo Narayanaya! Loving Namaskars. May the Divine Grace of the Lord of the Universe, the all Auspicious Great God, Mahadeva Siva, the blue-throated, wielder of the trident, be upon you all upon this eve of the holy Mahasivaratri. Let us for a while repeat together the most sacred Divine Name of Five-letters that is pleasing to the Lord. Om Namah Sivaya Om Namah Sivaya (five times) Glory be to the Lord of gods, the destroyer of the poison of spiritual Ignorance (Ajnana), the all-compassionate and the bestower of Supreme Liberation to those who take refuge at his feet. You are blessed indeed to have uttered His Divine Name with faith, reverence and love. The Cuttack session of the Second All Orissa D. L. Conference commenced with a procession of Gurudev’s holy Padukas accompanied with Sankirtan Party. After flag-hoisting at the avenue the session commenced with the Lord’s Name, followed by the opening of the exhibition of spiritual literature, photographs and Ayurvedic products. Then a beautiful portrait of Gurudev was
86
ADVICES ON SPIRITUAL LIVING
unveiled. Next Mr. D. Sahu, the Advocate-General, delivered his thought-provoking address welcoming us all. The chief guest was Swami Ramakrishnanandaji of Bhuvaneshwar who gave his Upadesh now. Next Sri Radhanath Rath, editor of “The Samaj”, spoke beautifully in Orria. The Proceedings came to a close after my talk and concluding Kirtan. The second session also was very well attended and marked by enthusiastic Sankirtan, Bhajan, prayer, exposition of Yogas, a discourse on Indian culture, a period of silent meditation and concluded with an excellent film show, wherein the assembled devotees had the Darshan of Gurudev, Ganga, Himalayas, etc. It was well organised and the sincere devotees of the Cuttack Branch had made all necessary arrangements with care and love. A very nice bilingual Souvenir has been published and some useful spiritual tracts were distributed free to the public. The two day’s programme at Puri was drawn upon the same pattern as that at Cuttack. There was also a brief programme at Bhuvaneshwar on the 23rd January on our way from Cuttack to Puri. Before leaving Puri however, I went to the famous Math established by Sri Sankaracharya to have Darshan of the present Jagadguru Swamiji Maharaj of the Peeth, who was then on the 65th day of his long fast, on the cow-slaughter issue. As we went up to His Holiness’ room numerous devotees were going in line up the staircase leading to his room. The Swamiji Maharaj was lying on a cot covered with a warm rug. After paying my respects I enquired about his health and prayed that the Lord may fulfil his cherished desire and that he may soon be enabled to return to normal diet. He spoke to me for a little while stressing upon the point that in our Sanatana Dharma there is no separation between the spiritual and material and that Sannyasins should not hesitate to take part in seemingly secular matters when these have a direct connection with the religion and its time-honoured traditions. We silently listened to his brief discourse and noticing that he was very weak, we withdrew from his presence after offering our salutations. The ancient Math premises need strengthening and renovation very badly and I feel it a duty, especially of the adherents of this particular Peetha to come forward with generous contributions and take up this task of effecting all the needful repairs and improvements to this eastern seat established by Adi-Guru Sri Sankara Bhagawatpada. One feature of the Puri session of the Orissa D. L. Conference that I particularly liked very much was the item of Sankirtan before the Divine presence of Lord Jagannath inside the sacred precincts of the great temple. This was the opening item on both the afternoons. We felt supremely blessed to have this opportunity of chanting the Lord’s Name in that sacred place. The Orissa Conference was well arranged through the efforts of Sri H.K. Kar, working President of the Cuttack Branch, the able secretary Sri Chintamani Pati, Sri Kanhucharan Mahapatra of Puri and Prof. D.C. Choudhry. Sri Chitta Ranjan Mohanty and Sri Satyajnanam offered their most valuable co-operation and seva in contributing to the success of the arrangements. Of course it goes without saying that the revered Sri S. C. Debo looked after us throughout our entire stay and tour within the Orissa State territory, right from the night of the 16th January, when we reached Berhampur until the midnight of 25th January, when he took leave of us on the platform of Berhampur Railway Station and saw us off on our way to Gujarat and Saurashtra. Sri S. C. Debo’s help in the able management and supervision of all programmes throughout our tours is inestimable. Our grateful thanks are due to all the Office-bearers and members of the D.L.S. Branches of Berhampur, Cuttack, Bhuvaneshwar and Puri including friends Sri Dharma Rao, Ramana Murty and Sri Gandhiji.
87
VAST FIELD OF DIVINE LIFE ACTIVITIES
Leaving Puri on 25th night and after some programmes at Tanuku, Relangi, Undarjavaram (Sri Sankara Sivananda Kshetram) and Hyderabad I leached Rajkot on the morning of 31st Jan., ‘67, and drove to Virnagar, the Headquarters of the Gujarat-Saurashtra Divine Life activities. Here I was very happy to participate in the inauguration by the Swiss Consul. General Mr. Othmar Rist, of the new Surgical Block of the Saurashtra Central Hospital, where Dr. Sivananda-Adhwaryoo is the Chief Medical Officer. It was a very colourful function conducted with great enthusiasm and sincerity. Numerous prominent people from Rajkot were present at the function on 1st February. Mr Perrie Oppligar, the Representative in India of the Organisation Swiss Aid Abroad also come for this occasion. Now for the 20th All India Divine Life Conference at Rajkot. This Rajkot Conference had been a triumph of good organisation, wonderful co-operation, coordination and intelligent management. The ten sessions on the 5th, 6th, 7th and 8th of February together with the three early morning prayer meetings at 6 a.m. were all well attended by the public of Rajkot. Delegates from more than ten D. L. S. Branches within Gujarat Saurashtra and from Maharashtra (Bombay Branch), the Chief Organiser of Andhra Pradesh D. L. S., from Rasipuram D. L. S Branch (Salem-Madras State) and about 15 Sadhus and Sadhaks from Rishikesh Headquarters participated in the Parishad. All the Office-holders and members of the Rajkot Divine Life Society had worked earnestly under the tireless active help and guidance of Dr. Sivananda-Adhwaryoo. The venue was the well know Rashtra-Shala where the late revered Mahatma Gandhiji stayed while he was at Rajkot during the freedom-struggle days. A very huge Shamiana had been erected with an imposing double-gate leading to it. The flag hoisting on the morning of 5th was an impressive ceremony. The speaker’s dais was a huge stage that could easily accommodate fifty persons and was tastefully decorated by the local artists in conjunction with Sri Saunder Rajan of Ashram and Sri Mansukhlal of Patan. The Shamiana could easily accommodate five thousand persons and was filled to capacity daily. H. H. Jagadguru Sankaracharya of Dwarka inaugurated the Cbnference on the 5th morning and gave his blessings after speaking upon the principles of Divine Life and their importance to the people of the present time. Revered Sri Popatbhai Malaviya, a veteran citizen of Rajkot city sent his address through his worthy son Sri Vasant Bhai, who read it. Learned speakers gave their wise deliberation upon important subjects, like Spiritualisation of Human Society, Education and its Problems, Vedanta in Actual Practice, essence of Religion, Saints of Bharatavarsha, Gospel of Bhagawad Gita, Education, Teacher and the Students, etc. Chief among the speakers were H. H. Sri Swami Atmasthanandaji Maharaj of the Sri. R. K. Mission; the venerable Harjivanlal Mehta of Bhavnagar, the veteran and leading Theosophist of Western India; Acharya Sri Nalin Bhatt of Bhartya Vidya Bhavan, Bombay; Pujya Pandit Deena Nath Dinesh of “Manava Dharma”, Delhi; Yogiraj Sri Manuvaryaji Maharaj of Ahmedabad; revered Sri Swami Bhadra of Prarthana Samaj, Surat and Sri Paramanand Gandhi as representative of Sri Panduranga Sastri Sadhvi Sri Sadguna Shree Ji, a Jain Sannyasini also spoke twice. The second day’s afternoon session was exclusively a seminar on Education and Students, attended by numerous High School students besides the general public. The first prize in Essay Competition was won by Sri Bakul, a student of the High School at Palanpur. The night session of the 6th February was made over to Padmasri Sri Dula Kag Baba, the renowned folk-poet who thrilled the vast audience with his wonderful compositions and recitations. The huge gathering sat spellbound for two hours listening to his poetical discourse on the Ramayana. On the final day we had the unique good fortune to have at the Conference
88
ADVICES ON SPIRITUAL LIVING
worshipful Shri Baba Ranchoddassji, who came at midday and graced the function. He addressed the people spiritedly urging them to break the chains of selfishness and take to the life of selflessness, self-sacrifice and dedication to the service of the distressed and relief of the suffering everywhere. A beautiful cut-out of Sri Gurudev in sitting pose was at the background of the dais. It was a life-like painting. The entire Shamiana was hung with ethical and spiritual mottoes. The organisers of the Parishad had arranged to have one pamphlet having Gurudev’s teachings to be freely distributed to the public during each session on all the days of the Conference. A different leaflet was given at each one of the ten sessions of the Conference. In addition to this, free literature in the form of two books and a booklet, namely, ‘So Says Sivananda’, ‘Education, Teacher & Student’ and ‘Sadhana Tattva’ were freely given to everyone attending the Conference. The local press at Rajkot gave fullest possible co-operation to the organisers of the Conference while the local educational institutions too responded favourably and appreciatively their efforts in rousing the students towards the higher idealism in life and greater devotion to Dharma. As a result of the Conference (which became the talk of the town) the weekly Saturday Satsanga of the Rajkot Divine Life Society Branch is having a packed Hall with numerous new comers participating. We await the issue of the valuable Conference Souvenir. My warmest congratulations to all associated with the D. L. S. Branch of Rajkot. They are determined to follow up the Conference with enhanced activity and earnestly hope to make its impact lasting and permanent. My heart-felt sincere thanks to the D.L.S. organisers and devotees in the different places visited for their loving, and noble help in enabling me to bring the spiritual message and the teachings of Gurudev Sivanandaji Maharaj to the people of Andhra Pradesh, Orissa and Gujarat. It is through their devout efforts alone that I am able to serve all and thus fulfil my seva to the sacred memory of Satgurudev. In each State there must be some one or two persons from among the Branch organisers themselves who will be able to tour round that State, once in a while, sharing Gurudev’s teachings with all people in different places. My capacity to do this task personally is necessarily limited. This limitation must be made up by my lay-brothers in the field of Divine work. Such is my thought at this moment. In the spreading of Gurudev’s teachings alone there is hope for restoring India to the path of Dharma in daily life. Everywhere I have travelled I have been hearing the doleful complaint of break-down of Dharma and the prevalence of immorality. Gurudev’s teachings of the purification of personal life and spiritualisation of home environment is the one effective foundation of basing a changed order of our Nation’s social life. I pray to the Lord that He may help us all to live a pure life, to practise the Divine Life precepts and to spread the Divine Life teachings throughout the nation at this crucial hour. Now let me conclude with this ancient prayer of the Rig Veda: “May our purpose be common, common our assembly and common the mind; let thoughts be united too. I give for you a common objective. Worship with unison, worship with a common offering and dedication.” By the time this letter reaches you the Sacred day of Maha Sivaratri might have already come and gone. Here I share my thoughtful views in this connection. While this letter is posted from Rajkot I am close by the shrine of Somanath which is just 15 miles away and which is one of the 12 Jyotir Lingas, Maha-Sacred will be observed with due solemnity here as in thousands of other
89
VAST FIELD OF DIVINE LIFE ACTIVITIES
shrines of Lord Siva throughout the country. Fasting and vigil are the two main disciplines of this all-night-worship that culminates in the dawn of new morn. How wonderfully and how very aptly does this signify the very essence of spiritual life and bring out its true inner content! Spiritual life is movement through the darkness of primal spiritual ignorance towards the light of Divine experience. The earnest keeps close to God and in continuous worship he moves through the long drawn dark night of his soul towards the dawning of Divine Wisdom. In this period of constant endeavour to commune with God, he has to exercise great dispassion and self-restraint and keep ever awake while the world sleeps. Unremitting vigilance is the price for liberation. Fasting actually signifies the denial of sense-appetite and refusing to feed the desires and cravings of the lower self in man. Renouncing all sense-indulgences, controlling senses and subduing desires the seeker exercises vigilance keeping himself ever in a state of spiritual wakefulness and aspiring for the dawn of God-realisation. He is ever awake to his grand goal of life, the ethical and spiritual ideals, and the higher principles that guide the soul from the unreal to the Real and from death to Immortality. He achieves the goal through unshakable faith and continuous worship, despite the surrounding loom of phenomenal life. Lord Siva Himself embodies this ideal of abstinence, awareness and adoration. He is the great God ever immersed in absorbing adoration of the supreme SELF-REALITY in a state of unbroken inner awareness and totally dead to the objective-sense-universe through a perfect subdual of desires. All cravings are burnt up and the ashes adorn the divine body of this Lord of Yogis. Such is the God we adore upon the Maha Sivaratri day. Both the worship and the worshipped one thus bring out very essence of spiritual quest in and through their outer form. O beloved seeker, control your senses. Conquer your mind. Sublimate your desires. Reject the lower food of gross sense-experience. Become a Maha Upavasi, starve the Vasanas. Be alert and awake through constant Vichara and Viveka. Be up and doing continuous unbroken worship of the Divine. Never mind if darkness now prevails. Like dazzling lightning manifests brilliantly through the densest dark clouds, like the bright sun ending the darkness of night, the light of the Divine wisdom will flash forth in your life and illumine it forever. Stick to your vows. Be established in worship. Surmount all obstacles. You will triumph. May success attend thy efforts and crown thy quest with supreme fulfilment. May you attain the other shore of this ocean of Samsara and reach supreme blessedness. To lead the spiritual life is your sole purpose here on earth; all else is but meaningless delusion. Pursuit of goals other than God-experience is a hopeless failure to understand the very purpose of existence and a deplorable waste of most precious life. Time flies. Come now. Waste no more time. Seriously take up to spiritual life and progress upon the inner path that leads to God-realisation. Live every moment for realising God. Waste not time in vain matters. This world is vanity fair of brief duration. All things perish and pass away. He who is wise is vigilant and careful. He attains the goal and makes life fruitful. May God bless you. With regards, Prem & Om, Yours in Gurudev. March, 1967 —Swami Chidananda.
90
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XXXIX
THE RAMAYANA—THE LIGHT-HOUSE OF INDIA
Immortal Atma-Swarupa! Blessed Seeker After Truth! Om Namo Narayanaya! Loving Namaskars, Salutations to you in the holy name of Sri Gurudev Sivananda. May God bless you. This month sees the advent of the New Year according to the Indian Almanac both by the solar calculations as well as the lunar calculations. The Lunar New Years day falls on the 10th April and Solar New Year’s day on the 14th. Therefore, before proceeding further I wish to send you first my joyous greeting for this Yugadi or Samvatsara-Arambha and express my very best good-wishes to you for a bright and happy New Year. May you have an auspicious beginning, and good health, joy, prosperity, progress and success in all right undertakings. May this New Year bring you many new opportunities for selfless service, doing good unto others, acts of mercy and love, intensified spiritual Sadhana and service of the country. May you be enabled to walk the path of Dharma and do the right at every step. May this year be full of achievements and blessedness, both material and secular as well as spiritual and Divine. Now I have a special request to make to you and that is that you should read the Ramayana with meaning completely once before the sacred Ramanavami day. I make it with a special purpose because I believe that through this study you are going to be immensely benefited, and also we have in the Ramayana the real and the right solution for the widespread troubles and sufferings which have invaded our national life in recent years. The guided ideals of national life are provided for us in the two Divine personalities, whose annual worship falls during the current month, I mean Lord Sri Rama and Bhagavan Anjaneya, more familiarly called Sri Hanumanji. Lord Sri Rama is called the Maryada Purushotama or the foremost among the ideal, righteous man as he was Divinity embodied as the paragon of virtue and righteousness. He stands for us as the dazzling and unparalleled example of absolute rectitude in personal conduct and public life. Rarely we do come across such a stirring and inspiring personality to lift us up to a lofty plane of life and conduct. To contemplate a noble personality, to ponder His life, to reflect upon His noble deeds and His words of wisdom and to strive to follow in His footsteps sincerely to the best of one’s ability is the sure and certain way of freeing our nation from the clutches of the fell monster of moral corruption and cultural degradation. Lord Rama is the Light of India and His life is true Way to lead Bharatavarsha from darkness to Light. The misuse and abuse of force and power is the dire disease that is afflicting mankind today. The heroic personality of Lord Hanuman which verily dominates in the Ramayana almost second to Lord Rama Himself is the other great ideal that commands our attention. Sri Hanuman combines in Himself infinite strength and power, with perfect surrender to the will of the Divine. Hanuman is an unconquerable warrior of tremendous prowess, who put himself at the feet of the Lord as an obedient servant, at His disposal. He is always the great Dasa of Rama. His ego was offered up at the feet of the Lord and his strength was utilised in the service of the Lord. This is the finest and noblest use of one’s forces. This leads to the highest good. Where power is abused through
91
THE RAMAYANA—THE LIGHT-HOUSE OF INDIA
selfishness, egoism and materialistic motive, it brings sorrow, suffering, turmoil and confusion. Human activities when divorced from the Divine principle swerve one away from righteousness and bring grief. To keep close to God is the secret of right living, and guarantee of lasting and real welfare. Study the Ramayana, one of the main treasures in our cultural heritage. Study it either in the original or in the vernacular or English. There are two very excellent English versions. One is Rajaji’s Ramayana, published by Bharatiya Vidya Bhavan, Bombay, and the other is the English translation of Tulsidas Ramayana by F. H. Growse. Both are packed with wonderful wisdom. They will bring a new light into your life and show you the path to joy, peace and highest blessedness. May the Grace of the Lord Sri Rama grant you devotion, discrimination, dispassion and divine illumination. The sacred day of Sri Ramanavami (18th April) marks also the memorable birthday of Sri Samartha Ramadas Maharaj, the great Maharashtrian saint and spiritual Guru of emperor Shivaji. Sri Samarth Ramdas attained God-realisation through the Practice of the Divine Name. Though a Jnani, a Yogi and a Sidhaa Purusha of the highest order, Ramadas proclaimed to all the glory, the greatness and the unfailing efficacy of the Ramayana. He thus set his seal upon the unique trend in modern spirituality wherein the Divine Name occupies the central place in the path of Sadhana. In this Kali Yuga in the midst of diverse modes of Sadhana, the Yoga of Name Japa stands supreme occupying an unrivalled, distinct place of its own. The Divine Name of the Lord is the main support of seekers after God, today. It is an indispensable Sadhana. Cling to the Divine Name, O beloved seeker, and overcome all obstacles and come out victorious. The Name is Nectar. The Name will confer upon you the Divine bliss and transcendental peace. Repeat the Name. Sing it in Kirtans. Write it in Mantra notebook. Constantly remember the Lord with the help of His Name. Meditate on the Self. Become filled with the Divine Name. In the present times of unrest, distress, famine conditions and mutual dissension engage yourself in earnestly working to counter these conditions. Help to provide food in the scarcity area. Set up groups to gather and send such help to places in need. Selflessly serve all. Work to relieve distress. Promote harmony and unity amongst people wherever you go. Be a peace-maker and a unifier, in the name of God. Do not think it is the business of the Government only to do this noble task. Do not expect others to do when you can also do it. Let noble Karma Yoga elevate your life to a higher level on the spiritual life. The almost warm weather here at Rishikesh has once again given place to a spell of chill weather with high winds and rain. There is perhaps snow storm in the upper regions of the Himalayas. Our prayers should indeed be offered for the welfare, comfort and the safety of the shivering soldier-brothers in those regions keeping watch on the border, in the bitter icy-cold weather of the Northern heights. May God bless you all! With regards, Prem and Om. Yours in Gurudev —Swami Chidananda
April, 1967
92
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XL
DIVORCE NOT RELIGION FROM YOUR DAILY LIFE
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya! Loving salutations and greetings in the holy name of Gurudev Sivananda. May the spirit of his Divine Life Message he rekindled in your heart with new freshness and vigour at this moment, when the season of Spring is in its peak point and will soon lead on to the Summer. All life is quickened, newly activated in the vernal season and I pray that a perennial spring season may reign within your heart and may keep ever-fresh flowers of moral loftiness and spirituality there in. With the advance of spring and the eve of Summer a challenge faces you in great urgency today. Rains have failed in number of areas in our country. People are facing desperate situations of thirst and starvation. Those of you who are fortunate and safe must stir yourself and see what you can do to help your brothers and sisters of the drought-stricken areas. Give up the mentality of thinking that this is the problem of Government and as long as you have paid your taxes dutifully your responsibility ends. This is not quite so simple. As a civic entity your duty might have ended with the paying of the taxes. But as a moral and spiritual entity your duty now stands squarely before you. It calls you. Yours is a moral responsibility and a religious duty before the gaze of God Himself. Religion means active compassion. Devotion means service. Love means sacrifice. Spirituality means feeling the sufferings of others and entering into their experience and struggling to relieve them by all possible means accessible to you. Spirituality without compassion and active service to those in distress is a spurious spirituality which will take you nowhere. Rush to the aid of those in distress. Think of ways and means of how best you and your friends, associates and relatives can join together and give urgent and immediate help to those in travail now. God is to be worshipped equally in this manner too. Let your Bhakti and love for God manifest itself in service to the living God that is before you suffering in the garb of starving men and children and cattle. The vision of Adi Sankaracharya and sublime compassion of the great Lord Buddha claim your serious attention at this hour. If you call yourselves Indians, if you recognise your heritage in the lives and examples and lofty teachings of these two unique persons, if they are still enshrined in your heart and if you remember them both upon the eve of their sacred Birth Anniversary, then behold, see the one as man manifest in all living beings, in the starving, in the diseased, in the poverty stricken, in the suffering and the sorrowing people in endangered areas, where drought, famine and epidemics afflict countless of your brothers and sisters. See “Shiva in Jiva” as the great Vivekananda Swamiji put it and worshipfully offer your compassion as your Maha-Aradhana to this Divinity Manifest as man. Set aside for a while your comfortable religion of early morning bath and your temple Pradakshina and Gayatri and Gita Parayana and take up the worship of the living God at this time of need. Let your religion be the religion of service. This is the moment, when your religion is on trial and you are being tested upon the touchstone of the actual realities of life. Know now what your religion means when it comes face to face with life and its pains. You cannot escape this issue that confronts you. You cannot and should not hide your head under the sand. Demonstrate in the laboratory and testing ground of dynamic life what your religion has done to
93
DIVORCE NOT RELIGION FROM YOUR DAILY LIFE
you and what it has made out of you. If your religion has not made you selfless, sympathetic, serviceful and sacrificing then bundle it up and throw it into the sea. It is not religion. It is delusion. Start a new and begin to become truly religious. Behold the presence of God in all and worship Him through ceaseless service in dedicated spirit. Trample down your selfishness. There is no greater disease than selfishness O Seeker! Cleanse thyself of this disease and become beloved of God. Religion must be living and it must enter into your daily life. And it must regulate your relations with the rest of your fellowmen. Otherwise it is at best lop-sided and little understood, and it defeats its own purpose and will avail you nothing. Let the Atma-drishti, the Atma-Bhava of Adi Shankara lighten up your approach to life. “Sarvam Khalvidam Brahma”, “Sarvam Brahma-Mayam”, declare the voice of the spiritual Idealism that is your life-breath. This vision must be translated into action if your cultural Idealism, your spiritual concepts and religion must become a living force for progress and achievement for you. Awake then and LIVE YOUR RELIGION and SPIRITUALITY. Divorce not your religion from your daily life. Do not divide God and man apart. Religion and life, God and man, they constitute a mystical unity and whole. Recognise and apply this. Practise this awareness. You cannot love God and neglect man. You cannot worship God and ignore suffering humanity. Love and worship God. Befriend and serve thy fellow beings. This is religion. This is what Buddha and Sankara would have you do. It is not only necessary to Be Good but it is even more necessary to DO GOOD whenever and wherever life demands it of you. It does so now! The religion that does not manifest in dynamic daily practice, that does not enter into the very fabric of your character and nature (Svabhava and Achara) and does not infill every little thought and act of yours, that religion will die. It will not live because it is not a living, throbbing reality to you. It becomes as a burden of dead bones. Religion is life. Make it a purely subjective process and keep it away from your active daily life in the midst of your fellow-men,—by this isolation of your inner from the challenges of your outer living, by this divorce from reality, it loses all vitality and will stagnate. There will be no growth, no progress or development and no attainment. It becomes static and sterile. It becomes as a fossil—pretty but pretty useless. You will just be religious person with no religion in you. Religion means nearness to God. Religion means awareness of God’s Presence not only as a theological fact but also as an indwelling Reality in all forms of life around you. Religious life is more than bath and Puja and Parayana, more than visiting temples, performing ceremonies and going on pilgrimage or even mere Japa and Sadhana only. Religious life implies, must imply for you a life of responsiveness to this inescapable fact of God’s Presence in everything everywhere around you. It implies your active recognition of this fact that “God is here. He is right here in these men and things I am dealing with, I am living amidst and working together in partnership with”. It means this recognition and the natural result of it, namely the coming into your life of a heightened sensitivity to the essential divine quality of all things and beings, a reverence towards this Universal manifestation (Virat or Vishvaroopa) of the Supreme Spirit and a feeling that all human life and activity is a process of spiritual communion with the Supreme Being immanent in His creation. Thus you enter into relationship with your God through your life and work. You draw nearer to Him day by day. You approach your goal with each fresh dawn and each new sunset. This is the technique of constant spiritual progress and continuous spiritual unfoldment. It is the secret of true Religion. It is Religion-man’s nearness to God and God’s Presence in man.
94
ADVICES ON SPIRITUAL LIVING
This spirit is vitally necessary for you. For then alone it will be a living force in you to combat the downward pull of the lower nature in you. This power alone can oppose and overcome the assailing unspiritual factors in life with which you will have to continuously contend. Again and again you will have to invoke this higher Shakti in your earnest Sadhana to annihilate the baser Rajasic and Tamasic elements of the lower nature that persist and tend to prevail in your life. Again and again you should determinedly destroy and overcome this opposition within you and establish the rule of pure Sattva and the “Daivi-sampatti” in your nature. This is the process unfolded in the life of the divine Parashurama Avatara that we recall this month by observing the anniversary of Parashurama Jayanti. In this process the unregenerate gross undivine aspect will contrive to entrench itself behind unassailable conditions of persistence by numerous devices, as the demonical Hiranyakashipu did of yore. It is then that even in Yoga and in Sadhana Life dynamic Rajas has to be added on to your essential basis of pure Sattva—refer the emergence of the Man-Lion, the great Narasimha Avatara that ultimately put down Hiranyakashipu. Power of will, spiritual determination and a pervasive opposition to the undivine in all its aspects and all its details becomes the form of this overcoming. Hence the need for your spirit of religion to interpenetrate into every phase and activity of your day-to-day life. Then it becomes the upholder and support of your moral and ethical nature which is the very foundation of the supreme spiritual Illumination. Religion and moral-ethical life are interdependent and mutually indispensable, the one to the other. Remember, Reflect, Meditate and LIVE this truth, this law. Then you will realise the Divine Reality that is behind this law. May God bless you! May you understand the essence and the secret of Religion, Sadhana and Realization and attain the Highest Blessedness and Bliss in this very life! My prayerful Good wishes ever abide with you Beloved Seeker of God! With regards and love, Yours in Sri Gurudev —Swami Chidananda
1st May 1967.
Sivanandashram Letter No. XLI
SATSANG IS GOD’S GIFT
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya. Salutations and greetings in the name of Sri Gurudev. May the blessings of God be with you always. As I write these lines from Gurudev’s holy Ashram, the early morning sunshine falls upon me and reminds me that hot summer days have now arrived. The Sun has commenced to turn on its intense summer days and it is difficult even to imagine that just two months before in March, this place was in the grip of an almost winter-like cold wave. In the present heat one finds it difficult even to remember that recent chill-spell.
95
SATSANG IS GOD’S GIFT
This entire area is now in the grip of the annual Yatra spirit. With summer has started a steady stream of pilgrims flowing towards the high Himalayan shrines—holy Badrinath, Kedarnath etc. Doors of the sacred temples have opened last month and the devout pilgrim is blessed and sanctified by the Darshan of the Lord. At Rishikesh too, as well as across the Ganges, everywhere there are Satsangas in progress. Thousands of devotees and seekers are highly benefited, inspired and elevated by these Satsangas and spiritual Sravana. Verily this is a Divine region. The Satsanga of his Holiness Swami Bhajananandaji at Paramarthaniketan, the Satsanga of revered Sri Hanumanprasad Poddarji Maharaj and H.H. Swami Sharananandji Maharaj at Geeta Bhavan, the Satsanga of Pujya Shri Mastram Babaji upon the big rock in the Ganges nearabout Lakshmanjhula side are all Divine boons granted by God for the people of this present age. Anyone who comes to Rishikesh during summer must certainly reap the benefit of these Satsangas. Persons of Vedantic inclination can attend the Satsanga of His Holiness Swami Chaitanyagiriji Maharaj at Kailash Ashram and also have Darshan of His venerable Holiness Sri Swami Vishnudevanandji Mahar creates in you the sense of reality of God. It brings about dawn of discrimination. The beginning of wisdom is only to be got in Satsangas. Satsanga takes you into an inner quietness, where restlessness subsides and peace prevails. Satsanga gives you new understanding and opens your eyes to your former follies and errors. It throws light upon the path leading to wisdom and perfection. Satsanga is a boat to take you across the ocean of Samsaric existence to the far shore of Immortality and Eternal Blessedness. Satsanga is God’s gift to believing mankind. This Uttarakhanda is verily the blessed home of Satsanga since time immemorial. The holy Himalayas and the sacred Ganges have created here a divine atmosphere that is unique and unparalleled in the entire world. I like to say a word to you about a very important thing with reference to the present prevailing state of affairs in this country as well as throughout the whole world today. The typical features to be observed in the present-day condition seem to be a growing tendency towards mutual hostility, violence amongst sections of people, a tendency to form parties in conflict with other similar parties, emphasising difference instead of unity and oneness, sacrifice of truth and the practice of falsehood in the interest of immediate profit and personal gain. And above all a general restlessness in all fields of man’s life. It is important at such a time to have a firm centre in which to abide, to have firm stable moorings founded on fundamental principles and ideals in life. This alone will give stability to your mind and personality without which you will be swept away upon the tides of restlessness that keep coming up again and again. Hold on to noble principles. Hold on to fundamental Virtues. Stick to a code of conduct. Adhere to a moral pattern of thought, speech and action. Base yourself upon Dharma or Righteousness. Have an Ideal before you and try to conform to that ideal in all your life and deeds.
96
ADVICES ON SPIRITUAL LIVING
This is the way to remain firm and stable in an agitated age and to acquire a strength that will enable you to resist the impact of adverse and unspiritual forces around you. Hold on to the Divine Principles within you and never move away from it under any circumstances. This will provide you with unassailable protection and strong defence against all combined forces of disorder and disruption in social and ethical life. Trials, trouble and temptations will no longer devastate you and disperse your personality. Your life will be as a house built on rock. Therefore O Seeker be bold! Hold on to noble Principles. Know that Virtue, Character, Moral Code, Dharma and an Ideal these indeed constitute your real strength, your true wealth and life. They give substance to the emptiness of modern existence with its superfluous sensationalism and pleasure pursuing mentality. Principled living is the bulwark against chaos. Virtue is defence against temptation and degeneracy. Character is power. Dharma is firmness. Your Ideal is a shining light in darkness around you. God speed you onward upon this Shining Path O Child of Eternal Light! Move on towards the Goal of divine perfection. Ever press onwards through all the vicissitudes of life and its ever-changing scenes. You have a great purpose to fulfil, a grand grand goal to reach. Tarry not on the way nor allow trifles to divert you from this glorious quest and its glorious destination. Rise upon the wings of Virtue and Worship! Gradually ascend into the pure air of spiritual living. Soar into the high heavens of God-Experience. My prayers are ever with you! I wish you Peace, Joy and Illumination. With regards, love and good wishes. 1st June, 1967 —Swami Chidananda
Sivanandashram Letter No. XLII
SERVICE TO SUFFERING HUMANITY IS THE TRUE WORSHIP OF GOD
Beloved Immortal Atman! Blessed seeker after Truth! Om Namo Narayanaya. Loving Namaskars. Loving salutations and greetings in the holy name of Gurudev Sivananda. May the special grace of Gurudev be granted unto you upon this month, when the most holy day of Vyasa Puja or Gurupurnima occurs. Ashadha Purnima is to us all a most sacred and supremely blessed day sanctified by the ancient tradition and filled with inspiration, elevation and spiritual renewal. A new dawn awaits all Sadhakas and spiritual aspirants upon this great day. There is a subtle inner spiritual wave set up within your heart at this highly auspicious anniversary, which, if you perceive and take hold of, will take you ahead to greater heights of spiritual progress and inner unfoldment. Prepare from this day onward to meet that holy day with receptive spirit and right attitude of faith, reverence and spiritual exception. You will be immensely benefited now. Have special prayers to the Guru every day in the early morning time. Repeat the Guru-stotras with deep Bhava. Do Japa of your Guru Mantra with renewed zeal. Worship the Guru with fervour and Bhakti. Meditate on the Guru for a little while each night before retiring to bed. And observe the Guru-Purnima day befittingly
97
SERVICE TO SUFFERING HUMANITY IS THE TRUE WORSHIP OF GOD
with devout spirit and spiritual Bhava. May Guru-Kripa descend upon you and make your life blessed and Divine. I shall share with you now last month’s special event. After my letter to you in the previous issue, Gurudev sent me south to Tumkur in Mysore State for guiding the Second All-Karnataka Divine Life Conference which was held there on the 10th, 11th and 12th June, under the auspices of the Tumkur Divine Life Society Branch. This was a very inspiring and thrilling event of three days, when the people of the town gathered in good numbers to receive the spiritual message of Sri Gurudev and to get light and inspiration from many holy men and scholars. His Holiness the Jagadaguru Sankaracharya Maharaj, of the Shrada Peeth, Dwaraka, graciously inaugurated the Conference, convened at the Tumkur Town Hall. The people had the great good fortune of getting his Upadesh and blessings. Sri Gokak, the learned Vice-Chancellor of the Mysore University, gave a most enlightening discourse one of the days. Their Holiness Sri Swami Prabodhanandaji of the Ramakrishna Ashram of Bangalore and the Swamiji of Saddhaganga Mutt, blessed the assembly through their illuminating spiritual talks. This Conference has created a unique spiritual wave in the town and stirred the hearts of many persons into spiritual aspiration and thirst for knowledge. Sri C.K. Jai Simha Rao, Sri K. Siddhagangiah and Sri P. Narasimhulu deserve our special congratulations for the event. On the 13th June Gurudev’s Seva was done at Bangalore just as on the 8th June when this Sevak arrived from Delhi. The evening Satsang on the 8th at the Malleswaram Rama Mandir was specially memorable because the assembled devotees all responded wonderfully to call for help of the famine sufferers at Bihar and gave their offerings in the divine Presence of Lord Rama Himself. On this occasion Sri Nikam of Mysore Creations himself donated Rupees One Thousand for this urgent cause of Famine Relief. The collected amounts were immediately sent to the Bihar Manav Rahat Mandal that is running a Free Kitchen at Rahka near Garhwa in the district of Palamau in Bihar. The Ranka Free Food Kitchen is feeding about 8000 persons daily. The Satsang on the 12th June was in the home of Sri and Smt. C. D. Reddy at Wilson Garden, Bangalore, both of whom are devout followers of His Holiness Sri Swami Chinmayanandaji Maharaj, the renowned spiritual teacher of the present times well known everywhere for his inspiring Gita Yajnas and Upanishad Yajnas. In the evening this servant addressed a gathering at the Indian Institute of World Culture to a very earnest and appreciative audience. The next engagement was at Rasipuram, near Salem in Madras State, organised by the Divine Life Society at Rasipuram. Sri S. Chandrasekharan had organised several programmes of Satsanga, discourse etc., with the help of his spiritual friends under the guidance of H. H. Sri Swami Sivananda Sreenivasanandaji. Sri M. S. A. Jayaraman was my kind host during the brief stay and served me with great devotion, due to his high adoration of Sri Sadgurudev. The Salem Town D. L. S. Branch also organised one nice Satsang at the Shantashramam on the 16th June before my departure for Tiruvannamalai. This time Gurudev conferred upon me a unique blessing of undertaking a pilgrimage to the sacred Samadhisthan of Bhagavan Sri Ramana Maharshi at Ramanashram, near the holy temple town of Tiruvannamalai. The solemn ceremony of Kumbhabhishekam to the new Mandapam
98
ADVICES ON SPIRITUAL LIVING
raised over Sri Bhagawan’s Samadhi, took place on the 18th of June and the Sevak was present there at the loving invitation of Sri T. N. Venkataraman, the present head of the Ramanashramam. It was really a grand and an inspiring event and during the three days I was there, the blessed presence of Sri Bhagawan Ramana was felt as a tangible inner experience at once purifying, sanctifying and spiritually elevating. I recalled the visit of Sri Gurudev to this holy Ashramam during his youthful and vigorous Parivrajaka days. I had the unique good fortune of meeting people like revered Sri Muruganar, Sri Arthur Osborne, Sri Nagamma and Sri Venkataratnam and such others, all of whom had the supreme blessedness of close contact with Sri Bhagavan during his life-time. Also, I had the privilege of getting the Darshan, of bowing before holy Sri Janakibai Mata, the God-intoxicated devotee of Sri Ramana Bhagavan. I was happy to be there and to meet them all and also revered Dr. T. M. P. Mahadevan and to listen to his beautiful speech in Tamil. The entire Kumbhabhishekam ceremony conducted by a select group of a large number of learned Vedapathis and Shastries with meticulous care according to strict Vedic ritual was most befittingly conducted and it was a great success. My warmest congratulations to the Trustees of the Ashram for raising this worthy memorial over the Divine resting place of Bhagavan Sri Ramana Maharshi. His Presence and Power indeed radiate from this vibrant Shrine. Prostrating ourselves before Sri Bhagavan Ramana, we took our leave on 19th morning and returned to Sri Gurudev’s holy Ashram on Ganga making a brief halt enroute at Hyderabad where I had the joy of meeting a number of noble Sadhakas and seekers of God and at New Delhi where I spent a day at “Shivanandam”, the blessed home of Smt. Sivananda Vanibai to hold a special Satsanga in the evening of the 20th June. Since returning to Gurudev’s abode on Thursday the 22nd, I have been filled with thoughts of distressing famine situation in Bihar. Please let me know what you have done after seeing my letter sent to you in the May Issue of this journal. Have you taken any step to offer your Seva to the suffering brothers and sisters there? Did you send your substantial contribution to the relief work being carried on there by revered Acharya Sri Vinobha Bhave, Sri Jayaprakash Narayanji or by the Manav Rahat Mandal (under the holy guidance of Sant Ranchod Dasji) that is running Famine Relief Camps at Ranka Chinia and Bhandria in the district of Palamau in Bihar. Did you organise any kind of relief work through the help of your friends, relatives and associates? Or have allowed my appeal to go in vain? Will you do it urgently just now? Can you not actually feel the suffering and the agony of the helpless people at this moment? They are a part of us. Their suffering should not go unheeded by even one single true son or daughter of Bharatavarsha. Here is an example of a sincere soul feeling genuinely for his fellow country-men. Sri Bishen Sarup Sharma of Chandigarh sent Rs. 44/- and wrote in his letter: “After going through your letter No. 40 appearing in ‘Divine Life’ for May, 67, I was greatly moved and impressed and decided then and there in consultation with my wife to contribute Rs. 44/towards “Living God”, who have been hard hit by scarcity of food in Bihar. “This sum of money was in fact specially kept apart by Sri B. Sharmaji to perform a Ramayana Akhandapath to which he had made a Sankalpa (intention) sometime back. Sri Sharmaji writes, “It was to be done in third week of May, 1967 and sum of Rs. 44/- was exclusively kept for this purpose. This religious ceremony would have given me some mental satisfaction and glory. But after going through your letter I earnestly feel that this little donation of Rs. 44/- towards the people of drought-hit area would really go a long way to benefit the cause of Real Religion so strongly pleaded by your Holiness”. This is noble. This is great. This is grand. This is the spirit we want and I may tell you that this donor is a man of very modest means not drawing a big salary and has a family of six
99
SERVICE TO SUFFERING HUMANITY IS THE TRUE WORSHIP OF GOD
persons to support. Similar too has been the gesture of Sri A. R. Nikam of Mysore Creation who spontaneously offered Rs. 1000/-. I specially call upon the devotees of Gurudev residing in Bihar to stir themselves up and immediately go to the aid of the distressed. Noble souls like Sri Vedanta Jha (Jamshedpur), Sri Shiva Madhavi Devi (Arrah), Rani Chandravati Singh (Gaya), Sri Jittan Singh (Dhanbad), Sri Gopinath (Sitarampur), Srimati Adyavati Sahai (Bhagalpur), Sri M. K. Sinha (Patna), Vinoy Vihariji, and such others must now rise to this occasion and freely give of themselves in works of charity, compassion, selfless Seva and help in various ways. I request them to organise Seva, or offer help towards work being done by Sri Vinobhaji as well as Manav Rahat Mandal. Pujya Vinobhaji and Sri Jayaparkash Narayanji are engaging themselves in Darbhanga area in North Bihar and the address of the other organisation is Manav Rahat Mandal, P. O. Ranka (Via Garhwa), Distt. Palamau (Bihar); A latest report from this spot-worker tells me that the actual famine conditions are more or less under fair control now. The present urgent need seems to be rather of opening up of deep wells for supply of water and also provision of medical aid. With coming of rains may be the fodder-situation for cattle might ease somewhat. But water-problem still continues to be acute, as also medical aid for disease that now prevails as a result of the starvation and under nutrition. Contacting these agencies is the best way of making it clear what is the type of help you may best offer in this situation. May God inspire you to enter into this noble work with your heart and soul. I Pray without fail every day that through His grace and to the earnest effort of all the people of this land that trials of these suffering-brothers may soon be over. May health, prosperity, wealth and welfare prevail in this land and all over the world. God bless you all. With regards, Prem and Om, 1st July, 1967 —Swami Chidananda
Sivanandashram Letter No. XLIII
BHARATVARSHA IS HOME OF PREMABHAKTI
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya! Om Namo Bhagavate Sivanandaya! In the holy name of Sri Gurudev I send you all my Greeting and Good Wishes. On behalf of Sri Gurudev, whose Mahasamadhi Anniversary has just been celebrated two days ago, on Sunday the 30th July, I wish you the best of health, long life, prosperity, success and happiness. May Gurudev Sivanandaji graciously grant you the highest spiritual blessedness and supreme Divine Bliss. Upon this fourth Anniversary of his Mahasamadhi I am reminded with intensity of the four cardinal tenets of Gurudev’s Gospel of Divine Life, namely service, devotion, meditation and
100
ADVICES ON SPIRITUAL LIVING
realisation. These four comprise the very life and essence of his simple yet sublime spiritual teachings. They sum up his central message to mankind. This Divine Life message he has left for us all, propagate and spread and broadcast all over the land. His Divine Life teachings, he has left to you and me, to live, practise and personify in our daily life. The world should behold the practical expression of Divine Life in the disciples and followers of Sri Gurudev Swami Sivananda. Service is the root of Divine Life. Devotion and worship form the growing tree of spiritual life. Meditation is the flower that blossoms in this life of devotion and worship. Realisation is the fruit of such spiritual life. I call upon you to reflect upon this fourfold principles that constitute the four pillars of Gurudev’s great spiritual mission. I commend them to you afresh, in the wake of this recent fourth Anniversary of Gurudev’s holy Mahasamadhi. Base your life upon selflessness and service of others. Grow in devotion and daily worship of God. Train the mind in concentration and meditation through gradual, regular spiritual Sadhana. Obtain the Divine fruit of God-realisation and Immortality. Shine with Divine radiance. Proclaim the Divine message of Gurudev through the length and breadth of the land. Proclaim it wherever you are and wherever you go. Make this Seva part and parcel of your life’s activity. Renounce greed, selfishness, anger and jealousy. Become established in Truth, Purity, Love and Selflessness. Value Sadachara above all things. Lead a life of self-control. Live a spiritual life of faith, devotion and aspiration. Seek the Immortal. Move towards the eternal Reality. Realise the transcendental Truth and be in bliss. Rejoice as a liberated soul, freed from the bond of birth and death. This is the servant’s earnest exhortation to you upon this occasion, O follower in the footsteps of Gurudev! Beloved Atman, observe this month as the month of intense prayer, worship and practice of Divine Name. Pray for the welfare of all mankind. Pray for Peace in the whole world. Pray for the relief from suffering and sorrow of all those who are in distress due to war, disease, floods, famine and natural calamity. Pray for the cessation of international tension, violence, hatred, distress and hostility. Pray for the grace of the Lord to grant to man better understanding, spiritual awakening, feeling of brotherhood and oneness, mutual tolerance and spirit of co-operation and service. Pray daily. May the force of united prayer draw man out of darkness of hatred and hostility, and take humanity into a new age of harmony, goodwill, peace and spiritual concord. Indian religious tradition believes in the occasional descent of Divinity to relieve mankind from travail. Ten such descents of Lord Vishnu are narrated in ancient Puranic texts. On the 11th of this month is the Jayanti of the last of the tenth Avatara, Bhagavan Kalki. He is Lord Vishnu Incarnate, as an invincible spiritual warrior, moving in the world relentlessly destroying every vestige of wickedness, sin and evil and restoring to the earth a state of righteousness, goodness and freedom from sin. Setting aside the universal aspect of this process may you invoke this power within the confines of your own individual personality. Make this month a starting point for the commencement within you of such a process of the total annihilation of all that is undivine and unspiritual of all that is unworthy and impure and a triumphal return to a state of perfect goodness, purity, holiness and spirituality. Eradicate from your nature with resoluteness, determination and dynamic effort, the least vestige of grossness and evil, and grow into a state of lofty virtue, moral beauty and perfection. Set about this task with energy and sound faith in yourself. God speed you to fullest success in this noble task onward unto perfection.
101
BHARATVARSHA IS HOME OF PREMABHAKTI
This ideal life of Lord Rama and the Divine Lila of Lord Krishna are very much in my thoughts at this moments when I am writing this letter. Sage Valmiki’s Epic biography of the Divine Life of Lord Rama was made available to vast masses of common people through the Immortal poetic work “Sri Ramacharita Manas” by Sant Tulasidas. This great devotee and saintly poet of Bharatavarsha lives in the hearts of all through this great service he has rendered to the masses. As I mentioned last year his exquisite Hindi poetical work is available in its English version for you to study. The book is replete with thrilling incidents and inspiring spiritual admonitions. The entire work is a marvel of rare beauty of expression and excellence of composition. To be absorbed in his study is a sort of Savikalpa Samadhi as it were. Its study is soul-sanctifying. It is work that has in it the Divine Power of transforming your life. This is because it is filled with spirit of deep devotion, limitless faith and the power of Rama Nama. The whole of India will be celebrating Sri Tulasidas Jayanti on the 12th of this month. Commence a systematic study of Ramayana of Tulasidas upon that auspicious Anniversary day. A spiritual treasure contained in the nectarine lake of Ramacharitamanas will be obtained by those who bathe in it by a daily study of this most beautiful scripture. Two gems from it I place before you here. Sant Tulasidas says: “It may be possible to quench your thirst by drinking water of a desert-mirage, it my even be possible to know everything about the horn (non-existent) of a hare, it may even be possible that darkness rises up and destroys the sun (all is that these impossible things may be possible), but impossible it is that by turning away from God one may ever hope to find happiness”. Then again: “I behold the whole Universe is permeated by the Lord (Siyaram) and has with my two hands folded, I salute everything in this Universe.” The great Purnavtara, the Divine Lord Krishna, too, fills my mind today for we shall all be soon celebrating His blessed Jayanti or Birth-anniversary at the end of this month (27th August). This is a day of great rejoicing. People throughout India, especially, in Mathura and Brindavan, will be filled with ecstasy, and overflowing with bliss upon the occasion of this wondrous day. So, too, in raptures of devotion will the Bhaktas be at Udipi and Guruvayur in the South, at Jagannathpuri, at Dwarka, Dakoor and Nathdwara in the West. Lord Krishna is easily the very heart and the life-centre of the doctrine of Bhakti in this blessed land of Bharatavarsha. Bharatavarsha is the home of Prema-Bhakti. Bhakti is the one invaluable essence in your life. Life without Bhakti is verily a dreary waste. Waste not precious human birth turning away from God. God is the only one unfailing source of Bliss, Peace and Immortality. Attain Immortality and Blessedness by devoting your life by diligent worship of the Lord and ceaseless quest to attain spiritual union with Him. Beloved Self perform an eight-day Anushthana of the Divine Mantra of Bhagavan Sri Krishna Om Namo Bhagavate Vasudevaya commencing from 20th August and concluding on the 27th August night. Do a minimum of three Malas of Japa every day. Those who find it possible may do 12 Malas a day, otherwise three malas without fail, preferably in the night. The advent of the Divine occurs in your life when you turn your gaze at the Lord and Lord alone. Thus the world recedes from your vision and fades away from your sight even as the darkness of night-fall makes the world and its objects to fade away and vanish from sight leaving you alone. So, too, let it be night for you what to the worldly-minded people attached to sense-objects is the bright day-light of world-awareness. Let your senses be subdued and quiet, as are the senses of a sleeping person at night. Attain this sense-subdual through the spiritual discipline of Yama and Niyama and self-restraint. Make your mind indrawn even as the sleeper’s mind has totally withdrawn itself from perception of and contact with the sense-experiences of this objective world. Attain this inwardness
102
ADVICES ON SPIRITUAL LIVING
through the practice of Pratyahara, Uparati and genuine Vairagya. Even as a sleeper at midnight is deep asleep and dead to the world, so, too, be thou dead to this phenomenal existence and deeply absorbed in the Divine Reality. Ceaselessly work for this attainment through a state of Yoga. Sleep the Yoga-sleep of perfect inward awareness. Experience the Divine. May He manifest Himself within your heart with a dazzling brilliance of a million suns. Significant, therefore, is the advent of Lord Krishna in the darkest hour of the midnight for by it we are shown the conditions that are required to be fulfilled if the Lord’s advent in our life is to be made possible. Beloved seeker, through discrimination and non-attachment gradually turn the senses and the mind away from this phenomenal world, through Yama and Niyama, austerity and discipline and subdue the senses. Through Vichara and Vairagya, through Pratyahara and Virakti make the mind inward and God-ward. Through the practice of deep meditation and continuous remembrance become absorbed in the Lord and attain the full awareness of the Divine presence with the depths of your innermost consciousness. Then Krishna is born. Divinity will fill you. Bliss will pervade your life. Everything will be touched with the beauty of His Divine Presence. Auspiciousness and joy will brighten your days. You will rejoice and rejoice for the Lord has now come into you and He abides in you and you in Him. May Lord Krishna bless you. Another Anniversary of an outstanding significance is what they term the Upakarma day. It is the day for renewal of the sacred thread by all the twiceborn Hindus throughout Bharatavarsha. In this annual renewal of the sacred thread lies the spirit of eternal renewal of the great principles that uphold the Sanatana-Dharma. The sacred threads stand for the lofty principles of Truth, Purity and Austerity. Satyam, Brahmacharya and Tapas constitute the foundation of the life of Dharma and moral Integrity. Thread constitutes the essence of character and good conduct. Without these three fundamental virtues a human being cannot uphold his true nature. A man is a man in name only, unless his life is based upon good character, and his conduct is based upon Dharma. It is this eternal vitality of Dharma and Sadachara that have upheld our culture through the bygone years. Our allegience and adherence to and faith and steadfastness in these pious moral principles of Truth, Chastity and Self-control are affirmed again and again upon this significant day of Upakarma. Our adoption of these three great principles as the code of life is signified and symbolised through the act of our wearing afresh this sacred thread upon Upakarma day. May these three principles of Satyam, Brahmacharya and Tapas ever hold the rightful place in the life of children of Maha Bharata. Lastly let me conclude by paying my homage to the memory of the one of the greatest Yogins, the world has ever produced, namely, great Sri Jnaneshwar Maharaj of Maharashtra. He was an Akhanda Brahmachari, a Master Yogi, a great devotee of Lord Krishna and a propounder of the Gospel of the Bhagavad Gita. His Immortal work Jnaneshwary Gita is a priceless mine of spiritual information and instructions. After a marvellous career Sri Jnanadev Maharaj took Jiva Samadhi at Alandi at the young age of twenty years. Thousands of people will be gathering at his living Samadhi of miraculous grace and blessings at Alandi, 14 miles from Poona, upon this holy Jnaneshwar-Jayanti-day on 28th August. It is the invisible presence of these great illumined souls and their subtle spiritual power that uphold India and its Dharma and spiritual culture at the present time. Glory be to the Master Yogi! Glory be to the Lord’s Divine Avatara! Glory be to their Immortal and inspiring examples that show us the path of perfection! May we walk in the light of their radiant light and teaching and attain the Divine Goal of life and become supremely blessed.
103
BHARATVARSHA IS HOME OF PREMABHAKTI
I am very happy to send you my good wishes. With kind regards, Prem and Pranams, Yours at Gurudev’s Feet, 1st August, 1967 —Swami Chidananda
Sivanandashram Letter No. XLIV
SIVANANDA—SHINING EMBODIMENT OF DIVINE
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Bhagavate Vasudevaya! Loving salutations and good wishes to you. I am happy to greet you all upon the eve of Sadguru Swami Sivanandaji’s auspicious Birthday Anniversary (80th), that devotees all over the world will be celebrating on the 8th of this month. This time the day is made doubly auspicious, due to the holy Sri Ganesh Chaturthi festival also falling on the same date. As you know, the sacred Ganesh Chaturthi worship is an annual day, specially regarded and highly suitable for making any auspicious beginning, Spiritual life and spiritual endeavour are a process of continuous renewals and new beginnings every day, as it were. It is a process of dynamic progress. You are reborn afresh in the spirit at each moment, when you make a new determination, when you take a fresh step forward, upon this path of Divine Life. It is even as we human beings look upon a new dawn and a new radiant sunrise day after day. Such is the spiritual life. May the 8th of September, therefore, be to you a glorious new stage in your spiritual journey in every way. I pray that Sri Ganesha, the Lord of success and fulfilment, may shower his choicest blessings upon you and grant you all success in your sincere efforts to attain God-realisation and Divine perfection in this very life. Success in any field of human life, success in self-management and character building, success in moral culture, success in spiritual Sadhana is all the result of patient and persevering effort. It is the continuous effort without impatience that enables one to reach the end of the journey. Failure to persevere is usually due to distractions by other petty goals and attractions. One should be wise enough not to be lured away by the attraction of unworthy immediate ends while upon the path. The ultimate end should ever be kept before you, in your vision, as the blazing beacon light that calls you onward and ever onward. That should be the greatest attraction more than all other attractions in this Universe. You must move towards it as a piece of iron towards a powerful magnet. Divine Life is a life where God occupies the most central position. It is a life where God is the one Supreme value and dominates all else. It is a life delighting in God. Divine Life is life where there is no room for sorrow or dejection or depression, where there is no room for grumbling or complaining, for, you feel that the all Blissful Divine One is your Treasure of treasures, that He belongs to you and you before to him. Then what can you lack or want, and what more can you
104
ADVICES ON SPIRITUAL LIVING
desire or wish for? When you have Him, you feel full and complete. You desire for naught else. This is the spirit of Divine Life. You feel that you dwell in Him and He dwells in you. When this is the fact, the glorious fact, the beautiful and blissful fact, where is the room for sorrow or dissatisfaction. Divine Life, therefore, is a life of fullness and joy. It is a life of never-ending sweetness and ever-present inspiration. There is no life more sublime, more lofty and supremely satisfying than such Divine Life. We had in Gurudev a visible and shining embodiment of this Divine Life in His own grand person. Does he not radiate still the self-same light before your inner vision. Walk in that light. That is the Divine path. That is the Birthday celebration. You are bound to succeed. Nothing can deter one who perseveres, who has patience, who does not lose heart and who cheerfully keeps moving onward, with faith and love. I must now express my keen appreciation and admiration for all those Sadhakas and Devotees, who participated in the Gurupurnima, Aradhana and Sadhana week functions. We had a very good attendance and conduct of all the Sadhakas, who had come from different centres of Divine Life Society, from many parts of the country was ideal and exemplary in every way. They strictly adhered to the daily programmes and went through all the disciplines of the three Sadhana sessions of each day, with keen aspiration, earnestness and enthusiasm. They are really most blessed. I am immensely happy to tell you all that the Ahmedabad Branch of the Divine Life Society conducted very nicely a similar Sadhana-week programme, as well as the Gurupurnima and Aradhana Utsave under the enthusiastic guidance of Acharya Manuvaryaji Maharaj, brother Suryakant B. Shah and Sri Chaturbhujdas Chimanlal Sheth, an ardent devotee of Gurudev and his noble spiritual work. My warmest congratulations to them and all Ahmedabad Devotees. The Bellary Branch of Divine Life Society gave me a pleasant surprise by organising a similar ten-day programme through the earnest efforts of Sri Y. Rama Raoji of that Branch. In different parts of the city, programmes were held on different days and Sri Rama Raoji has created a spiritual stir in the city due to the unique programmes. I warmly congratulate him and his friends and colleagues of Divine Life, who co-operated in making this undertaking a success. Sri Joogalal Sheth of the Sri Radhakrishna Mandir helped greatly in these celebrations. May God bless them all. Here at Gurudev’s holy Ashram, the gathered devotees made this entire period one of blessedness and spiritual inspiration. My most grateful thanks are offered for all of them who contributed in a generous manner towards these functions and enabled us to meet all requirements of the assembled devotees without any difficulty. I must particularly thank Sri Javebhai Bhikhabhai Patel of Petlad, who bore a good part of the feeding expenses at the kitchen. I thank also Sri Sakaram Rao of Bombay, for his devoted gift of Sandalwood pieces for the purpose of daily Chandan at Gurudev’s Samadhi Shrine as well as Sri Viswanath Mandir. Also, for his loving presentations of Dhoties and towels for the use of Ashram inmates. This useful offering he brings with him invariably every year during this holy period. I also thank brother Sharadananda Yogi at Gangotri (Himalayas), who sent various kinds of devotional Puja items for that day’s Maha-Puja at Gurudev’s Samadhi, including a huge garland of the rare Brahma Kamalas, that grow in the Himalayan heights, Sri Chamanlal Sharmaji of Delhi for his offering of clothing for the Samadhi Shrine, Sri B. Srikantiah of Bangalore for Sandalwood oil, Agarbathis and Sandalwood Powder,
105
SIVANANDA—SHINING EMBODIMENT OF DIVINE
and Sri A. C. K. Ramaswami Chettiar of Bangalore for packets of Agarbathis so lovingly sent. God bless them all. My joyful thanks. Upon the organisational side of the functions and their smooth conducting day after day, our revered and beloved Doctor Saheb Sri Sivananda Adhwaryoo did yeoman service and relieved Sri Swami Krishnanandaji Maharaj and other concerned by taking upon himself entirely this onerous responsibility at Swami Krishnanandaji’s special request to him in this connection. This is a yearly Seva during this period that Sri Adhwaryoo Maharaj does, for which we cannot sufficiently express our gratitude. By Shouldering the entire burden of the conduct of the strenuous Sadhana programmes, he provides a very great relief to the hard-pressed Ashram authorities, during this time of greatly increased pressure of duties. In this task he was helped very greatly by our “Chinna Swami Garu” (Chota Mahatmaji) Sri Swami Devanandaji Maharaj. My many many thanks to both of them. And to the many honoured visitors who willingly turned themselves into volunteers and shared many tasks by working with enthusiasm in different Seva including serving meals at Pangat etc., my warmest love and sincere thanks. The actual celebrations of both the holy Guru-Purnima day (21st July) and the holy Maha-Punyatithi Aradhana day (30th July) were indescribably inspiring, elevating and grand. All were caught up in the waves of devotion, worshipfulness and prayerfulness, and felt uplifted into a feeling of spiritual presence of Gurudev. Upon both these sacred days you were in my thoughts and I personally offered worship to Gurudev, I did on behalf of you and all. I performed the worship in the name of all the members of the Society, of all the Divine Life Society Branches and of all the disciples and devotees of Sri Gurudev all over the world. I also offered Abhisheka, Archana and Arti in the name of our brother Swamis abroad, like Swami Sahajanandaji, Swami Shivpremanandaji, Swami Venkatesanandaji, Swami Vishnudevanandaji, Yogiraj Satchidanandaji, Sivananda Radha of Canada and others. The Aradhana Anniversary night Satsanga continued into the small hours of the early morning of the next day concluding at about 3.30 a.m. On the Punyatithi day, we had the great joy of a visit by our old Gurubhai His Holiness Jeevanmukta Maharaj Sri Swami Visveshwarananda Saraswati, who came from his Jivanmukta Ashram, near Jhandiala Guru, in district Amritsar. The holy Swamiji Maharaj graced our night Satsanga, as also the special afternoon meeting of that day, when he gave a very interesting and inspiring discourse, recalling several experiences of his with Gurudev during the day of his close association in his Seva. You will see a detailed report of the celebrations in the News and Notes Section. May you all worshipfully celebrate the 8th of September as a Divine Day of rebirth, renewal and a fresh spiritual beginning with new determination to lead an ideal life and to the attainment of Divine perfection. May God bless you with peace, bliss and immortality. With my deepest regards, best good wishes, love and prayers for your highest welfare and supreme blessedness. Yours in Sri Gurudev —Swami Chidananda
1st September, 1967.
106
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. XLV
LET US INVOKE MOTHER’S DIVINE BENEDICTION
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya! Om Sri Durgayai Namah! May the Divine Mother bless you with health, happiness, all auspiciousness and supreme blessedness! May Her Divine Grace shower upon you always and bestow upon you long life, prosperity, success in all undertakings and unhampered progress in the path of Dharma and Virtue and Divine Realisation. May Her Shakti enable you to overcome the dark and adverse forces in life, bring about joy and plenty and crown your life with Spiritual Illumination, Bliss Divine and Supreme Peace. May you live a life triumphant, conquering all obstacles and come out victorious. You are on the eve of a great period of national worship, a worship of the Divine Mother. The ten days of Durga Puja will soon commence and will lift the hearts of millions of people all over India into a higher level of devotion, religious fervour, faith and worshipfulness. Upon the night of the 4th will start this annual worship and on the 13th will be the great vijaya, the day of VICTORY. Defeatist mentality, frustration, dejection, pessimism and failure-oriented living should all take to their heels and vanish upon this great and auspicious day. Let there be the upsurge of the new hope and new vitality and a new spirit in our national life and in your own life, too. May you enter into a new life upon Vijayadasami day. Upon the rising tide of fervent devotion let the inner and outer life of this country rise into an exalted plane of purposeful endeavour, of resolute will and all-round achievement. More than ever before we all need today the Shakti of the Divine Mother. The course of current events has to change giving place to the positive, constructive and progressive era in the immediate future. Let us therefore, invoke, in one voice, the Mother’s Divine benediction. In a single united prayer from Northmost Himalayas to Kanya Kumari and from Eastmost Assam to our Western limits let our aspiring hearts rise up to the feet of the Divine Mother, so as to draw Her Grace upon this land. May you all see the Divine Mother visibly embodied in Bharatavarsha, the great Mother in Whose lap our Culture and Civilisation has been cradled for centuries past. Bharat-Mata is Divine Mother, personified. Join to make a strong, united and loving brotherhood in the worshipful service and love of this Motherland. Work together to make this land a land of peace, a land of wisdom, a land of plenty and a land of Universal Love. Build up a Sharatavarsha that becomes a force for good among the world of nations. Among yourself be united. Feel the unity of your culture. The great disease of modern mankind is the emphasising of differences and the forgetting of the unifying factor. Be cured of this disease. Stress not upon diversity. See the unity underlying apparent superficial diversity. Your heritage is one. Your view of life is one. Your common aspiration must bring you closer and unite you into oneness. Then alone Bharatavarsha can fulfil the ideal of Lokahita, the ideal of Viswa-kalyana and Manav- seva. In doing this verily you would be worshiping Divine Mother Durga or Parvati Whose living presence is manifest in the Motherland. India needs Mother’s grace more than ever before at this present moment, this time. Do not
107
LET US INVOKE MOTHER’S DIVINE BENEDICTION
approach Her with your little personal prayer. Do not ask Her of fulfilment of petty selfish desire. Rather may your 9 days’ worship be dedicated to the cause of the welfare of the entire nation, pray for all humanity. May your worship be dedicated for the release of Bharatavarsha from her present afflictions. May your worship of the Mother be dedicated to the cause of National unity, cultural brotherhood and welfare of the entire land. This achievement of unity, brotherhood and common-weal would be your greatest victory rather than gain against any other country or people. Make effort in the right direction. Unify. Unify. Unify. May Divine Mother bless you. O blessed Mother of the Universe! O compassionate Mother, deign to cast Thine eye of mercifulness and love upon suffering humanity. I implore Thee Mother with folded hands to grant that all mankind may have peace and happiness. I bow at Thy feet and beseech Thee to bring to an end all hatred, enmity, war and violence. May there be peace on earth. Grant that all those in sorrow, pain and suffering may be relieved of their distress and obtain comfort, joy and well-being. Grant to man the light of better understanding so that he may cast aside greed and selfishness and walk the path of virtue. Fill his heart with the spirit of service and spontaneous love for all beings. Guide Thou his footsteps along the path of wisdom and goodness so that mankind may soon move into a brighter tomorrow of harmony, concord, mutual tolerance, co-operation and spiritual oneness in God. May man cast out evil tendencies from his nature and adopt the rule of Dharma and virtue in his conduct and his dealings! Universal Mother, draw away erring man from the path of self-destruction and genocide into the path of Divine Life of Truth, Purity and Universal Love. Upon my knees in worshipfulness and fervent prayerfulness I call upon Thee Mother to take mankind towards Peace, Happiness and Blessedness. Victory to Thee! Mother; May Thy divine might triumph over all that is unspiritual and un-divine and ungodly. May this world become a house of joy for Thy Children to dwell in and to work for their destined goal of spiritual perfection. May love prevail in the hearts of all! May justice and compassion impel their hands to right action. May Your Presence be felt by all and at all times. Glory be to Thee! Hail, Hail to Thee O Glorious Mother of the Universe! Beloved and blessed Children of the Divine Mother, live divinely in a way worthy of your Mother both as the invisible Universal Self, as well as the visible Bharata Mata. The way to peace and happiness lies not through falsehood, greed and selfishness but in truth, simplicity and selflessness. Virtue leads to happiness. Where there is deliberate adoption of evil ways of living and acting great pain and sorrow result. Decline of virtue is the source of sorrow. Natural calamities come as the direct consequence of evil ways. The universal law of cause and effect should not be ignored. This law is not only for the individual but to whole groups, entire societies and to nations as well. To cherish and inculcate and encourage virtuous living is the greatest service of the motherland. The rule of virtue as a social code of conduct should be adopted over the entire country and the same should be taught systematically as a Science of Life in all educational institutions in the form of a specific subject in the syllabus in all universities throughout India. In this lies the salvation of this country. This alone will make our reverence of Goddess Saraswati true and significant. Do not confine your concept of the great Mother Vidya-Dayini merely to History or to Algebra and Geography nor to Botany and Biology. They are like accumulation of zeroes minus the positive factor of the Science of Life implied by Dharma Shastra. Man must first be taught how to live like a noble and ideal human being. Then other forms of knowledge add to his happiness and progress. Otherwise lacking the gift of humanity all other knowledge runs the risk of perversion and misuse. This very knowledge then becomes the root of suffering and the cause of self-destruction.
108
ADVICES ON SPIRITUAL LIVING
Let Dharma Shastra therefore take its rightful place in our social and national life. Let Dharma Shastra become part and parcel of education which is being given to the growing generation. This alone will be guarantee tomorrow of national stability and order, in the place of the instability and disorder today. Man creates conditions and circumstances according to his nature and behaviour. His nature and behaviour are moulded by right education. Right education creates character, refinement and culture. Character and true culture are the only true safeguards against varnished barbarism. Let education, therefore, be illumined with ethics and become a process of character-building and of man-making. Let education create a decent and dignified generation which in its turn would effectively create a stable and progressive society that would lead the nation into a bright future. Let us invoke the aid of God that our prayer may be realised in coming days. Beloved Atman, this is your sacred mission in life,—to promote virtue in all fields of your society, in which you live and move, as a responsible citizen and an individual benefiting from the society and its wealth. As a member of this spiritual institution and as a true follower of our worshipful Gurudev Swami Sivanandaji you must raise aloft the great principles of service, devotion and spiritual idealism. You must raise your voice in the cause of righteousness. You must strive ceaselessly to live in truth, purity and selfless love and service. You must ceaselessly strive to propagate these virtues through your life and labours. Thus I urge you to be earnest, purposeful and dynamic in Divine Life. May God bless you. May the Grace of Divine Mother enable you to victoriously achieve this noble mission of living and spreading Divine Life through the sincere and persistent combined efforts of you all. May truth, righteousness and goodness emerge triumphant for the highest good of all. Wishing you joy, peace and blessedness and with my warmest regards, Yours in Gurudev Swami Chidananda
1st October, 1967
Sivanandashram Letter No. XLVI
LET THE LIGHT OF VIRTUE EVER SHINE BRIGHT IN YOUR CHARACTER
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya! Om Sri Mahalakshmyai Namah! Salutations and greetings of the season to you all. In the holy name of Sri Gurudev I wish you all a most happy Dipavali and pray that the radiant Goddess Lakshmi may shower Her Grace upon you and grant you prosperity, plenty, success and all-round blessedness. May auspiciousness attend upon you at every step. May health, beauty, virtue and spiritual progress accrue to you. I wish you and all your near and dear ones health, joy and advancement in life.
109
LET THE LIGHT OF VIRTUE EVER SHINE BRIGHT IN YOUR CHARACTER
This bright Festival of Lamps comprises a Universal collective expression of the spirit of our ancient Vedic prayer TAMASO MA JYOTIR GAMAYA,—“from darkness lead us unto Light.” Upon this Dipavali night every year we affirm our determination to banish darkness with bright lights. Spiritual ignorance is darkness. Anger is darkness. Hatred is darkness. Greed is darkness. Illiteracy and lethargy is darkness. Deceit and treachery is darkness. Disloyalty and subversion is darkness. Unrighteousness is deep darkness. So is gross materialism. The opposite of these comprises light. Through virtue and wisdom, through purity and truthfulness, through unselfishness and service awaken the Light of Divine Life and banish darkness. Let the light of virtue and goodness shine bright in your character and conduct. Let thy thoughts be noble, thy feelings sublime, thy speech polite and friendly, all the actions kind and good. Let every noble word and deed be as so many bright lamps in this darkness of selfish materialistic earthly life. Become a centre of Light. My special greetings this month to all devotees and votaries of Lord Kartikeya or Skanda Bhagavan, the warrior-son of Uma-Maheshvara. The devotees of Velayudha Muruga everywhere in India will be observing the holy Skanda Sashti this week. Places like holy Palani, Tiruchandur, Tiruttani and similar Kshetras will be overflowing with Subrahmanya Bhakti and the praise of the youthful wielder of the Divine Spear. Earnest devotees in our country’s Capital will be worshipping on 7th November at His shrine at Uttar Swamimalai. Bhagavan Kartikeya bestows success in Sadhana to spiritual aspirants! He is the embodiment of Daivi Sampatti and Sadhana Shakti. He personifies the power of Divine Grace as the irresistible inner force that ultimately overcomes all unspiritual and ungodly factors in the seeker’s life. His Divine Spear is the power of sustained meditation which overcomes all obstacles and pierces the veil of Ajnana bringing the Sadhaka face to face with God. We bow to the exalted memory of the great Sage Yajnavalkya, the most towering spiritual personality of the Upanishadic era. His Birth Anniversary falls on the 11th of this month. He was the grand old man of Divine Wisdom who shone resplendent in the great royal court of the philosopher-king Raja Janaka of Mithila. Some of the most precious wisdom-gems from the priceless Upanishadic treasure are the illuminating words of Sage Yajnavalkya. In his immortal discourse to his perceptive wife Maitreyi, the venerable sage expounds the Atman as the one and the only supreme value in all existence. In this inspiring dialogue between the sage-husband and aspiring wife, we find the essence of India’s spiritual genius and the central concept of the Indian vision of man and his life’s goal. In this we have the keystone to the invisible structure of our sublime spiritual heritage. I salute that great soul Yajnavalkya who gave us this inspiring and electrifying truth. O children of Bharatavarsha, lose not this vision of life. This is the very life-impulse in Indian culture. A unique worship takes place in this month. It is the worship of sacred Tulasi (holy Basil) exclusively conducted by ladies only. It is a woman’s worship of a Holy Lady, who has been sanctified and elevated to the status of a celestial being. There is significance in this worship. For Tulasi personifies the lofty virtue of feminine chastity. Tulasi is the ideal of faithful and unswerving loyalty to the chosen Lord of one’s heart. It is a singleness of devotion, and dedicated adoration of the one and only chosen partner of your life. Tulasi is Maha Pativrata. She ranks with Anasuya, Sita and Tara. Feminine chastity is a Divine Virtue. It is the glory and resplendence of Bharatya
110
ADVICES ON SPIRITUAL LIVING
Samskriti (Indian Culture). It is a rare fragrance in woman’s personality. It is a real power possessed by a lady, which makes her a Goddess in her family and a shining light of the home. A chaste woman is worthy of worship. The gods themselves bow at her feet. A woman who is firmly established in this lofty virtue of chastity is verily a Divine being, though in human garb. She purifies the entire society in which she lives. They can overcome the whole world. All men are as mere children before such an exalted soul. This is the true glory of real Indian womanhood. Hail to Devi Tulasi! Hail to all ideal women of chastity, purity, spotless morality, nobility and sublime dignity. My silent prostrations and adorations at their worshipful feet again and again. I should not conclude without recalling to your mind two great religious reformers and spiritual leaders who have left their mark upon the Indian Society and given to us a heritage of wisdom and worship. The great Guru Nanak in Punjab and the extraordinary Sant Jnaneshvar Maharaj of Maharashtra opened up new era of religious toleration, broad-mindedness and universality. They form a common heritage of the whole of this nation. The teachings of Guru Nanak Dev are incorporated in the holy ‘Guru Granth Saheb’. The teachings Of Sant Jnaneshvar Maharaj are enshrined in his immortal classic “The Jnaneshvari Gita”. These great leaders brushed aside empty forms and rituals and brought out the spiritual essence of real religion. They strove to root out blind superstition and gave back to man a living faith in and love for the Universal Godhead. They boldly proclaimed the spiritual oneness of all men. They challenged the claim of selfish orthodoxy to a monopoly of man’s approach to his Creator. They expounded the indescribable greatness of God’s Divine Name and the importance of leading a pure life of good conduct and service unto others. They stressed upon the spiritual meaning and purpose of man’s life on earth. The culture of this country has been indeed enriched by the lofty contribution made by the life and work of these noble two sons of Bharatmata namely, Sant Jnaneshvar Maharaj and Sadguru Nanak Dev. May their teachings spread. May their name live forever. May they be ever enshrined in your heart. Glory to Guru Nanak. Glory to Sant Jnaneshvar. O you resplendent sons of Mother India, may you guide the people of this blessed land towards unity, selflessness, mutual co-operation and a life of purity, service and sacrifice. May your inspiring teachings guide us all along the path to a Good Life and God-vision. I close now with some good news to all lovers of Divine Life. The Society’s Branches in Andhra Pradesh have finalised the plans for the holding of the Eleventh Andhra Pradesh Divine Life Conference. Shri P. Ramalingeshwar Rao, advocate, is organising the Conference and the venue is Kovvur, (in West Godavari District) which is his hometown. The dates are made to coincide with the Makara Sankranti or Pongal holiday, that is the 13th, 14th and 15th January, 1968. I wish the Conference glorious success. Another happy event is the Fourth International Yoga Convention at Gondia, Maharashtra, organised by the International Yoga Fellowship of Monghyr under the able guidance of my spiritual brother His Holiness Paramahamsa Swami Satyanandaji to whom the institution and all its admirable activities are devoutedly dedicated by its holy Foundress Ma Yogashakti, the dynamic chief disciple of Paramahamsa Satyanandaji Maharaj. The Convention is meeting from the 1st November to the 7th November and is attracting Yoga enthusiasts from many countries. This is a developing Yoga Movement which promises great future possibilities, holding much benefit to people all over the world. I wish this Yoga Movement all the success that it richly deserves.
111
LET THE LIGHT OF VIRTUE EVER SHINE BRIGHT IN YOUR CHARACTER
With my prayer to the Lord for your highest happiness and welfare and with my best Dipavali good wishes and greetings I close this letter. Accept my best regards and Prem. Yours at Sri Gurudev’s feet, —Swami Chidananda
1st November, 1967
Sivanandashram Letter No. XLVII
SPIRITUAL AWAKENING—PURPOSE OF HUMAN LIFE
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya!. Blessed Atman! Through these lines I seek to arouse within you a constant awareness of the spiritual purpose of your life. I seek to remind you of the great importance of upholding Dharma in your daily life. I strive earnestly to hold up before your vision the lofty goal of God-realisation and to place before you our worshipful Sri Gurudev’s central teachings of selfless service, devotion to God, daily spiritual meditation and Supreme Divine Illumination. To bring the light of spiritual and moral ideals in every walk of life and into every activity of yours is the aim of this monthly letter of mine that comes to your goodself from this most holy and beautiful Ashram of Sri Gurudev Sivananda, where it is my sacred privilege to serve at his feet as his earnest servant and slave. It brings to you the voice of the Himalayas and message of the mother Ganges and it comes you with a call to Divine Life of truthfulness, purity, compassion, kindness, love and practical goodness. The Sivanandashram Letter tries to further this spiritual service of seekers and Sadhakas, which was Gurudev’s central mission in life. It carries the essence of Yoga and Vedanta and Gurudev’s gospel of religion in daily life and worship through service. If by doing this, I am enabled to repay even the tiniest fraction of the immeasurable deep debt of gratitude, which I owe to the sacred feet of Gurudev, I would deem myself most blessed. Thus this monthly Sivanandashram letter is to the writer the means, whereby the great Guru is served and by which you too who are Gurudev’s spiritual heirs receive my service. It constitutes one of the avenues through which I render service to sacred Bharatavarsha and Bharatiya Samskriti (our mother-culture) by constantly reminding her children about their noble heritage, their serious duty and the sublime ideal which they must fulfil in their lives, individual as well as corporate.
112
ADVICES ON SPIRITUAL LIVING. Look back and briefly review the eleven months that have gone by. How has been the year with you? Or rather shall I ask you how have you been during this period of the year that is now drawing to close? Have you made it a year of progressive self-culture and self-conquest? How much have you gained physically, ethically and spiritually? Have you earnestly worked towards certain set goals and significant attainment? Have you striven to make life a Divine Life? Have these past eleven months seen a substantial advance in truthfulness, purity and self-control, kindness and goodness and the overcoming of anger? These are the questions before you, which you must answer at this moment. It is in the light of these true and honest answers that you can move towards the coming India, with the right understanding of yourself and right determination to utilise the days ahead properly and well, to your highest benefit and for your greatest good. This right understanding, right resolve and right action verily constitute the essence of real life. The most valuable and the most important thing in a country and its people is the culture that they evolved. Their culture contains their distinctive sense of value, their view of life and their ideals of conduct and what they consider to be the ultimate goal to be attained by them through this life. Life in India had ever been based upon the great culture, derived from the Vedas that were the repositories of deep wisdom. The highest wisdom of this richest treasure is to be found in the later parts that are known as the Upanishads. The very essence of this Upanishadic wisdom is contained in the sublime little scripture, The Bhagavad-Gita, the Universal Gospel of all mankind. It is the direct personal teachings of God Himself in His incarnation as Lord Krishna. The supremely auspicious day, upon which this Divine Wisdom was given to man, is marked by the Gita Jayanti, which is the sacred Anniversary to all people throughout India. On the 12th of this month this auspicious Anniversary will be observed everywhere in this land by all patriotic sons and daughters of India. The Srimad Bhagavad Gita is an immortal treasure inherited by you. Peace, joy and freedom from fear will be yours if you received the teachings of Gita and imbibe its wisdom. To live in the spirit of Gita is to be master of all situations and to possess the secret of successful living. Will you be victim of life or come victorious through life? You can choose and decide what you will. The wonderful Bhagavad Gita will enable you to do this and will help you to go through life as a master and as a changeless witness of the changing scene. All things are possible to man if he will manfully exert and persevere in his efforts. Thus declares the Gita. Absorb into your very self the wondrous message of Gita. Live, breathe and act in the spirit of its sublime gospels. Follow its practical teachings; you will obtain strength, joy and peace. It will grant you complete freedom from tension, worry and fear. It will reveal to you the secret of mental equipoise amidst all circumstances. Herein I give you a gist of Gita teachings. Listen carefully. Remember and act. Thou art immortal Soul. Thou art neither body nor mind. Thou art indestructible, imperishable Atman. Nothing can harm you. The physical body has birth and death. But it is only a covering or mere cage in which you reside while on earth. You are deathless. In your real nature thou art Immortal. Remember this. Realise this. Now become free from all weakness, fear and superstition.
113
SPIRITUAL AWAKENING—PURPOSE OF HUMAN LIFE
Live with this radiant awareness and perform all actions in a spirit of inner detachment and desirelessness. Have neither love nor hatred. Be balanced in pleasure or pain, loss or gain, and success or failure. Be alike to good and evil persons. Neither become unduly elated nor depressed by any events, or occurrences. Such equanimity brings peace. This peace grants happiness. Control the senses. Control the mind. Subdue desires. Persevere in this practice. Have self-reliance; be confident. Uplift thyself through determined effort. Slay all cravings. Sit alone in silence every day. Sit in a steady posture. Do not shake the body. Be relaxed. Breathe evenly. Withdraw the mind and the senses. Turn thy gaze and fix it within. Now gently concentrate and meditate. Gradually the mind will become steady like the flame of the lamp in a windless place. Meditate, Meditate, Meditate. You will come face to face with the inner Reality and attain wisdom. Do not indulge in mere talk and philosophical gossip. Be a practical man. Do something noble in this life. Develop virtue. Live to serve others. Regard life as a sublime Yajna or self-offering meant to be glorified by dedication to the noble cause of working for the happiness of others. Such work verily becomes worship of the Supreme. Inwardly be ever united with the Divine through constant remembrance of Him. This Universe is the manifestation of the Lord. Behold Him in the glories of the Nature. See Him in all names and forms. Feel His Presence at all times. This enables you to enter into communion with Him. You will have the descent of His Grace. Prepare thyself for this Divine descent through right conduct, right faith and purity of life. Overcome Rajas and Tamas. Fill your life with Sattva Guna. Make your life pure and Sattvic in all its details. Have knowledge of the three gunas. Learn to discriminate between the divine and the undivine, between the spiritual and unspiritual, between the holy and the unholy. Manifest in your life and conduct the divine qualities and totally renounce and cast out the undivine from thy nature. Give up totally lust, anger and greed. Surrender yourself at the feet of the Lord. Follow the sacred teachings of the Gita. Fulfil the Divine Will. You will never come to grief. Health, prosperity and victory will be thine. Cling firmly to the Lord and go thy way doing all thy duties in a spirit of detachment and joy. Blessed Self, this is indeed the call of the Gita to you. Respond to it. Crown your life with success. I am glad to tell you that we are having three Divine Life Conferences next month (January, 1968) in Gujarat, Andhra Pradesh and Orissa consecutively. The First Gujarat State Divine Life Conference is to take place on the 4th, 5th, 6th and 7th January, 1968 in Baroda. The Twelfth Andhra Pradesh Divine Life Conference is fixed for 11th, 12th and 13th January, 1968 at Kovvur (West Godavary Dist.). The Twenty-first All India Divine Life Conference and the Third All-Orissa Divine Life Conference are to take place at Berhampur, (Dist. Ganjam) on 21st, 22nd, 23rd and 24th January, 1968. Divine Life Society Members and devotees in the different States mentioned above should make the best use of this opportunity and try and attend their respective Conferences. The Cuttack D. L. S. Branch has rendered noble service in the cause of the relief of people affected by the terrible typhoon that has caused untold havoc in Orissa. Report has been received of their group of volunteers that went to the affected area and served the distressed there. This is a noble activity that is pleasing to the Lord and will confer blessings upon the selfless Sevaks.
114
ADVICES ON SPIRITUAL LIVING
I bow in Homage to Bhagavan Sri Dattatreya and to Lord Viswanath whom we remember and specially worship during this month. May God shower His Divine grace upon you all and grant you health, long life, prosperity and Divine Blessedness. With regards, Prem and Om, Yours in Sri Gurudev 1st December, 1967. —Swami Chidananda
Sivanandashram Letter No. XVLIII
GLORY OF GURUDEV’S UNIVERSAL PRAYER
Radiant Immortal Atman! Blessed Beloved Divinity! Adorations and homage unto the supreme Universal Being! Salutations to you in the holy name of the worshipful Guru Sri Swami Sivananda. At the dawn of the New Year I send you through this letter my sincere Greetings and good wishes for your long life, health, happiness, prosperity and highest spiritual blessedness. May God shower upon you His Divine Grace, and fill all your days with joy, peace, plenty and spiritual beauty. May all obstacles be overcome, may all difficulties depart, may all problems be solved and may discord give place to harmony. May the Music of Divine Life fill your life with melody and sweetness. Upon this solemn and auspicious anniversary of the conclusion of the old year and the commencement of the New Year, I wish to proclaim to you briefly Gurudev’s Message of Divine Life now. Resolve to live a life of selflessness and service unto all beings. Worship God with devotion and develop Divine Love. Meditate upon the Supreme Being regularly each day without fail. Ever aspire to realise the eternal Reality (God), through right enquiry, discrimination and metaphysical reflection and spiritual contemplation. Strive to lead a pure life of noble good conduct and holiness in thought, word and deed. Be a doer of good action. Develop the vision of One in the spirit of Unity. Practise the Presence of the Divine and dedicate all the actions to the Divine. Life is meant to manifest the highest divine nature that is inherent within you. Utilise life towards this sublime end here and now. Start living this Divine Life today. Waste not time. Postpone not. Do not hesitate. Do not worry. Be bold and cheerful. You will have a glorious future. Strive on with fullest hope. You are bound to succeed. You will succeed, I assure you, my beloved Friend! God speed you upon this bright path to divine perfection and eternal blessedness. Today on the threshold of the New Year I call upon all and appeal to you, and urge you to exert ceaselessly and do your best to give a positive touch and constructive turn to the prevailing atmosphere and mood of negativity, vandalism and arrogance that appear to be prevailing on all sides at the moment. Live and work to uphold the name and honour of your Motherland, of your culture. Work for love and unity. Do everything you can to save the integrity, solidarity and identity
115
GLORY OF GURUDEV’S UNIVERSAL PRAYER
of your country and its worthy way of life. By every means strive to safeguard the ideals and values you have inherited as the food of the life and labours of numerous noble dedicated sons and daughters of our country, who had lived before us over the previous centuries. The two great needs of humanity as a whole are being neglected everywhere and this is resulting in gloom and confusion. These vital needs are to live with the idealism and adherence to virtue. Social ills, economical ills and political ills, all result out of the degradation of the human nature and individual character through loss of faith in idealism and development of selfishness. Consequently virtue has become a casualty and unhappiness and confusion are the direct results. The law of life cannot be ignored and broken, nor its consequences escaped. The Law is that virtue and goodness ultimately lead to welfare and happiness. Misery and misfortune are the inevitable results of evil ways of living bereft of virtue. This is a fact. And when will man be wise and realise this? There is urgency to do so now. Do all that you can to practise and uphold these two great principles of idealism in life and adherence to virtue. Man must be guided by them or otherwise there is no other way out of conflict, calamity and suffering. Why court sorrow and needlessly invite sufferings upon yourself when you can behold right at hand the gateway that leads you to joy and blessedness to peace and stability? I ceaselessly pray that wisdom might prevail and mankind will invite joy and well-being through the Good Life. Blessed Atman, join me in my prayers. Let us pray ceaselessly for commonweal and universal welfare, prosperity and happiness. Let me remind you of worshipful Gurudev’s admonition, He said, “Watch and pray. Pray and work. Work and wait”. This then must you do to achieve any worthwhile goal before this life passes and you have to quit this stage of the eternal drama of life. Be watchful. Be prayerful. Be active and be patient. Activity without prayer will lead you to greater bondage. Prayer without watchfulness will be assailed by temptations too strong to overcome. Work without patience will lead to frustration and pessimism. Prayer when not backed up by corresponding work to express itself runs the risk of evaporating into unrealistic sentimentalism. Be watchful unto prayer. Pray and diligently labour to make the prayer to come true. Work and patiently wait upon the will of God. For to work is your duty and the part that you have to play. The bringing about of the result of work, you should leave in the hands of God. When this letter reaches your hands I shall probably be in Baroda (Gujarat) participating in the All-Gujarat Divine Life Conference. For I shall be leaving Rishikesh this evening to commence my annual tour. On the night of the 7th, after the conclusion of the Conference, our Ashram party will leave Baroda for Andhra Pradesh via Bombay-Hyderabad to arrive at Kovvur for the 12th Andhra Pradesh Divine Life Conference, fixed for 11th to 13th January. From 14th to 18th January follows a brief tour of A. P. visiting three or four centres. We are to reach Berhampur on the night of the 19th to have last moment consultations on the next day regarding 21st All-India Divine Life Conference & the Orissa D. L. Conference, both of which commence simultaneously on January 21st and conclude on January 23rd. There is a week’s tour in Orissa including a visit to sacred Jagannath Puri before departing from Balasore for Calcutta on 31st. At Calcutta our brothers Sri Rajani Mohan Chakrawarty and Sri Sivananda Neelakantan, with the generous help of Sri Raghunath Singh Aggarwal, are bringing out the Bengali Edition of the book, “GOD AS MOTHER” and intend to have it released on the 1st or 2nd of February. Therefore this servant with his party will sojourn briefly in the city of the Divine Mother on the first two days of the month of February. Then I am to visit the Divine Life Society Centres at Rourkela and Rajgarh (M. P.) before
116
ADVICES ON SPIRITUAL LIVING
continuing further. The return to the Ashram will be early in the 4th week of February, to be in time for Holy Mahasivaratri, which is on 26th February. During the whole of March this servant will be at Sri Gurudev’s Ashram at the Headquarters. The Chikmagalur Branch of the Divine Life Society in Mysore State has decided to conduct the 3rd All-Karnataka Divine Life Conference at Chikmagalur on 5th, 6th and 7th April. This Sevak will attend. Immediately after the Conference, there is likelihood of his having to travel to South Africa from where insistent requests have been coming for a visit. If it is the Lord’s Will I shall have to go whenever the inevitable travel formalities are finalised. I suppose Gurudev will look to it as he thinks fit. In the meanwhile chill winter has closed in upon these northern parts; there is a comparative lull in the temple of visiting devotees and seekers at this holy Ashram. Yet despite the cold there are always some earnest souls braving the winter and seeking the peace and spiritual inspiration of this Ganges bank abode of Gurudev Sivananda. The special Forest Satsanga before the Dattatreya Temple on the 16th December on holy Dattatreya Jayanti day was reminiscent of the holy function during Sri Gurudev’s time. The Forest resounded with the Kirtan of the Lord’s Name and the devotees partook of the Prasad squatting under the trees upon the bare earth in the jungle. Holy Christmas was solemn and inspiring and actively assisted by a number of seekers from countries abroad who happened to be present on that Great Day. The midnight worship of the great Yogi of Nazareth, the divine incarnation Jesus, was celebrated with both devotion and fervour as well as gaiety and joy so as to give the seekers from foreign lands a touch of homely spirit to this their holiest and most important festival of the year. They were made to feel that this too was their home and that they were truly in the midst of their family (Spiritual family). The 24th Pratishtha Anniversary of Lord Sri Viswanath was celebrated at the Sri Viswanath Mandir on the 31st of December. That night the Satsanga went upon beyond 12 o’clock midnight to conclude with solemn midnight meditation of the Great Night commencing in the last portion of the departing year and carried onward into the first quarter of the New Year. All the devotees arising from the meditation took leave of one another after exchanging New Year Greetings. Beloved Friend, a New Year lies before you. Look forward and move into this period ahead with faith and hope and in charity. The past has passed on. Forgive and forget your erring friends or offenders. Enter into a new life of Divine Compassion, goodness, love and magnanimity. Now, this day, take God into your home and make Him a member in your family. Learn to live with God, in God, for God. Establish Him in your heart. Express Him through your life. Let your home radiate with the living Presence of the Divine. May thy entire family grow into a divine household. Strive to achieve this and this will be your greatest contribution to contemporary society as well as to your Bharatavarsha, your Mother Country. This indeed would constitute the really wise, sane and rational process of bringing about a true Welfare State. The goodness of man is the key to happiness of mankind. Individual character and conduct is the root of social and national welfare. Character is the greatest wealth. Sadachara is Divine. In character lies the secret of successful planning and of all during attainments. Our Culture stands for Character. I commend to you the UNIVERSAL PRAYER by Sri Gurudev as the unfailing formula for happiness, prosperity and success. Peace and progress will result from this Great Prayer. The sublime essence of all the scriptures and the teachings of all the holy saints and men of wisdom is contained in this wonderful prayer. Make it your life-breath. Beloved Friend, try earnestly to live this prayer. During this year propagate this prayer far and wide. It is of priceless worth. Each line of it is more worth than its weight in gold! I request all of you who read this, to try to get the prayer printed (in any size, big or small, and on any
117
GLORY OF GURUDEV’S UNIVERSAL PRAYER
paper, fine or coarse) and distribute it widely and freely. Print it on one side only so that people can paste it on board or frame it. Translate it into your vernacular language. Get it published in monthly magazines or weeklies or daily papers. Introduce it in schools, clubs and groups. It is universal. It belongs to the whole world. It is above religion. If it is done on costly paper and in big size, you may fix a nominal price if you may wish. If you cannot manage to print it by yourself get together half a dozen of your friends and manage to print a thousand copies at least. Let this world-saving prayer reach every home. Make this prayer circulate throughout the universe. Teach it to your children. Recite it daily at dawn and eventide. MAKE THIS YEAR 1968 A PRAYER YEAR. Great good will come out of it. In this issue of this magazine I have got this Universal Prayer printed on a separate page elsewhere. That page is perforated. You can carefully detach the page by tearing off along the perforated line. Preserve it as a special New Year gift from Gurudev Swami Sivananda, the holy Master of the Himalayan Region. It will bless your home. It will take you towards Divine Perfection. It shows the path of Divine Life. May God bliss you. May this New Year be a glorious year for you. You have my best wishes for your long life, health, happiness, prosperity and success. I send you my love, regards and salutations in the name of God and in the name of Gurudev Sri Swami Sivananda, the light of our life. Thou art Divine. Live Divinely therefore. Abide in God and walk in Light. Yours in Sri Gurudev, January, 1968. Swami Chidananda
Sivanandashram Letter No. XLIX
LIVE DIVINELY
Worshipful Atma Swarup! Beloved seekers after Truth! Om Namo Narayanaya! May the blessings of Sadgurudev be upon you. May He grant health and happiness, peace and prosperity to you. I am writing this monthly letter from Andhra Pradesh, where we just had the sanctifying Darshan of Lord Ramachandra at the Bhadrachalam temple. The living Deity of this temple is a unique aspect of Lord Sri Rama, as the transcendental Divine Being. The Lord is worshipped here not as Dasaratha-Rama, but as Vaikuntha-Rama. The Lord here is in the Chaturbhuja of four-handed form. He bears the Sudarshan Chakra, the sacred Shaukha and He has the bow and arrow at the other hands. The famous saint Bhadrachalam Ramadasa Swami was supremely graced by Lord Sri Rama here. Through him I pray to the Lord to bestow upon you all Vidya, Tushti, Pushti and Paramashanti. After taking leave of you in my January, ’68 letter, I came away the same day to Delhi and thence to Gujarat, where was held the All-Gujarat Divine Life Conference on 4th, 5th, 6th and 7th January at Baroda. The Gujarat Conference was indeed a great success and created a spiritual thrill in that city. It was hailed as a great event, where the light of Indian Culture shone resplendently once again and the call of the Motherland was sounded to bring people back into the path of Dharma and
118
ADVICES ON SPIRITUAL LIVING
to the message of the great souls. Men of wisdom were brought to the eager citizens of Gujarat in general, and Baroda in particular, during the four momentous days. A soul-nourishing feast of wisdom and inspiration and practical guidance for noble living was verily offered to the thousands of people, who turned up day after day, by outstanding personalities like the most revered and worshipful Sri Narahari Shastriji Maharaj, the renowned exponent of the holy Srimad Bhagavatham, Acharya Sri Panduranaga Shastriji Maharaj of Bombay, H.H. Jagadguru Sri Sankaracharyaji Maharaj of Dwaraka Mutt, H.H. Revered Yogiraj Sri Manuvaryaji Maharaj of Yoga Sadhana Ashram of Ahmedabad, Sri Swami Krishnanandaji, Bhadran, Sri Goswami Indu Bhushanji Maharaj, revered Swami Mahadevanandaji Maharaj of Brindaban, Sri Swami Narayanaji Maharaj, revered Swami Bhadraji, venerable Jain Muni Yatish Hemchandraji, the venerable Jivandas K. Mehta, revered Sri Nalinbhai Bhatt, Sri Vishnudev S. Pundit, Sri Prabhakar Dongre and Sri Moulvi Moulana Mohammud Sakir Saheb. Shri P.C. Mankodiji and U. V. Swadiaji together with their very sincere group of devoted friends worked earnestly day and night to make this holy event a successful and noble Seva to the citizens of Baroda and Gujarat, by bringing to them the message of Yoga, Bhakti and Vedanta and the Satsanga of holy people and the venerable leaders and providing them with period of invaluable spiritual regeneration through Satsanga, prayer, Shravana-Sadhana and Nama-sankirtana and Katha. The chief guests on the various days dwelt upon the present social and ethical problems of the country and drew the attention of the audience to their solutions and appealed to them for co-ordinated efforts by all in working for the progress of Bharata. A sublime spiritual atmosphere was created in the city and may felt uplifted as the result of the conference and Darshana of numerous holy people, who had graced the occasion. I verily felt blessed to be in their sacred company. All the organisers deserve our most grateful thanks for this noble undertaking. We left Gujarat for Andhra Pradesh on midnight of the 7th and reaching Bombay on the 8th morning, we proceeded to Kovvur via Hyderabad for the Andhra Pradesh Divine Life Conference on the 11th, 12th and 13th January. Kovvur received the special love of Sadgurudev during his memorable tour in 1950 as the place that accorded him a most glorious welcome, wherein lakhs of people had gathered from all surrounding villages over a radius of more than 40 miles. The Kovvur Conference was a thorough success due to the keen enthusiasm and devoted efforts of Sri P. Ramalingeshwara Rao Guru, who had organised the wonderful reception in 1950. Very many saintly persons and learned scholars gave the people a spiritual feast of lofty teachings, inspiring admonitions and invaluable ethical and spiritual guidance to help them and to achieve self-conquest and to lead an ideal life conducive to the welfare of all beings and to the attainment of spiritual blessedness. Holy men of erudition and spiritual wisdom like Kavi Yogi Sri Shuddhananda Bharatji of Yoga Samajam, Trivikrama Ramanandaji of Courtallam. H.H. The Gayatri Pithadhipati, revered Swami Avdhutendra Saraswati, revered Swami Nityanandaji Maharaj of Yajnavalkya Ashram, revered Vidyanandaji of Shivagiri Mutt, revered Sri Janabai Mataji of Sadhu Mata Ashram at Rajahmundry, Gita-Vyas Sri Subba Rao of Secundcrabad, Satchidananda Saraswati of Chevendrapalayam—all blessed the Conference with their enlightening Upadesha Messages of India’s Ethical and spiritual culture and Gurudev’s Gospel of Divine Life were brought into the lives of numerous people by this holy Conference of three days at Kovvur. A unique item in this Conference was the formal unveiling of the Sivananda Stupa (a memorial pillar) to commemorate the historic visit of Gurudev Swami Sivanandaji Maharaj to this holy Ghoshapadi Kshetra in 1950, during His Holiness’ All-India Tour.
119
LIVE DIVINELY
Situated in the Sivananda Park, this Pillar is topped by a beacon light visible all around and contains the teachings of Gurudev and the Mahamantra engraved upon it. Sri P. Ramalingeshwara Rao, our Gurubhai, exerted himself, day and night, to make the Conference fruitful and successful in giving much spiritual benefit to countless people. He has verily earned the Grace of God by this great and noble Jnana Yajna. The very next day of the Conference we crossed the river Godavari to visit Rajahmundry, where H. H. Sri Swami Karunyanandaji Maharaj, our Gurubhai is carrying on noble humanitarian service through his well-known institution Gautami Jiva-Karunya Sangha. Sri Swami Karunyanandaji had arranged a very big public function in the evening of the 14th January at the Sri Ramakrishna Samathi Hall in Rajahmundry and we were taken in a grand Kirtan procession to the Hall. This servant rested for that night in the calm, quiet Tapovanam away from the city, before leaving early morning for Bhadrachalam. While we were in Andhra Pradesh we visited two Divine Life Society Branches for functions on the 17th and 18th. The one at the village of Madikondur near Guntur was organised by Sri Lakshmiah, Central Excise Inspector, a very ardent, disciple of Gurudev who had convened a very well attended meeting of the entire village. The second was at the Sivananda Sevashramam at Dendaluru near Eluru. Here, the foundation was laid for a Prayer Hall in front of the Ashram. The last function in Andhra Pradesh was at the beautiful Gita Bhavan at Eluru. Very huge crowds awaited our arrival at Dendaluru. After bowing before Bhagavan’s Vigraha with Rukmini by His side, I had the holy privilege of conducting Sankirtan of the Divine Name with the vast gathering and giving them a message of service, devotion, meditation and Self-realisation. Immediately after the meeting I boarded the train at Eluru. Travelling northwards we went to Orissa State next, where the Divine Life Conference took place on 21st, 22nd and 23rd at Berhampur, about which I shall write later. After the Conference we travelled to Puri, the holy city of the Lord of the Universe, to pay our homage to Sri Bhagavan Jagannath. Then, after a brief tour of some of the Branches in Orissa State, we left for Calcutta. In the last part of the tour I had the joy of meeting beloved Gurubhai Sri Ram Premji Maharaj at Balasore. I was very happy to meet him after many years. Thus has passed on the month of January. So do pass on days, weeks, months and years of this brief life on earth. Therefore, great is the need for one to be awake, alert and active in the path of God-quest so as to attain the goal, before life passes away. Blessed souls, utilise well every moment of this precious life, that is a divine gift from God. Strive towards this noble goal. Do all the good that you can, at all times that you can, to all beings on earth. Become an ideal person. Have the goal of a perfect moral life and God-attainment before you and live to attain it through purity, truth, selfless service, worship of the Lord and daily meditation. Ever discriminate between the Real and the unreal, between the Eternal and the temporary. Do not postpone this all-important task of life for an uncertain future. Do it now. Be a seeker after Dharma and Atma-Jnana. All else will pass away. These two alone are the enduring values in this universe. Let Dharma and Divine Realisation be your goal. Lead the Divine Life of service, devotion, meditation and ceaseless quest and attain this goal here and now in this very life. May God bless you. With kind regards, Prem and Om, February, 1968 —Swami Chidananda
120
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. L
HOLY MISSION OF GURUDEVA
Beloved Immortal Atman! Blessed Seeker of Truth, Om Namo Narayanaya. Loving salutations and greetings in the holy name of Gurudev Swami Sivananda. May the divine grace, of the great God, the Lord of the Universe, Jagadishwara, Mahadeva be upon you and may He grant you, progress, prosperity, success and supreme happiness both in your secular and spiritual fields of life. I am most happy to tell you in this letter about the very successful conduct of the 21st All India Divine of the 21st All-India Divine Life Conference and the 3rd Orissa Divine Life Conference conducted at Berhampur through the sincere efforts of the Berhampur D.L.S. Branch and the Orissa D. L. S. Central Committee with a well represented local Reception Committee headed by Sri P. V. N. Murthyji, Sri Ramachandra Rao, Kedarnath Raju and others. It was excellently organised and the three days’ sessions provided great spiritual inspiration and awakening to the numerous people who attended in large numbers day after day. Revered Sri Sarat Candra Debo, the Chief organiser of our Orissa tour itinerary was host to me at Berhampur, and as usual looked after me and my party with great love and hospitality. During our one-week’s stay Berhampur, Revered Mataji Srimati Sivananda Narayana Rao was hostess to us one day and Sri Murthy Garu and Sri Kedarnath Rajuji were hosts upon different days. The Conference was addressed by a number of saints and holy men and eminent thinkers. H. H Maharshi Kavi Yogi Sri Shuddhananda Bharatiji Maharaj inaugurated the All-India Divine Life Conference on the 21st January morning after having hoisted aloft the Divine Life banner, amidst the roaring chant of the sacred Pranava (AUM). Next, after his address followed the inauguration of the 3rd All-Orissa Divine life Conference by revered Sri Vishwanath Dasji, ex-Governor of Uttar Pradesh and a great Bhakta of Lord Jagannath. H. H. Sri Swami Avadhootendra Samswatiji, the great Sankirtanist Bhakta, thrilled the gathering daily, with his most elevating Sankirtans of the Divine Name of the Lord. Sri Swami Bodhendra Puriji gave an inspiring discourse in Telugu. H.H. Sri Swami Ekatmanandaji of the Sri Ramakrishna Math of Bhubaneswar lovingly participated in this spiritual conference and blessed all by his beautiful spiritual discourse on the spiritual path and the Goal of Divine Realisation. Prof. Venkateswara Rao of Vizianagaram College, Dr. G. S. N. Murthy of Kharagpur, D. C. Chaudhuryji of Berhampur and others gave inspiring lectures, and a very impressive Yoga-Asana-demonstration was given by Sri N. S. V. Row of Tanuku and his nephew, an able young Yoga student. Another excellent feature of this Conference programme was the large-scale poor-feeding, that was arranged on the day after the Conference. It was well organised and a large number of deserving people partook of this feeding. Dakshina was also given to them. An effective spiritual awakening was brought about in this city through this conference and a religious wave created by the three days’ programme. The Conference has brought out a valuable tri-lingual Souvenir to mark this important spiritual event in the cultural history of Orissa State. After this 3rd D. L. Conference within the month of January, there was a week’s tour of Orissa to fulfil engagements in different D. L. S. Centres like Dighopahandi, Bomaki,
121
HOLY MISSION OF GURUDEVA
Govardhanpur, Chatrapur, Khurda Road, Keonjhar and Balasore. Sacred Puri was visited to pay homage to the Lord of the Universe in the famous temple of Jagannath. At Keonjhargarh mammoth gathering turned out to hear and receive Gurudev’s Message of Divine Life and of Yoga and Vedanta. The Nagar-Kirtan filled the entire town with the Divine Name of the Lord. At Balasore I met brother Sri Ram Premiji at Ram Niketan after more than twelve years. We were both happy at this meeting. From Balasore we travelled onward to Calcutta at the special request of beloved Sri Sivananda-Nilakantanji who had arranged a public function to release the first Bengali edition of the book ‘God As Mother’ which describes the mystery, the glory and the greatness of the Divine Mother. On Thursday, 1st February, we arrived at Calcutta. That afternoon after paying our homage to Divine Mother Bhavatarini at the holy temple of Dakshineswar and paying my respects to H. H. Sri Swami Vireshwaranandaji Maharaji at Belur Math we proceeded straight to the Ravindra Sarobar Hall for the Public meeting. The Bengali Book was duly released after prayers to Gurudev and the Divine Mother. The publication of this book is the result of the loving labour of Sri Rajani Mohan Chakravartyji, Sri Sivananda-Nilakantan, Sri Niranjan Sen and Sri N.C. Ghosh. May the Blessings and Grace of the Divine Mother be upon them all for this noble Seva rendered to the brothers of Bengal. At Calcutta Sri Ram Ratan Prasadji of Koderma (Gaya) took leave of me to go to Gaya to meet Sri Swami Venkatesanandaji, who was coming from Rishikesh. Sri Ram Ratanji had been of immense Seva to the servant throughout this tour during the entire month of January. Our next programme was at Rourkela where the D. L. S. Branch had fixed up suitable public engagements in different parts of the township. This included the inauguration of an Eye Camp organised by the Lion’s Club and an address to the young engineers of the Steel Town at the Gopabandhu Auditorium. Sri Kasipathy, Taneja, Sarthy and others looked after us all with great care and devotion, and made all arrangements nicely during our two days’ stay. Raigarh (M. P.) was our next camp for two days, on the 5th and 6th February. Sri G. P. Sharma had made suitable arrangements for a number of Satsangas and public meetings. The discourse to the students of the Science College received rapt attention and warm response by the gathered students and staff. We visited the School of Yoga set up there under the auspices of the Raigarh Divine Life Society Branch. It is doing excellent Yoga training work under the direct guidance and inspiration of H. H. Paramahamsa Swami Satyanandaji Maharaj. Dr. Sharma, Sri Chottelal, Prahlad Rai and friends were all full of devotion and took keen interest in this Jnana Yajna. We left Raigarh for Hyderabad via Gondia and Nagaur. On 7th morning we arrived at Gondia for a brief visit to the Sivananda Public School, whose dedication was to take place on the 13th. Sri Amubhai Seth very kindly received us and took us home for our brief halt and sent us by car to Nagpur to board the train for Hyderabad. Sri Patwardhanji, D. F. O. who has been taking very enthusiastic part in the progress of the Sivananda Public School work met me at Nagpur, and I was glad to hear from him about the plans for the commencement of the work at the Public School this summer. At Hyderabad a sacred Nam-Saptah had been arranged by the devout Mataji Sri Lalita Deviji who had accompanied worshipful Swami Ramadas Maharaj on his world tour in 1954. For a whole week, from the 8th to the 14th of February, we experienced veritable Vaikuntha at her residence “Durga Nivas”. It was converted into a blissful spiritual Centre resounding with the all-purifying chant of the all Powerful Divine Name day and night. The thrilling Sankirtan of H. H.
122
ADVICES ON SPIRITUAL LIVING
Swami Avadhootanandji lifted the audience into elevated moods of devotion and fervour. Three separate booklets expounding the glory and greatness of the Divine Name were published for distribution to the devotees who come to this spiritual feast. It was a rare blessedness in this age of scepticism and disbelief. From Hyderabad this Sevak visited Bombay briefly to attend the inauguration of the Bombay School of Yoga and its Yoga Seminar on 18-2-1968 and thence came to Jaipur on the 19th for a three-day programme of Satsanga and spiritual discourse arranged by the Jaipur Branches of the Divine Life Society. Thus through the Seva of this body and mind the Lord gets done the work of His great messenger Gurudev Sivananda at whose feet this servant’s life is dedicated in devotion. This present letter would really be incomplete without my expressing once again my deepest appreciation, admiration and joyful thanks to the organisers of the three Divine Life Conferences at Baroda (Gujarat), Kovvur (A. P.) and Berhampur (Orissa) in particular and the organisers of all the different Satsanga and lecture programmes in different Centres in general for their noble participation in furtherance of Gurudev Swami Sivanandaji’s holy Mission of revitalising and spreading the culture of our Mother-Land. I am immensely happy and most grateful to them all. They are doing a noble service to the people of Bharatavarsha by their work in the field of Jnana Yajna and the propagation of the message of Divine Life of selfless service, devotion to God, unfailing and regular daily meditation (inner spiritual communion with Divinity) and aspiration for Divine Realisation. Theirs is indeed a truly national service by the spread of Yoga and Vedanta without which our culture cannot survive and without the knowledge of which no Indian can be really a true Indian. Yoga and Vedanta constitute the very essence of Indian Culture. The recent tour undertaken by this servant has shown him the good work being done in this special field of our national life by the various followers of Sadguru Swami Sivananda Dev and the various Centres of Divine Life Society in different States of India. May God shower His Grace upon all these noble souls engaged in this worthy spiritual work, even amidst their multifarious day-to-day domestic and professional activities. Let them carry forward this noble good work with confidence and enthusiasm and progress onwards in their spiritual service to the country and their inner life of Yoga and Vedanta. They are playing a humble yet vital role in the reconstruction of Dharma and the rebuilding of spiritual India. This is a sacred task, which will contribute to human welfare and world-peace in the days to come. This Karma Yoga in the form of Loka-seva is the need of New India that is struggling to emerge out of a world crisis through which She emerged undamaged in spirit and yet with a new and clear knowledge of Her proper role in the world ahead and with the fitness and the power to fulfil this role for the benefit of all mankind. May God grant the people of Bharatavarsha the needful vision for this lofty task and also the unity, nobility and the sense of mission to rise up to it at this crucial turning point in world history which is also her own history inevitably! May the followers of Gurudev Sivananda Dev and the votaries of Divine Life recognise this historic significance of their work and work dedicatedly to contribute their highest and best in this great national spiritual resurgence and service through Her Cultural re-emergence. The last place to visit upon this tour was Delhi enroute Hardwar. Here I had the very great joy of meeting beloved Swami Muktananda Paramahamsa Maharaj, the worshipful head of the Gurudev Ashram at Vajreshwari near Bombay. Sri Swamiji Maharaj is an illustrious disciple of the renowned Siddha Purusha Sri Swami Nityananda Yogi of Ganeshpuri. Revered Muktanandaji received this servant with great love and showered his divine affection upon me when I visited him at the house of his ardent devotee Capt. Pratap where he was residing at Delhi. I feel very blessed
123
HOLY MISSION OF GURUDEVA
indeed for having had the good fortune of the holy Darshan of this holy man of God. We had a joyous Satsanga for an hour during this visit. Great is the blessedness of meeting saints. I take leave of you all now with love, regards and good wishes. Remember that this year is a special year. It is the 25th Anniversary year of the Pratistha of the holy Sri Vishwanath Mandir as well as the Silver Jubilee of the Akhanda Maha-Mantra Kirtan at the Ashram. May you take to the Likhit Japa of this Holy Mahamantra with earnest devotion. The prince among Bhaktas, Sri Chaitanya Mahaprabhu revived this Mahamantra and spread in throughout India by his wonderful Prachar during his lifetime. This month is most appropriate indeed of such a similar nation-wide propagation of this wonderful Mantra because on 14th March falls the holy Birthday anniversary of Chaitanya Mahaprabhu or Lord Gouranga. May you all celebrate this divine Birthday and make it the starting point of a wave of Prachar of this wonderful Mantra given by God, for the redemption of man in this Kali Yuga. Let all the quarters resound with the chant of “Hare Rama Hare Rama, Rama Rama Hare Hare; Hare Krishna Hare Krishna, Krishna Krishna Hare Hare.” May all beings be uplifted from bondage, sorrow and ignorance and may all attain the supreme realm of Freedom, Bliss and Divine wisdom. God bless you all! Yours in Sri Gurudev, March, 1968 —Swami Chidananda.
Sivanandashram Letter No. LI
WONDERFUL IS THE SIGNIFICANCE OF MANTRA-WRITING
Beloved Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya. Loving salutations in the holy name of Gurudev Swami Sivananda. I am immensely happy to inform you all that there has been an enthusiastic response to the call for the Mahamantra Likhit Japa Yajna in connection with the forthcoming Silver Jubilee of the Mahamantra Akhanda Kirtan that has been in progress since the year 1943, from the December 3rd. Already Sri Gandhiji and Sri Govinda Rajuji of the Berhampur Branch and Smt. K. Gopalraj Urs of the Ladies’ Branch, Mysore have set to work starting a Mantra-writing Campaign at their places. Similarly the Baroda Branch has also started a Mantra-writing Campaign and have printed special Mantra-writing notebooks for distribution to all those who join this sacred Nama-Yajna and undertake to commence the Mantra-writing systematically. May this Yajna create a sublime, elevating and all-purifying spiritual wave that will uplift the minds of all men and flood the heart of humanity with finer feelings of compassion, tolerance, brother-hood, spiritual oneness and Universal love. May the divine power of the Name purify the world-atmosphere and bring about the
124
ADVICES ON SPIRITUAL LIVING
cessation of hatred, war and violence, and make love prevail and establish abiding peace in the world. Since this servant’s return to Gurudev’s holy abode, he has become aware of the increasing interest, that is being evinced in the Divine Life Message and Gurudev’s teachings in all parts of India. Correspondence from all directions makes abundantly evident this increasing trend towards the spiritual side of life. Active work in bringing more and more fortunate people into the path of ethical and spiritual idealism is being done. I would like to mention here as a typical example the exceptional noble Seva of Sri B. Narasimha Rao of Bangalore, who within a short period has enrolled more than 50 new members to the Divine Life Society, thus opening to the fortunate souls the doorway to the actual treasures of our spiritual culture and Divine science. Sri B. Narasimha Rao is indeed a Karma Yoga Veera and deserves to be congratulated for his entirely selfless Seva to the cause of noble Jnana Yajna. God bless him. Since 1st January, 1968 numerous devotees have been enrolled as new members. I welcome them all and wish them a bright and glorious future full of ideal living, spiritual joy, divine peace and highest blessedness. I have some good news for all members and readers in general. The two long awaited books will soon be ready and available to you. ‘The Bhagavad-Gita’ with translation and Gurudev’s invaluable commentary (10,000 copies) is nearing its completion at the Ashram Press. It is likely to be ready by Gurudev’s holy Aradhana Day, this year. The other book, ‘EPISTLES OF SWAMI SIVANANDA’ (4000 copies) brings you the incomparable Upadesha of Sri Gurudev in his own hand-writing. This is a rare treasure. It will be ready in a couple of months’ time. I most heartily thank the numerous Jnana Yajna donors who have readily given their noble contribution towards the bringing out of these two books as also some other works that are in the Press. Great is the blessedness of these wonderful souls, who have become participants in this noble spiritual work in bringing the light of wisdom into the lives of modern men and women. They have become the instruments of God in bringing divine peace any joy into the hearts of countless beings in this restless world. Jnana Yajna is the noblest Seva of mankind. Jnana Yajna is the greatest of all Yajnas. In this letter I must tell you something about my programme of the near future. If it is Lord’s Will, this servant is likely to go abroad sometime, on Gurudev’s work. He is being called to South Africa by the persistent loving insistence of the noble spiritual brothers over there. I am pressed to come there on a visit of 3 to 5 months. Nearly ten years ago, towards the end of 1958, Sri Gurudev was requested to send me by the saintly Swami Sahajanandaji Maharaj, the pioneer organiser of Divine Life work in South Africa. He had founded the First Branch at Durban in 1948-49. At that time I could not go. The next time in 1959 when Sri Gurudev sent me abroad to the States, Swami Sahajanandaji Maharaj requested me to consider the possibilities of a visit to South Africa, en route to West. I could not do so; neither could I come via South Africa on my way back to India in 1961. Since then he tried to take me there along with him in 1963 when he visited the Headquarters sometime after Sri Gurudev’s Mahasamadhi but the time had not come and God’s will was otherwise. It seems now that the time has come and I must go. If the travel formalities are finalised, then I shall sail from Bombay on the 2nd May. In that event I shall arrive at the Sivanandashram, Durban, on 10th May and witness the glories of the holy Master’s Divine Work in that country. It will be a blessed day indeed for me.
125
WONDERFUL IS THE SIGNIFICANCE OF MANTRA-WRITING
Meantime, I am on my way to Mysore State to participate in the 3rd All-Karnataka Divine Life Conference at Chikmagalur convened by the Chikmagalur Branch of the Divine Life Society. After the Conference (which is on 5th, 6th and 7th April) I proceed directly to Coimbatore, to bring the message of Bharatvarsha’s culture and idealism to my brothers in the Government Central Jail there, which is one of the largest jails, having nearly 3,000 inmates. Then I have to return to the Headquarters before the Ardha-Kumbhasnan upon Vaishaka Sankranti-day, on 13th April. During my absence from the Headquarters, my Beloved and worshipful Gurubhai, revered Sri Swami Krishnanandaji Maharaj will be presiding over the holy Ashram and gathering, and bless all the devotees who visit there to pay their homage to Sri Gurudev at His Holy Samadhisthana. Revered Sri Swami Krishnanandaji is my own self and we are not two but one. He shall be in Gurudev’s place to all devotees and disciples of our brotherhood, during the occasions of the forthcoming sacred Guru Purnima, Aradhana, Birthday, etc. Sri Gurudev’s grace is fully upon him. Sri Swami Madhavananda Maharaj and Sri Swami Premanandaji Maharaj are ably assisting him in administering the activities at the Headquarters. I shall leave you now to direct your hearts and minds toward the Supreme Divine Reality in Its glorious form of Bhagavan Sri Ramachandra. The advent of the supremely ideal Avatars is an event of national worship in this country. May you all engage yourself in the worship of Lord Rama. May the Divine Rama Nama be enshrined in your heart and constantly uttered by your tongue. Contemplate the ideal of this Divine Being. Worship Him with devotion. Meditate upon the Lord. Behold Him in all beings and things. Adore Him through truth, purity and service. Offer Him the flowers of good deeds, virtuous conduct and ideal life. Let Lord Rama be your goal and ideal. Let Him be your supreme refuge. May His grace crown your life with supreme blessedness and Divine Illumination. Om Sri Ramaya Namah. Om Sri Ram Jai Ram Jai Jai Ram. Glory be to Lord Rama. Glory be to Sri Gurudev. With regards, love and all good wishes, Yours in Gurudev —Swami Chidananda
1st April, 1968
Sivanandashram Letter LII
LET US WAKE UP
Beloved Immortal Atman! Beloved Seekers after Truth! Om Namo Narayanaya. Loving salutations and greetings in the holy name of worshipful Gurudev Swami Sivanandaji, I greet you also in the name of the Compassionate Buddha, the veritable embodiment of divine love and merciful kindness, the Light of mankind, who will be worshipped all over the world upon the coming full-moon Day of Vaisakha Purnima. That is Buddha Jayanti. This is a particularly significant and specially sacred day to this servant because it was on this day, 25 years ago, that I reached the feet of our worshipful Master, whom I had the holy
126
ADVICES ON SPIRITUAL LIVING
privilege of serving for nearly twenty years. It was on this Sacred Buddha-Purnima-Day that I first beheld his stately radiant personality, bowing down my head in homage at his lotus feet. That blessed moment sustains this servant ever upto this present moment. Hail Buddha! Hail Gurudev Sivananda! May their grace be upon us all. Since writing to you last in my April letter of the previous issue, the travel formalities have been finalised and as I had already mentioned I shall be mentally bidding good-bye to all of you and departing from India on Thursday, the 2nd May. A most auspicious day indeed as it is Thursday, the Guru’s day, and also it happens to be the holy Adi-Sankaracharya Jayanti, the Birthday Anniversary of Jagadguru Sri Adi-Sankaracharya. May this great world teacher’s benedictions help me to spread the message of Vedanta and Yoga, wherever the Lord takes me. The steam-ship Cambodge departs from Bombay harbour on 2nd May, and upon it Sri S. Nagarajan, my devoted and faithful Personal Assistant and myself are booked to sail that day. Departing that day, the voyage to Durban is scheduled to be completed in seven days’ time, reaching Durban on the 8th day, namely the 10th May. This means, that by the time you receive this letter this servant will be in the open sea. I pray that the gracious blessings and good wishes of you all may go with me to guide me in this Seva. Now, let me tell you of two auspicious and successful events. One was the visit by a Divine Life party to Assam to bring the message of Yoga and Vedanta there. Devotees of Gauhati had arranged an eight-day spiritual programme from 24th March to 31st March at Gauhati and Shillong. I joined them on the 29th. This eight days’ programme has created a spiritual stir and numerous people have responded to the message. A new Branch of the Divine Life Society was inaugurated at Gauhati, and it promises to be an active centre of Satsanga and Jnana Yajna. The other outstanding event was the most successful Third All-Karnataka Divine Life Conference, organised by the Chikmagalur Branch of the Society at Chikmagalur town. This Conference was attended by thousands with tremendous enthusiasm and was graced by eminent holy saints like the revered Shivakumar Swamiji Maharaj of Siddha Ganga Math, a great Jnani Swami Shankaranandaji Maharaj of Ajjampura Ashram, H.H. Jagadguru Shankaracharya of Dwarka, revered Sri Swami Parbuddhananda of the Ramakrishna Mission Ashram of Bangalore, and several others blessed this conference with their presence and spiritual discourses. A large scale feeding of the Lord in the form of the poor was conducted on the 8th April. All credit goes to the very earnest efforts of the sincere organisers Sri B. Subbayaji, Sri M. J. Kodandarama Setty, Sri K. Satyanarayana Rao, Sri Kashi Viswanath Setty and their colleagues of Chikmagalur Branch. May God bless these noble souls and their families as well as their other helpers and associates in this glorious spiritual conference. Truly they have all worked wholeheartedly and brought about a sublime Adhyatma Yajna in this Kali Yuga. My heart overflowed with great joy when I attended and participated in this holy conference. On the concluding day, the afternoon session was highlighted by the addresses of His Holiness Jagadguru Dwarka Sankaracharya, General K.M. Cariappa and Padmashri Shivamurthy Shastriji Maharaj. The holy Jagadguru spoke on the essence of Indian Culture ideal in life, while General Cariappa addressed the audience in deep earnestness, making a fervent appeal to all people of the country to uphold a high standard of purity and morality in public and private life and work for a Nationwide revival of a spirit of selfless service and dedication to the country’s welfare. He exhorted all to cast out selfishness, shake off laziness, purify the heart and to serve the Nation at large. His was a stirring call to the nation and the essence of the message is LET US WAKE UP. By your life, conduct and every action to raise high and uphold the good name of your motherland is the first and foremost duty. This is true mother-worship. The Chikmagalur
127
LET US WAKE UP
Conference has brought out an excellent bi-lingual Souvenir, entitled Satsanga, which contains 350 pages and a number of valuable instructive articles both in Kannada and in English language as also a number of select illustrations. It is a very fine publication. This servant had the joy of meeting all the representatives of Divine Life in Karnataka. The next Annual Divine Life Conference in Karnataka will have its venue at Bellary at the request of Bellary Branch of the Divine Life Society. Karnataka is progressing ahead in Divine Life work. Now the Taskar Town Branch at Bangalore has raised its own building. The first floor is to be a Swami Sivananda Mandir with Gurudev’s Marble Murty enshrined in it. The ground floor is already housing the printing press. Karnataka is a holy State, which is publishing 5 different monthly journals; Bangalore Branch publishes Divya Jeevana (Kanares), Bhadravati Branch Divya Darshana and the Taskar Town Branch one bulletin in English, one in Tamil and one in English and Tamil combined. The holy season of Yatra has commenced. This year the Kumbha-Mela at Hardwar has brought lakhs of people and therefore the pilgrimage to the Himalayas will be very large indeed. Innumerable people will also come to offer their worshipful homage at Gurudev’s sacred Samadhisthana. They will have the privilege of paying their respects to revered Sri Swami Krishnanandaji Maharaj at the Ashram. He is my veritable Self and during coming months he will preside over all gatherings and meet and bless the devotees, who flock to this place. I hope to keep in touch with you through the monthly Sivanandashram letters. All correspondents may henceforth directly address their letters, on matters of guidance, to revered Sri Swami Krishnanandaji Maharaj as the Acting President during my absence, or to Sri Swami Madhavanandaji Maharaj, functioning in the former’s place. Beloved Atman! walk in the footsteps of Lord Buddha. Be a man of compassion, love and peace. Hurt not any one. Be generous and kind. Walk the pure way. Be a door of helpful deeds. Live to serve. Then only the Light of the Lord can descend on you. Be bold. Let the Truth of Vedanta fill thee with strength. You are essentially divine. Fearlessness and freedom are your birthright. Be Divine. May God bless you. With regards, love and prayerful good wishes, Yours in Sri Gurudev, 1st May 1968 —Swami Chidananda
128
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. LIII
HEARTY SEND OFF FROM BOMBAY AND WARM RECEPTION AT THE DURBAN SIVANANDA ASHRAM
Worshipful Immortal Atman! Blessed Seeker after Truth! Om Namo Narayanaya! Salutations in the name of Gurudev and my greetings and good wishes to one and all of you. This letter is being mailed to Rishikesh from the Sivanandashram at Durban, (South Africa). I despatch this with a special pleasure and eagerness. Because, I am now out of India and this letter provides me a valuable means of speaking my thoughts to you all, even though separated by thousands of miles from you, and a far distance away physically. I thank Gurudev for this facility provided through this medium. This present letter I have commenced on board the ship “CAMBODGE”, on which I travelled from Bombay to South Africa. Since departure from the Bombay Harbour on Thursday the 2nd May, the voyage has been smooth on a calm sea under a clear sky and in bright sunny weather. The atmosphere being restful, the body has had an opportunity to relax and get a little rest without pressure of any programmes and engagements. Prior to embarking on the voyage, the last two weeks in India were very busy ones; 24th of April was the busiest date at the Ashram. There were many leave-taking programmes including a special Satsanga in the forenoon in front of Gurudev’s sacred Samadhisthana immediately after conclusion of Paduka Puja, offered to Gurudev. During that Satsanga I had the privilege of making revered and beloved Sri Swami Krishnanandaji Maharaj occupy my seat and declaring to the assembled gathering that they should all regard him as the Head of the Institution and that they would receive from him the same Bhava and the Seva as I have been trying to manifest towards them all. Sri Swami Krishnanandaji Maharaj also addressed the audience and gave them a brief account of the circumstances that have led to my undertaking this present visit to South Africa and what it meant in terms of Sri Gurudev’s Spiritual Mission and His Institution, the Divine Life Society. During this talk he touched upon the unique work of the South African Divine Life Society and the excellent progress it had made since its inception in 1951 and revered Sri Swami Sahajanandaji Maharaj, who now guides the work from the Headquarters of Durban. Taking leave of all Gurubandhus at the Ashram on 24th April, I arrived at Delhi the next morning for a full day’s programme before leaving for Hyderabad the same night. The Delhi programme included a devout worship offered to Gurudev’s Paduka (as it was Thursday) by Sri C. R. Sud and all his family at their residence, “DIVYA DHAM” at Bengali Market. The Swami Sivananda Cultural Association had arranged a send-off function at the nice auditorium of Pubjab National Bank on Parliament Street. At Hyderabad I had a full day programme with a similar send-off function in the evening, organised on behalf of all the Divine Life Society branches of Andhra Pradesh. Many delegates had come from the different DLS. Centres including delegates from two Centres outside Andhra Pradesh, namely from Khurda Road and Bellary. The Kovvur
129
HEARTY SEND OFF FROM BOMBAY AND WARM RECEPTION AT THE DURBAN SIVANANDA ASHRAM
Divine Life Society Branch had prepared a special address for the occasion in addition to the address prepared by the Hyderabad Divine Life Society. Bombay Divine Life Society branches arranged a number of programmes on the last two days I was in India, i.e. 30th April and last of May. Here also there was one main send-off function arranged on the forenoon of the 1st May at the Kannada Educational Society High School at Wadala. I wish to express here my deepest gratitude for the immense good-will and affection which these Gurubandhus have showered upon me on the eve of my departure. Just before coming to Bombay for the abovementioned programmes I had the unique privilege of visiting His Holiness Sri Swami Muktanandaji Maharaj, at his “Sri Gurudev Ashram”, Ganeshpuri, and spending 3 days in his holy company. He is a well-known spiritual leader and disciple of the great Siddhapurusha, the worshipful Sri Nityanand Bhagavan. This visit is a fulfillment of a promise, made to the most revered Sri Muktananda Babaji Maharaj, when this servant had the joyous privilege of meeting him last time in February at Delhi. It proved to be a rewarding spiritual retreat, when I had the opportunity of visiting the sacred Samadhisthana of Nityananda Bhagavan as also of partaking of the Satsanga of revered Swami Muktanandaji Maharaj. The Ashram is beautifully kept up and very systematically conducted under the personal directions of revered Swami Muktanandaji Maharaj. The are many cottages, a fine Guest House and spacious Satsanga Hall called Turiya Mandir. Daily programme is very punctually carried out in an organised manner. Hari Nam Sankirtan, Gita-Patha and Vishnusahasranama-Patha are daily done by all Satsangas. Sri Swami Maharaj is generous-hearted and very charitable in nature. The beautiful garden gives joy to the eyes. Swamiji is an excellent organiser. Diamond Jubilee Anniversary of his Birthday was approaching at that time and those at the Ashram and all his devotees were busy in preparing for this important and special event. After taking the saint’s blessings, I came to Bombay on the 29th night. During the brief stay at Bombay I had the joy of visiting Sri Natvarlal G. Parikh, the great devotee of Sadguru Sri Swami Ramadas Maharaj (beloved Papaji) of Ananda Ashram. Sri Swami Ramadas Maharaj had graced Sri Natvarlalji’s residence upon various occasions by staying with him while visiting Bombay. Sri Natvarlal Parikh has preserved with great reverence the chair, upon which Pujay Papaji used to sit, while staying with him. He also played for us the tape-recordings of the chanting of the holy Ram Mantra by Pujya Papaji himself as well as Pujya Mataji and other devotees. The departure day, 2nd May, was especially auspicious and holy as it was both a Thursday as well as the holy Anniversary of Jagadguru Adi Sankaracharya’s sacred Birthday or the Sankara Jayanti. Therefore, at the Harbour before going on board the vessel I was prompted to observe this holy Anniversary. Accordingly, we put up Gurudev’s sacred Padukas upon a seat and with Swami Devanandaji’s help duly conducted at the harbour itself Guru Paduka Puja with Archana, Arati etc. The holy Prasad was then distributed to all those who were present. Invoking the grace of Sri Dattatreya Bhagavan, of Adi Shankara Bhagavat Pada and of Sri Gurudev upon all the devotees present, I prayed to the Lord to confer upon everyone long life, health, spiritual progress, illumination and supreme spiritual blessedness. The Embarkation Hall resounded with the loud Sankirtan of the Lord’s Name and the holy Chant of Maha Mantra and Maha-Mrityunjaya Mantra.
130
ADVICES ON SPIRITUAL LIVING
After going on board the ship, we had a period of meditation and silent prayer in the specious lounge until all visitors were requested to leave. They all then got down from the ship and stood in a group on the pier and commenced to sing the Names of the Lord until the ship started to move away from the harbour soon after midday. A number of devotees had travelled all the way to Bombay to participate in the farewell programmes and to give this servant a personal send-off at the harbour on the sailing day. The were Mr. & Mrs. Sud, Mr. & Mrs. A.D. Sharma, Sri K. M. Massand and Sri A. Sundaramji from Delhi, Sri U. V. Swadia from Baroda, Sri Sreyas Kumar Shah sent by his father Sri Suryakant B. Shah on behalf of Ahmedabad D.L.S., Sri Dr. Sivananda-Adhwaryooji Maharaj from Virnagar, Gujarat Divine Life Centre, and Sri Pranalalbhai Maharaj and his entire family from Rajkot. From Hyderabad D.L.S. Sri T. Venugopala Reddyji had come similarly to give personal send-off, from Poona N.V. Viswanathan (the brother of Sri N.V. Karthikeyanji of Hq.) had come with his revered mother. I wish to say how very much I appreciate this very kind gesture on the part of all these above-mentioned devotees, in having taken so much trouble in order to be graciously present to see me off. My many thanks also to the various kind devotees, who presented me with gifts of personal utility on the eve of my departure. Among them I must mention Sri Atmaram Nagarkarji Maharaj of Poona (father of Sri D. Nagarkarji of Sivanandashram) who had sent a Thermos Flask and a set of stainless steel vessels for my daily use specially monogrammed with my name in Hindi. I am grateful to him for his thoughtfulness and to others too, who gave their kind presents In this connection I should not fail to mention the excellent gifts of free literature printed and presented to me by certain good friends for free distribution during this tour. The literature lovingly offered is firstly by Mr. Manchandani of Nilam Printing Press, Lajpat Nagar, New Delhi and Sri M.M. Massand, D.L.S. Lody Colony with the help of Sri A.D. Sharmaji, 74 Rabindra Nagar, New Delhi, 1000 copies of the booklet ‘Key to World-Peace and Happiness’ containing teachings from the main great Religions of the World, compiled by Gurudev Swami Sivananda (culled from a former similar booklet printed by Sri Gamadas of Sri Vidya Press, Kumbakonam, Madras State under the title “Unity of Religions”), the Universal Prayer with border, 20,000 copies of book marks, Divine Life for Children and art cards containing spiritual teachings on one side and the prayer on the other. Secondly, by Dr. Sivananda-Adhwaryoo big sized framable copies of Universal Prayer in Gujarati version and English version separately, with beautiful border and the Divine Life motto Serve, Love, etc. 1000 copies. Thirdly by Sri Raviraj Bhalla of Janta Press, Connaught Place, New Delhi similar framable Universal Prayer on large sized card and some small sized cards containing an inspiring paragraph of spiritual sentences. I am very specially grateful to the gracious persons responsible for the above-mentioned gifts. God bless them. Besides these, the Ashram press has also kindly contributed its item to this free literature in the form of an art card with a spiritual message on one side and the Universal Prayer on the other. Sri Swami Dayanandaji and Sri Narasimhuluji of the Y. V. F. A. Press were kind enough to expedite this work and get it ready in time before the departure date. While writing this on board the ship, it is 4 p.m. and the sea is clam and there is a brilliant sunshine outside. Letters from South Africa to India seem to take about 8 days in reaching Rishikesh even when sent by Air Mail. Thus, this is likely to reach Sivanandashram in the later part of May for being sent to press with the Divine Life matter for its current June issue.
131
HEARTY SEND OFF FROM BOMBAY AND WARM RECEPTION AT THE DURBAN SIVANANDA ASHRAM
At this point, in the middle of the present year 1968, I would wish to urge you all once again to remember two important Yajnas being undertaken by Sivanandashram. These have been announced earlier in the Jan. and Feb. ’68 issues of this journal to which I draw your attention again now. They are (a) Jnana Yajna Project and the (b) Maha-Mantra-Koti-Likhit Japa Yajna. The former will be found in the outer cover of the January issue. It is a special Yajna instituted last year (September 1967) under the auspices of the 80th Birthday Anniversary of Sadgurudev. The reprint of 5000 copies each of the two important books “Practice of Yoga” and “Conquest of Mind” is the objective. These two are invaluable major works of Sri Gurudev Swami Sivanandaji Maharaj of inestimable value to all the Sadhakas on the path of Yoga. The latter Yajna, namely, the Maha-Mantra-Koti-Likhit Japa Yajna is under the holy auspices of the Akhanda Maha Mantra Kirtan that has been going on since 1943 December. The writing of 3½ crore times Maha-mantra is the Yajna and its purpose is universal welfare, peace and progress of mankind towards a life of Dharma, unity and spiritual fellowship. Wonderful response from numerous quarters has been forthcoming towards this Likhit Japa Yajna. I would suggest that all devotees throughout India and abroad should join together and contribute and construct a special room to be termed Divya-Nama-Mandir wherein all the holy Likhit Japa received will be carefully preserved and reverently worshipped as Chaitanya Shakti of Satchidananda Parabrahman. I have not thought of the details of the design but this idea to befittingly enshrine the sacred Name has occurred to my mind and this I have placed before you for your active consideration and early action. Big contributions are not necessary. If a great number of people take part in this work even a small contribution of 50 paisas per person or one rupee per head will enable the construction of a suitable Nama Mandir. If the campaign is not extended to a great number of people but if it is confined to a limited number only then there arises the need for comparatively bigger contributions. However that be, it would be in the fitness of things if this construction is completed as early as possible, to be declared open on the auspices of this sacred Silver Jubilee. Otherwise the Likhit Japa received from numerous quarters is likely to be placed in different places due to want of a central place. It is my earnest desire that the sincere and devout efforts of countless seekers and Sadhakas do not go in vain. That should be befittingly perpetuated in the form of permanent collection of this most sacred Nama Yajna. To all readers I would like to mention here that our Ashram (D.L.S. Hq.) has agreed to actively coordinate with the efforts of the Tehri-Garhwal District Leprosy Relief Association in its work of reorganising the Brahmapuri Leper Colony and putting it upon a stable financial basis. We have decided to co-operate in this work upon the special request of the above association, which is facing difficulty in carrying on its work. I therefore request all those who have a special interest in helping the cause of our brothers afflicted with this disease to make special contribution towards this work. They may be sent to Sivanandashram, Rishikesh in the name of the “Divine Life Society” P.O. Shivanandanagar, Dt. Tehri-Garhwal, (U.P.), with separate covering letter to specify the purpose of this remittance. In case you send your contribution by M. O., then please do not mix up, specifically earmark for this purpose alone. List of the contributions received each month will be published in the “Divine Life” Magazine of the subsequent month. This is a noble cause and all must help. In this connection I must certainly acknowledge with deepest gratitude the very loving contributions graciously being given by the kind-hearted mother Mrs Banoo Ruttonjee, Sri
132
ADVICES ON SPIRITUAL LIVING
Dinshaw Paowalla, Mr. & Mrs. B.N. Kaul and a couple of others, towards relief of the lepers in the locality. Before I conclude, I must tell you of the blessed moment when the ship drew alongside the pier at Port Natal (Durban Harbour) and I had the Darshan of the worshipful Sri Swami Sahajanandaji, Gurudev’s favourite spiritual child and spiritual representative in South Africa and all the most blessed souls assembled at the quay side to receive this servant. After going through the formalities of Immigration, Sri Swami Sahajanandaji personally came up into my cabin before I came down from the ship. We were meeting after 4 years and my joy was great. We sat for a couple of minutes of brief Satsanga offering our prayers to Sri Gurudev and to the Almighty Lord. We then went down to the assembled devotees patiently waiting since forenoon for the ship’s arrival. There was joyous exchange of greetings, feelingful welcoming and devoted offering of beautiful carnations wreathed into Malas. We then had a little Kirtan and prayer right there on the pier and were soon speeding towards the Ashram in a car brought by devotees, with all our luggage following in the Divine Life Society-van. Half an hour’s drive through the city brought us to its outskirts to the area known as the Reservoir whereupon a breeze-swept hillock stands the Sivanandashram. Down in the valley beside the Ashram flows the Umgeni river, our local Ganga here. It is wonderful to be at Sri Gurudev’s Ashram in this land 6000 miles away from Sivanandanagar. I felt like arriving at home. After sitting out for a while with devotees, who were awaiting there, I rested for a little while and proceeded to the spacious Prayer Hall for an evening Satsanga, when I conveyed to all assembled devotees the affectionate good wishes and greetings of all my Gurubandhus of Sivananda Ashram, Rishikesh. Thus at last I was amidst these wonderful, devoted and dedicated children of Gurudev in this far-off land. I do not yet know what programmes await me here but you will know all about it in next month’s South African letter. The season of Satsangs and holy Yatra had already commenced at Rishikesh and nearby even before this servant had left Gurudev’s abode. Now they must be in full swing in all the important institutions like Gita Bhavan, Paramarthaniketan, Swarg-ashram etc. This is the period when you can see the dynamic spirituality that actively fills this blessed area of the sacred Uttarakhand. Kirtans and Bhajans, prayers and spiritual practices, devotional gathering and discourses, reflection and meditation go on apace from morning till evening. Countless aspirants come from distant parts to renew themselves spiritually and to nourish their inner self with the nectar to be obtained in the blessed Satsangas that specially abound here during this period. The real inner India and the undying soul of Bharatvarsha is glimpsed here and you come face to face with a living culture that has braved many a storm and withstood the vicissitudes of time. As this letter reaches your hand many a thousands of your brethren of Bharata would be high up in the Himalayas rejoicing in the thrilling Darshan of Lord Badrinarayan and Kedarnath Shiva, in their remote shrines situated in the region of the snow-clad peaks of the Himalayas. Blessed seekers! wherever you are, may your life be rich with such Satsanga and Darshan. May your life be filled with worship, devotion and spirituality and ever be blessed with the awareness of Divine Presence. May your body mind and personality be a veritable holy Uttarakhand filled with purity, spirituality and God’s Presence. May your inner self ever be seeking to be united with Divine Reality. With regards, Prem and Om Namo Bhagavate Vasudevaya, June, 1968 Yours in Sri Gurudev —Swami Chidananda
133
SIVANANDA’S MISSION SPREADS ACROSS THE OCEAN
Sivanandashram Letter Nos. LIV & LV
SIVANANDA’S MISSION SPREADS ACROSS THE OCEAN
Worshipful Immortal Atman! Beloved Seeker after Truth, Om Namo Narayanaya. Salutations to you all in the holy name of Sri Gurudev Sivananda, to whose feet we have offered our heart’s adoration and devout worship upon the holy day of Gurupurnima and the sacred Anniversary of his attaining to the Eternal. May the light of his teachings ever illumine life’s path for you and may his sublime spiritual message of Divine Life inspire you to walk the noble way of truth and purity, of love and goodness and of service, worship, meditation and God-realisation. May Guru Kripa ever abide with you. Last month I failed to communicate with you through this monthly letter and for this, you must pardon me. The matter for July Sivanandashram Letter got delayed in the post. Through the letter I had wanted to inform you that though away in South Africa I would yet participate in the holy worship of both the sacred days by conducting them here at the Sivanandashram, Durban. I am happy to inform you now that the Gurupurnima day was befittingly observed here with a full day programme of early morning prayer and meditation at 5.30 a.m. (it being mid-winter here now), forenoon Satsanga with Guru Padukapuja at midday, afternoon Sadhana hour at 3.30 p.m. when we read the Brahma Sutra Bhashya and a glorious night Satsanga with Kirtan, Bhajan, discourses, music etc, from 6.00 p.m. to 10.00 p.m. which concluded with a showing of movie film taken at Headquarters Sivanandashram, bringing Gurudev’s glorious Darshan to the huge audience on that blessed day, and surprisingly enough the movie included a scene of Padapuja actually being offered by a batch of devotees to Gurudev in his Kutir. Thus was Gurupurnima. My stay and tour of visits to Divine Life Branch Centres in different places in this country have been verily a revealing experience to me. I have been inspired to behold the depth of devotion people here have for Gurudev and the boundless faith they have in him. I marvel at the phenomenon and wonder at the way in which Sri Gurudev living in a small under-ground-cellar like room by the Ganges’s Side in remote Rishikesh has yet reached out through his Satsankalpa and his lofty labours into this distant land and brought the light of Divine Life into countless homes here, inspiring people towards Dharma, Yoga and Bhagawad Bhakti. Their Guru Bhakti is exemplary and I feel humble before the living quality of the faith of these devotees in Gurudev, his holy name and his unfailing grace. It is thus that the spiritual mission is progressing across the ocean in such a far distant land through the miracle of dedicated work by the South African disciples of Sri Gurudev. My adorations to these noble souls, who have spread the light of Divine Life and Sanatana Dharma and Yoga in this land. Long may the light of Gurudev’s spiritual gospel continue to shine in this land and throughout the rest of the world, too. It is gratifying to note from some of the correspondence received from India that quite a number of D.L.S. Branches in India have taken the observance of Gurudev’s sacred Mahasamadhi Aradhana in a very befitting manner with suitable religious programmes. In doing this some of them have remembered to place the necessary emphasis upon Gurudev’s Jnana Yagna mission and
134
ADVICES ON SPIRITUAL LIVING
thus have arranged to bring out very useful and valuable publications. Among such I may mention the Pattamadai and Rasipuram Branches and Bangalore and Mysore Branches. At the time when you receive this letter you will all be looking forward to a month full of very auspicious and inspiring celebrations of different kinds. Already you would have finished observing the important Birthday Anniversary of Sant Tulasidas who blessed India with his immortal work, the holy Ramacharitamanas. The many-sided ideal of Lord Rama’s exemplary personality has been brought close to the vast masses of common people by this boon conferred upon India by Sant Tulasidas. Lord Rama is enshrined in countless thousand of hearts today due to Sant Tulasidas. He has made the Ramayana a living force in a great part of India and thus endeared himself to the laymen, who know no Sanskrit. Sant Tulasidas is a benefactor of the nation. An important religious Anniversary falls on the 8th. It is the Upakarma Day when millions in the nation will rededicate themselves to the sacred Gayatri Mantra. It is a day for the renewal of the sacred thread and for Gayatri Japa in a special way. Brahmacharins and Grihasthas alike are reminded of the vow of triple self-control. They resolve anew to turn towards the light and worship wisdom in their quest for illumination. On the 15th, while the entire nation will celebrate the advent of Lord Krishna, our beloved members in Maharashtra will observe in addition a similar anniversary i.e. the Jayanti of Sant Shri Jnaneshwar Maharaj, the bestower of the immortal work Jnaneshwari Gita. The last day of the month is Sri Radhashtami dear to the lovers of Sri Krishna and the Vaishnava devotees following the path of Prema Bhakti. Blessed Mother Radha shines as supreme embodiment of total self-effacement in an all-absorbing love of the Lord. Fervent hearts will thrill with inspiring and intense devotion MA RADHE. The holy village of Barsana will be turned into heaven upon this blessed day. I shall leave you all to this wonderful month of August by bidding you Om Namo Bhagavate Vasudevaya. May you be steeped in the pure bliss of the Lord’s Name and of Divine Krishna Prema. May you ever abide in the peace and light of the Lord’s Divine presence. With kind regards, Prem and Om, Yours in Sri Gurudev 1st August, 1968 —Swami Chidananda
135
SIVANANDA’S BIRTHDAY MUST BE A DAY OF RETROSPECT AND SPIRITUAL REASSESSMENT AND SELF SCRUTINY
Sivanandashram Letter No. LVI
SIVANANDA’S BIRTHDAY MUST BE A DAY OF RETROSPECT AND SPIRITUAL REASSESSMENT AND SELF SCRUTINY
Worshipful Immortal Atman! Beloved Seeker after Truth, Greetings in the name of Sri Gurudev. Om Namo Bhagavate Sivanandaya. This letter brings to you my heart-felt spiritual good wishes on the eve of the sacred SIVANANDA JAYANTI. The 8th of September is a day that shall ever be regarded by countless thousands of souls as a supremely blessed and auspicious day because it gave them that great and noble saint who brought a new awakening into their lives and whose teachings came as a great shining light to illumine their path towards Divine peace and blessedness. To all Gurudev’s disciples the 8th September is a great day, which gave to them their spiritual Master, Divine guide and loving saviour. May this Sivananda Jayanti now bring into your hearts the Illumination, Realisation and the Divine bliss and Wisdom that is Gurudev. This Divine Light and Wisdom which enlivened the outer from of Swami Sivananda is the Eternal Gurudev, who has never ceased to be and who now is enshrined in your heart as a light within at every moment. Whenever you move and act upon the lofty principles of Divine Life, then and there is Sivananda born anew into your life. To walk along the holy path of truth, purity and universal love is to celebrate his Birthday. To practise selfless service, devotion to God, daily meditation and enquiry into the nature of Reality is verily a perennial Sivananda Jayanti. Gurudev lives in all and is ever born afresh in all those, who are practising and perpetuating his gospel of Divine living. Gurudev is Divine Life. He is in Divine Life. Divine Life is rooted in him. He lives vibrantly active in those, who earnestly strive to live in the spirit of his sublime spiritual teachings. May God give us the strength and inspiration to make Gurudev a living force in this present-day world, where the crying need is idealism. Gurudev is personified idealism in a living way. May His Birthday impart a fresh and vigorous impulse to your aspiration towards an ideal life of virtue and spiritual quest. This is my special prayer to the Almighty Lord upon this holy Anniversary of Gurudev’s earthly birth. May his life shine for ever. May every day, each sunrise see “Sivananda” being born anew in countless thousands of hearts and countless lives everywhere in the world in the form of ideal daily life. Let each rising sun see the lotus of Divine Life blooming out in the hearts of Gurudev’s innumerable disciples and devotees the world over. Thus may the beauty of the Divinity within manifest in this world as Auspiciousness and Bliss. SIVANANDA. Beloved Atman! the essence of life is the fulfilment of the duty that stands before you. It is the proper doing of that which requires your attention at this moment. Reflecting too much about the future, speculating too much about the future are deceptive processes that deprive you of the present, which is in fact the only true time that you have got. Now is what you have. Recognise this vital fact about life and be wise. Be up and doing on the path of virtue and actively fulfil Dharma and move towards perfection. It is not to say that forethought and intelligent planning are useless
136
ADVICES ON SPIRITUAL LIVING
and to be discarded. But the point is while you exercise forethought and you are planning, at the same time be up and doing in the present. The planning has its place but it is not a substitute for action in the Now! They are to be carried on simultaneously. Action initiated is by itself the valuable factor that points out the lines on which the right planning is to be done. Learn to live in the NOW. Recognise the value of the Present. Money that has been lent away to another, time that has been allowed to go by and become the past,—these two will not be available to you when need for them arises. Let not fanciful tomorrows rob you of the most important today. Strive to make each day as perfect as you can. Live each day ideally and fill them with spiritualised activity. Do this and your future will be safe and contain a harvest of blessedness for you. There is no need to unnecessarily keep waiting for some wonderful opportunity or extraordinary opening to prove your worth to God or man. No need to keep on thinking and speculating what your true work or life’s mission is, or how you can commence a task in the most proper way and do it in the best manner it can be done. The important thing is to take circumstances as they are and start doing the thing that is before you to do. As you are, as things are now, do what you can here. If you do this, God will open up new avenues for you and take you towards bigger and better tasks. For He has seen, is seeing that you are DOING what He has already put before you in life for your hands to do. Use what opportunities you have. Do not wait for imaginary opportunities to present themselves. You are where you should be. What you have to do that verily is given to you. Therefore, where you are, there do what you are called upon to do. Longing for great achievement is all right. But working for it is the very essence of its ultimate attainment. And this working is neither done in the past nor done in the future. Work is only done NOW. This is the truth. Recognise this and you make your life a success. In spiritual life and in spiritual evolution it is the little things in every day life that have tremendous importance. It is through doing little things in an ideal way day after day, that one ascends the spiritual way up towards perfection. To forget little things of every day life and await for some great opportunity and keep preparing for some unique and tremendous act is a great Maya which deludes and leads astray many really sincere seekers and aspirants. They are deceived by their own mind. The ordinary little things of your day-to-day life, by their very littleness begin to seem insignificant and thus they fail to arrest your attention and thus you lose the hundred golden opportunities that you daily come across hour by hour and minute by minute on every side. Be aware of this. Remember! myriad tiny strands they are that go to make up a mighty strong rope. Every day, all day long, through the years, use every little opportunity moment by moment in your ordinary life. This is the essence of Yoga. This is the secret of attainment. This is the key to progress and success. There is a wise Sanskrit saying, “By the falling of drops of water the pot is gradually filled up. In the same way verily is it the case with wealth, with learning and with Dharma, too”. Precisely thus indeed your spiritual life also. On a little hillock stands this Durban Sivanandashram of the Divine Life Society of S. Africa, from where Chidananda sends you this letter. About a furlong away down the slope of this hill flows the river Umgeni which I have named as our local Ganga. We have been having very strong winds from the interior which herald the approaching summer season. Winter has started to take leave. In India the fierce summer would have given place to the monsoon rains. At Rishikesh the holy river Ganga must be in floods, reaching the upper banks of Muni-ki-reti and Swargashram with its rushing torrent. She was always the beloved Mother to Sri Gurudev and doubtless she has
137
SIVANANDA’S BIRTHDAY MUST BE A DAY OF RETROSPECT AND SPIRITUAL REASSESSMENT AND SELF SCRUTINY
risen close to the verandah of our holy Master’s Ganga-Kutir. May the Grace of holy Mother Ganges grant you all long life, health, happiness and highest spiritual blessedness. Mother Ganges is verily an aspect of Divine Mother Para Shakti Herself. She is a visible manifestation of Mother’s sin-destroying, life-purifying and liberation-bestowing power of Adi-Shakti. The holy Ganga is Vidya-Maya manifest in tangible from in this world of ours. Glory to the Mother. Blessed are those who are privileged to live on her holy banks. Their lives will be crowned with Divine Illumination. The auspicious worship of the Divine Mother is to take place in this very month. During the quarter of a century, that this servant has had the privilege to live at Gurudev’s sacred feet, he has rarely missed the annual Navaratra Puja. This time, however, Gurudev has wished my presence in another part of his spiritual estate. Very many Hindus here in S. Africa are Devi worshippers. They all observe the Navaratra Puja. Beloved Sadhakas, pray fervently to the Divine Mother Durga to inspire you with inner spiritual strength to progress onward upon the spiritual path with courage, wisdom and firm determination. Observe strict discipline during the entire period of the Puja, from September 23rd to the 30th. Get up at 4 a.m. in the morning, take bath and sit and do Japa of Mother’s Name. Glorify her through Stotras and Bhajans. Pray fervently from the bottom of your heart. Ask her the boons of discrimination dispassion and true devotion. Pray to her to bless you with a pure character, ideal good conduct and the grace of Divine Life. Seek from her the strength to control your senses, conquer desire, curb the egoism and stick to the vows of truth, purity and loving kindness into all beings. Observe partial fast (taking only milk) throughout the day and break your fast at sight only after worshipping the Divine Mother. After Puja take only some very light, pure diet as her Prasad. Sleep only six hours at night. Look upon women as veritable manifestations of Divine Mother. Take the vow of adhering rigidly to the great Eka-patni-vrata. Let the Vijaya Dasami day see triumph victoriously over all unspiritual Samskaras, sinful tendencies and wrong habits of the past. Be gloriously reborn into shining new light of spiritual purity, sublime idealism and lofty Divine Life of Yoga and Vedanta and highest Dharma. Become for ever established in discipline, austerity, self-control and spiritual practice. Strive towards a worthy ideal and ever more towards the Supreme Goal. May the blessed Divine Mother shower upon you her abundant Grace and grant you peace, bliss and immortality. Jai Bhavani. This beautiful country, half a century ago, gave to India a transformed and inspired Mahatmaji (Bapuji) who came to Bharata as an apostle of freedom and a friend of the masses, converted by the lofty life and the stirring teachings of Leo Tolstoy and John Ruskin to a life of simplicity, service and sacrifice. The youthful patriot returned home as a saviour to dedicate himself for the emergence of Svatantra Bharata. His noble life, his idealism, his selfless dedication and patriotism shine as great example for the people of India today. The youths of India must turn to his great life and inspiring example if they really would be worthy sons and daughters of Bharatavarsha. The nation is preparing to pay homage to his memory at the centenary of his birth, next year. The whole of India, young and old, rich and poor, non-officials and officials, will take a pledge to walk in his footsteps and to carry out his ideals and this should be the most important feature of observing his sacred Birth Centenary. On a nationwide scale, everyone must take up the devout
138
ADVICES ON SPIRITUAL LIVING
study of his Autobiography (My experiments with Truth). Study circles must be formed everywhere for this purpose. All must purchase a copy of this book immediately and commence reading. The Nav-Jeevan Trust could do well to bring out an easy and simplified, abridged edition of it for young folks to read. From October this year a great movement must be set a foot to fill people with Gandhi-consciousness all over the country. All journals must join hands and help in this task. His 18-point constructive programme should receive countrywide attention. Earnest leaders and other persons must approach the holy Acharya Vinobhaji and request for his guidance and advice as to how best Bapuji’s Centenary should be observed and his advice must be heeded. The holy memories of his noble life rose up before my mind when I went on a humble pilgrimage to the Phoenix Settlement here, near Durban, which he founded in 1904 and when he lived a simple life of service and formulated the concept of Satyagraha and published the Newspaper “Indian Opinion”, this simple wooden cottage set in the country-side and surrounded by farm land is still preserved as it was during his time. There were no cots. Gandhiji and his children slept on the floor. His daughter-in-law (his son Manilal Gandhi’s wife) received us courteously and we were shown round Pujay Bapuji’s cottage. Many old photographs are there which recall long by-gone events and occasions. Gazing at them one is transported into an era of courageous idealism, towering moral stature, real greatness and far-sighted wisdom. I was thrilled to find in one of the rooms a series of unform paintings placed in a row along the walls, each painting depicting visually the central meaning of each line of Sant Narsibhakt’s well-known Gujarati song “Vaishnava jan to tene Kahiye”. The full text of this song itself appeared in bold script by the side of the first picture in the series. Upon enquiry I learnt that it was probably purchased by Mrs. Manilal Gandhiji. Phoenix Settlement still carries vibrations of peace, spiritual beauty and serenity of Gandhi’s spiritual personality. This visit was memorable. May his life and lofty example be to our country as a great shining light to guide its people along the upward path of honour, dignity, virtue, truth and purity. Before closing let me appeal to each one and all of you individually and collectively to prepare to observe Pujya Mahatma Gandhi’s Birth Centenary year that is close approaching. Please commence this task from the 25th of September, one full week in advance of Bapuji’s Birthday on 2nd October. Draw up a yearlong programme of silent, yet ceaseless activities to bring about a total revival of Bapuji’s teachings and the Gandhian way of life throughout the length and breath of Bharatavarsha. Herein lies your supreme welfare and the future good of the nation. Flood the entire country with the light of Gandhi-Vad. This is the special duty of the youth of India. Let Yuvak Bharathi wake up to this noble task awaiting them now. God bless you all! Jai Sri Gurudev! Jai Bapuji! Regards and Prem, 1st September, 1968 —Swami Chidananda
139
GANDHIJEE—PERSONAL GOSPEL OF DIVINE LIFE
Sivanandashram Letter No. LVII
GANDHIJEE—PERSONAL GOSPEL OF DIVINE LIFE
Worshipful Immortal Atman! Beloved Seeker after Truth, Om Namo Narayanaya! Loving salutations in the name of Sri Gurudev and Mahatma Gandhi, the Father of our Nation who dedicated his entire life to an attempt to re-establish the ethical ideal in the life of the people of our country. The period from 2nd October, 1968 to 2nd October 1969 is verily a hallowed 12 months, for it will constitute the Gandhi Year. It is a blessed year marking the centenary of this truly Great Soul’s advent upon earth. To me this Gandhi-year really signifies a Rama-Nama Year as well as a year of Truth speaking, Promise-Keeping, Self-Searching, Fasting and Praying and Selflessly Serving. To me all these mean Gandhiji. He also means to me unfailing daily prayer, deep love for India, an identification with villagers and their villages. He also means self-control, moderation, rejection of chemical drugs and trust in Nature. To follow these ideals that he embodied and practised in his life is the most essential and indispensable part of this Centenary celebrations. May God inspire each son and daughter of Svatantra Bharatavarsha to turn to Gandhiji as a guiding Light in the path of the nation’s onward march. Enough has India suffered by rejecting the Gandhian way of life. Let the country’s main task in the observation of this Gandhi Year be a restoration of the Gandhian way to its right and proper place in the life of the nation which seems to revere Gandhiji but does not heed his golden teachings. Here is now an opportunity to set right this error and accept the Wisdom Light of his teachings back in to people’s daily life. This is the nation’s chance now. Sri Gurudev Swami Sivanandaji had great admiration for Mahatma Gandhiji. He held him in high veneration and concurred with his ethical teachings. Gurudev considered Bapuji as the foremost exponent of Nishkamya Karma Yoga in this age. Referring to him Sri Gurudev has written, “Study the autobiography of Mahatma Gandhiji. He did not differentiate between menial service and dignified work. Scavengering of the latrine was the highest Yoga for him. This was the highest worship for him. He himself had cleaned the latrines. He had the science of Pranayama, meditation, abstraction, awakening of the Kundalini, etc. They were disappointed when they were asked to clean the latrine first, and left immediately. Gandhiji himself did the repairing of his shoes. He himself used to grind flour and would take upon his shoulders the grinding work of others also, when they were unable to do their allotted portion of work for the day. When an educated person, a newcomer, felt shy to do grinding work, Gandhiji himself would do this work in front of him, and then the man would do the work himself from the next day, willingly.” Sri Gurudev regularly sent each and everyone of his books to Gandhiji, whenever it was printed. The Divine Life Magazine and Gandhiji’s Harijan Magazine were in exchange. Towards the closing period of his life, Pujya Bapuji had a desire to spend sometime in silence and seclusion
140
ADVICES ON SPIRITUAL LIVING
quietly in Uttarakashi. His well-known secretary, beloved Sri Mahadev Desai, came to Uttarakashi to personally inspect the place and fix up a suitable hamlet for Gandhiji. Sri Jugal Kishore Birlaji undertook to provide facilities and accommodation, in the Himalayas. Sri Mahadev Desai came to Sivananda-Ashram to consult and get advice from Sri Gurudev in this connection. Pujya Gurudev endorsed this idea and heartily recommended that Gandhiji should certainly avail himself of such Ekanta. But, alas, his work among people so claimed him that he was never able to fulfil this inner urge for silence and seclusion. In the year 1946, this servant had the unique blessedness of having a private meeting with Bapuji when I went as an emissary of Gurudev taking with me a set of his books as a present to Gandhiji and conveying his greetings, love and good wishes. It was in New Delhi in the summer of the year 1946 and I was a junior Brahmachari of the Ashram and in my 29th year. Gandhiji was then putting up at the Bhangi Colony at the northern end of Reading Road (now Mandir Marg) where it met the Panchkuye Road. At 2.30 p.m. on a torrid June day, I went into his presence inside a thatched mud-hut, where he was resting on a long wooden plank, with a moist towel round his head. I salutated him placing my forehead at his feet. Bapuji made kind enquiries about Gurudev and remarked that he was receiving all valuable books by Swamiji. When I presented the bundle of books, he had the bundle untied and took up and glanced through each one of the eight or ten books I had taken with me. He knew of the work of the Divine Life Society and voiced his warm appreciation. I sought his blessings for my spiritual life. Bapuji replied that I was already blessed that I had the good fortune of the guidance of a holy saint like Swami Sivanandaji. And he added, “May the Almighty grant you His Grace in your quest.” While departing I asked him for a message to Gurudev. He replied, “What message can I give? Swamiji’s message of spiritual living is inspiring thousands all over the world. We need such good work, Please convey to him my Pranam.” While saying this Gandhiji brought his palms together in Namaskar. I took leave giving place to other visitors waiting outside. That was the last time I saw him. During the week before this interview I attended Bapuji’s evening prayer meeting on two days. Bapuji was a Karma Yogin, a devotee of stupendous faith and a saintly man whose depth of humility has left an indelible impression upon this servant. Gurudev beamed with affection and joy when I narrated about this meeting with Mahatma Gandhiji and about what I felt in his presence. Subsequently, Bapuji did send a brief message to Sri Gurudev. I read regularly all Bapuji’s writings appearing in the Harijan. I also read ‘the Unseen Power’ compiled by Sri Jeg Pravesh Chandra, “Gita the Mother”, “Self-restraint vs. Self-indulgence” and such other books of Gandhian teachings. The little book of prayers and Bhajans, the “Ashram Bhajanavali” has ever been a favourite book of mine. In the December of 1947 I was physically ill during the Autumn material season. Sri Gurudev sent me and Gurubhai Sri Swami Visveswaranandaji Maharaj to Nagpur in Central India for medical treatment under a pious doctor-devotee, Sri B.A. Vaidya. He had his clinic at Dhantoli and was a highly respected honorary physician in the well-known Mayo Hospital of Nagpur. He got me admitted there for treatment and while at Hospital, the sudden shocking news of Bapuji’s passing away reached us there on the hospital radio. The entire hospital staff was stunned. I remembered they had a prayer meeting to which I was called though I was a patient there. You will note that between the Divine Life Society’s cardinal principles and Gandhiji’s own ethical principles there is a complete identity. Both Gurudev and Bapuji insisted upon
141
GANDHIJEE—PERSONAL GOSPEL OF DIVINE LIFE
Satyam-Ahimsa-Brahmacharya as the indispensable basis of the Good Life and the very essence of Sadachara. They gave to character the highest place in human values. Moral principles and ethical conduct came first in the teachings of both of these great sons of modern India. Thus Ahimsa, Satyam, Brahmacharya and prayer, selfless service and practice of the Divine Name constitute the identical fundamentals of both Gandhism and Divine Life. These also comprise the very basis of Gandhiji’s and Gurudev’s personal life. May God give unto all the children of Bharatvarsha the inner strength and aspiration to practise these great precepts and live a life according to these principles. May the sublime memory of Gandhiji’s life and teachings inspire you to grow into an ideal person and fulfil the sublime pattern of the Good Life. Glory be to Mahatma Gandhi. May you all join whole-heartedly and work earnestly to celebrate this Gandhi Year in a worthy, dynamic and effective manner. I wish you every success in this immediate noble task which is the duty and the privilege of every Indian. There is a unique significance in the occurrence of the holy Vijayadashami day (Dassera) on 1st October, just one day before the 2nd October which inaugurates this Gandhi Centenary year. The Divine Mother’s victory over demons or Asuras is not to be regarded merely as a long bygone event in some remote mythological age in the forgotten past. If, year after year this annual Vijayadasami day just means the memory of some fossil event of the distant past, the observance would be meaningless and quite devoid of a currently dynamic content. This is not so. It has a vital implication for today, and for here and now, to us. This day is meant as a day of dynamic reassertion of our firm faith in the power and ability of the higher forces in man to overcome and subdue the baser instincts and urges of the lower self in human nature. This day is meant to provide scope repeatedly for man and the world to correct themselves and recover their lost ground and forge ahead in their progress towards idealism. It is a day of hope, of renewed self-confidence and fresh efforts to establish the rule of righteousness in your heart. Let the significance of the close association of Vijayadasami and Gandhi Jayanti this year be well recognised. Conquest of evil must be followed with the practice of good. May the Indian nation as a whole enter into a glorious new day of moral awakening and ethical progress under this sublime auspices of Mahatma Gandhiji’s Shatabda Samvatsar or Centenary Year. May the muck and darkness of untruth and impurity in private and public life, in individual and collective life, now vanish and give place to the good life of truth, purity, nobility and morality. Thus, may you all people of good-will join hands from the Himalayas to Kanya Kumari, from Assam to Punjab in heralding the advent of the real Divali. Prepare thus for the coming Festival of Lights and worship of the Divine Mother Mahalaxmi, the Goddess of auspiciousness and blessedness. May She Shower Her Grace upon you all. You are surely contributing Mantra writing to the Mahamantra Yajna on 3rd December. I urge you all to contribute the maximum possible quota of Likhita Japa towards this spiritual undertaking. Ever since I made known this Japa Yajna project to the devotees in South Africa more and more people have commenced the Mantra writing. During my ten days’ stay in Johannesburg in August, the devotees there already put a quota of 80,000 Mantras before I left them. They will be sending the Japa Sankhya direct to the Ashram in the 3rd week of November. I call upon you and all your family and friends to vigorously carry on this great Likhit-Japa Yajna. There is a special reason for my saying it. Different Yugas have their distinct Sadhanas for attaining God. Thus what used to be attained through penance, ceremonial worship and meditation in the previous Yugas is now attainable in this present age through the practice of the Divine Name. Nama-Sadhana is Yuga Dharma in the spiritual field in Kali Yuga. In the various forms of Nama Sadhana like Japa, Kirtan,
142
ADVICES ON SPIRITUAL LIVING
etc. Likhit-Japa has a very important place. It effectively brings the concentration of mind by binding down the practitioner’s total attention in this unique integrated process of the Mantras to the accompaniment of audible repetition of the same. Practise it and experience it for yourself. You will see the amazing effects it has of arresting the wondering mind and giving you peace and concentration. Move onward. Time does not stop. Life hurries by. You must be active in spiritual life as the minutes and hours fly past, as days and months flow by and as the years roll on. You must progress onwards and ascend higher and higher towards the pinnacle of Divine Perfection. Attain this glorious destiny. You are born for it. May your days be filled with Light. With calm resolution, with bright hopefulness and with cheerful boldness proceed without pause upon the blissful path of spiritual life. In joy move forward, in joy carry on Sadhana. Attain supreme Joy. Before I conclude let us offer salutations to the noble Bali Chakravarti, who is a supreme example of the highest and the ultimate Sadhana of Nava Vidha Bhakti, namely Atmanivedana. Bali Chakravarti’s greatness called forth the advent of the Lord as the Divine Vamanavatara. In this form the Lord accepted the supreme self-offering of the great king Bali Chakravarti. On the 22nd of this month numerous devout people worship king Bali of hallowed memory. We also salute the illustrious sage Yajnavalkya; this month ends with the birth anniversary of this greatest Jnani of the Upanishadic era. I shall now leave you to look forward to the solemn six-day worship of Kartikeya Bhagavan during the period of the annual Skanda Shashthi Puja. May the blessings of the resplendent Siva-Kumara, who is Wisdom and Divine Power personified, bestow upon you fullest success in spiritual life and grant you bliss, peace and immortality. I pray for the welfare, prosperity and happiness of all beings in the entire universe. Om Sri Sharavanabhavaya Namah. With regards, Prem and Om, Yours in Sri Gurudev, Swami Chidananda
1st October, 1963
Sivanandashram Letter No. LVIII
GURU NANAK—WORLD AWAKENER OF MODERN AGE
Worshipful Immortal Atman! Blessed Seeker after Truth, Om Namo Narayanaya. Salutations and greetings in the name of Gurudev Sivananda. May the inspiration of Gurudev’s sublime spiritual teachings impel you ever onward upon the shining path of virtue, noble character and moral perfection. Let Gurudev’s call to spiritual life take you onwards towards the goal of God-Realisation. Ethical living and spiritual striving constitute the very soul of Bharatavarsha. These two indicate the very essence of Indian culture. Take these two away from your life, then life becomes essenceless, meaningless and useless. Without these two factors the Indian Nation and the Indian Culture will be dead things. Remember this and be
143
GURU NANAK—WORLD AWAKENER OF MODERN AGE
awakened and alert. Lose not these laving principles of India’s existence. Keep them alive. Help to propagate these all over India, throughout the country. Last month I shared with you my thoughts about the great soul, Bapuji. I tried to define Mahatma Gandhiji’s personal Gospel of the Good Life. This wider teachings of National awakening and progress was also touched upon in the previous letter. This month it is the Lord’s wish that I say something about our country’s concept of ideal womanhood. A true lady, in the view of the Indian culture, is an embodiment of virtues. Modesty and chastity are the basic qualities of the Bharatiya Nari (Indian woman). Purity of character was indeed the very life of the true Indian lady. The great ideal before the Indian woman is undoubtedly the lofty ideal of Pativrata Dharma. This meant the chaste wife’s total loyalty and fidelity to her husband whom she must love, revere and serve with deep devotion, looking upon him as her visible God. Except her husband there is no man existing for her. All men in the universe she regards as her children, feeling herself to be the mother of all humanity. For, in Bharatavarsha the woman is primarily glorified as the Mother and not as the wife. Her wifehood is but the concern of only one individual in the whole world and that is her lawful wedded husband, the Patidev. To the rest of mankind she is mother. This is instinctively recognised and accepted by everyone throughout India. Go anywhere in India you will find that in all the numerous vernaculars the universal common term of addressing a woman is “mother”. It is Mataji or Amma or Ma or Thayi etc. all meaning mother. The Pativrata Nari (woman) is verily a Goddess on earth. She is worshipped by the celestials. Her home is a heaven on earth. Everything she touches becomes sanctified. In her Divine Life radiates. She will become a worthy mother of noble offspring. The glory of such a Pativrata is indescribable. Such Pativrata upholds the entire nation, nay the entire world at large. The ideal woman of India is also the ideal mother of her children. She is the first educator and inspirer of the unfolding soul in young children. Her home is the nursery of the generation of tomorrow. Queen Madalasa imparted spiritual consciousness to her infant sons. The mother of Shivaji inspired him and moulded him to become the defender of Dharma and Vedic Religion. The noble Sumitra blessed her only son Laxmana and willingly sent him to the forest to follow and to serve his elder brother Sri Rama. What wonderful courage and self-sacrifice and idealism on her part. With a great example to all mother, to be ready to set aside selfish affection for the sake of duty and righteousness. This is the true love of a mother; not deluded attachment merely. November, this time, has a unique feature. It contains an unusual emphasis on “Vrata” because it has three Ekadasis or Lunar days of fasting. The 1st, 16th and the 30th of November are all Ekadasis. The first and the last are very special in that the Ekadasi on the first in the very sacred Hariprabodhini Ekadasi and the last one is the famous Ekadasi i.e. Gita Jayanti. It is very interesting to consider the spiritual aspect of these disciplines like periodical fasting, vigil, silence, etc. These entail self-restraint, self-denial and renunciation. They also imply your refusal to allow some particular sense of yours to give expression to its natural propensity. It means forgoing something you like to do. In this is involved the exercise of sense-control which in turn entails exercise of your will-power. On the whole it is a process of manifesting the dominion of the spirit over the flesh. Thus it is an invaluable aid in the process of awakening and manifesting spiritual consciousness. Understood in this light, such penances become significant and valuable not merely to the devotee or a Bhakta but it becomes equally important and effectively helpful even to a Vedantin or Raj Yogi who may start their Sadhana from the higher level of the mind.
144
ADVICES ON SPIRITUAL LIVING
The spiritual mechanics of a Vrata lie in the power of the seekers’ genuine aspiration, overcoming the sense-urges of his physical nature, the desire-urges of the mental nature and the Adhyasa springing out of the ego-principle. This assertion of its choice and preference of love of God to love of earthly things becomes at once a token of its sincerity and earnestness as well as the recognition of the all fullness and self-sufficiency of the true self as opposed to the lower nature in man. The exercise of such self-restraint and self-denial when rationally practised can ignite spiritual awakening within the seeker. Amongst numerous Vratas fasting, vigil and silence have retained a unique place of their own not merely in the field of formal religion but more especially in the spiritual life of seekers in quest of Self-realisation. The third Ekadasi in this month is also the sacred Gita Jayanti day. This year Gita Jayanti assumes a very special significance (and importance too). Because, the Bhagavad Gita was verily life itself to Mahatma Gandhi. Bapuji regarded the Gita as a veritable Mother to him. He declared that throughout his life the Bhagavad Gita has been to him a guide, friend, adviser, unfailing help and sure solution to all problems. He who turns to the Gita never goes away empty-handed. The Srimad Bhagavad Gita was Mahatma Gandhiji’s constant companion, most favourite scripture and supreme source of inspiration, light and wisdom. He drew strength, courage and comfort from the Gita. It behoves the present Government of India to initiate a campaign to bring about a nation-wide interest in studying the Gita. The All India Radio must have a daily Gita period for Sri Dinanath Dinesh to recite one whole chapter of Gita every day. The different State broadcasting programmes should also start Gita recitations on their daily programme. The Spirit of Bapuji will surely rejoice. Now, there is a request to make when this letter reaches you I would have already departed from South Africa for Mauritius and Rhodesia, etc. There is continuous touring and engagements throughout the months of November and December. I shall be moving from country to country. As such letter correspondence would be almost impossible due to continuous engagement in different places. Hence I would request that people may refrain from writing letters to me except in such matters that may be extremely urgent, or important and absolutely indispensable. Such letters can only be few and I shall try to attend to them as best as I can. If there is any such matter of importance which you wish to communicate, then it may be addressed to my Nairobi camp which we shall reach on 17-11-1968. Such important letters could reach me here uptill 27th November. After that I shall be getting ready to depart for West Germany. The Nairobi address is c/o Sri D.N. Sodha, J.N. Sodha & Broshers P.O. Box 2128. Nairobi, Kenya, East-Africa. It will be my endeavour to attend to any such letters depending upon its urgency. It should be appreciated that while serving Gurudev in this part of the world I have necessarily to bestow my time and attention to Lord’s children here. Hence this inability to devote time to letter writing. The country will be observing this month the holy Birthday Anniversary of the great Hindu Saint and Religious Teacher, the worshipful GURU NANAK DEV of sacred memory. Among Hindu saints revered Guru Nanak holds a unique place of spiritual importance due to the fact that he worked to remove the superstitions and defects that had grown into the religious life of India and obscured the glory of Sanatana Dharma. Nanak Dev was a Mahapurusha (a great illumined soul) who came at a turning point in the history of Hinduism to reform it by clearing up the cumbersome burden of the rigid formalities, ritualism and ceremonial worship and preach the direct and simple
145
GURU NANAK—WORLD AWAKENER OF MODERN AGE
spiritual approach to God-realisation by declaring the Yuga-Dharma or the special Sadhana of the present age, namely the practice of the Divine Name, the Sadhana of ceaseless remembrance (Smaran), service unto all beings (Seva) and the path of good conduct. The Path to God taught by Guru Nanak Dev is the greatest boon bestowed upon all of us in this age. Nam, Smarana, Seva, Sadachara, these constitute the supreme Sadhana of this age. The essence of religion and spiritual life was thus revealed by Guru Nanak and a great wave of spirituality was generated by him which raised up Hinduism to a new high level through his advent and divine teaching. The entire Hindu world owes a deep debt of gratitude to this great messenger of God. I earnestly appeal to all my beloved Sikh brothers and sisters who revere and honour this great holy teacher to come together in a loving unity with the entire Hindu fraternity by recognising in Guru Nanak Dev the great unifying factor. The esteemed Sikh fraternity must reflect well and understand that the great Guru Nanak whom we all equally revere and love would not have dreamt of creating a barrier and a division between the children of Bharatavarsha by his life and teachings. On the contrary Nanak Dev expounded the way of love, brotherhood, service and spiritual unity. Let all sons and daughters of India respond to Guru Nanak’s call to spiritual life, love, Seva and Sadachara Jivan. Sanatana Dharma and the Path of the Ten Gurus are not contrary to each other but are complimentary currents in the progressive stream of India’s spiritual life. They are twin treasures that really go together to enrich the cultural heritage of our country, its people and their religion and spiritual life. The great and grand organisation that came into being to defend the ancient Dharma of the land, now let it enrich and strengthen and beautify that same Dharma and help to support it in the midst of modern ungodly trends and currents. and Man and of Dharma! May we all honour and pay homage to his sacred memory in this way upon his holy Birthday. Worshipful Nanak Dev is a great Hindu Saint, the holy Adi-Guru of the Sikh brothers, a national teacher of India and world awakener of the modern age. Glory to Guru Nanak! Long may his spiritual teaching be practised by thousands all over India and the world. May He continue to guide Mankind upon the path of Love, Service and God-realisation. Jai Satguru Nanak Dev! Beloved Seeker, be intent upon leading the Divine Life of Truth, Purity, and Universal Love and Compassion. Practise the Sadhanas of selfless service, devotional worship, meditation and ceaseless inquiry into the supreme Reality which is your ultimate Goal and destination-divine. The leading of the Divine Life saves you from a hundred dangers and removes all affliction and misery. Doubt not, discuss not, nor argue unnecessarily about higher spiritual matters. But be rooted in faith and practise Sadhana daily. Never forget this important point. The essential thing is faith, sincerity, and practice. God bless you with Joy, Peace and Illumination. With best regards, Prem and Pranams, Yours in Gurudev, —Swami Chidananda
1st November 1968
146
ADVICES ON SPIRITUAL LIVING
Sivanandashram Letter No. LIX
SWAMI VENKATESANANDA AND SWAMI SAHAJANANDA LIVING MIRACLES OF GURUDEVA
Hare Rama Hara Rama, Rama Rama Hare Hare; Hare Krishna Hare Krishna, Krishna Krishna Hare Hare. Worshipful Immortal Atman! Beloved Seeker after Truth, Om Namo Narayanaya! Salutation and my loving greetings to you in the name of Gurudev Sivananda. This letter brings you my very best wishes for a Happy New Year, Bright and Joyful, and containing twelve months filled with prosperity, progress, success and much auspiciousness, blessedness and peace. May Gurudev’s Grace grant you great spiritual unfoldment and divine experience bringing to you peace, bliss and illumination! To my beloved fellow-seekers in India I extend my greetings for the most auspicious holy anniversary of the sacred Makarasankranti day, the day of the Uttarayana Punyakala. May this significant, sacred day mark for them a day of enhanced spiritual aspiration, for a whole-souled dedication to the quest of God over and above all other lesser objectives and pursuits of mundane life. Gurukripa shower upon you this Makarasankranti Day! On Wednesday, the 23rd of October, 1968, came to a close my half year’s visit of South Africa. After exactly five months and 12 days stay in this progressive republic, this servant left for the islands of Mauritius at the loving invitation of revered Sri Swami Venkatesanandaji Maharaj sent through the officials of the Divine Life Society in Mauritius. This stay, tour and service of the spiritual seekers and lovers of God in this beautiful country of S. Africa has been to me a matter of deep satisfaction and spiritual consolation. The devotion, the loyalty and the sincerity of all the members of the Divine Life Society of South Africa and its various Branches is most exemplary and worthy of highest praise. Everywhere I went I met conclusive proof and repeated confirmation of it and this filled my heart with great joy. Verily, it is not without reason that Sri Gurudev cherished such a great love towards his South African devotees, right from the start until the last days of his life. Our beloved Swami Sahajanandaji is Gurudev’s living miracle. The South African devotees of Sri Gurudev are a spiritual treasure that Gurudev has bestowed to this great continent. These devotees and the Divine Life Society of S. Africa indeed constitute the blessing and an asset to social life of that country. Their loving work inspired by Gurudev’s ideals in the interest of the religious life of the South African Indian community has done a very great deal to restore the genuine spirit of real Hinduism to that section of people, who were fast drifting away from their spiritual moorings and being swept away into the vortex of dry materialistic living and mere pursuit of sense-satisfaction. The practice of collective Sankirtana, Japa of the Ishta Mantra, regular study of spiritual literature, conduct of weekly Satsangas, periodical Sadhana sessions, all these have now become practices familiar amongst our people, thanks to the sincere work of the Divine Life Society under the leadership of revered Sri Swami Sahajanandaji Maharaj. Swami Sahajanandaji, with the broad-heartedness, universal vision and feeling of brotherhood, all qualities so much like Gurudev’s nature, has become a unifying factor to the different sections of the Hindu community. They have all come to feel at home in the Divine Life Society, no matter to what particular religious
147
SWAMI VENKATESANANDA AND SWAMI SAHAJANANDA LIVING MIRACLES OF GURUDEVA
subsection they may belong to by their family tradition and lineage. Not only this; even towards the people and groups belonging to other faiths a pattern of perfect tolerance has been demonstrated which has made the Divine Life Society and the Sivanandashram of Durban a by-word for universality and fellow-feeling. Sri Swami Sahajanandaji (and through him the Sivanandashram and the Divine Life Society, Durban) has become identified with all religious institutions, movements and groups in Durban so much so that it has evoked in all these quarters similar reciprocal feelings towards Gurudev’s Divine Life Work. I thus witnessed an abundance of good-will created by this practical application of Gurudev’s teachings and principles. The same noble attitude and principle is followed by the Divine Life members in all the places, they function in S. Africa, Sri Les and Pat Pearson, through their Sivananda School of Yoga and Choto Govan and his colleagues keep up this ideal of service, devotion, tolerance and universality in Johannesburg. Sri Chavda, Munsook, V. Daya, P.D. Govender, Christi Reddy and their friends all work nobly in distant Cape Town. Mr. and Mrs. Buttner and daughter and O. Gopar and family of East London and Sri Velayudha Reddy and family and their friends at Port Elizabeth similarly spread these teachings in these two important cities. Sri T.V. Lilavathy Pillay and Dr. Padeyache keep alive this light in the historical town of Kimberley. Sri S.V. Sollier and his family with the loving co-operation of Sri Pat Pillay and family and with abundant good-will of Mr. F. L. Gteen, Director of the Daily Representative carry on this noble work in the beautiful and peaceful Queenstown. The direct personal guidance of Sri Desai and Narayananda make the town of Tongast an important Centre of this Divine Life work. The Centres of Stanger, Darnell and Dalton are similar outposts that usefully cater to the religions and spiritual needs of this semi-rural and purely rural communities of the above places. Merebank and Chatsworth near Durban are progressive branches and Mr. C.N. Chetty of the former is a dynamic worker in the cause. The price of place for an outstanding feature however goes to Pietermaritzburg devotees of Sri Gurudev. They have by their wonderful effort brought into being two beautiful Ashrams in this provincial capital of Natal. Thanks to the earnest work of Sri Bridgemphan and his friends Sri A.S. Pillay and Sri Morgan Naidoo, Mother Christi, Sri Krishnan and their colleagues. All this wonderful and noble work has made my visit and tour an inspiring experience, which I shall long remember with much admiration, immense satisfaction and great joy. I also express here my grateful thanks for their gracious gesture in giving a generous purse upon the eve of my departure from Durban on 21.10.1968 at the farewell Reception at Sivanandashram. This is a noble gesture indeed. May the Lord grant them a thousand fold in return. I must record here my keen sense of gratitude and deepest appreciation to the South African Government, and specially to its Department of Indian Affairs, for the kind attitude and very sympathetic understanding towards my visit and my spiritual work in their country amidst their people. This was most encouraging. Local Officials in the different cities I visited tended to be helpful and co-operating in providing the needful facilities for this good work. The religious tolerance of the Government is noteworthy. Its helpful attitude is praiseworthy. The kindness shown to me by officials, small and big alike, in Government Departments I remember with gratitude. My thanks to them all. May God bless them. My eight days’ visit to Mauritius and my stay at the Sivananda Yoga Ashram under the gracious personal supervision of our beloved Gurubhai, the revered Sri Swami Venkatesanandaji Maharaj, is one of my most cherished memories in this present tour. Sri Gurudev is very active upon
148
ADVICES ON SPIRITUAL LIVING
this island through the wonderful work of Swami Venkatesanandaji Maharaj. All the officials of the Divine Life Society of Mauritius and the entire following of brother Venkatesananda Swamiji, were kindness personified to this servant of Gurudev. They showered their love upon me and looked to my every little need. Gatherings were organised all over the island to receive my humble Seva unto the children of that island-country. My grateful thanks to one and all of them. May God bless them all. Right here I wish to express to you the wonderful joy that filled my heart last month when I received a Cablegram from the Ashram informing me about the completion of the three crore and a half of the Mahamantra Likhita Japa to celebrate the Silver Jubilee of the Akhanda Mahamantra Kirtan Yajna at Sri Gurudev’s holy Ashram. My heart verily danced with joy and sang in happiness when I visualised the spiritual rejoicing that must have marked the functions at the Ashram upon that divine jubilee. Indeed Sivanandanagar must have been a veritable Vaikuntha upon that blissful day thrilling with Nama-Sankirtana. I extended my heartfelt congratulations to one and all who have participated in this great Likhita Japa Yajna and contributed towards making up the aggregate total of three and a half crore of the sacred Mahamantra. Great is the blessedness and the unique good fortune of all those, who had joined this Yajna of the Divine Name and whose Nama-Dhana will now be enshrined permanently in the Divya-Nama-Mandir. You are indeed thrice blessed! I send you all my heartiest greetings and Best Wishes for a Joyful and Auspicious New Year. May God shower His Divine Grace upon you all in whichever part of the world you are. May he grant you a Bright, New Year full of much Blessedness. Look back briefly to assess the valuable lessons you have learnt during the past year. Enrich yourself with this knowledge. Be wise. Move into this New Year equipped with this wisdom, wakeful and alert, hopeful and resolute, confident in faith and trust. Utilise every moment of the coming year profitably and to your highest gain. This is a Divine factor. Use it with reverence. Safeguard it as the treasure that it verily is. Utilised well, it can grant you success and prosperity that can bestow unto you bliss, peace and immortality. Be fully resolved to fill your New Year with much selfless service, much spiritual Sadhana, duties faithfully done, with Japa, Kirtan, meditation and Divine experience. Here and now create Vaikuntha and Satya-Yuga by your spiritualised activities and Divine Bhava. I wish yon a glorious New Year in every way. At this time of the commencement of the New Year I wish to state my heartfelt thanks and gratitude to the numerous people, who have sent me their loving Greetings and gracious Good Wishes for the holy Christmas and the New Year. It is most kind indeed of all of them to remember this servant at the feet of Holy Master Sivananda and thus express their affectionate goodwill through their greetings. I thank each and every one of them from the bottom of my heart. To each I hereby express my sincerest good wishes for their happiness throughout the New Year. This Year also I would pray that all of you propagate the Prayer of Sri Gurudev. Let this prayer go around the whole world, enter into every heart and be upon everyone’s lips. May this prayer be given place in all newspapers and periodicals throughout the length and breadth of the country. May God bless you all with spiritual Light, Joy and Divine Peace. May the Lord inspire you to stick to the noble path of spiritual aspiration, service, Sadhana and God-realisation. May each day find you advancing higher and higher towards the glorious goal of Divine Perfection. Om Namo Bhagavate Sivanandaya! Jai Gurudev!
149
SWAMI VENKATESANANDA AND SWAMI SAHAJANANDA LIVING MIRACLES OF GURUDEVA
With my best regards, Prem and Pranams, Yours in Sri Gurudev, December, 1968 Hare Rama Hare Rama, Rama Rama Hare Hare; Hare Krishna Hare Krishna, Krishna Krishna Hare Hare. —Swami Chidananda
Sivanandashram Letter No. LX
MYSTERIOUS WORKING OF GURUDEVA’S GRACE
Worshipful Immortal Atman! Beloved Seeker after Truth, Om Namo Narayanaya. Salutations and my loving greetings to you in the name of Gurudev Sivananda. This letter brings my very best wishes to you all, for this present letter, in a way, constitutes a Jubilee in itself because it is the 60th Sivanandashram Letter and it has entered therefore its Diamond Jubilee, numerically speaking. I give thanks to Sri Gurudev at this juncture of its Jubilee number for having prompted me to commence this letter when I did. It has enabled me to convey to you my thoughts and feelings, my ideas and prayers and my views and wishes to you and thus seek to serve Gurudev’s spiritual children in His name. Being quite unable to correspond individually with the numerous devotees of Gurudev, I have found some satisfaction and solace by these Sivanandashram Letters because they have enabled me, to some extent at least, to make up for this regrettable shortcoming. Gurudev has taken this servant onward into other circles of his devotees since writing to you the last letter. From Rhodesia after a brief visit to Malawi (the former Nyasaland) at the loving invitation of Sri Gordhandas Mathuradas, we travelled to Zambia for a week’s programme of public lectures and Satsangas from 11th Nov. to 16th Nov. The Zambia programme was arranged by Sri Uttam Ranched, an ardent Bhakta who had recently returned from India after a week of retreat in Sivanandashram in Rishikesh. We had Satsangas in the main towns of Livingston, Lusaka (the Capital City), Luanshya, Ndola, Mufilera and Chingola through the various Indian centres in these places. On the 17th of November flying from Ndola this Sevak landed in Mombasa the same evening through an extraordinary working of Gurudev’s grace. Actually there was no flight to Mombasa that day and the Air Zambia place was bound for Dar-es-Salaam in Tanzania where I was supposed to spend the night. Mombasa was all organised for programmes the very same evening. It looked inevitable that they were all to be terribly disappointed. In this situation, just at the last moment when the plane approached Dar-es-Salaam airport for landing, the ground control refused permission to the pilot for landing saying that recent rains had made the air strip temporarily unsafe. The pilot was instructed to fly to Mombasa Airport instead. And for the first time ever the Zambian Airways jet went on and landed there bringing this Sevak wonderfully in time to start with the Mombasa programme as though everything had been pre-planned with perfect timing! This is but
150
ADVICES ON SPIRITUAL LIVING
one of the many ways at many times that the mysterious workings of Gurudev’s grace has been manifesting itself throughout. Mombasa people could hardly believe the occurrence when the facts dawned upon them. The devotees’ rejoicing knew no bounds. Dr. J. R. Sharmaji had organised a busy programme for the three days 17th, 18th and 19th November. On 20th we arrived at Nairobi and had the joy of meeting two well-known devotees of Gurudev, namely Sri D. N. Sodha and Sri C. J. Patal whom I had known through correspondence for many years. It was such a happiness to see the torch of Indian Culture being kept brightly burning in this distant outpost across the ocean by the Indian community at Nairobi. A learned scholar and educationist, Shri Shantilal Thakar had taken great pains to organise an excellent programme and with the willing selfless Seva of Sri D. N. Sodha he had given fullest possible publicity to the various meetings, etc. The High Commissioner for India in Kenya, Sri Prem Bhatiaji, presided over the main meeting in the city. Sri Bhatiaji I found to be a highly cultured gentleman with great humility and devotional temperament. He was indeed a worthy representative of Bharatavarsha’s culture and possessed the true Bhava of a Bhakta and a Grihasthashrami of noble nature. Sri Shantilal Thakar I saw was an evolved Sadhaka and Yogi and was centre of inspiration and spiritual light to the Indians in Nairobi. He is doing yeoman service in spreading the knowledge of the lofty Upanishads and the Bhagavadgita. Sri Ramanbhai Patel who was our host in Nairobi is a noble soul who served us with great sincerity and devotion during our stay with him. From Nairobi Sri Gurudev took his servant to Kampala in Uganda to the pious home of Sri Bepin K. Vadgama, who is a great Bhakta and Satsanga-Premi. He is the life and soul of the Divine Life Society in Kampala and he had organised the entire tour of East Africa. We had busy engagements in Kampala, Jinja, and then at Kisumu and Nakuru and finally concluded the tour at Nairobi again on the 30th before flying to West Germany that night. Mr. & Mrs. Hans Franke of the Divine Life Society Branch of Porz-Eil have put their home at our disposal during these ten days of the W. German programme. Meetings at Cologne, Erlangen, Dortmund and at Porz-Eil were very satisfactory and the Satsangas at the Branch wonderful. Winter has well set in. It is extremely cold. Last night the temperature was minus and there was frost upon the ground. At the Franke’s home they put out rice and bread crumbs on the open balcony outside the window and numerous sparrows and blackbirds crowd. The river Rhine flows by the town at about a mile’s distance from the house. Gurudev’s books and photographs fill their home. Devotion pervades it. Recordings of Kirtans, Bhajans and Mantras are played here every day. My only difficulty here has been accustoming myself to delivering discourses sentence by sentence and waiting for each sentence to be translated into the German language for the German audience. I have to keep hold of the emerging ideas and prevent them from running away. There is a distinct awakening and a rapid spreading of spiritual values in all countries in the West. This is evident in every place this servant has been visiting during this tour. As in Germany, even so is in France and in England, too. At this moment, right here in Paris, there is evidence of great interest in Yoga, not only Hatha Yoga but also Raja Yoga and the inner spiritual life. Genuine and earnest spiritual aspirants among the French people I have had the happy privilege to meet. A great many of them have been directly or indirectly influenced and inspired by Sri Gurudev’s spiritual teachings.
151
MYSTERIOUS WORKING OF GURUDEVA’S GRACE
Like Sri Hans and mother Margarete Franke in Porz-Eil in W. Germany, here in Paris Mr. Guy des Pinardes conducts a D. L. S. Branch under the name of Centre de Yoga Vedanta Sivananda. Mr. Des Pinardes got his training from Yogiraj Sri Swami Vishnudevananda, Montreal, in 1962-63 and from Swami Sharadananda at Rishikesh Ashram in 1965. He was blessed by Sri Gurudev in 1962. There are many other Yoga Centres working here. The spiritual discourses of the recent Paris programme were very attentively received, with great earnestness. Though the process of speaking through an interpreter who translates your talk sentence by sentence makes you feel rather crimped and stiffed at times, yet it is satisfying and rewarding to the heart when one considers the spiritual service that it implies and the response that it evokes in the listening souls. Who can say that Sri Gurudev is gone and that he does not actively continue his spiritual ministry. Sri Gurudev is very much active indeed and his work is certainly moving forward and gaining momentum. To witness this is itself a benediction and an inspiration. This servant leaves for Belgium on 2nd February, 1969, for a two weeks’ programme in that country where there is a very strong movement of Yoga quite widespread with various centres in many towns and cities including its capital Brussels. The Divine Life Society Branch in the town of Aalst is being conducted by the Kiekens family with very great sincerity and loyalty to Sri Gurudev to whom all the members are deeply devoted. They are endowed with much spiritual Samskaras. After Belgium, a pressing request from Greece by our old friend Mother Lila Vlaouch of Athens takes me there for a week’s tour. Then the important programme of Holland by Dr. L. Eversdyk Smulders, writer and traveller well known in North India, who had visited Sri Gurudev in 1958-59, will bring me to Holland in the first week of March for 10 day’s engagements. Then this servant will have to cross the Atlantic where work awaits through Yogiraj Sri Swami Vishnudevananda Maharaj, Sri Swami Shivapremananda Maharaj, Bill Eilers & Mrs. C. Sheldan, etc. who expect this Sevak on the other side. I am filled with immense joy to learn from the glowing reports received from my beloved brothers at the Ashram about the wonderful and enthusiastic way in which the two sacred Silver Jubilee events were very successfully celebrated under the gracious and able guidance of most revered Sri Swami Krishnanandaji Maharaj and Sri Swami Madhavanandaji Maharaj with the loving and enthusiastic help of the numerous Ashram Sadhakas and visiting devotees. They are indeed most blessed and extremely fortunate, who took part in the festival of spiritual joy which these two sacred Jubilees occasioned. The Divine Name Temple (Divya Nama Mandir) will become a centre of tremendous attraction to draw all souls towards the Spiritual Path and the Sadhana of the practice of the Divine Name of God. It will infuse power into the hearts of those who behold it and approach it. Those who worship the NAME enshrined therein will obtain the boon of Bhakti. From here I send my special felicitations to Sri Swami Vivekananda of Sivanandashram who contributed half a lakh (50,000) of Likhit Japa towards the Mahamantra Yajna, this figure being the highest among the Ashram residents. Divine Mother endow him with such Sadhana Sakti and such Nishtha and Dharana always and take him rapidly towards the goal of God-realisation.
152
ADVICES ON SPIRITUAL LIVING
Akhand Nama Sankirtana should increasingly become a very regular feature of the activities of all Divine Life Society Branches all over the country and the world at large. They must all adopt Akhanda Kirtana as a prominent feature in their programmes. Even where there is no D.L.S. Branch, devotees and disciples of Sri Gurudev wherever they are living should take a keen interest in having such periodical Akhanda Nama Kirtanas organised for varying durations as in within their capacity. Dawn to midday is one method. Sunrise to sunset is another form. From midday to 7 p.m. or 8 p.m. is another method which people will find suitable to participate in on Saturdays. When you wish to combine vigil, then the pattern of sunset to sunrise is to be followed. Some arrange such continuous chants from sunset until midnight upon special festival days or holy days. Sri Gurudev Sivanandaji Maharaj always encouraged and enthused devotees to arrange Akhanda Kirtana upon occasions of marriage, birthday, any auspicious inauguration, New Year, etc. and also upon all holy days like Sri Rama Navami, Sri Krishna Janmashtami, etc. The state of things in the present day world calls for the infusion of spiritual force into the stream of human life in this universe today. The supreme method of doing this in this age is by generating and releasing the indescribable Power of the Divine Name into the life stream of contemporary mankind. This will help greatly in creating goodwill, erasing of tensions, overcoming hatred and pacifying conflicts and hostilities. It will bring about peace and change the hearts from Tamas into Sattva-Guna. Thus will you help restore order and harmony to a world that seems bent upon heading towards disharmony and chaos by its deliberate wilfulness. Spiritual power is positive force and is certain to overcome negative forces. For, this is the Law. Join ranks and co-operate in evoking this spiritual force through the potency of the Divine Name. Loving greetings to you all in the name of the Lord of the universe, the great God, Lord Siva, for whose devout worship the entire country is preparing itself upon this most auspicious month. May the choicest blessings of Bhagawan Vishvanath be upon you all. May He bestow upon you all auspiciousness, Divine Bliss, supreme Peace, Spiritual Illumination and Highest Blessedness. The sacred day of Mahasivaratri I shall observe with our Hindu brothers in the Indian community in London on the 15th February. My prayerful thoughts will be with everyone of you who are in the holy land of Kashi, Rameshwar and Baijyanath Dham. May Lord Siva grant you all Bhakti, Vairagya, Jnana and Kaivalya! May you be ever absorbed in the worship of Siva manifest as Jiva and strive for union with Him manifest within you as the Self, the Antaryamin, Pratyagatman! With love, regards and Om Namah Sivaya, Om Namo Bhagavate Sivanandaya. Yours in Sri Gurudev January, 1969 —Swami Chidananda
153 | https://www.scribd.com/doc/7245303/Advices-on-Spiritual-Living | CC-MAIN-2018-17 | refinedweb | 88,518 | 62.88 |
LED blink
Now it’s time for your first project! Let’s start by learning how to use the most basic and commonly used component: the LED. It’s everywhere in life, for lighting, indication, or decoration...
For those coming from the software programming world, you may be familiar with the traditional “hello world” program. In the world of electronics, we have a similar starter project: blinking an LED!
Learning goals
- Understand how the digital output signal works.
- Get to know ohm's law and figure out the relations between current, voltage, and resistance.
- Start to write code and learn some Swift programming knowledge.
🔸Background
What is digital output?
In electronics and telecommunication, electronic signals carry data from one device to another to send and receive all kinds of information. They are always time-varying, which means the voltage changes as time goes on. Different voltages can convey infos and be decoded to a specified message. Depending on the ways the voltage changes, the signals are divided into two types: digital signal and analog signal. You'll take a look at the digital signal in this tutorial.
In most cases, a digital signal has two states: on or off. It is suitable to work with some components, such LED (which is either turned on or off), the button (which will be only pressed or released) ...
Here are different expressions to represent two voltage states:
note
For our board, 3.3V represent true and 0V represent false. Of course, there are many other possibilities, like 5V for true.
GPIO (general-purpose input/output) pins can handle digital output and input signals. You’ll set it as output in your code.
You can use a digital output to control the LED both built onto the board or external LEDs (not included). For the LED module on your kit, when you apply a high signal to the LED, it will turn on, and if you apply a low signal, it will be off.
🔸New component
Diode
The diode is a polarized component. It has a positive side (anode) and a negative side (cathode). In the circuit, the current can only flow in a single direction, from anode to cathode. If you connect it in an opposite direction, the current will not be allowed to pass through.
Symbol:
LED
LED (Light-emitting diode) is a type of diode that will emit light when there is a current. Only when you connect it in the right direction – connect the anode to power and the cathode to ground - is the current allowed to flow, lighting up the LED.
Symbol:
info
How to identify the two legs of LED?
- Typically the long leg is positive and the short leg is negative.
- Alternatively, sometimes you will find a notch on the negative side.
The LED allows a limited range of current, normally no more than 20mA. So you should add a resistor when connecting it to your circuit. Or the LED might burn out when driving too much current.
When you connect the LED in the circuit, there are two cases to control the LED:
- Connect the anode to a digital output pin and cathode to ground. When connected this way, the LED turns on when the pin outputs a high signal. This is how the LED is connected on the Feather board.
Pin is the digital output pin, R is a resistor, is an LED, and GND is ground
- Another method is to connect the anode to a power source and connect the cathode to a digital output pin. When the digital output signal is high, there is no voltage difference between two ends of the LED, but when the digital signal is low, current is allowed to flow, causing the LED to turn on.
Vcc is a power source, R is a resistor, is an LED, and pin is a digital output pin
There are many types of LEDs. The LED on your SwiftIO Circuit Playgrounds is a small variant designed to be convenient for mass production.
Resistor
The resistor functions as a current-limiting component which, just as its name suggests, can resist the current in the circuit. It has two legs. You can connect it in either direction as it is not polarized. Its ability to resist the current, called resistance, is measured in ohm (Ω).
Symbol: (international), (US)
info
How can you tell how much resistance a resistor provides?
Each resistor has a specific resistance. Note the colored bands in the diagram. Each band corresponds to a certain number. Here is an online guide and calculator to determine how to total the value of all the bands together.
Challenge
What’s the resistance of the sample resistor R1 pictured above, as well as the resistors R2 and R3 below? See below for the answer!
Answer
- R1: 10KΩ with a tolerance of ± 5%
- R2: 330Ω with a tolerance of ± 5%
- R3: 470KΩ with a tolerance of ± 1%
This kind of resistor is useful primarily when you DIY some stuff. However, the SwiftIO Feather board and the rest of the kit uses surface mount resistors as they are smaller and more suitable for mass production.
🔸New concept
Ohm’s law
When starting with electronics, you must get familiar with these three concepts: voltage, current, and resistance:
- Voltage measures potential energy between two points.
- Current describes the rate of flow of electric charges that flow through the circuit.
- And resistance is the capability to resist the flow of current.
An intuitive and common analogy is water pressure in a tank. Imagine a water tank with water inside and an opening at the bottom.
In this scenario, the water pressure (water level) is like voltage, the opening is like resistance, and the amount of water spilling out is like current.
- Looking at the first figure, very little water will come out (current) because there isn’t much pressure (voltage) and the opening is small (resistance).
- In the second example, we’ve increased the water level (voltage), but kept the same sized opening (resistance), which results in an increase in the flow of the water (current).
- Finally, in the last one, we’ve also increased the size of the opening (reduced resistance), keeping the water level (voltage) the same, resulting in another increase in flow (current).
Ohm’s law describes how voltage, current and resistance interact with each other and works similar to the water tank above. The formula is:
V = I * R
V: voltage (unit: volts or V)
I: current (unit: amps or A)
R: resistance (unit: ohm or Ω)
Using some simple algebra, we can also put forward the following formulas:
R = V / I
and
I = V / R
As stated previously, all digital pins on the SwiftIO Feather board output a high signal of 3.3V. If the resistance in the circuit is 330Ω, the current would be 0.01A.
Exercise
Given an LED with the following characteristics, how many ohm resistor should you use to complete the circuit, using the 3.3V digital out pin source?
- Forward current: 15mA max
- Forward voltage: 3.0V
Here is the equation:
R = (V-Vled) / Iled
- V: supply voltage
- Vled: forward voltage for the LED, that is, voltage drop as the current across the LED.
- Iled: forward current for the LED (usually 10-20mA). It’s the maximum current. If you don’t have the specs about LED, you could normally suppose it to be 20mA.
The resistor needed for the LED is:
R = (3.3 - 3.0) / 0.015 = 20Ω
Btw, the resistance of the LED itself is little so you could ingnore it.
Frequently you will be unable to find a resistor that matches the exact theoretical value. When this happens, you can use a resistor that has a slightly greater resistance.
In general, the resistance calculated is a minimum requirement. You can also choose a resistor with much larger resistance. Doing so will cause the LED’s brightness to change with it. (Greater resistance will cause the LED to be dimmer)
Serial circuit and parallel circuit
Serial and parallel circuits are the ways to connect more than two devices in the circuit.
In a serial circuit, devices are connected end-to-end in a chain, like R1 and R2. The current flows through them in one direction from positive to negative. And the current flowing through each device is the same.
In a parallel circuit, the devices share two common nodes, like R3 and R4. Node (a) connects both two devices, so the current could flow through either of them. The voltage between two nodes (a and b) is the same, so the voltages spent on R3 and R4 are the same.
In your real situation, the circuit would not be that easy. The serial and parallel circuit would both be used when building the circuit.
Let’s look at an example. You will know better about two circuits.
- In the first circuit, the two lamps are connected in series, so the switch can control both of them. If any of the lamps breaks down, even if the switch is closed, the other lamp will not be lit.
- In the second circuit, the two lamps are connected in parallel, you can control any of them by using the corresponding switch that is connected to it in series: switch1 controls the lamp1, switch2 controls the lamp2. And the two lamps work separately.
Open, closed and short circuit
In addition to the previously mentioned types of circuits, there are three more you need to know about: open circuit, closed circuit, and short circuit.
- The first figure is a closed circuit. This allows current to flow freely from the positive terminal through a load that consumes electric power, finally returning back to the negative terminal.
- In an open circuit, there is a gap somewhere on the circuit, therefore disallowing any current to flow through it.
- Current tends to flow through the path with lower resistance, if you accidentally connect the positive to the negative terminal of the power supply, the current will flow directly through this path and bypass the other paths with higher resistance. The resistance of wires are so small that you could normally ignore it. This causes a short circuit. When the current reaches sufficiently high levels, this can cause serious damage.
Current safety
In a complete circuit, the current will always flow from the point of higher voltage (usually power) to the one of lower voltage (usually ground or GND). Consumed energy is turned into light, heat, sound and many other forms.
If you were to connect the power directly to the ground using a wire, this would cause a short circuit. It can (and usually do) cause damage to your circuit and board, and is also very possible to start a fire.
Another warning: if you’re not careful about selecting an appropriately strong resistor to resist the level of current flowing through the circuit, the devices can be burnt and damaged (and additionally cause a fire hazard).
🔸Circuit - LED module
The image below shows how the LED module is connected to the SwiftIO Feather board in a simplified way.
The LED is connected to D19. GND and 3V3 are connected respectively to the corresponding pin on the board.
info
On circuit diagrams, the red line is usually for power and the black line for ground.
The circuits are all built when designing the board, so you don’t need to connect any wires. And as mentioned before, the white sockets are used to build the circuit after the board is disassembled.
note
The circuits above are simplified for your reference.
🔸Preparation
Class
DigitalOut - as indicated by its name, this class is used to control digital output, to get high or low voltage.
Global function
sleep(ms:) - Make the microcontroller suspend its work for a certain time, measured in milliseconds.
🔸Projects
1. LED blink
In your first try, let’s make the LED blink - on for one second, then off for one second, and repeat it over and over again.
Example code
// First import the SwiftIO and MadBoard libraries into the project to use related functionalities.
import SwiftIO
import MadBoard
// Initialize the specified pin used for digital output.
let led = DigitalOut(Id.D19)
// The code in the loop will run over and over again.
while true {
//Output high voltage to turn on the LED.
led.write(true)
// Keep the LED on for 1 second.
sleep(ms: 1000)
// Turn off the LED and then keep that state for 1s.
led.write(false)
sleep(ms: 1000)
}
Code analysis
Here are some key statements for this program, make sure you understand them before you start to code.
// Comment
This is the comment for the code used to explain how the program works and also for future reference. It always starts with two slashes.
import SwiftIO
import MadBoard
These two libraries are necessary for all your projects with the boards. In short, a library contains a predefined collection of code and provides some specified functionalities. You can use the given commands directly without caring about how everything is realized.
SwiftIO is used to control input and output. It includes all the necessary commands to talk to your board easily.
MadBoard contains the ids of all types boards. The ids for different types of boards may be different since the numbers of pins are not same. Make sure the id used in your code later is correct.
let led = DigitalOut(Id.D19)
let is the keyword to declare a constant. A constant is like a container whose content will never change. But before using it, you need to declare it in advance. Its name could be whatever you like and it’s better to be descriptive, instead of a random name like abc. If the name of your constant consists of several words, then except the first word, the first letter of the rest words needs to be capitalized, like
ledPin. This is known as the camel case.
The class, in brief, is more like a mold that you could use to create different examples, known as instances, with similar characteristics. The class
DigitalOut provides ways to change digital output, so all its instances share the functionalities. The process of creating an instance is called initialization.
The constant
led is the instance of the
DigitalOut class. To initialize it,
- The pin id is required.
Idis an enumeration including the ids of all pins. As for enumeration, enum for short, it could group a set of related values. Just remember that the id needs to be written as
Id.D19.
- The
modeof the digital pin is pushPull in most cases and you will know more about it in the future.
- The
valuedecides the output state of the pin after it's initialized. By default, it outputs a low level. If you want the pin to output 3.3V by default, the statement should be
let led = DigitalOut(Id.D19, value: true).
In this way, the pin D19 would work as a digital output pin and get prepared for the following instructions.
while true {
}
It’s a dead loop in which the code will run over and over again unless you power off the board. The code block inside the brackets needs to be indented by 4 spaces.
note
Sometimes you find nothing that needs to run repeatedly, you could add
sleep in it to make the board sleep and keep in a known state.
led.write(true)
The
led instance has access to all the instance methods in the
DigitalOut.
write() is one of its methods. You’ll use dot syntax to access it: the instance name, followed by a dot, the method in the end. Then you decide the voltage level as its parameter,
true for high voltage,
false for low voltage. A value either
true or
false is of Boolean type.
sleep(ms: 1000)
An instance method needs dot syntax to invoke it, but a global function doesn’t. You can directly call it. The function
sleep(ms:) has a parameter name
ms and a parameter (the specified period). During sleep time, the microcontroller would suspend its processes.
info
Both methods and functions group a code block, and you could realize the same functionality by calling their name. Their difference is that a method belongs to a class while a function is separately declared.
Why add this statement? The microcontroller executes state change of digital pins extremely quickly. If you just change the output state between high and low, the LED will be on and off so quickly that you cannot notice it. So a short period of time is added here to slow the speed of change. If you want the LED to blink faster, you could reduce the sleep time.
info
When using methods or functions, why do some parameters need to add a name and others don't?
Let’s look at the source code below for example:
func write(_ value: Bool)
A function parameter has a argument label and a parameter name. The argument label is used when calling a function. While there is an underscore “_” before the parameter name
value, it means the label can be omitted when invoking the function:
led.write(true).
func sleep(ms: Int)
In this case,
ms serves as the argument label by default, so it's necessary:
sleep(ms: 1000).
2. LED morse code
Example code
Have you heard of Morse code? It encodes characters into a sequence of dashes and dots to send messages. To reproduce it, you could use long flash and short flash respectively. In morse code, s is represented by three dots, o is represented by three dashes. So the SOS signal needs three short flashes, three long flashes, and then three short flashes again.
// Import the libraries to use all their functionalities.
import SwiftIO
import MadBoard
// Initialize the digital output pin.
let led = DigitalOut(Id.D19)
// Define the LED states to represent the letter s and o.
let sSignal = [false, false, false]
let oSignal = [true, true ,true]
// Set the LED blink rate according to the values in the array.
func send(_ values: [Bool], to light: DigitalOut) {
// The duration of slow flash and quick flash.
let long = 1000
let short = 500
// Iterate all the values in the array.
// If the value is true, the LED will be on for 1s, which is a slow flash.
// And if it’s false, the LED will be on for 0.5s, which is a quick flash.
for value in values {
light.high()
if value {
sleep(ms: long)
} else {
sleep(ms: short)
}
light.low()
sleep(ms: short)
}
}
// Blink the LED.
// At first, the LED starts 3 fast blink to represent s, then 3 slow blink to represent o, and 3 fast blink again.
// Wait 1s before repeating again.
while true {
send(sSignal, to: led)
send(oSignal, to: led)
send(sSignal, to: led)
sleep(ms: 1000)
}
Code analysis
let sSignal = [false, false, false]
let oSignal = [true, true, true]
Here, two arrays are used to store the info of two letters. Since there are only two states: fast or slow flash, you could use boolean value to represent two states.
false corresponds to quick flash.
An array stores a series of ordered values of the same type in a pair of square brackets. The values above are all boolean values.
func send(_ values: [Bool], to light: DigitalOut) {
...
}
You will create a function to finish blinks for a single letter. It needs two parameters: the first is an array of boolean values that stores the info for a letter; the second is the digital pin that the LED is connected to.
This function is to make your code more organized and clear. Of course, you can use other ways of abstraction.
info
Usually, it's better not to use the variable or constants that are declared out of the function itself. All stuff needed is passed in as its parameters. As you invoke the function, you will then tell which pin is going to be used and what the values are. Thus you could use this piece of code in other project without modifying the code. This practice would be really helpful as you work on great projects in the future.
let long = 1000
let short = 500
Set the duration of LED on-time. The values are stored in two constants so it would be clearer as you use them later.
for value in values {
...
}
This is a for-in loop. It has two keywords:
for and
in. It’s used to repeat similar operations for each element and usually used with arrays. The code inside the curly brackets would repeat several times to iterate all elements in the array.
value represents the elements in the array
values. It doesn’t matter if you use
value or a, b, c to name it. But it’s better to use a descriptive name.
if condition {
task1
} else {
task2
}
This is a conditional statement. The if-else statement makes it possible to do different tasks according to the condition. The condition is always a boolean expression that will return either true or false. And it will use some comparison operators to evaluate the value as follows:
- Equal to:
a == b
- Not equal to:
a != b
- Greater than:
a > b
- Less than:
a < b
- Greater than or equal to:
a >= b
- Less than or equal to:
a <= b
If the condition evaluates true, task1 will be executed and task2 will be skipped. If the condition is false, task2 will be executed instead of task1.
In the code above, the
value is judged to know how long the LED should be on.
light.high()
light.low()
Set high or low voltage. This is similar to the method
write(), but it’s more straightforward. The statement
led.write(true) of course works.
🔸More info
If you would like to find out more about some details, please refer to the following link: | https://docs.madmachine.io/tutorials/swiftio-circuit-playgrounds/modules/led | CC-MAIN-2022-21 | refinedweb | 3,660 | 73.27 |
Timeline)
- …
10/30/08:
- 23:54 Ticket #17055 (p5-class-insideout-1.09 Port Submission) created by
- Hi, I've attached the Portfile for p5-class-insideout-1.09. Thanks, …
- 23:45 Changeset [41345] by
- New port - devel/apr_memcached, a memcached client in C …
- 23:34 Changeset [41344] by
- acme: nuke since the functionality has been integrated into …
- 23:24 Ticket #16671 (gnutls-2.4.1 has moved: fetch failed) closed by
- fixed: master_sites updated in r41343.
- 23:23 Changeset [41343] by
- devel/gnutls - update master_sites, ticket #16671
- 23:16 Ticket #12532 (ImageMagick 6.3.5: Resizing an Image Causes Deallocation of a Pointer Not ...) closed by
- worksforme: Closing, lack of response, can't reproduce here.
- 22:33 Ticket #17054 (gtetrinet update to 0.7.11) created by
- Patch attached.
- 22:18 Changeset [41342] by
- tea: don't use -flat_namespace or -undefined suppress, use port: style …
- 22:16 Changeset [41341] by
- jed: don't use -flat_namespace or -undefined suppress
- 22:15 Changeset [41340] by
- xplc: don't use -flat_namespace or -undefined suppress
- 21:55 Changeset [41339] by
- shared-mime-info: don't use -flat_namespace or -undefined suppress
- 21:53 Changeset [41338] by
- orbit: don't use -flat_namespace or -undefined suppress
- 21:52 Changeset [41337] by
- openslp: don't use -flat_namespace
- 21:47 Changeset [41336] by
- linc: don't use -flat_namespace or -undefined suppress
- 21:45 Changeset [41335] by
- dbus-glib: don't use -flat_namespace or -undefined suppress
- 21:44 Changeset [41334] by
- dbus: don't use -flat_namespace
- 21:11 Ticket #16931 (Openjpeg won't upgrade) closed by
- fixed
- 20:29 MacPortsDevelopers edited by
- Correct entry (diff)
- 19:59 MacPortsDevelopers edited by
- Fix alphabetical bits (diff)
- 19:47 Changeset [41333] by
- Add a really basic script to help generate a starter Portfile
- 18:26 Changeset [41332] by
- gimp: update meta-port to 2.6.2.
- 18:24 Changeset [41331] by
- gimp2: update to 2.6.2.
- 17:54 Ticket #17009 (gimp-2.6.0 +without_gnome -dbus Dependency Compile errors) closed by
- invalid: OK, but if you're going to do it that way then stick with that for the …
- 17:40 Changeset [41330] by
- Add my in-progress work on recursive port dependency stuff
- 17:16 Ticket #17050 (py25-cairo-1.4.12 update to 1.6.4) closed by
- fixed: Fixed in r41329. Thanks.
- 17:14 Changeset [41329] by
- py25-cairo: version update 1.4.12 -> 1.6.4 and fixed livecheck (closes …
- 14:11 Changeset [41328] by
- Updated to 0.1082.
- 14:09 Changeset [41327] by
- New portfile for DRC-FIR
- 14:08 Changeset [41326] by
- Updated to 0.44.
- 14:06 Changeset [41325] by
- Updated to 0.87.
- 14:04 Changeset [41324] by
- Updated to 0.10.
- 14:02 Changeset [41323] by
- Updated to 1.50.
- 13:57 Changeset [41322] by
- Updated to 1.19.
- 13:55 Changeset [41321] by
- Updated to 0.40.
- 13:53 Changeset [41320] by
- Updated to 0.83.
- 13:20 Changeset [41319] by
- net/pidgin & net/finch: Added perl plugin support.
- 13:02 Ticket #17053 (Upgrade lzo2 to 2.0.3) created by
- lzo2 2.03 is available. Attached patch includes the uprev.
- 12:51 Changeset [41318] by
- Total number of ports parsed: 5089 Ports successfully parsed: 5089 …
- 12:02 Changeset [41317] by
- evince: remove dependency on gdk-pixbuf which is obsolete gtk1 …
- 12:01 Ticket #16781 (libxml2-2.7.1 does not exist anymore) closed by
- fixed: uprev to 2.7.2 committed in r41316 (maintainer timeout and this appears to …
- 12:01 Changeset [41316] by
- Uprev to 2.7.2 per ticket #16781 (3 weeks old, committing due to …
- 11:53 Changeset [41315] by
- cairomm: add openmaintainer.
- 11:52 Changeset [41314] by
- cairomm: add missing dependency on libsigcxx2.
- 11:48 Changeset [41313] by
- cairomm-devel: add missing dependency on libsigcxx2.
- 11:33 Changeset [41312] by
- cairomm-devel: add patches to fix OS X specific build problem caused by …
- 09:45 Ticket #17044 (evince wants old libopenjeg) closed by
- fixed: Great, although I think rebuilding poppler would have been enough since …
- 09:07 Changeset [41311] by
- poppler: add explicit dependency on port openjpeg which is autoconfigured …
- 08:44 Changeset [41310] by
- version 2.0.1
- 06:59 Changeset [41309] by
- ruby/rb-cocoa: remove `cd' from Portfile, suggested in macports-dev …
- 06:25 Ticket #16950 (cclient is at version 2007 but version 2007b is available) closed by
- fixed: Actually, the latest version is 2007d. It has been updated in r41307.
- 06:25 Ticket #15404 (cclient: needs universal variant) closed by
- fixed: Fixed in r41307.
- 06:24 Changeset [41308] by
- Provide variant description, simplify some logic
- 06:23 Changeset [41307] by
- mail/cclient: update to 2007d, add +universal variant
- 05:45 Ticket #17052 (pidgin-25.2 build error) created by
- […] Other variants fail as well.
- 03:23 Ticket #17051 (postgres account on leopard 10.5.5 cannot remote login (ssh)) created by
- i've successfully installed postgresql83, postgresql83-server …
- 03:16 Ticket #17050 (py25-cairo-1.4.12 update to 1.6.4) created by
- Update to latest (1.6.4) version.
- 01:59 Ticket #17040 (Cairo : add support for 64 bits platforms) closed by
- duplicate: Duplicate of #16007.
- 01:56 Ticket #17049 (pango +quartz cannot build 64-bit) created by
- 64 bits versions of Carbon framework does not have the atsui functions …
- 01:11 Changeset [41306] by
- Fix universal variant, just like r41252
- 01:01 Changeset [41305] by
- Add openmaintainer, mark the universal variant as unavailable
Note: See TracTimeline for information about the timeline view. | http://trac.macports.org/timeline?from=2008-11-03T02%3A40%3A46-0800&precision=second | CC-MAIN-2015-11 | refinedweb | 913 | 63.7 |
GetKeys tutorial (Python)
How to use GetKeys
What is GetKeys?
GetKeys is a Python module that allows you to detect a user input without them having to press enter afterwards.
Importing
Write
from getkeys import getkeys, keys to import getkeys and an extra feature
Key detection
To detect a key being pushed, write
k = getkey(). Note that the program will not continue until a key is pressed
Using k
Basic characters
For characters such as letters, numbers, symbols and spaces, write this after
k = getkey():
if k == "a": #change the a to whatever you want #Stuff goes here else: #Stuff goes here
Or to make it non-case-sensitive:
if k == "a" or "A": #Stuff goes here else: #Stuff goes here
Other characters
For escape, backspace, delete, enter, tab, home, end, insert and the arrow keys it is a little bit different.
if k == keys.ENTER: #Change the ENTER to one of the keys above. It must be capitalized and not abbreviated (eg. ESC and DEL should be ESCAPE and DELETE #Stuff goes here else: #Stuff goes here
Extras
You can also use
elif to detect which key is pressed. For example:
if k == "a": #Stuff goes here elif k == "b": #Stuff goes here else: print("Must press [a] or [b]!")
Thank you for taking this tutorial. Have a great day! 😀
You can add syntax highlighting to your code blocks by adding
pyafter the 3 backslashes (`):
Isn't it
if k == "a" or key == "A":?
Also, you can use
getch,getch():
:D
@Bookie0 For
Without adding the name of the object again it checks if the object
keyhas either
aor
bas it's value.
@MuffinsTheCat oh hm | https://replit.com/talk/learn/GetKeys-tutorial-Python/128030 | CC-MAIN-2021-17 | refinedweb | 277 | 77.27 |
vsftpd causes a vmalloc space leak in Lucid
Bug Description
SRU justification:
Impact: With activated network namespace (CONFIG_NET_NS) support it is possible to create new namespaces much faster than cleaning them up. This can lead to memory pressure and in the case of vsftp it is easily possible to bring down the server by just repeatedly connecting to it.
Fix: The issue was fixed by a long series of changes to make cleanup quicker. The vast amount of changes makes them unsuited for SRU. So it was decided that the safest way for a 2.6.32 based kernel is to turn that feature off (it was considered experimental until 2.6.37 anyway).
Testcase: Se report.
---
A simple stress test conducted on a KVM guest running standard updated Lucid with vsftpd demonstrates that memory is continuously used up until OOM Killer starts to protect the system (after ~12 min on my system). If test is terminated before that point is reached then memory is freed only after several hours. If vsftpd is stopped then memory is freed (after ~45 min on my system).
This does not occur with the 2.6.35 kernel (LTS backported kernel).
The test is started in this way:
$ for i in 1 2 3 4 5 6 7 8 ; do ./feedftp $i >/dev/null & done
What is observed during the test is that /proc/vmallocinfo grows continually with lines like the following being added:
0xffffe8ffff800
0xffffe8ffffa00
0xffffe8ffffc00
Attached:
- test script (see feedftp)
- tarball containing the proc file at various times during the test (see vmallocinfo.32.tar)
- dmesg output showing OOM Killer at work (see dmesg-oom.32.txt)
May be related: https:/
=========
ProblemType: Bug
DistroRelease: Ubuntu 10.04
Package: linux-image-
Regression: No
Reproducible: Yes
ProcVersionSign
Uname: Linux 2.6.32-28-server x86_64: [ 12.360149] eth0: no IPv6 routers present
Date: Wed Feb 16 14:00:19 2011
Lspci: Error: [Errno 2] No such file or directory
Lsusb: Error: [Errno 2] No such file or directory
MachineType: Bochs Bochs
PciMultimedia:
ProcCmdLine: root=UUID=
ProcEnviron:
LANG=en_US.UTF-8
SHELL=/bin/bash
SourcePackage: linux
Seems we got this already in Lucid.
It may be interesting if you had a spare disk and could do a bare metal installation of Lucid to repeat that test there.
Hi, we have this issue on bare metal installation as you say. On a Dell M605 (AMD processor) and on an IBM x3650 (Intel).
As well, it might help you to know that we tested it on SUSE with kernel 2.6.32-24, and the bug is not there.
Hi, I am working with Walter Richards. During our testing, we realized that it takes several hours to retrieve the memory after we stopped the ftp connections.
On our 32GB Dell server, it took 5 hours to fill all the memory (until OOM kills at 2.1GB of free memory). Then, it took 8 hours before it started to retrieve the free memory, and then it took another 7 hours to completely get the 30GB back...
Ok, so this is not really something conclusive yet, but it seems to me (when playing with that locally) that for that memory allocations to grow, there is no actual file transfer needed. Just looping through doing a connect and immediately disconnect again showed those 2M chunks growing. So I guess I can concentrate on that area further on.
So this is what I found out so far: whenever a client connects to vsftpd, it forks of a process to handle the connection. This is done in a way that also duplicates the network namespace (beside of the process namespace). This can actually be observed by the fact that every time that happens there is a message about "lo: Disabled Privacy Extensions" (which is slightly stupid to note as that is the default for lo). Anyway, so cloning the network namespace also sets up the snmp mib structures and those are allocated by pcpu.
The main problem seems to be that cleaning up those structures is done in Lucid for each interface on its own by putting it onto a work queue. This seems to be rather slow, so while the test case is running its seems the system is too busy with creating new namespaces than it is able to clean them up. Even after stopping the test this takes a while and because the way that vmalloc pcpu areas are handled can potentially stick even longer (the areas are not exclusively used by network namespace, something else may use parts of the area and the area cannot be cleaned up until the last user is gone).
Between 2.6.32 and 2.6.35, there was a series of changes that allowed to batch the cleanup of network namespace. The comment on one of those indicated that 4000 namespaces would have taken more than 7 minutes before and could be reduced to 44 seconds (at the price of an increased cpu load). I was able to backport all required changes and this seems to avoid the build up of the vmalloc area (I am not sure about that but it felt like the speed of connects and disconnects was lower). I am still reluctant to go that road because the required changes were somewhat big and the more gets changed, the higher chance to pick up some regression. Also the question is whether the test case models a realistic usage. To clarify, this is not a real leakage. It is a combination of specially allocated memory and slowness / complicated policy to free that allocations.
Hi,
our production servers have more than 250000 vsftpd connections for day:
# zgrep CONNECT vsftpd.log.3.gz|wc -l
260210
which is about 3 connections per second. Each connection may have up to 200 file transferts. The testcase produces about 15 connections per seconds. It is 5 times more than our reality, but we can see the problem with only 3 connections per seconds.
Btw, for the "Disabled Privacy Extensions" messages, this can be avoided by disabling the ipv6 (ipv6.disable=1 on the grub command line).
Thanks
The privacy extension message was more of a side note. It has been removed in current code (probably because of the limited use).
So the test case is making sense. And I was also beginning to think whether this could be seen as a security issue. As someone could bring down the server by doing many connects. It probably takes a while. Still...
Unfortunately I am not really happy with backports I mentioned before. They really seem to slow down the number of connects. So it could only be due to that, that the vmalloc space is not filled up quicker that it gets released. I think I have to do a few more experiments. Not sure it can be done but I would rather want to avoid making too large changes.
Unfortunately this got a bit hit by other issues I was looking at. So I did not really see any small change to improve things. I guess I need to reach out for help from upstream. Meanwhile there is this series of patches I backported from 2.6.35 that allow network namespaces to be cleaned up in batches. From my feeling this seems to slow down the rate I see the test tasks connecting, but this seems to be the same on 2.6.35. Maybe that is something one can live with.
In order to give other people a chance to look at that I have prepared kernel packages and put them to:
http://
Meanwhile I try to get some help...
Hi,
I installed the following files from your site and rebooted:
/root/linux-
/root/linux-
/root/linux-
/root/linux-
/root/linux-
/root/linux-
Then, my ftp tests worked properly without using any free memory... The file /proc/vmallocinfo stayed at around 5 lines (2 new lines only) (grep pcpu /proc/vmallocinfo). Before, it was constantly growing.
Seems it is fixed in this kernel level.
Thanks a lot!
Hi,
Sorry, I forgot to add a comment about the process netns: it was using a lot of CPU during my tests...:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
37 root 20 0 0 0 0 D 15 0.0 0:51.89 netns
7218 root 20 0 33464 1328 888 D 1 0.0 0:00.03 vsftpd
7220 root 20 0 33464 1328 888 D 1 0.0 0:00.03 vsftpd
7221 root 20 0 33464 1328 888 D 1 0.0 0:00.03 vsftpd
I think this is what you were affraid of... slowing down. I am not sure what would be the effect on my production servers.
Thanks!
Yes, basically cleanup is rather done in batches, which takes more cpu but could also affect lock contention. That and the fact that it requires backporting several patches which may cause effects we don't know of, causes me to be a bit reluctant about the changes.
After trying various approaches of backports which all seemed not really satisfying, it was decided that the safest way to go is to just turn off support for network namespaces. While this can have some impact on use-cases which try to containerize network, the feature was too immature to be turned on the first place. To use network namespaces in Lucid people should use the lts backport kernel.
The problem only occurs on Lucid with network namespaces turned on. So not valid for Maverick and later.?
Excerpts from Rachel Greenham's message of Sat Apr 16 11:25:10 UTC 2011:
>?
Rachel, Fix Committed means that the developers have it in their tree
but it hasn't been released yet. Presumably this means that netns will
be disabled in the next lucid kernel update.
Quite right, I should have noticed that. :-) I may just need to be patient then, although this being a production machine experiencing real problems since go-live with users connecting in volume may preclude patience. I had been considering embedding a java FTP server into our application instead, although now I've thought of that other advantages of doing so come to mind. :-) Late reply because commenting on this bug didn't subscribe me to it like I expected. Will subscribe now.
Accepted linux-
See https:/
Applied successfully to two test instances; can confirm absence of netns process, and nothing seems to be broken. :-) My problem is only exhibiting on a production server under load though, and while I can see elevated netns cpu usage most of the time it only becomes a problem intermittently, so it may take a little longer to install this there and see if it really helps.
This bug was fixed in the package linux - 2.6.32-32.62
---------------
linux (2.6.32-32.62) lucid-proposed; urgency=low
[ Brad Figg ]
* Release Tracking Bug
- LP: #767370
[ Stefan Bader ]
* (config) Disable CONFIG_NET_NS
- LP: #720095
[ Upstream Kernel Changes ]
* Revert "drm/radeon/kms: Fix retrying ttm_bo_init() after it failed
once."
- LP: #736234
* Revert "drm/radeon: fall back to GTT if bo creation/validation in VRAM
fails."
- LP: #736234
* x86: pvclock: Move scale_delta into common header
* KVM: x86: Fix a possible backwards warp of kvmclock
* KVM: x86: Fix kvmclock bug
* cpuset: add a missing unlock in cpuset_
- LP: #736234
* keyboard: integer underflow bug
- LP: #736234
* RxRPC: Fix v1 keys
- LP: #736234
* ixgbe: fix for 82599 erratum on Header Splitting
- LP: #736234
* mm: fix possible cause of a page_mapped BUG
- LP: #736234
* powerpc/kdump: CPUs assume the context of the oopsing CPU
- LP: #736234
* powerpc/kdump: Use chip->shutdown to disable IRQs
- LP: #736234
* powerpc: Use more accurate limit for first segment memory allocations
- LP: #736234
* powerpc/pseries: Add hcall to read 4 ptes at a time in real mode
- LP: #736234
* powerpc/kexec: Speedup kexec hash PTE tear down
- LP: #736234
* powerpc/crashdump: Do not fail on NULL pointer dereferencing
- LP: #736234
* powerpc/kexec: Fix orphaned offline CPUs across kexec
- LP: #736234
* netfilter: nf_log: avoid oops in (un)bind with invalid nfproto values
- LP: #736234
* nfsd: wrong index used in inner loop
- LP: #736234
* r8169: use RxFIFO overflow workaround for 8168c chipset.
- LP: #736234
* Staging: comedi: jr3_pci: Don't ioremap too much space. Check result.
- LP: #736234
* net: don't allow CAP_NET_ADMIN to load non-netdev kernel modules,
CVE-2011-1019
- LP: #736234
- CVE-2011-1019
* ip6ip6: autoload ip6 tunnel
- LP: #736234
* Linux 2.6.32.33
- LP: #736234
* drm/radeon: fall back to GTT if bo creation/validation in VRAM fails.
- LP: #652934, #736234
* drm/radeon/kms: Fix retrying ttm_bo_init() after it failed once.
- LP: #652934, #736234
* drm: fix unsigned vs signed comparison issue in modeset ctl ioctl,
CVE-2011-1013
- LP: #736234
- CVE-2011-1013
* Linux 2.6.32.33+drm33.15
- LP: #736234
* econet: Fix crash in aun_incoming(). CVE-2010-4342
- LP: #736394
- CVE-2010-4342
* igb: only use vlan_gro_receive if vlans are registered, CVE-2010-4263
- LP: #737024
- CVE-2010-4263
* irda: prevent integer underflow in IRLMP_ENUMDEVICES, CVE-2010-4529
- LP: #737823
- CVE-2010-4529
* hwmon/f71882fg: Set platform drvdata to NULL later
- LP: #742056
* mtd: add "platform:" prefix for platform modalias
- LP: #742056
* libata: no special completion processing for EH commands
- LP: #742056
* MIPS: MTX-1: Make au1000_eth probe all PHY addresses
- LP: #742056
* x86/mm: Handle mm_fault_error() in kernel space
- LP: #742056
* ftrace: Fix memory leak with function graph and cpu hotplug
- LP: #742056
* x86: Fix panic when ...
lxc is now not usable on lucid.
Actually, this isn't making sense to me. CLONE_NEWNET requires privilege, so this isn't something a random user can exploit. So what is the value in turning netns support off in the kernel as opposed to just stopping vsftpd from using it? (Attached debdiff not tested, but should suffice. I'll test if it will be considered IN PLACE of turning off CONFIG_NET_NS).
Fixing vsftpd looks like a much better fix for this!
On 01/06/11 17:08, Stefan Metzmacher wrote:
> Fixing vsftpd looks like a much better fix for this
It would seem at first sight to be simpler; but presumably the problem
was that there are bugs in the implementation in the Lucid kernel (and
upstream) that won't necessarily *only* impact vsftpd users, although we
were the ones who first reported it. Certainly from my practical point
of view I'd have been happy with a simple vsftpd update to remove the
problem. :-)
The bug being in the kernel, and backporting the fix to it being deemed
too complicated (see nearer the top of this bug report thread) the
decision was therefore to disable the feature.
To those that depend on the feature, ie: lxc users (aside: i hadn't
heard of that! after googling i may want to use it now!), given the
feature is buggy in the lucid - and upstream - kernel *anyway*, maybe
the appropriate action is to use the maverick backport kernel?
--
Rachel
On 02/06/11 14:32, Rachel Greenham wrote:
> On 01/06/11 17:08, Stefan Metzmacher wrote:
>> Fixing vsftpd looks like a much better fix for this
Also presumably disabling it in vsftpd will hurt people who want to use
that in an lxc setting without providing an easily-applied solution.
--
Rachel
As far as I understand the problem, the problem comes with creating a new network namespace with every clone() syscall.
In a lxc setup only the startup process creates a new network namespace, just once.
I can't see why vsftpd (without CLONE_NEWNET) won't run within an already established lxc session.
The released resolution broke a production environment here: See #844185
I propose this is instead fixed by disabling it in vsftpd.
On 07.09.2011 12:16, Alex Bligh wrote:
> The released resolution broke a production environment here: See #844185
>
> I propose this is instead fixed by disabling it in vsftpd.
>
The problem is that nobody can say that vsftp was or is the only vector that
allows to DOS a system doing something that involves network namespaces.
If netns is essential. It is probably a better solution to move to the
LTS-backports kernel which is newer and does not have those memory cleanup issues.
That is sadly not an option. LTS-backport kernel has a spectacular and easy to repeat Oops when namespaces are used. See #843892.
It is not guaranteed by the kernel (it certainly wasn't in 2.6.32) that namespaces would be created and deleted instantly and without undue system pressure. It seems to me that the bug is in applications which think this can be done. As an example, in 2.6.32 creating 1000 interfaces and deleting them takes a huge time on delete due to RCU sync issues. If a userspace program did this, prompted by an external user, our response would not be to disable creation and deletion of interfaces. Rather we'd fix the userspace program not to do it.
Note also that if vsftp continues to use clone(NEW_NETNS) (i.e. network namespaces) it is likely to suffer from #843892 anyway, so not using network namespaces will give you a stability increase. (NB - I have not tested vsftp against the bug in #843892 but as you can see from the text, it is hardly difficult to hit).
From the report it seems that this was broken in v2.6.32 and maybe fixed in v2.6.35. The commit below sounds plausable and might be worth looking at:
commit 02b709df817c0db
174f249cc59e5f7 fd01b64d92
Author: Nick Piggin <email address hidden>
Date: Mon Feb 1 22:25:57 2010 +1100
mm: purge fragmented percpu vmap blocks
Improve handling of fragmented per-CPU vmaps. We previously don't free
up per-CPU maps until all its addresses have been used and freed. So
fragmented blocks could fill up vmalloc space even if they actually had
no active vmap regions within them.
Add some logic to allow all CPUs to have these blocks purged in the case
of failure to allocate a new vm area, and also put some logic to trim
such blocks of a current CPU if we hit them in the allocation path (so
as to avoid a large build up of them).
Christoph reported some vmap allocation failures when using the per CPU
vmap APIs in XFS, which cannot be reproduced after this patch and the
previous bug fix.
Cc: <email address hidden>
Cc: <email address hidden>
Tested-by: Christoph Hellwig <email address hidden>
Signed-off-by: Nick Piggin <email address hidden>
--
Signed-off-by: Linus Torvalds <email address hidden> | https://bugs.launchpad.net/ubuntu/+source/linux/+bug/720095 | CC-MAIN-2021-04 | refinedweb | 3,106 | 69.52 |
Annotating matplotlib figures
Posted November 01, 2014 at 10:35 AM | categories: python matplotlib | tags: | View Comments
There is a nice picture of an ethanolamine molecule here . The first thing we consider is embedding this figure in a matplotlib figure. It is a little tricky because we have to create a special axes to put the image in. The axes are created in a fractional coordinate systems that is defined by [left, bottom, width, height]. Placing the figure where you want it is an iterative process that involves changing those values to get the image where you want.
So, note that (0, 0) is the bottome left corner of the figure, and (1, 1) is the upper right corner. So, to make an axes for the main figure that takes up 75% of the width and 80% of the height, and starts 20% from the left, 15% from the bottom, we use [0.2, 0.15, 0.75, 0.8]. That covers most of the space, and leaves room for labels.
The axes for the image is about the same, but it is a little trickier to figure out the width and height. In this example these arguments appear to just rescale the image.
Here is some code that puts the image near the upper left-corner of the plot.
import matplotlib.pyplot as plt from scipy.misc import imread import numpy as np im = imread('images/Ethanolamine-2D-skeletal-B.png') fig = plt.figure(figsize=(3, 4)) # left bottom width height f_ax = fig.add_axes([0.2, 0.15, 0.75, 0.8], zorder=1) # plot some function f_ax.plot(np.arange(10), 4 * np.arange(10)) plt.xlabel('some xlabel') plt.ylabel('Y') # axes for the image i_ax = fig.add_axes([0.22, 0.8, 0.3, 0.1], frameon=False, xticks=[], yticks=[], zorder=2) # add the image. zorder>1 makes sure it is on top i_ax.imshow(im) # print dir(i_ax) plt.savefig('images/fig-in-plot-2.png', dpi=300)
Figure 1: A matplotlib figure with an embedded images.
There it is.
Copyright (C) 2014 by John Kitchin. See the License for information about copying.
Org-mode version = 8.2.7c | http://kitchingroup.cheme.cmu.edu/blog/category/python-matplotlib/ | CC-MAIN-2017-39 | refinedweb | 363 | 76.93 |
The goal of this blog series is to run a realistic natural language processing (NLP) scenario by utilizing and comparing the leading production-grade linguistic programming libraries: John Snow Labs’ NLP for Apache Spark and Explosion AI’s spaCy. Both libraries are open source with commercially permissive licenses (Apache 2.0 and MIT, respectively). Both are under active development with frequent releases and a growing community..
As simple as it may sound, it is tremendously challenging to compare two different libraries and make comparable benchmarking. Remember that Your application will have a different use case, data pipeline, text characteristics, hardware setup, and non-functional requirements than what’s done here. spaCy 101 and the Spark-NLP Quick Start documentation first.
The libraries
Spark-NLP was open sourced in October 2017. It is a native extension of Apache Spark as a Spark library. It brings a suite of Spark ML Pipeline stages, in the shape of estimators and transformers, to process distributed data sets. Spark NLP Annotators.
spaCy is a popular and easy-to-use natural language processing library in Python. It recently released version 2.0, which incorporates neural network models, entity recognition models, and much more. It provides current state-of-the-art accuracy and speed levels, and has an active open source community. spaCy been here for at least three years, with its first releases on GitHub tracking back to early 2015..
Both libraries offer customization through parameters in some level or another, allow the saving of trained pipelines in disk, and require the developer to wrap around a program that makes use of the library in a certain use case. Spark NLP makes it easier to embed an NLP pipeline as part of a Spark ML machine learning pipeline, which also enables faster execution since Spark can optimize the entire execution—from data load, NLP, feature engineering, model training, hyper-parameter optimization, and measurement—together at once.
The benchmark application
The programs I am writing here, will predict part-of-speech tags in raw .txt files. A lot of data cleaning and preparation are in order. Both applications will train on the same data and predict on the same data, to achieve the maximum possible common ground.
My intention here is to verify two pillars of any statistical program:
- Accuracy, which measures how good a program can predict linguistic features
- Performance, which means how long I'll have to wait to achieve such accuracy, and how much input data I can throw at the program before it either collapses or my grandkids grow old.
In order to compare these metrics, I need to make sure both libraries share a common ground. I have the following at my disposal:
- A desktop PC, running Linux Mint with 16GB of RAM on an SSD storage, and an Intel core i5-6600K processor running 4 cores at 3.5GHz
- Training, target, and correct results data, which follow NLTK POS format (see below)
- Jupyter Python 3 Notebook with spaCy 2.0.5 installed
- Apache Zeppelin 0.7.3 Notebook with Spark-NLP 1.3.0 and Apache Spark 2.1.1 installed
The data
Data for training, testing, and measuring has been taken from the National American Corpus, utilizing their MASC 3.0.2 written corpora from the newspaper section.:
Neither|DT Davison|NNP nor|CC most|RBS other|JJ RxP|NNP opponents|NNS doubt|VBP the|DT efficacy|NN of|IN medications|NNS .|.
As you can see, the content in the training data is:
- Sentence boundary detected (new line, new sentence)
- Tokenized (space separated)
- POS detected (pipe delimited)
Whereas in the raw text files, everything comes mixed up, dirty, and without any standard bounds
Here are key metrics about the benchmarks we’ll run:
The benchmark data sets
We’ll use two benchmark data sets throughout this article. The first is a very small one, enabling interactive debugging and experimentation:
- Training data: 36 .txt files, totaling 77 KB
- Testing data: 14 .txt files, totaling 114 KB
- 21,362 words to predict
The second data set is still not “big data” by any means, but is a larger data set and intended to evaluate a typical single-machine use case:
- Training data: 72 .txt files, totaling 150 KB
- Two testing data sets: 9225 .txt files, totaling 75 MB; and 1,125, totaling 15 MB
- 13+ million words.
Getting started
Let's get our hands dirty, then. First things first, we've got to bring the necessary imports and start them up.
spaCy
import os import io import time import re import random import pandas as pd import spacy nlp_model = spacy.load('en', disable=['parser', 'ner']) nlp_blank = spacy.blank('en', disable=['parser', 'ner'])
I've disabled some pipelines in spaCy in order to not bloat it with unnecessary parsers. I have also kept an
nlp_model for reference, which is a pre-trained NLP model provided by spaCy, but I am going to use
nlp_blank, which will be more representative, as it will be the one I’ll be training myself.
Spark-NLP
The first challenge I face is that I am dealing with three types of tokenization results that are completely different, and will make it difficult to identify whether a word matched both the token and the POS tag:
- spaCy's tokenizer, which works on a rule-based approach with an included vocabulary that saves many common abbreviations from breaking up
- SparkNLP tokenizer, which also has its own rules for tokenization
- My training and testing data, which is tokenized by ANC's standard and, in many cases, it will be splitting the words quite differently than our tokenizers "-".
spaCy)
Note: I am passing
vocab from
nlp_blank, which is not really blank. This vocab object has English language rules and strategies that help our blank model tag POS and tokenize English words—so, spaCy begins with a slight advantage. Spark-NLP doesn’t know anything about the English language beforehand.
Training pipelines
Proceeding with the training, in spaCy I need to provide a specific training data format, which follows this shape:
TRAIN_DATA = [ ("I like green eggs", {'tags': ['N', 'V', 'J', 'N']}), ("Eat blue ham", {'tags': ['V', 'J', 'N']}) ]
Whereas in Spark-NLP, I have to provide a folder of .txt files containing delimited word|tag data, which looks just like ANC training data. So, I am just passing the path to the POS tagger, which is called
PerceptronApproach.
Let’s load the training data for spaCy. Bear with me, as I have to add a few manual exceptions and rules with some characters since spaCy’s training set is expecting clean content.
spaCy
start = time.time() train_path = "./target/training/" train_files = sorted([train_path + f for f in os.listdir(train_path) if os.path.isfile(os.path.join(train_path, f))]) TRAIN_DATA = [] for file in train_files: fo = io.open(file, mode='r', encoding='utf-8') for line in fo.readlines(): line = line.strip() if line == '': continue line_words = [] line_tags = [] for pair in re.split("\\s+", line): tag = pair.strip().split("|") line_words.append(re.sub('(\w+)\.', '\1', tag[0].replace('$', '').replace('-', '').replace('\'', ''))) line_tags.append(tag[-1]) TRAIN_DATA.append((' '.join(line_words), {'tags': line_tags})) fo.close() TRAIN_DATA[240] = ('The company said the one time provision would substantially eliminate all future losses at the unit .', {'tags': ['DT', 'NN', 'VBD', 'DT', 'JJ', '-', 'NN', 'NN', 'MD', 'RB', 'VB', 'DT', 'JJ', 'NNS', 'IN', 'DT', 'NN', '.']}) n_iter=5 tagger = nlp_blank.create_pipe('tagger') tagger.add_label('-') tagger.add_label('(') tagger.add_label(')') tagger.add_label('#') tagger.add_label('...') tagger.add_label("one-time") nlp_blank.add_pipe(tagger) optimizer = nlp_blank.begin_training() for i in range(n_iter): random.shuffle(TRAIN_DATA) losses = {} for text, annotations in TRAIN_DATA: nlp_blank.update([text], [annotations], sgd=optimizer, losses=losses) print(losses) print (time.time() - start)
Runtime
{
vocab labels. Then, I had to add those characters to the list of labels for it to work once found during the training.
Let see how it is to construct a pipeline in Spark-NLP.
Spark-NLP) }
As you can see, constructing a pipeline is a quite linear process: you set the document assembling, which makes the target text column a target for the next annotator, which is the tokenizer; then, the
PerceptronApproach is the POS model, which will take as inputs both the document text and the tokenized form.
vocab or English knowledge, as opposed to spaCy.
The
corpusPath from
PerceptronApproach is passed to the folder containing the pipe-separated text files, and the
finisher annotator wraps up the results of the POS and tokens for it to be useful next.
SetOutputAsArray() will return, as it says, an array instead of a concatenated string, although that has some cost in processing.
The data passed to
fit() does not really matter since the only NLP annotator being trained is the
PerceptronApproach, and this one is trained with external POS Corpora.
Runtime
Time to train model: 3.167619593sec
As a side note, it would be possible to inject in the pipeline a
SentenceDetector or a
SpellChecker, which in some scenarios might help the accuracy of the POS by letting the model know where a sentence ends.
What’s next?.
In the next installment in the blog series, we will walk through the code, accuracy, and performance for running this NLP pipeline using the models we’ve just trained. | https://www.oreilly.com/ideas/comparing-production-grade-nlp-libraries-training-spark-nlp-and-spacy-pipelines | CC-MAIN-2018-39 | refinedweb | 1,533 | 53.51 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.